Digital Game Storefront: Catalog, Checkout, Delivery, and Reviews
Medium · System Design · Software Engineer · Technical Screen
Prompt
Design a multi-page digital game storefront where players can browse titles by category, purchase and download games, and submit or read player reviews. Specify the user journeys, database schema, APIs, and backend invariants needed so these workflows stay consistent across caching, network timeouts, and retries.
No numerical traffic figures or business policies are pre-assigned—state concrete scale assumptions (catalog size, traffic load, build sizes, client platforms, and uptime targets) and define explicit store policies for pricing changes, refunds, download retention, payment confirmation proof, and review eligibility.
Cover three connected areas of the product:
- Catalog browsing & title pages: How games map to categories, how category pages maintain deterministic ordering and pagination with effective caching, and how shoppers transition to a game's detail view and purchase action.
- Checkout, entitlements, & installer delivery: How orders and external payment states progress across retries or uncertain network drops, how confirmed payments create durable ownership records, and how multi-gigabyte game builds are authorized and delivered efficiently.
- Player ratings & reviews: Who is permitted to create or edit a review, how duplicate submissions and abusive posts are handled, and how review pagination and rating summaries balance write consistency against cached reads.
Scope & Expectations
- Explicit policies & authority boundaries: Define clear rules for ownership, refunds, and review rights, separating cached UI hints from the authoritative backend records that permit purchases, downloads, and verified reviews.
- Data model, APIs, & idempotency: Design schemas, uniqueness constraints, and endpoints that prevent double charges, lost payments, duplicate reviews, or skipped/repeated items when paging.
- Binary delivery & cache isolation: Show how public catalog views, private per-user ownership states, and large game installers are cached and served without bottlenecking backend servers or leaking user state.
- End-to-end consistency under retries & refunds: Walk through checkout timeouts, webhook races, refunds, and review updates to show how orders, entitlements, download tokens, and rating aggregates stay aligned.
Step-by-step walkthrough
Clarify requirements and product policies
The prompt intentionally leaves traffic numbers and several product rules open. The central principle of this design is separating what a page displays from what actually authorizes an action. A browser landing on a "Thank you!" screen, a cached "Download" button, or a client sending
"verified": truemust never grant anything; every sensitive action must be checked on the server against an authoritative database record.First, let us define the core concept of ownership in this store: an entitlement is a durable database row recording that a specific user currently holds the right to download and review a specific game.
Functional requirements
- Browse: View all categories, page through games in a category with stable sorting, and open a game's detail page.
- Purchase: Buy a game with real money and see a truthful status (
paid,processing, orfailed), even across network timeouts and retries. - Download: Download owned game builds on supported desktop platforms, including reinstalls on a new computer or resuming an interrupted 50 GB transfer.
- Reviews: Submit, edit, or delete one's own review (1–5 stars plus text), and read paginated reviews plus the game's average rating.
Non-functional requirements and scale assumptions
- Catalog size: ~20,000 games across ~40 categories (1 to 3 categories per game).
- Traffic: ~1 million daily active users (DAU), viewing ~15 pages per day each.
- Artifacts and clients: Game builds are 1 GB to 100 GB (15 GB average). Users browse, buy, and review on the web or inside a desktop launcher (Windows and macOS), and the desktop launcher handles downloads and installation.
- Latency and availability: Catalog and detail pages target p99 latency under 300 ms and 99.95% availability (up to a minute of display staleness is fine). Browsing and downloads must stay up even if the external payment provider is down.
- Strict payment correctness: Never double-charge a user for the same game, never lose a completed payment, and never allow a download without confirmed payment.
Product policies we establish up front
Policy area Chosen rule When access is granted Only when our backend verifies payment with the payment provider (via a cryptographically signed webhook or a server-to-server status query)—never on a browser redirect. Valid payment evidence Provider payment record in status "succeeded" matching our order's exact amount and currency. Price changes mid-checkout Charge the database price at order creation; if it differs from the price shown on the user's cached page, stop checkout with 409 "price_changed". Download duration Unlimited reinstalls while the entitlement is ACTIVE; each signed download URL expires after 1 hour and can be refreshed if the entitlement is still ACTIVE. Delisted games Removed from sale, but existing owners keep their entitlement and can re-download. Refunds Allowed within 14 days; revokes the entitlement so no new download sessions are granted (already-installed local copies are not forcibly wiped). Review eligibility Requires an ACTIVE entitlement; at most one review per (user, game), editable and deletable with revision history. After a refund, the review stays visible, loses its "verified purchase" badge, drops out of the rating average, and cannot be edited (only deleted)—unless the user buys the game again.Out of scope: publisher upload portals, personalized recommendations, gifting, tax calculation engines, and in-game microtransactions.
Back-of-the-envelope numbers
Estimating traffic and data sizes early tells us which parts of the system are simple and which parts will break if designed naively.
Browsing Page views 1M DAU x 15 views/day = 15M/day = ~175/s average, ~870/s at a 5x evening peak API calls 1 to 3 per page view -> ~2,600 req/s at peak (mostly cacheable public reads) Catalog metadata 20,000 games x ~5 KB = ~100 MB -> fits easily in RAM on a single cache server Purchases Daily orders 2% of DAU buy/day = 20,000 orders/day = ~0.23 orders/s average Big game launch 50,000 sales in 1 hr = ~14 orders/s Order storage 20,000/day x 365 x 1 KB = ~7.3 GB/year Downloads Download sessions 1.5 per purchase (reinstalls, second PC) = 30,000 sessions/day Daily bandwidth 30,000 x 15 GB = 450 TB/day = ~42 Gbps continuous average Big launch spike 50,000 buyers x 60 GB in 3 hours = 3 PB in 10,800 s = ~2.2 Tbps Build storage 20,000 games x 15 GB x 2 platforms x 2 retained versions = ~1.2 PB Client transfer 50 GB over a 100 Mbps home connection (12.5 MB/s) = 4,000 s = ~67 minutes Reviews Writes 5% of buyers review = ~1,000 new reviews/day (+ small edit volume) Reads 40% of views load p.1 = 6M/day = ~70/s average, ~350/s at peakThree architectural lessons from the math
- Authoritative writes are tiny. Even during a blockbuster launch, ~14 orders per second and ~1,000 reviews per day are effortless for a single PostgreSQL primary database. We should keep orders, entitlements, and reviews in one relational database so state transitions happen inside real ACID transactions rather than brittle cross-service sagas.
- Download bandwidth is massive. Serving 42 Gbps every day and 2.2 Tbps at launch through backend application servers is impossible. Our backend should only issue tiny authorization tokens, while a CDN (Content Delivery Network—a globally distributed fleet of edge cache servers close to users) delivers the multi-gigabyte files from object storage.
- Catalog reads are identical for everyone—if we strip user state out. Public game details and category pages can be cached at the CDN, while a separate lightweight call fetches whether the logged-in user already owns those games.
User flows and API design
Here is how a user moves across the connected store pages, and which backend calls power each transition:
[ Category list ] ---> [ Category page: sorted, paginated grid of game cards ] | click a card v [ Game detail page: media, price, rating summary, page 1 of reviews ] | Buy | Download | Write / edit review v v v [ Checkout: card form ] [ Desktop launcher ] [ Review editor ] | 1. POST download-sessions 1. GET reviews/me (prefill) v 2. Fetch chunks from CDN 2. PUT reviews/me [ Order status: polling ] ---> [ Library: owned games ]To make retries safe and keep shared pages cacheable, we split the HTTP API into public catalog endpoints, private per-user endpoints, review endpoints, and a payment webhook:
Catalog (public, cached at CDN) GET /v1/categories -> 200 [{"slug": "rpg", "name": "Role-Playing", "game_count": 640}, ...] GET /v1/categories/{slug}/games?sort=popular|newest|title&cursor=...&limit=24 -> 200 {"games": [{"game_id": 12, "title": "...", "price": {"amount": 1999, "currency": "USD"}, "avg_rating": 4.6, "review_count": 310}], "next_cursor": "eyJ2Ijo..."} GET /v1/games/{game_id} -> 200 (description, screenshots, price, supported platforms, rating breakdown) Purchases, ownership, and downloads (authenticated; Cache-Control: private, no-store) GET /v1/me/ownership?game_ids=12,57,99 -> 200 {"12": "owned", "57": "pending", "99": "none"} POST /v1/orders Header: Idempotency-Key: 6f1c-... Body: {"game_id": 12, "expected_price": {"amount": 1999, "currency": "USD"}} -> 201 {"order_id": 901, "status": "AWAITING_PAYMENT", "payment": {"client_secret": "..."}} -> 200 (returns existing order if same Idempotency-Key or open order for this game exists) -> 409 {"error": "already_owned"} | {"error": "price_changed", "current_price": {...}} GET /v1/orders/{order_id} -> 200 {"order_id": 901, "status": "AWAITING_PAYMENT" | "PAID" | "FAILED" | "REFUNDED"} GET /v1/me/library?cursor=... POST /v1/games/{game_id}/download-sessions Body: {"platform": "windows-x64"} -> 200 {"build_id": 88, "base_url": "https://dl.example-cdn.com/builds/88", "manifest_path": "/manifest.json", "token": "eyJ...", "expires_at": "..."} -> 403 {"error": "not_entitled"} Reviews and webhooks GET /v1/games/{game_id}/reviews?sort=newest|helpful&cursor=...&limit=20 (CDN cached 60 s) GET /v1/games/{game_id}/reviews/me (uncached) PUT /v1/games/{game_id}/reviews/me Header: If-Match: 3 Body: {"rating": 5, "body": "..."} -> 200 {"review_id": 44, "version": 4, "status": "PUBLISHED", "verified_purchase": true} -> 403 not_eligible | 412 version_conflict | 422 invalid | 429 rate_limited DELETE /v1/games/{game_id}/reviews/me POST /v1/reviews/{review_id}/reports Body: {"reason": "spam" | "abuse" | "off_topic"} POST /v1/webhooks/payments (signed events from the payment provider)Three key design mechanisms appear in these endpoints:
- Idempotency key: A client-generated unique token sent with a request so that if the browser retries after a timeout, the server recognizes the repeat and returns the original order instead of creating a second one.
- Webhook: An authenticated HTTP callback sent directly from the payment provider's servers to ours whenever a charge or refund finishes, independent of whether the user closed their browser tab.
- Optimistic concurrency (
If-Match): Sending the version number the user started editing so the database rejects accidental overwrites (412 Precondition Failed) if the user edited the same review from another tab meanwhile.
Data model and database constraints
All authoritative records live in a single PostgreSQL database. Rather than relying only on
ifchecks in application code—which two simultaneous requests can pass at the same instant—we enforce invariants with primary keys and unique indexes:Catalog & Builds games game_id PK, slug UNIQUE, title, description, price_amount, currency, status (DRAFT | LISTED | DELISTED), release_date, updated_at categories category_id PK, slug UNIQUE, name game_categories (category_id, game_id) PK builds build_id PK, game_id, platform, version_label, manifest_key, total_bytes, status (UPLOADING | READY | RETIRED) -- partial UNIQUE (game_id, platform) WHERE status = 'READY' Orders & Entitlements orders order_id PK, user_id, game_id, amount, currency, idempotency_key, status (CREATED | AWAITING_PAYMENT | PAID | FAILED | EXPIRED | DUPLICATE_REFUND_PENDING | REFUNDED), provider_payment_id UNIQUE, created_at, paid_at UNIQUE (user_id, idempotency_key) UNIQUE (user_id, game_id) WHERE status IN ('CREATED', 'AWAITING_PAYMENT') payment_events provider_event_id PK, order_id, type, received_at entitlements (user_id, game_id) PK, order_id, status (ACTIVE | REVOKED), granted_at, revoked_at Reviews & Aggregates reviews review_id PK, game_id, user_id, rating (1..5), body, version, helpful_count, status (PUBLISHED | PENDING_MODERATION | HIDDEN), verified_purchase, created_at, updated_at UNIQUE (game_id, user_id) INDEX (game_id, status, created_at DESC, review_id DESC) INDEX (game_id, status, helpful_count DESC, review_id DESC) review_revisions (review_id, version) PK, rating, body, edited_at review_reports (review_id, reporter_id) PK, reason, created_at game_rating_stats game_id PK, verified_count, verified_sum, count_1 ... count_5 Async Side Effects outbox event_id PK, type, payload, created_at, published_atThe
outboxtable implements the transactional outbox pattern: writing a "send receipt email" or "purge CDN cache" job into the database inside the exact same transaction as the order or review update, so a background worker can reliably deliver it afterward without ever losing a notification if a server crashes right after commit.Why each database constraint matters:
UNIQUE (user_id, idempotency_key)guarantees a network retry onPOST /v1/ordersreturns the exact same order row.- Partial
UNIQUE (user_id, game_id) WHERE status IN ('CREATED', 'AWAITING_PAYMENT')catches a user who opens a second browser tab (generating a new idempotency key) for the same game and hands back the in-progress order instead of starting a second charge. payment_events (provider_event_id PK)makes duplicate webhook deliveries harmless no-ops.entitlements (user_id, game_id) PKguarantees a user can never hold two simultaneous entitlements for one game.reviews UNIQUE (game_id, user_id)guarantees double-clicking "Post review" updates one row instead of inserting duplicates.
High-level architecture and the authority boundary
Web browser / Desktop launcher | 1. Catalog JSON & images | 2. Private API (auth) | 3. 64 MiB build chunks v v v [ Catalog CDN ] --miss--> [ Stateless App Servers ] <--webhooks-- [ Payment Provider ] catalog | orders | downloads | reviews --create/query/refund--> | | \ v v \ signs 1-hr HMAC token [ Redis: game cards, [ PostgreSQL Primary ] v listing snapshots ] [ + Sync Standby ] [ Download CDN ] ^ [ + Read Replica ] (verifies token at edge) | | outbox rows | | v v [ Background Workers: snapshot builder, [ Origin Shield ] payment reconciler, CDN cache purges, | receipt emails, review moderation ] v [ Object Storage: builds & images ]At ~2,600 peak requests per second (most absorbed by CDNs) and < 100 writes per second, one modular stateless backend service is far cleaner than splitting into four separate microservices—we avoid network hops and distributed transactions while keeping clear internal module boundaries (
catalog,orders,downloads,reviews).Applying that authority principle across the system, every user-visible element is strictly separated from the backend record that authorizes it:
Feature Displayed on client (non-authoritative) Authoritative check on backend Purchase Provider widget "Payment complete!" Provider webhook or status poll verified by server or order status screen -> recorded as orders.status = 'PAID' Download "Download" button on game detail or Primary-DB lookup of entitlements.status = 'ACTIVE' library page when issuing a 1-hour signed edge token Review Review editor form or cached entitlements.status = 'ACTIVE' checked on write; "Verified Purchase" badge reviews.verified_purchase set only by the server Price "$19.99" shown on a cached game page games.price_amount read on order creation and matched against expected_priceDeep dive 1: catalog browsing, stable pagination, and caching
Why naive
OFFSETpagination breaks on dynamic sorts. Suppose a category sorted by popularity has 6 games[G1, G2, G3, G4, G5, G6]and a page size of 3:1. User loads Page 1 (OFFSET 0 LIMIT 3) -> sees [G1, G2, G3]. 2. Meanwhile, G4 sells a few copies and overtakes G3 -> live order is now [G1, G2, G4, G3, G5, G6]. 3. User clicks Page 2 (OFFSET 3 LIMIT 3) -> sees [G3, G5, G6]. Result: G3 appears twice, and G4 was completely skipped!In addition,
OFFSET 5000forces the database to scan and discard 5,000 rows on every request.Versioned listing snapshots in Redis. Because our catalog has only ~20,000 games across 40 categories (~1,000 games per category on average), we can precompute every
(category, sort)list ofgame_ids—just 40 categories x 3 sorts = 120 lists, each a few kilobytes—and store them in Redis as immutable numbered versions (v7,v8, ...). Ties are broken bygame_idso the order is 100% deterministic. "Popular" (7-day net sales) rebuilds hourly; "newest" and "title" rebuild whenever a game is listed or delisted.When a user loads page 1, the returned
next_cursorencodes both the snapshot version (v = 7) and the next slice index (p = 24). Even ifv8is published while they browse, their cursor keeps readingv7(retained in Redis for 2 hours), guaranteeing zero duplicates and zero skipped games:import base64 import json PAGE_SIZE = 24 def encode_cursor(version: int, position: int) -> str: # Pack snapshot version and slice offset into a URL-safe string raw_bytes = json.dumps({"v": version, "p": position}).encode("utf-8") return base64.urlsafe_b64encode(raw_bytes).decode("ascii") def list_page(versions: dict, cursor: str = None): """Return one page of game_ids and next_cursor from versioned Redis snapshots. versions maps {version_int: [ordered game_ids]}; highest key is newest.""" chosen_version = max(versions) position = 0 if cursor is not None: state = json.loads(base64.urlsafe_b64decode(cursor.encode("ascii"))) position = state["p"] # Stick to the user's starting snapshot if it has not expired yet if state["v"] in versions: chosen_version = state["v"] ordered_ids = versions[chosen_version] page_ids = ordered_ids[position : position + PAGE_SIZE] next_cursor = None if position + PAGE_SIZE < len(ordered_ids): next_cursor = encode_cursor(chosen_version, position + PAGE_SIZE) return page_ids, next_cursorAfter slicing the 24
game_ids, the server fetches their card metadata with a single Redis multi-get (MGET). If the catalog ever grew to millions of games where full lists no longer fit neatly as snapshots, we would switch to keyset pagination—using the last item's(sort_value, game_id)in an indexedWHERE (score, game_id) < (last_score, last_id)query so every page stays O(page_size).Caching without leaking user state.
- Category listings: Cached at the CDN for 60 seconds keyed by full URL (including
cursor), containing zero user-specific fields. - Game detail JSON: Cached in Redis and at the CDN for 5 minutes; purged via an outbox event whenever price or description changes.
- Images: Content-hashed URLs (
cover-9a4f1c.webp) cached at the CDN for 1 year (immutable). - Ownership buttons: Fetched separately by the browser via
GET /v1/me/ownership?game_ids=...against the read replica (Cache-Control: private, no-store). Even if replica lag makes a button briefly say "Buy" 500 ms after purchase, clicking it hits the primary database and safely returns409 already_owned.
- Category listings: Cached at the CDN for 60 seconds keyed by full URL (including
Deep dive 2: checkout state machine, retries, and reconciliation
Every order moves forward through well-defined states; terminal states never move backward:
CREATED ---> AWAITING_PAYMENT ---> PAID --------------------------> REFUNDED | | | | (timeout on | +---> FAILED (provider reports permanent failure) | provider call:| +---> EXPIRED (abandoned 1 hr; canceled at provider first) | retry reuses | | order_id key) +---> DUPLICATE_REFUND_PENDING ---> REFUNDED (rare race: late payment arrives when user already owns game or after order expired -> auto-refund queued immediately)Note that an ordinary card decline ("insufficient funds") leaves the order in
AWAITING_PAYMENTso the user can enter another card on the same checkout session without creating a new order.Happy path and atomic webhook transaction
- Browser calls
POST /v1/orderswithIdempotency-Keyandexpected_price. The server checks on the primary DB that the game isLISTED, the user has noACTIVEentitlement, andgames.price_amount == expected_price, then inserts anordersrow inCREATED. - Server calls the payment provider's create-payment API using
str(order_id)as the provider-side idempotency key, storesprovider_payment_id, updates the order toAWAITING_PAYMENT, and returnsclient_secret. - User completes payment in the provider's form. When the provider sends its signed
payment_succeededwebhook, our server verifies the cryptographic signature and runs one atomic PostgreSQL transaction:
BEGIN; -- 1. Deduplicate repeated webhook deliveries INSERT INTO payment_events (provider_event_id, order_id, type, received_at) VALUES ($event_id, $order_id, 'payment_succeeded', now()) ON CONFLICT DO NOTHING; -- (If 0 rows inserted, this exact webhook was already processed -> COMMIT and return 200) -- 2. Lock the order row and verify amount/currency match SELECT status, user_id, game_id, amount, currency FROM orders WHERE order_id = $order_id FOR UPDATE; -- If status IN ('PAID', 'REFUNDED', 'DUPLICATE_REFUND_PENDING'): already handled -> COMMIT. -- 3. Check whether the order was already expired/failed OR user already has an ACTIVE entitlement -- from a different order. If so, do NOT grant a second entitlement: -- set orders.status = 'DUPLICATE_REFUND_PENDING', insert outbox ('refund_payment'), COMMIT. -- 4. Normal success: mark order PAID and grant (or reactivate) the entitlement UPDATE orders SET status = 'PAID', paid_at = now() WHERE order_id = $order_id; INSERT INTO entitlements (user_id, game_id, order_id, status, granted_at) VALUES ($user_id, $game_id, $order_id, 'ACTIVE', now()) ON CONFLICT (user_id, game_id) DO UPDATE SET status = 'ACTIVE', order_id = EXCLUDED.order_id, granted_at = now(), revoked_at = NULL WHERE entitlements.status = 'REVOKED'; -- 5. If this buyer had a prior review from a refunded purchase, restore its verified badge -- and add its rating back to game_rating_stats in the same transaction. -- 6. Enqueue receipt email and cache purge via the transactional outbox INSERT INTO outbox (type, payload) VALUES ('order_paid', $payload); COMMIT;Handling timeouts, retries, and lost webhooks
- Browser times out after provider charged the card, then user clicks retry:
POST /v1/ordersmatches(user_id, idempotency_key)(or the partial unique index on open orders if they opened a fresh tab) and finds the existingAWAITING_PAYMENTorder. Before replying, the server queries the payment provider directly forprovider_payment_id: seeing"succeeded", it runs the exactPAIDtransaction above and immediately shows the user"PAID"! If the provider API is temporarily unreachable, the user sees"Payment processing"—never a second payment prompt. - Background reconciler: Every 5 minutes, a worker scans orders stuck in
CREATEDorAWAITING_PAYMENTfor > 10 minutes, queries the provider usingorder_id/provider_payment_id, and settles them. After 1 hour of inactivity, it cancels the payment intent at the provider first and only marks the orderEXPIREDonce the cancelation succeeds. A daily settlement job cross-checks the provider's payout CSV against ourPAIDandREFUNDEDorders.
- Browser calls
Deep dive 3: authorized downloads of 50 GB builds
Streaming multi-gigabyte builds requires keeping our servers on the control plane and the CDN on the data plane.
Issuing a short-lived edge token. When the desktop launcher starts or resumes a download, it calls
POST /v1/games/{id}/download-sessions:- The server queries
entitlementson the PostgreSQL primary (not a read replica, so a user clicking "Download" half a second after paying is never blocked by replication lag; ~0.35 req/s average and ~14 req/s at launch is trivial for the primary). - It verifies
entitlements.status == 'ACTIVE'(even ifgames.status == 'DELISTED') and looks up theREADYbuild for the requested platform. - It mints a 1-hour token authenticated with an HMAC (Hash-based Message Authentication Code—a cryptographic checksum computed with a secret key shared only between our backend and the CDN edge nodes, proving nobody tampered with the token fields):
payload = base64url(JSON({"uid": 42, "bid": 88, "exp": 1764529200, "kid": "k2"})) sig = base64url(HMAC_SHA256(edge_secret["k2"], payload)) token = payload + "." + sig Manifest request: https://dl.example-cdn.com/builds/88/manifest.json?token=<token> Chunk requests: https://dl.example-cdn.com/builds/88/chunks/00041-<sha256>?token=<token>How the CDN and launcher transfer 50 GB reliably
- Edge verification + shared caching: On every manifest or chunk request, the CDN edge node recomputes the HMAC in microseconds, checks
now < exp, and checks that/builds/88/in the URL matches"bid": 88inside the token. Crucially, the CDN strips?token=...from its cache key, so 50,000 buyers with 50,000 distinct tokens all hit the same cached bytes in RAM/SSD at the edge. - Chunked resume and integrity: Each build is split into 64 MiB chunks (~745 chunks for a 50 GB game), and
manifest.json(signed by our build pipeline) lists every chunk's SHA-256 hash. The desktop client downloads 4 to 8 chunks in parallel, verifies each hash before writing it to disk, and resumes after a laptop sleep or Wi-Fi drop by requesting only unfinished chunks. - Mid-download token refresh: Because 50 GB at 100 Mbps takes ~67 minutes, a 1-hour token will expire once near the end. When the CDN returns
403, the launcher callsPOST /download-sessionsagain: if the user still owns the game, it gets a fresh token seamlessly; if they refunded the game at minute 20, the refresh returns403 not_entitledand stops the rest of the download. - Launch protection: Ahead of major releases, we pre-warm chunks to edge PoPs and place an origin shield (a middle tier of cache servers in front of object storage) so thousands of regional edge misses collapse into a single read from object storage.
- The server queries
Deep dive 4: reviews, rating math, and refund consistency
Lock ordering so reviews and refunds never race. What if a user submits or edits a review at the exact millisecond their refund is being processed? Both paths touch
entitlementsandreviewsin the same lock order (entitlementsfirst,reviewssecond):Review write (PUT /reviews/me) Refund transaction ------------------------------------------------ ------------------------------------------------ 1. SELECT status FROM entitlements 1. SELECT ... FROM orders FOR UPDATE; WHERE (user_id, game_id) FOR SHARE; 2. UPDATE entitlements SET status = 'REVOKED' -> blocks if refund is updating entitlement! WHERE (user_id, game_id) AND order_id = $oid; -> if not ACTIVE, abort with 403. -> waits if review holds FOR SHARE! 2. Lock/upsert reviews row (verified = true), 3. UPDATE reviews SET verified_purchase = false check If-Match version, save revision. WHERE (game_id, user_id); 3. Update game_rating_stats by delta; COMMIT. 4. Update game_rating_stats by delta; COMMIT.Because
FOR SHAREandUPDATEconflict on theentitlementsrow, PostgreSQL serializes them cleanly: either the refund commits first (and the review write fails with403), or the review write commits first (and the refund immediately clearsverified_purchase = falseand subtracts its stars). Also noteAND order_id = $oidin step 2 of the refund: when an accidental duplicate payment is auto-refunded, it does not revoke the entitlement granted by the user's valid first order!One uniform delta rule for
game_rating_stats. Instead of scanning thousands of reviews on every page view,game_rating_statsstoresverified_countandverified_sum(pluscount_1 .. count_5). Every transition—create, star edit, delete, moderator hide, refund, or re-purchase—updates the row bynew_contribution - old_contribution:def contribution(review: dict | None) -> tuple[int, int]: """Return (count_added, stars_added) that a single review contributes to its game.""" if review is None: return 0, 0 if review["status"] != "PUBLISHED" or not review["verified_purchase"]: return 0, 0 return 1, review["rating"] def stats_delta(old_review: dict | None, new_review: dict | None) -> tuple[int, int]: """Compute (delta_count, delta_sum) to add to game_rating_stats on any state change.""" old_count, old_sum = contribution(old_review) new_count, new_sum = contribution(new_review) return new_count - old_count, new_sum - old_sumAbuse prevention and display consistency
- Validation & moderation: Ratings are integers
1..5; bodies are plain text up to 5,000 characters (HTML-escaped on render), capped at 10 writes/hour per user (429). Requiring an active purchase stops cheap bot spam; suspicious links or slurs enterPENDING_MODERATION, and 3 reports from distinct owners temporarily hide a review for moderator triage. - Read-your-writes consistency: Public review pages use keyset pagination on
(created_at, review_id)or(helpful_count, review_id), cached at the CDN for 60 seconds and purged via outbox on writes. Meanwhile, the game detail page fetches the logged-in user's own review via the uncachedGET /v1/games/{id}/reviews/me—giving read-your-writes consistency (the guarantee that a user immediately sees their own just-submitted change) even if other visitors see up to 60 seconds of cache lag.
- Validation & moderation: Ratings are integers
Scaling, failure modes, and key trade-offs
Scaling path. Three to six stateless app servers behind a load balancer easily handle ~2,600 peak req/s once CDNs absorb static and public traffic. PostgreSQL runs one primary, one synchronous standby (zero committed payment loss on failover), and one read replica (serving ownership overlays and hourly snapshot builds). If write volume ever grew 100x,
ordersandentitlementswould shard byuser_idwhilereviewspartitioned bygame_id, replacing their shared single-node lock with an outbox event plus a post-write ownership re-check.Failure handling
Component failure User impact Recovery and protection Payment provider slow or down Checkout temporarily unavailable A circuit breaker (an automatic switch that fails fast once error rates spike instead of tying up server threads waiting on timeouts) returns "Checkout temporarily unavailable"; browsing, library, and downloads continue normally; reconciler resolves in-flight orders. Webhook lost or delayed Order shows "Processing" briefly Status page polls GET /orders/{id}; provider retries webhooks with backoff; reconciler queries provider after 10 minutes.PostgreSQL primary crashes Writes pause for ~10–30 s Automatic failover to synchronous standby preserves every committed payment and entitlement; CDN keeps serving catalog pages. Redis cache lost Higher DB read load Rebuild 100 MB of cards and 120 snapshots from read replica in seconds; fall back to indexed DB queries meanwhile. Outbox worker delayed Receipt emails & cache purges lag Authoritative DB state is already committed; CDN 60 s / 5 min TTLs bound stale pages; alert on outbox queue age. Summary of core trade-offs
- Single relational DB vs. microservices per domain: Atomic transactions across orders, entitlements, and reviews with zero saga complexity, traded against single-primary write throughput that is still 100x above our needs.
- Server-verified webhooks + reconciler vs. trusting client redirects: Eliminates unpaid downloads and lost purchases, at the cost of building a
"Processing"UI state and background reconciliation. - 1-hour HMAC edge tokens vs. per-chunk backend checks: Offloads 42 Gbps–2.2 Tbps completely to the CDN, accepting up to a 1-hour revocation delay on an already-running download after a refund.
- Versioned Redis snapshots vs. live SQL
OFFSETqueries: Stable, duplicate-free paging and sub-millisecond reads, trading up to 1 hour of staleness on the "popular" ranking. - Owners-only reviews + cached lists + uncached
/reviews/me: Strong spam resistance, cheap public reads, and instant feedback for the reviewer, while other visitors tolerate up to 60 seconds of display lag.
Intuition & how it works
Think of this game store like a busy movie multiplex with three separate stations: a lobby display board showing movie posters and ratings, a box office ledger recording confirmed payments, and an auditorium ticket scanner checking a time-stamped wristband at the door. Anyone can look at the lobby board (fast, shared, and harmless if a rating updates a minute late), but waving a photo of a "Thank you for paying!" screen at the auditorium door gets you nowhere—the door scanner only trusts a wristband issued after the box office ledger recorded real money from the bank. That single principle—pages only display hints, while backend records hold authority—governs every flow in this design.
A naive implementation tangles display and authority together and quickly breaks in three ways. First, if the store grants a game when the user's browser redirects to /checkout/success, a clever user can visit that URL without paying, while a real buyer whose Wi-Fi drops right after their card is charged never gets their game—and gets charged twice when they click "Buy" again. Second, if game pages include "owned": true inside CDN-cached HTML or JSON, either User A sees User B's ownership state or caching must be turned off altogether. Third, streaming 50 GB game installers through application servers saturates backend network links with just a few dozen concurrent downloads.
Walk through a tiny four-event trace for Alice buying StarQuest ($19.99) to see how all pieces cooperate:
- Browse (cached display + private overlay): Alice loads the RPG category page (
cursor = v7, pos = 0) from a CDN (Content Delivery Network—a global network of edge cache servers close to users) and simultaneously callsGET /v1/me/ownership?game_ids=12, which sees no entitlement (a durable database row granting download and review rights) and renders a"Buy $19.99"button. - Checkout + timeout retry: Alice clicks Buy, sending
POST /v1/orderswithIdempotency-Key: k-91(a client-generated unique token so retries reuse the same order instead of creating duplicates). Her card is charged by the payment provider, but her browser tab times out before hearing back. When she clicks retry withk-91, our server finds order901, queries the provider directly, sees"succeeded", and in one database transaction marks order901asPAIDand inserts anACTIVEentitlement for(Alice, game 12). - Authorized download: Alice clicks Download in the desktop launcher (
POST /v1/games/12/download-sessions). Our server reads herACTIVEentitlement from the primary database and returns a 1-hour HMAC token (Hash-based Message Authentication Code—a tamper-proof signature created with a secret shared between our backend and the CDN). The CDN verifies that signature at the edge and serves 64 MiB chunks directly from cache without calling our backend again. - Verified review: Alice submits a 5-star review via
PUT /v1/games/12/reviews/me. The server locks herACTIVEentitlement row, stores her review withverified_purchase = true, incrementsgame_rating_statsby(+1 count, +5 stars)in the same transaction, and shows her new review immediately via the uncached/reviews/meendpoint while purging the 60-second CDN review cache in the background.
Key trade-offs
- One transactional PostgreSQL database vs. separate databases per microservice. Keeping orders, payment events, entitlements, and reviews in one relational database lets
"order PAID + entitlement ACTIVE + rating stats updated + outbox job queued"commit atomically in a single ACID transaction. Splitting them across separate service databases would require multi-step sagas and compensating rollbacks, while our actual write load (< 15 orders/s even at a big launch and ~1,000 reviews/day) is tiny for one primary with a synchronous standby. - Asynchronous server-verified payment confirmation vs. trusting the synchronous client callback. Waiting for a signed webhook (an authenticated server-to-server HTTP notification from the payment provider) or our own server-to-provider status query means building a
"Payment processing"UI state and a 5-minute reconciliation job, but it makes spoofed client callbacks, dropped browser connections, and double charges impossible. - 1-hour edge-verified HMAC download tokens vs. per-chunk backend checks. Having the CDN check a 1-hour signed token at the edge lets it serve 42 Gbps daily (and 2.2 Tbps during a launch) with zero per-chunk traffic to our servers and a shared chunk cache across all buyers. The trade-off is revocation latency: if a buyer refunds mid-download, their current token continues working for up to 1 hour until it expires and the launcher is refused a refresh.
- Versioned Redis listing snapshots vs. live SQL queries. Precomputing ordered lists of
game_ids per(category, sort)makes paging 100% stable (no skipped or duplicated games when rankings shift) and reduces reads to an in-memory slice, at the cost of"popular"rankings lagging by up to 1 hour—well suited to a 20,000-game catalog, whereas a multi-million-item catalog would switch to indexed keyset pagination (filtering withWHERE (score, id) < (last_score, last_id)instead of counting row offsets). - 60-second cached review pages + uncached author read vs. uncached live reads. Caching page 1 of reviews at the CDN (plus purging via a transactional outbox—a table written inside the main DB transaction so background workers reliably run side effects) absorbs 99% of read load. Fetching
GET /reviews/meuncached gives read-your-writes consistency (guaranteeing the author sees their own edit immediately), while other shoppers may see up to 60 seconds of delay if a purge lags. - Owners-only reviews vs. open reviews with a badge. Requiring an
ACTIVEentitlement makes review-bombing expensive because every review requires buying the game, at the cost of excluding players who played the game on another platform or tried a free weekend elsewhere.
Common mistakes
- Granting downloads on the browser's
"success"redirect rather than verifying payment server-to-server via a signed webhook or provider API query. - Creating a brand-new order and payment intent on retry. Omitting an
Idempotency-KeyonPOST /v1/orders(or omittingorder_idas the provider's idempotency key, or missing a partial unique index on open(user_id, game_id)orders) turns network timeouts and second browser tabs into double charges. - Treating a payment gateway timeout as
"FAILED". A timeout means the outcome is unknown; the order must remain pending (CREATEDorAWAITING_PAYMENT) until a webhook or background reconciler confirms whether money moved. - Revoking by
(user_id, game_id)alone when auto-refunding a duplicate charge. If a rare race produces a second payment for a game the user already owns, refunding that duplicate order must checkentitlements.order_id == refunded_order_idso it does not revoke the user's valid original entitlement. - Forgetting the re-purchase path after a refund. When a refunded buyer buys the game again (
REVOKED -> ACTIVE), thePAIDtransaction must also restoreverified_purchase = trueon their existing review and add its stars back intogame_rating_stats. - Caching per-user
"Owned"buttons or"Verified"inputs. Putting user state into CDN-cached game JSON leaks data across users, and acceptingverified_purchasein the client'sPUTbody lets anyone forge the badge. - Streaming gigabytes through app servers or signing the token into the CDN cache key. App servers cannot carry 42 Gbps of binary egress, and failing to strip
?token=...from the CDN cache key forces the CDN to cache a separate 50 GB copy per buyer. - Using
OFFSETpagination on popularity lists orCOUNT(*)/AVG(rating)scans per page view instead of cursor snapshots and incrementalgame_rating_statsdeltas.
Follow-up questions
- Walk through what happens when a buyer submits checkout a second time because the app timed out right after the payment processor captured the funds. When the browser retries
POST /v1/orderswith the sameIdempotency-Key(or even if the user opens a fresh tab with a new key, hitting our partial unique index on open(user_id, game_id)orders), the server locates the existingAWAITING_PAYMENTorder rather than creating a new charge. Before returning, the server queries the payment provider directly usingprovider_payment_id(ororder_id), sees status"succeeded", executes the atomicPAID + ACTIVE entitlementtransaction immediately, and returns"PAID"so the user lands straight in their library. If the provider API itself is temporarily unreachable during that retry, the UI displays"Payment processing"and either the delayed webhook or the 5-minute reconciler job settles the order shortly after. - Once an order is refunded under your store rules, what happens to new and already-running downloads? For a
PAIDorder within the 14-day window, our server first commits one database transaction settingorders.status = 'REFUNDED', revoking the entitlement (status = 'REVOKED'whereorder_idmatches), settingreviews.verified_purchase = false, updatinggame_rating_statsbystats_delta, and writing an outbox job that instructs the payment provider to return the money (revoking access before refunding money ensures a crash never leaves the user with both). Immediately after that commit,POST /v1/games/{id}/download-sessionsreturns403 not_entitled, blocking all new downloads and mid-download token refreshes. Any 1-hour HMAC edge token minted right before the refund continues working for at most the remainder of that hour, and already-installed local files remain playable unless we add an online license check at game launch. - How does your backend guarantee that an outdated cached page can neither unlock a download nor fabricate a verified-buyer badge on a review? Cached pages only control what buttons or badges are drawn; every action re-verifies authority on the server. Clicking a stale
"Download"button callsPOST /download-sessions, which readsentitlementsdirectly from the PostgreSQL primary database and returns403if the game was refunded. Likewise,verified_purchaseis never accepted from client input:PUT /reviews/metakes aFOR SHARElock on the primary'sACTIVEentitlement row to setverified_purchase = true, and the refund transaction clearsverified_purchase = falsewhile enqueueing an immediate CDN purge (bounded at worst by the 60-second review cache TTL, which is purely a brief display lag and grants zero privileges).
Follow-up questions
- Walk through what happens when a buyer submits checkout a second time because the app timed out right after the payment processor captured the funds.
- Once an order is refunded under your store rules, what happens to new and already-running downloads?
- How does your backend guarantee that an outdated cached page can neither unlock a download nor fabricate a verified-buyer badge on a review?
Similar questions
- High-Scale Game Marketplace Backend Architecture
- 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