System Design Part 0 Introduction

How to Think About System Design: Requirements, Estimates, Trade-offs, and HLD/LLD

Bill.Lin 17 min read

System Design series Part 0 (introduction) | Next: The Journey of an HTTP Request

Series map

This series goes from “one machine” all the way to “distributed systems”. Every post follows the same structure:

  1. Scenario and problem: start from a concrete situation, not from a term; the diagram at the top can be played step by step
  2. The simplest approach and its limits: find the simplest approach that works, then see where it breaks down
  3. Core mechanism: explain how it works with diagrams
  4. Comparing options: what each option gives up and what it gets in return
  5. In Java: implementations with Spring Boot, MySQL, and Redis
  6. Pitfalls and gotchas: security issues get their own “Security” list
  7. When to use it, and when not to: including “under what conditions to re-evaluate”
  8. References
Part Theme Posts
0 Introduction How to think about system design This post
1 Measurement basics Measure and estimate first, so you know where the bottleneck is 1-1 The Journey of an HTTP Request, 1-2 Latency, Throughput, and p99, 1-3 Napkin Math for Capacity Estimates
2 From one machine to many The first steps when one machine is not enough 2-1 Vertical Scaling, Horizontal Scaling, and Stateless Services, 2-2 Load Balancing in Depth, 2-3 Caching in Depth, 2-4 CDNs and HTTP Caching
3 Storage basics How data is stored and found 3-1 SQL vs NoSQL, 3-2 Indexes and B+Trees, 3-3 B-Tree vs LSM-Tree, 3-4 Transactions and Isolation Levels, 3-5 File and Object Storage, 3-6 Bloom Filters and HyperLogLog, 3-7 Full-Text Search and Inverted Indexes, 3-8 Geohash and Geospatial Indexes
4 Distributed data When one database can no longer hold the data or the load 4-1 Replication and Replication Lag, 4-2 Sharding, 4-3 Consistent Hashing, 4-4 Distributed IDs, 4-5 CAP and PACELC, 4-6 Consensus and Raft, 4-7 Distributed Locks and Fencing Tokens
5 Service communication How services talk to each other 5-1 REST, gRPC, and GraphQL, 5-2 Message Queues, 5-3 Pub/Sub and Delivery Semantics, 5-4 Idempotency and Idempotency Keys, 5-5 Real-Time Updates
6 Reliability What to do when things break 6-1 Redundancy, Failover, and DR, 6-2 Timeouts, Retries, Backoff, and Jitter, 6-3 Circuit Breakers and Bulkheads, 6-4 Rate Limiting, 6-5 Observability
7 Architecture evolution The system grows along with the team 7-1 Monolith vs Microservices, 7-2 Service Discovery, 7-3 Sagas and the Outbox Pattern, 7-4 Batch and Stream Processing
8 Security Security from a system design angle 8-1 Authentication: Sessions, Tokens, and OAuth 2.0/OIDC, 8-2 Authorization Models and the OWASP API Top 10, 8-3 After BOLA Gets Past the BFF: Identity Propagation Between Microservices, 8-4 Encryption in Transit and at Rest, and Secrets Management, 8-5 Abuse Prevention
9 Design problems Putting the building blocks together 9-1 URL Shortener, 9-2 News Feed, 9-3 Chat System, 9-4 Flash Sale Ticketing, 9-5 Notification System, 9-6 Leaderboard, 9-7 Distributed Scheduler
10 Delivery Shipping changes safely 10-1 Testing at Scale, 10-2 CI/CD and Deployment Strategies

How to read this series:

  • Prerequisites: you have built a web API with Spring Boot and used MySQL; you do not need to know Redis or message queues yet
  • Beginner path: Part 0 → Part 1 → Part 2 → the first four posts of Part 3 (up to 3-4 Transactions and Isolation Levels) → 6-2 Timeouts and Retries and 6-3 Circuit Breakers → any problem from Part 9, of which 9-1 URL Shortener is the easiest start. Specialized topics such as Bloom filters, full-text search, and Geohash can wait until you need them
  • Length: 51 posts, about 11 to 28 minutes each. The threat modeling in the second half of this post can also wait until you have read Part 8
  • Versions: code examples target Spring Boot 4.1; the Redis examples in 2-1 and 2-3 are written for Boot 3.x, with the Boot 4 differences noted in the text
  • Related: the Agent series uses an on-call incident assistant to show how an LLM agent copes with the timeouts, retries, and observability covered here; the JPA and connection pool implementations are in the Database category

Scenario and problem

