# 9.6. Sales rank

> A large ecommerce company wants to list the best-selling products, overall and by category. One product might be the #1056th best-selling product overall but the #13th under "sports equipment" and #24th under "safety". Describe how you would implement the system

I am assuming I am building the storage system, the backend. We get notified when a new product is added, or sold.

Clearly each object has various pointers for different rankings in different categories. Because there are many products, they might be saved in different machines. In the beginning, each product is ranked and assigned a number. A central machine controls the rest of the machines, which contains a list of all products for each category.

For the edit:

When the ranking changes for category X, all products from category X are visited (saved in the central machine) and their rankings updated. The rankings could be saved in a linked list, so that if a product goes from position 15 to 5, then only the positions 5-15 are updated and not each of them. If a product falls from 4 to 24, all positions from 4 to 23 get their number reduced by 1, the product previously in pos 4 gets 24, and the rest are unchanged.

For a new addition:

for the category of the new product + the overall category, the ranking of this new product is calculated and the corresponding products get their ranking changed.

For deletion:

for the deletion of product X with ranking Y, the linked list in position Y-1 just points to Y+1 instead of to Y. The numbers of the following elements are changed.

For lookup:

locate the object in the main machine, access it, get its rankings.

## Hints

> What is the expectation on availability and accuracy?

I would say both are important, but the accuracy of the products in the front is more important than the products at the back.

> Purchases occur very frequently, you should limit database writes

We can access the db every 50-100-1k purchases maybe

> Where would it be appropriate to cache data or queue up tasks?

When purchases are very frequent, we only access the database every min or something. And we can cache the information of the products that are sold most frequently, in a LIFO style

## Solution

Scope the problem, should we list the ranking of the past week, month, all time? Discuss with interviewer.

As an assumption, we can assume the ranking for more popular products is more important than that of the lesser popular ones.

The solution goes for a SQL type database, see book pages 397-400.
