Skip to content
All work
System Design · Full-StackLive · 2026

Scale Cart

A working online store built to learn system design hands-on. It runs on three servers behind a load balancer, serves busy pages from a Redis cache, and never sells the same last item twice.

  • Node.js
  • Express
  • MongoDB
  • Redis
  • Nginx
  • React

Scope note — Scale Cart is a learning project for system design. The store is live and fully working, but it is a demo shop, not a real business, so no real orders are shipped.

Overview

Scale Cart is an online store for clothing, shoes, watches and sunglasses. The shop itself is simple on purpose. The interesting part is underneath: I used it to turn each system design concept I studied into real, running code, then tested it under load. Every concept on this page solves a problem a real store would hit as its traffic grows.

Problem

Most store tutorials work for one user on one laptop. They break in predictable ways when real traffic arrives: the database receives the same query thousands of times, two buyers grab the last item at once, a double click creates two orders, and one crashed server takes the whole site down.

I wanted to meet each of those problems in a real codebase, not only read about them.

Why it matters

For a store, these failures cost real money. Overselling means refunds and unhappy customers. Duplicate orders mean double charges. A slow product page means people leave before they buy.

Each fix in this project maps to one of those risks, so every design choice can be explained in business terms, not only technical ones.

Solution

Three copies of the API run side by side behind Nginx. Nginx sends each request to the least busy copy, so one crash or one deploy never takes the store offline.

Product pages and search results are cached in Redis. When a popular cache entry expires, only one request rebuilds it. The others wait for that answer instead of all hitting the database at once.

Placing an order is one database transaction: check stock, take stock, save the order. Either all of it happens or none of it does. Each order also carries an idempotency key, so a double click or a retry returns the same order instead of creating a second one.

The sign-up form checks whether an email is taken using a Bloom filter in memory first, so most checks never reach the database.

A support chatbot answers questions about orders and products. It reads data only through tools on an MCP server, and it can only ever see the logged-in customer's own orders.

System design concepts

Every concept below is running in the live store. Each one says what it is in plain words and how Scale Cart uses it.

Scaling and availability

Horizontal scaling
Run more copies of the server instead of buying a bigger one. Scale Cart runs three API processes, on ports 4001, 4002 and 4003.
Load balancing (least connections)
Nginx sends each request to the copy with the fewest open requests. This works better than taking turns, because a login costs far more than a cached page.
Reverse proxy
Nginx is the only public entry point. It serves the React app, forwards API calls, compresses responses and keeps the internal servers hidden.
Health checks and failover
If a process fails twice in 10 seconds, Nginx skips it for 10 seconds and retries the request on another one.
Zero-downtime rolling deploy
The deploy script restarts one process at a time and waits for its health check to pass before moving on, so visitors never see an error.
Graceful shutdown
When a server is stopped, it finishes the requests it already has, then closes its database connections. It gives up after 10 seconds.

Caching and performance

Cache-aside with Redis
Look in Redis first. On a miss, read from MongoDB, store the result with an expiry time (TTL), then return it.
Cache stampede protection
When a busy cache entry expires, the first request rebuilds it and the others wait for that same result. In a load test this turned 291 identical database queries into 1.
Versioned cache keys
Every product cache key includes a catalog version number. Changing a product bumps the version with one Redis command, and old entries are simply never read again.
Fail open
If Redis is down or slower than 400 ms, the store reads from MongoDB instead. The cache can make the site faster, but it can never take the site down.
Connection pooling
Each server keeps up to 10 database connections open and reuses them, instead of opening a new connection for every request.
Browser caching
Built JavaScript and CSS files have a content hash in their name, so browsers keep them for a year. The main HTML page is always re-checked, so a new deploy shows up at once.

Database design

Compound indexes
Every product sort (best selling, newest, price) has a matching index, so the database reads results in order instead of sorting the whole collection.
Cursor (keyset) pagination
Each page starts right after the last item of the previous page. Page 1 and page 100 cost the same, unlike OFFSET, which reads and throws away every earlier row.
Covered queries
The "is this email taken?" check is answered from the email index alone. The database never loads the full user record.
No N+1 queries
An order with ten products loads all ten in one query and updates all their stock in one bulk write, instead of one query per product.

Correctness and consistency

ACID transactions
Stock, sales count and the order are saved together in one transaction. If any step fails, everything is undone, so stock never disappears without an order.
Preventing overselling
Stock is only taken if enough is still left at that moment. When two buyers race for the last item, one succeeds and the other sees a clear "sold out" message.
Idempotency keys
Each checkout sends a unique key, protected by a unique index. A double click or a network retry returns the first order instead of creating a second one.
Server-side pricing
Prices in the browser's cart are only a hint. Totals and shipping are always calculated on the server from the prices in the database.

Probabilistic data structures

Bloom filter
A small bit array that answers "definitely not taken" or "maybe taken". For one million emails at a 1% error rate it needs about 1.2 MB. A "no" skips the database; a "maybe" is confirmed with one indexed lookup.
Pub/sub sync between servers
When someone signs up on one server, it announces the new email on a Redis channel, so the other two servers add it to their filters too.

Security and protection