Your company is holding its annual online talk, with 3,000 seats. Marketing expects 50,000 people to be waiting online on the day sign-ups open, and about 24,000 sign-up requests to pour in during the first 30 seconds. Your manager drops one line: “Have a design for me by next week.”

Many people’s first move is to start drawing: Redis in front to reserve seats, Kafka in the middle to write to the database asynchronously, and a separate sign-up microservice behind it. The diagram looks great, but at this point you still do not know any of the following:

  • How high is the peak, really? Can one MySQL server take it?
  • When “never oversell” and “respond fast” conflict, which one wins?
  • When the extra Redis and Kafka fail, who reconciles the data?
Sign-ups for the annual talk1 / 4
Sign-ups for the annual talk50k in lineSign-up APIMySQLRedisKafka50k in lineMySQL50,000 waiting3,000 seats50k in lineSign-up APIMySQL24,000 in 30 ssign upSign-up APIRedisKafkaMySQLreserve a seatasync writewriteMySQLSign-up APIKafkaCan one server cope?No oversell, or fast?Who reconciles on failure?
  1. 3,000 seatsYour company is holding its annual online talk, with 3,000 seats. Marketing expects 50,000 people to be waiting online on the day sign-ups open.
  2. The first 30 secondsAbout 24,000 sign-up requests arrive in the first 30 seconds after opening, 800 a second on average. Your manager drops one line: "Have a design for me by next week."
  3. Draw a nice diagram firstMany people start by drawing: Redis in front to reserve seats, Kafka in the middle to write to the database asynchronously, and a separate sign-up microservice behind it.
  4. What you do not know yetBut you still do not know how high the peak really is, or whether one MySQL server can take it. When never overselling and responding fast conflict, which wins? When the extra Redis and Kafka fail, who reconciles the data?

The core of system design is not memorizing architecture diagrams. It is making trade-offs under constraints and explaining your reasons clearly. The tools are the last thing you pick.

The simplest approach and its limits

Start with the simplest version that works: one Spring Boot instance and one MySQL server. A sign-up is one INSERT plus one conditional UPDATE:

sql
UPDATE event SET remaining = remaining - 1
WHERE id = 42 AND remaining > 0;

The database checks remaining > 0; if zero rows are affected, the event is full, so it cannot oversell by construction. Next, use numbers to find its limits:

  • 24,000 requests ÷ 30 seconds ≈ a peak of 800 sign-up writes per second
  • Every sign-up has to update the same row in event. InnoDB queues updates to the same row: only one transaction at a time can hold that row’s row lock, and it releases the lock only at commit
  • Throughput ceiling ≈ 1 ÷ how long each transaction holds the lock: 1 ms of lock time gives 1,000 TPS, 2 ms leaves only 500 TPS

800 sits right on the edge. That is what estimation is for: you do not have to guess, because it tells you directly that the real bottleneck is that one hot row, not the CPU and not the number of application servers. Every design decision from here on revolves around this bottleneck.

Core mechanism: how to think through a design

flowchart TD
    A[Clarify requirements: functional / non-functional] --> B[Estimate: QPS, storage, bandwidth]
    B --> C[Define the API and data model]
    C --> D[HLD: components and data flow]
    D --> T[Threat modeling: mark trust boundaries and attack surface]
    T --> E[Find the bottleneck: dig into one or two key points]
    E --> F[List options, compare trade-offs, record the decision]
    F --> G[Evolution path: when to re-evaluate]
    G -. scale or requirements change .-> A

Functional vs non-functional requirements

Type Example from the sign-up system What it decides
Functional requirements Sign up, cancel, check remaining seats, join a waitlist when full API and data model
Non-functional requirements Peak of 800 writes/s, never oversell, p99 < 500 ms, 99.9% availability on the day, keep sign-up data for 1 year, only you can look up and cancel your own sign-up Architecture, component choices, deployment

Non-functional requirements must have numbers. “It has to be fast” is not a requirement; “p99 < 500 ms” is. “It has to be stable” is not a requirement; “99.9% availability on the day of the event (about 1.4 minutes of allowed downtime)” is.

How HLD and LLD divide the work

HLD (High-Level Design) LLD (Low-Level Design)
Questions it answers Which components exist, how data flows, how it scales and tolerates faults How classes and interfaces are split, what the tables look like, how errors are handled
Output Architecture diagram, data flow, capacity estimates, reasons for choices Class diagram, DDL, API spec, state machine
Main readers The team, managers, SREs Implementers, code reviewers
Cost of getting it wrong High (the database choice and the sharding key are close to irreversible) Relatively low (a refactor fixes it)

