AI Briefing
KO

Real-Time Unique Viewer Count Per Product: Redis vs MongoDB

·2024.09.25 14:38

Key point

Compared Redis and MongoDB to design a structure for aggregating real-time unique viewer counts per product.

1 / 2

Details

To show a non-duplicated user count in real time on the product detail page, an API-based lookup structure that can be applied the same way to both web and app is considered. Since traffic surges rapidly, NoSQL is put forward as a candidate instead of RDB, and among NoSQL options, Redis and MongoDB are compared.

For Redis, several data structures are reviewed.

  • Set: Using the product number as the key and storing user identification info is simple, but if deletion is missed due to failure to detect browser closure or network issues, stale data remains.
  • Set + Expire: Adding an expiration time makes cleanup easier, but since the structure only deletes an entry after no one has viewed it for 60 seconds, real-time accuracy suffers significantly.
  • Set + Hash: A separate batch job can clear data where exit detection failed, but it requires iterating over all products and user info, leading to heavy O(N) load.
  • Sorted Set: By storing a time value per user as the score and using ZREMRANGEBYSCORE to remove old entries, this offers the best balance. Although a batch job still needs to sweep through all products so it's not entirely lightweight, this approach is chosen considering convenience and performance.

For MongoDB, two designs are compared.

  • The first is an approach like userProductView, which upserts the product number, login ID, and timestamp. The aggregate can be obtained from the document count per product, but an index for search optimization and a TTL (expire) setting for user count synchronization need to be considered together.
  • The second approach puts a users array inside a single product document. The structure is simple, but as the array grows, iteration and update costs increase, and for frequently viewed products the document keeps growing, eventually requiring Batch Job cleanup again anyway.

In summary, considering real-time performance and providing lookups across multiple domains, Redis appears more suitable, but at a higher cost. Conversely, MongoDB may be easier to maintain since it doesn't need a batch job, but requires more careful handling of indexes and expiration settings. The conclusion reached is that rather than one DB being the definitive answer, the choice should be made by weighing requirements together with operational burden.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.