Shared rate limiting
Limits such as 10 failed logins per 15 minutes are counted in Redis, so all three servers share one count. With separate counters per server, the real limit would silently become 30.
Password hashing with scrypt
Passwords are stored as salted, deliberately slow hashes, and compared in constant time so response timing reveals nothing.
Access and refresh tokens
Access tokens last 15 minutes. Refresh tokens are replaced on every use and can be cancelled on all devices at once.
Request limits and timeouts
Request bodies are capped in both Node and Nginx, and clients that stay silent are disconnected after 30 seconds.

Search

Full-text search
Search runs on an Atlas Search (Lucene) index. It understands word forms ("jackets" finds "jacket"), synonyms ("trainers" finds "sneakers"), typos, and suggests results while you type.
Relevance ranking
Matches in the product name rank above matches in other details, and exact words rank above typo matches. Ties are broken by best sellers.

Architecture

  1. Client

    React storefront

    Vite build · served by Nginx

    Browser cache

    Hashed assets · 1 year

  2. Edge

    Nginx

    Reverse proxy · HTTPS · gzip

    Load balancer

    Least connections · failover

  3. API

    API :4001

    Express · Bloom filter

    API :4002

    Express · Bloom filter

    API :4003

    Express · Bloom filter

  4. Shared state

    Redis cache

    Cache-aside · versioned keys

    Rate-limit counters

    Shared by all servers

    Pub/sub

    Sign-up sync

  5. Data

    MongoDB

    Transactions · compound indexes

    Atlas Search

    Lucene full-text index

  6. Support AI

    MCP server

    Order and product tools

    OpenAI model

    Answers using tool calls

One public entry point, three identical API processes, and shared state in Redis and MongoDB. Any single API process can fail without taking the store down.

Support chatbot

Customers can ask the chatbot things like "where is my order?" or "show me black boots under $200". The model never touches the database. It can only ask to call one of four tools on a separate MCP (Model Context Protocol) server: list my orders, get one order, search products, and get one product.

The customer's identity comes from their verified login, never from the chat text. The server fills in the user ID itself, and the model cannot see or change it. So "show me another customer's orders" cannot work, however it is phrased.

Each answer has hard limits: at most 5 rounds of tool calls and a 25-second deadline. A confused model cannot loop forever or run up cost.

Implementation

The backend is split by feature: auth, products, search, orders and chat. Each feature has its own routes, service and model, so a change stays in one place.

Startup runs in a fixed order: connect to MongoDB and Redis, create indexes, load the Bloom filters, and only then accept traffic. Starting with an empty filter would wrongly report taken emails as free.

Each API process runs as a systemd service. If it crashes, systemd restarts it within 2 seconds, and each process is capped at 400 MB of memory so one leak cannot take down the machine.

Unit tests cover the Bloom filter, the cache, password hashing and the chatbot. Integration scripts run the full sign-up and order flows against a real database.

Engineering challenges

  • The last item in stock

    Two buyers can check stock at the same moment and both see one left. A guarded update inside a transaction means only one of them wins. The other's whole order is undone, and they see a clear message instead of a broken checkout.

  • A cache that caused a traffic spike

    Caching made pages fast until a popular entry expired. Then hundreds of requests missed at the same moment and all ran the same database query. Letting one request load the data while the others wait for it fixed this: one query, and everyone shares the answer.

  • Three servers, one set of rules

    Moving from one server to three quietly broke anything kept in memory. Rate limits became three times looser, and Bloom filters missed sign-ups made on other servers. Both now coordinate through Redis.

Key decisions

Least connections instead of round-robin
Requests differ a lot in cost. A login spends about 100 ms hashing a password, while a cached page takes a few milliseconds. Sending work to the least busy server keeps response times even.
Cursor pagination instead of OFFSET
OFFSET gets slower on every page, because the database reads and discards all earlier rows. Cursor pagination costs the same on page 1 and page 100.
Bump a version instead of deleting cache keys
Finding and deleting thousands of keys is slow and easy to get wrong. One increment makes them all stale at once, and the old entries expire on their own.
Redis is a speed-up, not a requirement
If Redis fails, the store gets slower but stays up. A cache that can take the site down adds risk instead of removing it.

Results

Duplicate DB queries on cache expiry (load test)
291 → 1
API processes behind the load balancer
3
Bloom filter size for 1M emails (calculated)
~1.2 MB

Technology

Frontend

  • React 19
  • React Router
  • Vite
  • TypeScript

API

  • Node.js
  • Express 5
  • Zod validation
  • Helmet

Data

  • MongoDB
  • Mongoose
  • Multi-document transactions
  • Atlas Search

Shared state

  • Redis cache
  • Redis rate-limit counters
  • Redis pub/sub

Infrastructure

  • Nginx
  • systemd
  • Let's Encrypt
  • Ubuntu server

AI support

  • OpenAI API
  • Model Context Protocol (MCP)

Contact

Have an AI product or workflow worth building?

Send me the problem — not the spec. If it’s a fit I’ll tell you how I’d approach it; if it isn’t, I’ll say so.

Faisalabad, Pakistan · PKT (UTC+5) · Working remotely