Secure Storefront Backend: Accounts, Carts and Safe Checkout
System DesignModel answerLast updated
Design a storefront backend where users sign up, log in, browse products, manage a personal cart and place orders safely, while APIs block access to other users' data.
Problem
You are designing the backend for an online store in which identity and access control are the central concerns. Walk through the following capabilities and the design decisions behind them:
- Account creation and login
- How a logged-in client proves who it is on later requests (server sessions or tokens)
- Browsing the product catalog
- A cart that belongs to one user
- Turning a cart into an order
You must also explain how each API ensures that one customer can never view or modify another customer's carts or orders.
Assumptions
- Passwords must never be stored in plaintext.
- The owner of a cart or order is taken from the authenticated identity on the request, never from a user ID the client sends in the body or URL as a source of truth.
- Placing an order must be safe to retry, for example when the client times out and sends the request again.
- Payment is out of scope. Checkout only needs to produce an order in a pending state.
Questions you may want to raise
- Should the client use server-side sessions, or short-lived access tokens with rotating refresh tokens?
- Do anonymous (guest) carts need to exist, and if so how are they merged into the account cart at login?
- Which operations are limited to administrators or other elevated roles?
What to deliver
Describe the data model, the main API endpoints, the authentication and session lifecycle, the authorization approach, the checkout flow with its retry protection, the main attack surfaces and their mitigations, and how you would test and monitor the system.
Hints
Hint 1
Start with who the caller is (authentication) and then what they may touch (authorization). Ask which identity the server trusts: the one it derived from the credential, not one in the request payload.
Hint 2
For retries, think about a client-generated unique key stored with a uniqueness constraint, so a repeated request returns the original result rather than creating a second order.
Hint 3
An order should not point at live product rows for its prices. Consider copying the item names, prices and quantities at checkout time, inside a single database transaction with the cart clearing.
Hint 4
List the attacks by layer: credential stuffing and enumeration at login, session fixation and theft, CSRF for cookie-based auth, and IDOR (accessing another user's object by guessing its ID) on cart and order endpoints.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and choose
I would assume a browser-based storefront plus possibly a mobile app. Decision: server-side sessions in an HttpOnly cookie for the web client (simple revocation, no token in JavaScript reach). If mobile or third-party clients matter, add short-lived access tokens (about 10 to 15 minutes) with rotating refresh tokens. Guest carts: yes, keyed by an opaque anonymous cart ID, merged at login. Roles: customer and admin (catalog management, order support).
2. Data model
users(id, email_normalized UNIQUE, password_hash, status, created_at)sessions(id_hash, user_id, created_at, last_seen, expires_at, ip/ua metadata, revoked_at)recovery_tokens(token_hash, user_id, purpose, expires_at, used_at)products(id, name, price_cents, currency, stock, active)carts(id, user_id UNIQUE)andcart_items(cart_id, product_id, qty, PRIMARY KEY(cart_id, product_id))orders(id, user_id, status, total_cents, idempotency_key, created_at, UNIQUE(user_id, idempotency_key))order_items(order_id, product_id, name_snapshot, unit_price_cents, qty)roles(user_id, role)
Store only hashes of session IDs and recovery tokens, so a database leak does not yield usable credentials.
3. Signup and login
- Password storage: a slow, salted, memory-hard hash such as Argon2id (or bcrypt/scrypt), tuned to roughly 100 to 300 ms per hash. Optionally add a server-side pepper held in a secrets manager.
- Signup: normalize the email, enforce a length-based password policy (minimum 8 to 12 characters, check against breached-password lists), and verify email ownership via a one-time link.
- Login: compare hashes in constant time. Return the same generic message ("invalid email or password") for unknown user and wrong password to avoid account enumeration, and keep response times similar.
- Throttling: rate-limit per account and per IP, with progressive delays or CAPTCHA, to blunt credential stuffing. Avoid hard lockouts that let attackers lock out victims.
- Session creation: generate a 128+ bit random ID, issue a new one at login (prevents session fixation), set
HttpOnly; Secure; SameSite=Lax(or Strict), with idle and absolute timeouts. - Logout and revocation: delete the session row. "Log out everywhere" and password change revoke all of a user's sessions.
- Recovery: single-use, short-lived (15 to 30 minutes), random tokens, stored hashed. Respond identically whether or not the email exists. Reset invalidates existing sessions.
4. Authorization
Authentication middleware resolves the cookie into a principal (user_id, roles). Handlers never read user_id from the request.
GET /cartandPUT /cart/items/{productId}operate on the cart looked up by principal's user_id. There is no cart ID in the path, which removes a whole class of IDOR bugs.GET /orders/{id}queriesWHERE id = ? AND user_id = principal.user_id. If no row, return 404 (not 403) so existence is not leaked.- Admin endpoints (
POST /products,PATCH /products/{id}) require theadminrole, checked server-side on every call. Consider re-authentication for sensitive admin actions. - Use unguessable IDs (UUIDs) as defense in depth, but never as the control itself.
- Product browsing (
GET /products, search, pagination) is public and cacheable via CDN.
5. Checkout with retry safety
POST /orders with header Idempotency-Key: <client UUID>.
In one database transaction:
- Look up
(user_id, idempotency_key). If it exists, return the stored order with the same response. - Load the cart items, lock the product rows (or use conditional stock updates
UPDATE ... SET stock = stock - qty WHERE stock >= qty). - Insert the order with status
PENDING, and insertorder_itemsas immutable snapshots of name and price. - Clear the cart.
- Commit.
The UNIQUE(user_id, idempotency_key) constraint is the real guard: two concurrent identical requests cannot both insert, and the loser re-reads and returns the winner's order. Keys are retained for something like 24 hours or the lifetime of the order. Same key with a different payload returns 409/422.
Pricing is computed on the server from the product table; client-sent prices are ignored.
6. Attack surface and mitigations
| Threat | Mitigation |
|---|---|
| CSRF (cookie auth) | SameSite cookies plus a CSRF token or custom-header check on state-changing requests; verify Origin |
| XSS stealing sessions | HttpOnly cookies, CSP, output encoding |
| Session theft/fixation | Rotate on login and privilege change, TLS only, HSTS |
| IDOR / horizontal escalation | Ownership derived from principal, scoped queries |
| Vertical escalation | Central role checks, deny by default |
| Enumeration | Generic errors, uniform timing, 404 for foreign resources |
| Credential stuffing | Rate limits, breached-password checks, optional MFA |
| Price tampering | Server-side pricing |
7. Guest cart merge
Anonymous cart stored under a random cookie. At login, merge into the user's cart (sum quantities capped by stock, or prefer the larger), then delete the guest cart, inside a transaction.
8. Testing and operations
- Horizontal-access tests: log in as user A, create cart and order, then as user B attempt every read and write on A's IDs and assert 404 or no effect. Automate this over every route.
- Vertical tests: customer calling admin routes gets 403.
- Retry tests: fire the same order request many times concurrently and assert exactly one order.
- Session tests: old session ID rejected after login, logout, and password change.
- Log auth events (login success/failure, reset, role changes) with request IDs, never passwords or tokens. Alert on spikes of failed logins.
9. Trade-offs and common mistakes
- Sessions give easy revocation but need shared storage (Redis or DB); JWTs scale statelessly but are hard to revoke, so keep them short-lived.
- Mistakes: trusting a
userIdin the body, returning 403 vs 404 inconsistently, using fast hashes like SHA-256 for passwords, computing totals from client data, linking orders to live product prices, forgetting to revoke sessions on password reset, and relying on idempotency checks without a database uniqueness constraint.