System design interviews usually stop at HLD plus one or two deep dives. In practice the two shape each other: as the next section shows, “the order of the SQL statements” in the LLD directly changes the capacity ceiling of the HLD.

Lightweight threat modeling

Once the HLD shows the data flow, follow each flow across every trust boundary it crosses (browser to API, API to database, service to service) and ask six questions. Their initials spell STRIDE:

Threat Question to ask Example from the sign-up system Countermeasure (where in the series)
Spoofing Who can pretend to be someone else? Signing up for someone else with a stolen account Authentication (Part 8-1 Authentication)
Tampering Who can change data in transit or at rest? Changing the memberId in a request to someone else’s and canceling their sign-up Take identity only from a verified token, never from request parameters (Part 8-2 Authorization Models and the OWASP API Top 10)
Repudiation Can you prove afterwards who did what? A user insists they never canceled Audit logs (Part 6-5 Observability)
Information disclosure Who can see data they should not? Walking through sequential sign-up IDs to read other people’s sign-ups Object-level authorization (Part 8-2 Authorization Models and the OWASP API Top 10)
Denial of service Who can make the service unavailable to others? Bots grabbing every seat the moment sign-ups open Rate limiting, CAPTCHA (Part 6-4 Rate Limiting, Part 8-5 Abuse Prevention)
Elevation of privilege Who can do more than they are allowed to? A regular member calling the admin “export attendee list” API Function-level authorization (Part 8-2 Authorization Models and the OWASP API Top 10)

You do not need a full report at the start. The point is to turn “who can touch which data” into requirements while the architecture is still easy to change, instead of patching it after launch.

Comparing options: a trade-off framework

Use the same framework for every architecture decision to force yourself to be clear:

  1. List at least two options, including “keep things as they are / the simplest option”
  2. For each option, answer: what do you give up, and what do you get. If you cannot name what an option gives up, you have not thought it through yet
  3. Rank by correctness > maintainability > performance, unless data shows that performance is the bottleneck right now
  4. Write down the conditions that trigger a re-evaluation, as a clue for yourself and new teammates six months from now

Applied to decrementing seats in the sign-up system:

Option How You get You give up Re-evaluate when
A. Conditional UPDATE Decrement seats with one SQL statement, plus a local “sold out” flag that rejects early Simplest, strongly consistent, zero operating cost Writes to the hot row are capped by lock time Load test p99 > 500 ms
B. Seat buckets Split the seats into N rows and decrement a random one each time Lock contention drops to about 1/N, still inside a MySQL transaction Counting all seats needs a sum; retries when the last seats are unevenly spread Too many retries near the end
C. Redis reservation + async write Atomic decrement in a Lua script, then write back to MySQL through an MQ Tens of thousands of decrements per second Two more components; reconciliation and compensation when Redis and the DB disagree Seats or traffic per event reach flash-sale level
D. Waiting room The frontend queues users first and lets them in in order Backend load fully under control Users have to wait; high cost to build and to design the experience Traffic far beyond what the backend can handle

For 3,000 seats and a peak of 800 per second, pick A first, and switch to B if the load test fails. Leave C and D for larger scale. The conclusion is not “A is best”; it is “A is enough at this scale, and we know when it will stop being enough”.

In Java: from HLD to LLD

Tables

sql
CREATE TABLE event (
    id        BIGINT PRIMARY KEY,
    title     VARCHAR(200) NOT NULL,
    capacity  INT NOT NULL,
    remaining INT NOT NULL,
    CHECK (remaining >= 0)
);

CREATE TABLE registration (
    id         BIGINT AUTO_INCREMENT PRIMARY KEY,
    event_id   BIGINT NOT NULL,
    member_id  BIGINT NOT NULL,
    created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    UNIQUE KEY uk_event_member (event_id, member_id)
);

uk_event_member lets the database reject duplicate sign-ups. MySQL enforces CHECK only from 8.0.16 on; it is the last line of defense.

The sign-up service

java
@Service
public class RegistrationService {

    private final JdbcClient jdbcClient;
    private final SoldOutFlag soldOutFlag;

    public RegistrationService(JdbcClient jdbcClient, SoldOutFlag soldOutFlag) {
        this.jdbcClient = jdbcClient;
        this.soldOutFlag = soldOutFlag;
    }

    @Transactional
    public void register(long eventId, long memberId) {
        if (soldOutFlag.isSoldOut(eventId)) {
            throw new SoldOutException(eventId);       // once sold out, requests never reach the database
        }

        try {
            jdbcClient.sql("INSERT INTO registration (event_id, member_id) VALUES (:eventId, :memberId)")
                    .param("eventId", eventId)
                    .param("memberId", memberId)
                    .update();
        } catch (DuplicateKeyException e) {
            throw new AlreadyRegisteredException(eventId, memberId);
        }

        // Update the hot row as the last step of the transaction: the lock is held only for the UPDATE and the commit
        int updated = jdbcClient.sql("""
                UPDATE event SET remaining = remaining - 1
                WHERE id = :eventId AND remaining > 0
                """)
                .param("eventId", eventId)
                .update();

        if (updated == 0) {
            soldOutFlag.markSoldOut(eventId);
            throw new SoldOutException(eventId);       // RuntimeException → rolls back the INSERT above
        }
    }
}
java
@Component
public class SoldOutFlag {

    private static final long TTL_MILLIS = 30_000;
    private final Map<Long, Long> soldOutUntil = new ConcurrentHashMap<>();

    public boolean isSoldOut(long eventId) {
        Long until = soldOutUntil.get(eventId);
        return until != null && until > System.currentTimeMillis();
    }

    public void markSoldOut(long eventId) {
        soldOutUntil.put(eventId, System.currentTimeMillis() + TTL_MILLIS);
    }
}

This code contains three LLD decisions, and each one affects the HLD:

  • INSERT first, then UPDATE: the other way round, the hot row’s lock would be held until the INSERT finished, the lock time would grow, and the throughput ceiling would drop. The order of the SQL is your capacity
  • Report failure with exceptions: SoldOutException and AlreadyRegisteredException are both RuntimeExceptions, so throwing one makes @Transactional roll back the whole transaction. If you “catch it and return an error code” instead, the SQL that already ran gets committed and a seat is lost for nothing
  • The flag is only an optimization; correctness lives in the database: SoldOutFlag is each machine’s own memory, and it does not matter that the machines are out of sync, because even when a flag is wrong, remaining > 0 in the SQL still prevents overselling. The 30-second TTL makes the flag expire on its own after someone cancels and a seat frees up

Writing the decision down as an ADR

markdown
# ADR-007: Decrement seats with a conditional UPDATE in MySQL

- Status: Accepted
- Date: 2026-11-22

## Context
About 24,000 requests expected within 30 seconds of opening (about 800/s), 3,000 seats, no overselling.
The bottleneck is a single hot row in the event table.

## Decision
Decrement seats with a single conditional UPDATE as the last step of the transaction,
plus a local "sold out" flag (30-second TTL) that rejects requests once the event is full.

## Alternatives considered
- Seat buckets: less lock contention, but counting totals and end-of-sale retries get complicated; not needed at the current scale
- Redis reservation + async write: highest throughput, but needs reconciliation and failure compensation

## Consequences
- Write throughput on the hot row depends on lock time; no non-essential work inside the transaction
- Re-evaluate when: load test p99 > 500 ms, or a single event has more than 20,000 seats

Pitfalls and gotchas

  • Choosing tools before finding the problem: deciding on Kafka, Redis, and microservices before any estimate leaves you with three more components to run, while the bottleneck is one line of SQL
  • Only covering the happy path: what about users double-clicking, retries after network timeouts, the few seconds of a database failover? The design document has to answer these
  • Non-functional requirements without numbers: without numbers you cannot sign off, and you cannot tell whether an option is good enough
  • Treating eventual consistency as free: say how long the inconsistency window is, what users see during it, and who fixes it
  • Trusting a cache or a flag for correctness: caches and local flags can expire or drift; use them to speed things up, never to guarantee correctness
  • No re-evaluation conditions: six months later traffic is ten times higher, and a new teammate who sees “why is this just one line of SQL” assumes the design was wrong, when the conditions simply changed
  • Treating CAP as the only thinking tool: CAP is a framework for one kind of decision, distributed consistency; most design decisions have nothing to do with it

When to use it, and when not to

  • A full HLD document: new systems, cross-team work, anything involving payments or data correctness, irreversible choices (database choice, sharding key, public API format)
  • One ADR is enough: a single, reversible technical decision, such as switching HTTP clients or tuning a cache TTL
  • No formal design: small changes you can roll back right away if they break; just do it and measure
  • When to re-evaluate: scale grows to 10 times the original, a core requirement changes (for example from “first come, first served” to “a lottery”), or the team size or organization changes

How much effort a design deserves depends on whether the decision can be reversed: decide reversible ones quickly and correct them with data after launch; only irreversible ones are worth extra time on estimates and comparisons.

References

Comments