High-Scale Game Marketplace Backend Architecture
Medium · System Design · Software Engineer · Onsite
Prompt
Design the backend architecture for a digital game marketplace built for a multi-million-player audience and a catalog of several hundred thousand titles. Traffic is heavily read-skewed: storefront browsing must remain highly available (where brief lag on charts or counts is acceptable), whereas monetary transactions and download permissions require strict correctness.
Support four core marketplace capabilities:
- Discovery & category feeds: Serve both data-driven charts (such as top-selling titles over a recent window and newly released titles from the past
Ndays) and tag-based genre catalogs (e.g., strategy, roguelike, racing, RPG), with pagination, sorting by popularity, star rating, or release date, and continuous chart updates as purchases and launches occur. - Rich-media title pages: Render descriptions, publisher profiles, regional pricing, OS compatibility, age ratings, tags, high-resolution screenshots, and streaming video trailers backed by object storage and CDNs.
- Checkout & binary delivery: Maintain user accounts and purchase histories integrated with an external payment processor, restrict installer downloads strictly to verified buyers via short-lived signed URLs, and handle heavy download bandwidth—including major launch-day spikes.
- Ratings & reviews: Allow verified players who have downloaded and tried a title to post 1–5 star scores and written reviews, maintain fast per-game rating summaries, and serve paginated review lists sorted by recency or helpfulness.
Scope & Expectations
- Service decomposition & storage layout: Define the main backend services, schemas, sharding/partitioning keys, and why specific workloads belong in relational databases, search indexes, caches, or object storage.
- Charts, rich media, & read scaling: Explain how dynamic charts, filtered genre queries, media renditions, and multi-tier caching handle high read volume and blockbuster release surges.
- Reliable commerce & high-throughput downloads: Trace order creation, payment processor confirmation, idempotent retries, and edge-authorized binary distribution.
- Review ranking & consistency boundaries: Show how review feeds and rating summaries stay fast at scale, clearly distinguishing operations that need ACID transactions from views that can converge asynchronously.
Step-by-step walkthrough
Clarify requirements and scope
A high-scale digital game marketplace combines two very different workloads under one roof: a high-volume, read-heavy storefront (thousands of category pages, trailers, screenshots, and reviews per second, where a few minutes of staleness is fine) and a strictly accurate commerce and delivery path (real-money orders, ownership records, and multi-terabit binary downloads, where losing a payment or handing out an unpaid game is unacceptable).
Functional requirements
- Browsing and discovery: Browse both dynamic categories (
top-sellingby recent sales,new-releaseslaunched within a rolling N-day window) and static genre categories (strategy,roguelike,racing,rpg, etc.), with pagination and sorting by popularity, rating, or release date. - Rich game detail page: Show title, description, publisher, regional price, platform compatibility, age rating, genre tags, responsive screenshots, and streaming video trailers.
- Purchase and download: Process real-money purchases through an external payment processor, record order history, restrict downloads strictly to verified buyers via time-limited signed URLs, and sustain massive launch-day download traffic.
- Ratings and reviews: Let players who have downloaded and tried a game post a 1–5 star rating and text review; serve the game's average rating plus paginated reviews sorted by most recent or most helpful.
Non-functional targets and clarifying assumptions
- Scale: ~20 million registered users (~5 million daily active users) and ~300,000 games across 3 platforms (Windows, macOS, Android) and 10 pricing regions.
- Availability and freshness: 99.95% availability for browsing and downloads. Top-selling rankings may lag by 5–15 minutes; new releases appear within ~2 minutes of their scheduled release timestamp; detail-page edits propagate within 5 minutes, while checkout always verifies the live authoritative price.
- Review eligibility (verified downloaders): Defined cleanly on the server as holding an active purchase and having started at least one download after the game's release timestamp (one editable review per user per game).
- Pre-orders: Supported—buyers can pay ahead of
release_atand pre-load encrypted files, unlocking at launch. - Out of scope: Personalized ML recommendations, tax compliance engines, in-game microtransactions, and social chat.
- Browsing and discovery: Browse both dynamic categories (
Back-of-the-envelope numbers
Sizing every path first reveals where simple single-node databases work and where sharding, streaming pipelines, or CDNs are mandatory:
Users and catalog Users 20M registered, 5M DAU Catalog metadata 300,000 games x ~8 KB = ~2.4 GB -> fits in one PostgreSQL DB and in RAM Category combinations ~100 genres x 3 sorts x 3 platforms x 10 regions = 9,000 genre views + dynamic lists Read traffic Total API reads 5M DAU x 40 req/day = 200M/day = ~2,300 req/s average, ~9,300 req/s at 4x peak Detail page views 5M DAU x 6 views/day = 30M views/day Purchases (writes) Everyday orders 3% of DAU buy/day = 150,000 orders/day = ~1.7/s average, ~7/s at 4x peak Hit game launch 100,000 sales in first hour = ~28 orders/s (short bursts higher) Order volume ~55M orders/year; ~1.05M orders in any 7-day rolling window Binary downloads Daily sessions 1.5 per purchase = 225,000/day; at 8 GB avg = 1.8 PB/day = ~167 Gbps average Hit launch (naive) 300,000 pre-orders x 80 GB = 24 PB; half in first 6 hrs = ~4.4 Tbps! With 3-day pre-load 24 PB spread over 72 hrs = ~0.74 Tbps average before launch Launch-hour buyers 100,000 new buyers x 80 GB = 8 PB; half in first 6 hrs = ~1.5 Tbps live CDN load Rich media (screenshots & trailers) Storage per game 12 images x 4 widths x 2 formats x 200 KB (~19 MB) + 2 trailers x 2 min across 4 bitrates (5+3+1.5+0.8 Mbps = ~155 MB each) = ~330 MB Total media storage 300,000 games x 330 MB = ~100 TB in object storage Media bandwidth Images: 30M views x 1.5 MB = 45 TB/day (~4 Gbps) Trailers: 15% of views watch 40 s at 3 Mbps (15 MB) = 67.5 TB/day (~6 Gbps) Reviews and helpful votes Writes 4% of purchases = ~6,000 reviews/day (~2.2M/year); helpful votes ~60,000/day Hottest launch game 1M helpful votes in launch week = ~1.7 votes/s averageWhat the math tells us
- Reads outnumber writes by > 1,000x, so public responses belong in Redis and a CDN (Content Delivery Network—edge cache servers distributed close to users worldwide), while relational databases easily handle the tens of writes per second.
- Catalog metadata (2.4 GB) needs zero sharding; the real catalog challenge is serving 9,000 filtered/sorted views and keeping dynamic rankings fresh without hammering the commerce database.
- Binary downloads (~167 Gbps daily, multi-terabit on launch day) dominate bandwidth, requiring edge token verification at CDNs plus encrypted pre-loading before blockbuster launches.
API design
We separate public cacheable storefront endpoints (which include
platformandregionin the query string so CDN cache keys never mix currencies or OS support) from authenticated user and publisher endpoints:Storefront & Discovery (public, CDN-cached) GET /v1/categories?platform=windows®ion=US GET /v1/lists/top-selling?platform=windows®ion=US&genre=roguelike&cursor=...&limit=30 GET /v1/lists/new-releases?platform=windows®ion=US&genre=roguelike&cursor=...&limit=30 GET /v1/genres/{genre}/games?sort=popularity|rating|release_date&platform=windows®ion=US&cursor=... -> 200 {"games": [{"game_id": 501, "title": "...", "cover": {"w320": "...", "w640": "..."}, "price": {"amount": 2999, "currency": "USD"}, "rating": 4.6, "review_count": 2140}], "next_cursor": "...", "as_of": "2026-11-30T12:10:00Z"} GET /v1/games/{game_id}?region=US User Commerce, Downloads & Reviews (authenticated; Cache-Control: private, no-store) GET /v1/me/library?cursor=... GET /v1/me/ownership?game_ids=501,502 POST /v1/orders Header: Idempotency-Key: ... Body: {"game_id": 501, "region": "US", "expected_price": ...} -> 201 {"order_id": 8801, "status": "AWAITING_PAYMENT", "payment": {"client_secret": "..."}} GET /v1/orders/{order_id} POST /v1/games/{game_id}/download-sessions Body: {"platform": "windows"} -> 200 {"build_id": 77, "base_url": "...", "manifest_path": "/manifest.json", "token": "...", "expires_at": "..."} GET /v1/games/{game_id}/license?platform=windows (returns decryption key once now >= release_at) GET /v1/games/{game_id}/reviews?sort=recent|helpful&cursor=...&limit=20 (public, CDN-cached 60 s) GET /v1/games/{game_id}/reviews/me (uncached) PUT /v1/games/{game_id}/reviews/me Body: {"rating": 5, "body": "..."} PUT /v1/reviews/{review_id}/votes/me Body: {"helpful": true} Publisher & Payment Gateway POST /v1/publisher/games/{game_id}/assets -> presigned object-storage upload URL POST /v1/publisher/games/{game_id}/builds -> presigned chunk upload URLs POST /v1/webhooks/payments -> signed gateway events (succeeded, failed, refunded)Why these shapes work well at scale:
- Idempotency key (a unique client-generated request ID) on
POST /v1/ordersensures network retries never double-charge, whilePUT .../meon reviews and votes makes repeated clicks naturally idempotent. expected_priceguards against stale cached pages: if the live database price changed since the page was cached, checkout halts with409 price_changedinstead of charging an unexpected amount.as_oftells clients the exact timestamp of a cached ranking snapshot.
- Idempotency key (a unique client-generated request ID) on
Data modeling and storage choices
Different data domains have different access patterns and consistency needs, so we pair PostgreSQL for authoritative records with specialized derived read stores:
1. Accounts DB (PostgreSQL, unsharded ~20 GB; owned by User Service) users user_id PK, email UNIQUE, password_hash, display_name, country, birth_date, status user_identities (provider, provider_subject) PK, user_id sessions session_id PK, user_id, refresh_token_hash, expires_at 2. Catalog DB (PostgreSQL, unsharded ~2.4 GB + media refs; owned by Game Catalog Service) games game_id PK, publisher_id, slug UNIQUE, title, description, age_rating, status (DRAFT | SCHEDULED | LISTED | DELISTED), release_at, updated_at game_platforms (game_id, platform) PK, min_os, current_build_id tags tag_id PK, slug UNIQUE, kind (genre | feature), name game_tags (game_id, tag_id) PK prices (game_id, region) PK, amount, currency, updated_at media_assets asset_id PK, game_id, kind (cover | screenshot | trailer), position, content_hash, status (PROCESSING | READY | FAILED), variants_json builds build_id PK, game_id, platform, manifest_key, content_key_id, total_bytes, status 3. Commerce DB (PostgreSQL, sharded by user_id; strongly consistent; Purchase & Entitlement Services) orders order_id PK, user_id, game_id, platform, region, amount, currency, idempotency_key, status (CREATED | AWAITING_PAYMENT | PAID | FAILED | EXPIRED | REFUNDED), gateway_payment_id UNIQUE, created_at, paid_at UNIQUE (user_id, idempotency_key); partial UNIQUE open order per (user_id, game_id) payment_events gateway_event_id PK, order_id, type, received_at ledger_entries entry_id PK, order_id, account, amount, currency -- double-entry (sums to 0) entitlements (user_id, game_id) PK, order_id, status (ACTIVE | REVOKED), granted_at, first_download_at outbox event_id PK, type, payload, created_at, published_at 4. Reviews DB (PostgreSQL, partitioned by game_id; owned by Review Service) reviews review_id PK, game_id, user_id, rating (1..5), body, status, verified_owner, helpful_up, helpful_total, helpful_score, created_at, updated_at UNIQUE (game_id, user_id) INDEX (game_id, status, created_at DESC, review_id DESC) INDEX (game_id, status, helpful_score DESC, review_id DESC) review_votes (review_id, user_id) PK, helpful rating_stats game_id PK, review_count, rating_sum, count_1 ... count_5Derived read stores (all rebuildable from PostgreSQL + event logs)
- OpenSearch (search index): One document per game (
tags,platforms,regions,release_at,prices,popularity_7d,bayesian_rating,review_count) to answer all 9,000 genre + platform + region + sort queries without precomputing 9,000 separate tables. - Redis: Stores precomputed
top-sellingversioned ID lists (rank:...) and pre-rendered game detail JSON (game:{game_id}:{region}). - Object storage + CDNs: Stores ~100 TB of immutable media renditions and petabytes of 64 MiB binary chunks.
- Kafka + Data Warehouse: Carries
catalog_changes,purchases,refunds, andreview_changesfrom transactional outbox tables (events written in the same DB commit as state changes, then relayed to Kafka) to update Redis, OpenSearch, and nightly analytics safely.
Why these shard keys fit. Every hot commerce lookup ("my library", "do I own game X?", "my orders") filters by
user_id, so sharding Commerce byuser_idkeeps every transaction on a single shard; per-game sales totals are aggregated asynchronously from Kafka rather than cross-shard queries. Conversely, reviews are read per game page, so partitioning Reviews bygame_idkeeps every review list andrating_statsupdate on one partition. Starting with 64 logical shards (database schemas) mapped onto 2 physical PostgreSQL primaries lets us scale later by moving schemas to new machines without rewriting application queries.- OpenSearch (search index): One document per game (
High-level architecture
Web / Desktop / Mobile Clients | | | 1. Public lists, | 2. Authenticated | 3. Encrypted / | pages, media | API calls | chunked builds | v v v [ Storefront CDN ] [ API Gateway: JWT auth, [ Download CDNs ] (JSON + media) rate limits ] (HMAC verified at edge) | miss | | v v v +----------------+---------------------+------------------+ [ Origin Shield ] | | | | | v v v v v [ Browse / [ Catalog & [ User [ Purchase & [ Review [ Object Storage: Ranking Svc ] Media Svc ] Svc ] Download Svc ] Svc ] media & builds ] | | | | | | ^ | ^ v v v v v v | v | [Open- ] [Redis] [Cat] [Redis] [User] [Commerce] [Pay ] [Reviews] [ Media Workers: Search] [ranks] [DB ] [docs ] [DB ] [DBs ] [Gtwy] [DB ] resize & HLS ] ^ ^ | | | | | +--- outbox ---> [ Kafka Event Bus ] <----+ | | | | +--- [ Index Updater ] <----------+ +---> [ Stream Ranking Job & Warehouse ]How components interact cleanly:
- User Service handles registration and login against the unsharded Accounts DB and mints short-lived signed JWTs verified at the API Gateway.
- Browse Service and Catalog Service serve storefront reads entirely from Redis and OpenSearch on cache misses, keeping source databases off the hot read path.
- Media Workers asynchronously resize uploaded screenshots and transcode trailers from Object Storage, notifying Catalog Service when renditions are ready.
- Purchase & Download Service owns the strongly consistent Commerce shards, talks to the payment gateway, and mints signed CDN tokens and pre-load decryption keys.
Deep dive 1: dynamic categories, genre rankings, and pagination
Each category type uses the mechanism matched to how fast its underlying signal changes:
1. Top-selling (5-minute streaming snapshots + nightly warehouse reconciliation)
Querying
GROUP BY game_idacross user-sharded commerce databases on every request would be prohibitively slow. Instead,purchases(+1) andrefunds(-1, carrying the originalpurchase_hour) flow through Kafka partitioned bygame_id, so every event for a given game lands on the exact same stream worker:Commerce shards --outbox--> Kafka (key = game_id) --> Stream workers maintain 168 hourly buckets (7 days) per (game_id, platform, region) --> Every 5 min: emit top 1,000 per scope (overall AND per genre) --> Coordinator merges worker top-1,000 lists -> writes immutable snapshot v{N} to RedisWhy the merge is 100% exact: because Kafka partitions by
game_id, a game's total count is never split across workers. As long as each worker emits its top 1,000 for each(platform, region, genre)scope before merging, any game in the global top 1,000 of that scope is guaranteed to be in its own worker's top 1,000! We also deduplicate byevent_idso Kafka's at-least-once replay never double-counts an order:WINDOW_HOURS = 168 # 7 days * 24 hours def ranking_key(item: tuple[int, int]) -> tuple[int, int]: units_sold, game_id = item # Sort highest sales first; break ties by smaller game_id for deterministic paging return (-units_sold, game_id) class PartitionTopSellingCounter: """Tracks 7-day rolling net unit sales for one Kafka partition keyed by game_id.""" def __init__(self): self.units_by_hour = {} # game_id -> {hour_bucket: net_units} self.seen_event_ids = set() # deduplicates at-least-once Kafka replays def on_event(self, event_id: str, game_id: int, purchase_hour: int, delta_units: int): if event_id in self.seen_event_ids: return self.seen_event_ids.add(event_id) hourly_counts = self.units_by_hour.setdefault(game_id, {}) hourly_counts[purchase_hour] = hourly_counts.get(purchase_hour, 0) + delta_units def top_k(self, current_hour: int, k: int, allowed_games: set[int] | None = None): """Return [(units, game_id)] for top k games in this partition (optionally within one genre).""" oldest_hour = current_hour - WINDOW_HOURS + 1 candidates = [] for game_id, hourly_counts in self.units_by_hour.items(): # Evict buckets older than 168 hours for hour in list(hourly_counts): if hour < oldest_hour: del hourly_counts[hour] if allowed_games is not None and game_id not in allowed_games: continue net_units = sum(hourly_counts.values()) if net_units > 0: candidates.append((net_units, game_id)) candidates.sort(key=ranking_key) return candidates[:k] def merge_partition_tops(partition_lists: list[list[tuple[int, int]]], k: int) -> list[int]: """Merge per-partition top-k lists into the exact global top-k game_id list.""" merged = [] for part_list in partition_lists: merged.extend(part_list) merged.sort(key=ranking_key) return [game_id for _, game_id in merged[:k]]In production,
seen_event_idsis bounded to a recent time window in RocksDB/Flink state, only non-fraudPAIDorders count (at most 1 unit per user per game), and a nightly warehouse job recomputes the 7-day totals from raw ledger history to heal any drift. Pagination cursors encode(snapshot_version, offset)—keeping the last 3 snapshots in Redis (15 minutes) so a user paging throughv42sees zero duplicates or skipped games whenv43arrives.2. New releases (OpenSearch time-window filter)
Scheduled games are indexed ahead of time with their
release_attimestamp.GET /lists/new-releasesrunsrelease_at BETWEEN (now_minute - 30d) AND now_minutesorted by(release_at DESC, game_id ASC). Roundingnowdown to the current minute makes the query cacheable at the CDN for 60 seconds, so games appear automatically within ~2 minutes of launch without any cron job flipping flags.3. Static/genre categories and Bayesian rating sort
OpenSearch filters by
genre,platform,region, andstatus = LISTED, using keyset pagination (search_after: [last_sort_val, last_game_id], which jumps directly to the next index entry in O(page_size) instead of scanning deepOFFSETs). For sorting by rating, raw averages fail because a brand-new game with a single 5-star review (5.00) outranks a classic with 2,000 reviews averaging4.60. Instead, we sort by a Bayesian average—a weighted average that blends a game's reviews withC = 50virtual reviews at the store-wide meanm = 3.80:bayesian_rating = (C * m + rating_sum) / (C + review_count) Game A (1 review, 5.0 avg): (50 * 3.80 + 5) / (50 + 1) = 195 / 51 = 3.82 Game B (2,000 reviews, 4.6 avg): (50 * 3.80 + 9200) / (50 + 2000) = 9390 / 2050 = 4.58 -> ranks higher!Deep dive 2: rich game detail pages and media delivery
Pre-rendered regional detail documents. Joining
games,game_platforms,tags,prices,media_assets, andrating_statson 30M daily views would waste database CPU. Instead, Catalog Service pre-renders one self-contained JSON document per(game_id, region)into Redis (game:501:US) and caches it at the CDN for 5 minutes. Whenever an outbox event signals a price edit, new screenshot, or updated rating summary, a worker re-renders that Redis key and purges its CDN URL. Per-user buttons ("Buy"vs"In Library") are fetched separately via/v1/me/ownershipso the detail JSON stays 100% shareable.Media upload, processing, and immutable delivery
- Direct upload: Publisher calls
POST /publisher/games/{id}/assetsand receives a presigned URL (a temporary, cryptographically signed link allowing the publisher's browser to upload raw files directly into Object Storage without passing multi-hundred-megabyte videos through our API servers). - Rendition pipeline: Workers generate WebP + fallback JPEG images at 4 widths (
320,640,1280,1920px) and transcode trailers into an HLS adaptive bitrate ladder (HTTP Live Streaming—splitting video into short 2–4 second.ts/.m4ssegments at 360p, 480p, 720p, and 1080p so players switch quality smoothly to match their connection speed). - Content-addressed immutable URLs: Every rendition is stored under a hash of its content (
media/501/8f3b2c/w640.webp) and served withCache-Control: public, max-age=31536000, immutable. Updating a screenshot produces a new hash and a new URL in the detail JSON—zero stale images and zero media cache purges! Trailers stream only when clicked (lazy play), keeping trailer egress around ~6 Gbps instead of 10x higher. - Stampede protection: On a hit launch page, request collapsing at the CDN merges thousands of simultaneous edge misses for one URL into a single origin fetch, and a single-flight lock (one thread rebuilds Redis while concurrent misses wait on that result) protects PostgreSQL if a Redis key expires.
- Direct upload: Publisher calls
Deep dive 3: purchase, download, and launch-day pre-loading
Purchase flow with two-hop idempotency and a double-entry ledger
Client Purchase Svc Commerce Shard (by user_id) Payment Gateway |-- POST /orders (Idem) ->| read live price; insert order CREATED ------------>| | |-- create payment (gateway idem_key = order_id) --->| |<-- client_secret -------|-- update order AWAITING_PAYMENT <------------------| |-- card / 3DS ---------->|--------------------------------------------------->| | |<----------- signed webhook: payment_succeeded -----| | | SINGLE SHARD TX: dedupe payment_events; | | | order -> PAID; balanced ledger_entries; | | | entitlement -> ACTIVE; outbox -> "purchase" |- Authority: Only a verified gateway webhook (or our 5-minute background reconciler querying orders pending > 10 minutes) transitions an order to
PAIDand grants anACTIVEentitlement—never the client UI. - Double-entry ledger: Every
PAIDorder records balanced rows inledger_entries(debit cash clearing, credit publisher payable + store commission, summing to zero), and refunds append reversing entries, giving finance and daily gateway settlement checks an auditable trail.
Secure downloads and taming a 4.4 Tbps blockbuster launch
- Edge-verified HMAC tokens:
POST /v1/games/{id}/download-sessionschecksentitlementson the user's primary commerce shard, setsfirst_download_at(oncenow >= release_at), and returns a 1-hour HMAC token (a tamper-proof hash signed with a secret shared between our backend and the Download CDNs) scoped to(user_id, build_id, expires_at). Download CDNs verify the HMAC at the edge and omit?token=...from the cache key so all buyers share cached 64 MiB chunks behind an origin shield (a middle cache layer shielding Object Storage). - Encrypted pre-loading for hit launches: Without pre-loading, 300,000 pre-order buyers pulling an 80 GB build at launch would spike egress to ~4.4 Tbps. Instead, starting 72 hours before
release_at, pre-order buyers download the chunks encrypted with AES-GCM using a per-build content key (~0.74 Tbps gentle average). Atrelease_at, clients add a random 0–60 s jitter and callGET /v1/games/{id}/license(~5,000 tiny req/s for one minute, served from shard replicas because pre-order entitlements are hours/days old) to fetch the 32-byte decryption key! For the 100,000 buyers who purchase on launch day (~1.5 Tbps live traffic), we reserve multi-CDN capacity (two CDNs steered via DNS/client manifest) and pre-warm chunks ahead of launch.
- Authority: Only a verified gateway webhook (or our 5-minute background reconciler querying orders pending > 10 minutes) transitions an order to
Deep dive 4: ratings, reviews, and cross-shard consistency
Cross-shard eligibility and closing the refund race. Because
entitlementslive on theuser_idcommerce shard whilereviewslive on thegame_idreview partition,PUT /v1/games/{id}/reviews/mecannot lock both in one single-node SQL transaction. Here is how we keep them consistent even if a refund occurs at the exact same moment:- Review Service calls Entitlement Service (primary read) to verify
status == 'ACTIVE',first_download_at IS NOT NULL, andnow >= release_at. - On the game's review partition, one local transaction upserts
reviews(UNIQUE (game_id, user_id),verified_owner = true) and updatesrating_statsby(new_contribution - old_contribution). - Normally, a later refund emits a
refundsKafka event whose consumer setsverified_owner = falseand subtracts the rating delta. To catch a refund that committed between step 1 and step 2 (whose Kafka consumer already ran before step 2 inserted the row), Review Service performs one post-commit re-check against the commerce primary: if the entitlement is nowREVOKED, it immediately clearsverified_owner = falseand reverses the stats delta (with a nightly reconciliation job as a backstop if the service crashes mid-step).
Ranking "most helpful" reviews fairly. Sorting by raw
helpful_upburies newer reviews, while sorting by raw percentagehelpful_up / helpful_totalranks a review with3 / 3(100%) above one with90 / 100(90%). Instead, we store and indexhelpful_scoreusing the Wilson score 95% confidence lower bound—a statistical formula asking "given the sample size, what is the lowest plausible true helpfulness rate?":3 helpful out of 3 votes (100% raw) -> Wilson lower bound = 0.44 90 helpful out of 100 votes (90% raw) -> Wilson lower bound = 0.83 -> ranks higher!Page 1 of most recent and most helpful (via keyset pagination) is cached at the CDN for 60 seconds, while the author fetches their own review uncached via
GET /reviews/mefor instant read-your-writes feedback. Sudden bursts of 1-star reviews trigger review-bombing alerts for moderators.- Review Service calls Entitlement Service (primary read) to verify
Reliability, consistency matrix, and key trade-offs
Where strong vs. eventual consistency applies
Data / Operation Consistency model Mechanism Orders, ledger, entitlements Strong (ACID) Single-shard PostgreSQL transactions + unique keys Checkout price verification Strong Read live from Catalog primary on POST /orders User's library & own review Read-your-writes Read from user's / game's primary shard Download authorization Strong on session start; Primary-shard check + 1-hr edge HMAC token <= 1 hr revocation window Game detail pages & prices shown Eventual (seconds–5 min) Outbox re-render + CDN purge + 5 min TTL New-releases & genre lists Eventual (1–2 min) OpenSearch near-real-time index + 60 s CDN TTL Top-selling lists Eventual (5–15 min) Kafka stream snapshots + nightly warehouse checkFailure recovery highlights
- Payment gateway outage: Circuit breaker halts new checkouts cleanly while browsing, library, and downloads stay 100% online; reconciler resolves in-doubt orders once the gateway recovers.
- Commerce shard primary failure: Automatic failover to its synchronous standby preserves all committed payments; clients retry safely with the same
Idempotency-Key. - Kafka, OpenSearch, or Stream job outage: Authoritative writes continue into outbox tables; top-selling serves the last good Redis snapshot (displaying its
as_oftimestamp) or falls back to a 15-minute replica SQL aggregate; genre pages fall back to cached page-1 lists in Redis. - Regional CDN degradation: Multi-CDN steering shifts chunk downloads to the secondary CDN while launchers resume per 64 MiB chunk.
Summary of key trade-offs
- Stream-computed 5-minute snapshots vs. live SQL for top-selling: Sub-millisecond reads, stable cursors, and zero load on commerce shards, traded against 5–15 minutes of ranking lag and operating a stream job.
- OpenSearch for 9,000 genre views vs. precomputing every list: Flexible filtering and Bayesian/date/popularity sorting in one engine, accepting 1–2 minutes of eventual consistency.
- Sharding commerce by
user_idand reviews bygame_id: Keeps every hot read/write single-shard, requiring Kafka streams for per-game sales counts and a post-write re-check for review eligibility. - Encrypted pre-loading + 1-hour edge HMAC tokens: Converts a 4.4 Tbps launch cliff into a smooth 3-day pre-load plus tiny key fetches, at the cost of client decryption logic and a <= 1-hour refund revocation window.
Intuition & how it works
Picture a massive megastore during a midnight video-game launch: millions of window-shoppers walk past display walls checking charts, screenshots, and reviews, a handful of cash registers carefully verify credit cards and stamp receipts, and a fleet of delivery trucks parked around every neighborhood hands out pre-packed boxes to anyone holding a valid receipt stamp. A high-scale game marketplace works by splitting its architecture along those exact three lines: a heavily cached, eventually consistent read plane for browsing, a strongly consistent, user-sharded commerce plane for money and ownership, and an edge-authenticated CDN delivery plane (Content Delivery Network—edge servers placed close to users worldwide) for multi-gigabyte media and game binaries.
A naive monolithic design collapses under this workload in three predictable places. Running live GROUP BY game_id SQL queries over 55 million annual orders or AVG(rating) scans over millions of reviews on every page load melts the database under 9,300 peak requests per second. Using raw star averages lets a game with one 5-star review outrank a classic with 2,000 reviews averaging 4.6, while OFFSET pagination skips and duplicates games whenever rankings shift. Worst of all, letting 300,000 buyers pull an 80 GB game at midnight without pre-loading creates a ~4.4 Tbps bandwidth cliff, and serving any of those files through backend servers saturates their network links immediately.
Trace four everyday events to see how the architecture handles both accuracy and scale:
- Purchase (strongly consistent write): User
42buys CyberDrift ($29.99) viaPOST /v1/orderswith an idempotency key (a unique client token ensuring retries reuse the same order). When the payment gateway sends a signed webhook confirming payment, User42's commerce shard runs one ACID transaction: it marks the orderPAID, writes balanced double-entry ledger rows (accounting entries whose debits and credits sum to zero), grants anACTIVEentitlement (durable download right), and appends apurchaseevent to a transactional outbox (a database table flushed reliably to Kafka). - Dynamic top-selling update (eventual consistency): Kafka routes that
purchaseevent bygame_idto the single stream worker responsible for CyberDrift, incrementing its current hourly bucket in a 168-hour (7-day) sliding window. Every 5 minutes, workers merge their top-1,000 lists into an immutable versioned snapshot (v43) in Redis, so millions of shoppers readtop-sellingin microseconds with stable pagination cursors. - Pre-load and launch download (edge data plane): Three days before launch, User
42's launcher callsPOST /download-sessions, receives a 1-hour HMAC token (a cryptographic signature verified at the CDN edge without calling our servers), and pre-loads encrypted 64 MiB chunks at leisure; at launch second, a tinyGET /licensecall delivers the 32-byte AES decryption key so the game unlocks instantly without a multi-terabit download stampede. - Review and rating update: After downloading and playing, User
42submits a 5-star review (PUT /games/501/reviews/me). Review Service verifies eligibility against User42's commerce shard, updatesreviewsandrating_statsatomically on Game501's review partition, re-checks the entitlement once post-commit to guard against a simultaneous refund, and asynchronously updates OpenSearch's Bayesian average (a weighted average pulled toward the store mean until enough reviews accumulate).
Key trade-offs
- 5-minute streaming snapshots vs. live queries or per-purchase re-sorting for
top-selling. Precomputing top-1,000 snapshots every 5 minutes from agame_id-partitioned Kafka stream keeps reads O(page_size) in Redis, preserves stable versioned cursors across pages, and puts zero load on commerce shards. Updating a live sorted set on every single purchase would cause shifting pages for zero user-visible benefit, while running SQLGROUP BYqueries directly on commerce shards becomes progressively heavier as order history grows. - OpenSearch index vs. precomputing all 9,000 genre list combinations. With ~100 genres x 3 sorts x 3 platforms x 10 regions (plus future price or feature filters), a single OpenSearch cluster holding 300,000 small game documents answers every filtered
new-releasesand genre query via keyset pagination (search_afterusing the last item's sort value andgame_id), trading 1–2 minutes of indexing lag and rare boundary shifts when hourly popularity scores refresh. - Strong consistency for money vs. eventual consistency for discovery. Orders, payment events, ledger entries, and entitlements use single-shard PostgreSQL ACID transactions because bugs there lose money or grant free games. Category charts, detail documents, and list rating counts propagate asynchronously in seconds to minutes via Kafka, unlocking aggressive Redis and CDN caching and keeping browsing up even if commerce or Kafka lags.
- Sharding commerce by
user_idand reviews bygame_id. Every hot commerce call ("my library", "my orders", "check my entitlement") touches a single user shard, and every game's review list andrating_statslive on a single game partition. The trade-off is that per-game sales counts must come from the Kafka stream rather than a SQL query, and review creation needs a cross-shard ownership check plus a post-write re-check to catch concurrent refunds. - Encrypted pre-loading + 1-hour edge HMAC tokens vs. live backend-checked downloads. Edge HMAC verification lets dual CDNs serve 167 Gbps daily and multi-terabit launches while sharing one cached copy of each chunk across all buyers, and encrypted pre-loading smooths 24 PB of pre-order downloads over 72 hours (~0.74 Tbps instead of ~4.4 Tbps). The costs are client encryption/key-fetch logic, pre-booking ~1.5 Tbps of CDN capacity for launch-day buyers who did not pre-order, and accepting up to a 1-hour refund revocation window on active download tokens.
- Immutable content-hashed media URLs vs. overwrite-and-purge URLs. Storing resized WebP/JPEG screenshots and HLS trailer segments (HTTP Live Streaming—short multi-bitrate video chunks for adaptive playback) under content-hash paths enables a 1-year
immutableCDN cache with zero purge races, trading minor background garbage-collection work for unreferenced old assets. - Bayesian ratings and Wilson helpfulness scores vs. raw averages. Blending star ratings with a prior (
C = 50virtual votes at3.8stars) and ranking helpfulness by the Wilson score lower bound (the 95%-confidence conservative helpfulness ratio, ranking90/100at0.83well above3/3at0.44) prevents tiny sample sizes from hijacking top lists, while the UI still displays the familiar raw average and total count.
Common mistakes
- Querying
SELECT game_id, COUNT(*) FROM orders GROUP BY game_idon live traffic (especially across user-sharded databases) instead of maintaining sliding-window counts via an event stream and caching versioned snapshots. - Filtering by genre after taking only an overall top-1,000 per stream partition, which silently drops top games in smaller genres; each partition must emit top-K per
(platform, region, genre)scope before merging, and deduplicate Kafka event IDs so replays do not double-count sales. - Using
OFFSETpagination or raw star averages, causing duplicate/skipped games when rankings change and putting 1-review games at #1 on "Highest Rated". - Routing publisher uploads, trailers, or 80 GB builds through backend API servers, instead of using presigned URLs for direct-to-object-storage uploads and CDNs with an origin shield for downloads.
- Trusting client-side payment
"success"redirects or omitting idempotency keys, which allows unpaid entitlements on spoofed redirects and double charges when network calls time out. - Mixing per-user
"Owned"flags into CDN-cached detail JSON, either leaking user libraries across shoppers or destroying CDN cache hit rates. - Ignoring the blockbuster launch cliff, sizing download bandwidth only for the 167 Gbps daily average while overlooking multi-terabit release-hour spikes, CDN cache stampedes, and pre-loading.
- Scanning
reviewsto computeAVG(rating)on every detail-page load instead of updating arating_statsrow transactionally whenever a review is created, edited, hidden, or un-verified by a refund.
Follow-up questions
- How would you prevent publishers or botnets from manipulating top-selling charts and star ratings? For
top-selling, count only gateway-confirmedPAIDorders that pass fraud checks, cap contribution at one unit per(user_id, game_id), and subtract refunds from their original purchase hour so buy-and-refund loops net to zero; additionally, flag coordinated clusters of newly created accounts sharing payment fingerprints, device IDs, or IP subnets so they are excluded from chart rankings without blocking legitimate library access. For reviews, requiring both anACTIVEpaid entitlement and a recorded download (first_download_atafterrelease_at) imposes a real financial and bandwidth cost per review, while per-user rate limits, Bayesian smoothing (C = 50), and anomaly alerts on sudden review spikes quarantine review-bombing bursts for moderators. - How would you deliver a 2 GB bug-fix patch to 500,000 owners of an 80 GB game without re-downloading the whole 80 GB? Store builds using content-defined chunking (splitting files at rolling-hash boundaries rather than fixed byte offsets so inserting bytes near the start of a game archive does not shift and invalidate every subsequent chunk) at a finer patch granularity of 1–4 MiB per chunk alongside a signed manifest of chunk SHA-256 hashes. When version 1.1 ships, the desktop launcher compares the new manifest against chunks already on disk and fetches only the ~2 GB of changed chunk hashes from the CDN (or applies binary diffs between version 1.0 and 1.1 for hot transitions). Before publishing the update notification, pre-warm the new chunks into both CDNs behind the origin shield and roll out update prompts with client jitter over 30–60 minutes so half a million launchers do not stampede at the exact same second.
- How would you expand the store globally to enforce regional pricing, regional availability, and local data-residency laws? Keep the 2.4 GB Catalog database globally replicated read-only to every serving region, storing explicit per-region rows in
pricesandregional_availability—and enforce checkout pricing using the verified billing country of the user's payment instrument rather than an easily spoofed VPN IP address. Pin each user's Commerce shard (orders,ledger_entries,entitlements) and personal account row to their home geographic region to satisfy data-residency rules and keep checkout low-latency, while embeddingregionin every storefront CDN URL and Redis key (game:501:JP) so cached pages always show local currency and legal availability.
Follow-up questions
- How would you prevent publishers or botnets from manipulating top-selling charts and star ratings?
- How would you deliver a 2 GB bug-fix patch to 500,000 owners of an 80 GB game without re-downloading the whole 80 GB?
- How would you expand the store globally to enforce regional pricing, regional availability, and local data-residency laws?
Similar questions
- Digital Game Storefront: Catalog, Checkout, Delivery, and Reviews
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency