跪拜 Guibai
← Back to the summary

From Frontend to Full-Stack: The 12 Backend Thinking Patterns AI Won't Tell You

Preface

It's been a really long time since I last posted. Let me start by explaining why I'm writing this article.

First, I'll lay out the core thinking map in three parts: data must not be wrong: traffic must hold up; and when things go wrong, you must be able to catch it—so you can get a sense of what the article is about before reading on.

Problem Main Layer Category
1. Data modeling: will the data still be correct later? Database (table structure) Data must not be wrong
2. Security: what happens if someone calls directly, bypassing the frontend? Filters, Service Data must not be wrong
3. Idempotency: what happens if the same request is called twice? Service, Database Data must not be wrong
4. Concurrency: what happens if two people call at the same time? Service, Database Data must not be wrong
5. Transactions: what happens if execution fails halfway? Service Data must not be wrong
6. Database: what happens when data volume becomes 1000x? Repository, Database Traffic holds up
7. Cache: if the same data is read repeatedly, do we have to hit the database every time? Service and Database Traffic holds up
8. Async: which steps can the user wait for? Service Traffic holds up
9. Rate limiting: what happens if traffic exceeds the system's capacity? Nginx, Filters Traffic holds up
10. Fault tolerance: what happens if a dependency goes down? Service when calling external services Can catch it
11. Observability: if something goes wrong, can you find it? Every layer Can catch it
12. Release compatibility: what happens when old and new versions run simultaneously? Whole chain Can catch it

With AI, the barrier to writing code has dropped a lot. Before, frontend devs wanting to write backend had to grind through Java, Spring, and databases; now you just tell AI and the interface is written in seconds. So I think in the AI era, frontend devs moving to full-stack is inevitable—you need to know some backend.

So what do you need to know? Syntax and APIs still need learning; at least you need to understand every line AI writes, otherwise you won't spot its mistakes. But you don't have to memorize everything; you can look up details anytime. But understanding alone isn't enough—what really separates people is thinking: you need to see what problems this code will have in a real environment.

I started learning AI application development and backend fairly early. The biggest takeaway is this: with the same code AI writes, someone with backend thinking can see at a glance "this will lead to duplicate orders" or "this will oversell," while others see nothing wrong until it goes live and breaks. So this article organizes what I think are the most important parts of that thinking in plain language, sharing it with friends who are also transitioning to full-stack.

This article doesn't cover Java syntax or Spring internals—not because they're unimportant, but because there are plenty of tutorials and you can ask AI. This article only covers what AI won't proactively warn you about. The whole article revolves around one of the most common and important features: submitting an order.

Let's look at an example. Say you send AI the following requirement:

Write an order API with Spring Boot + MyBatis: after the user selects a product and quantity, submit it, check stock, deduct stock, create an order, then send an SMS and add points. Also write an API to query order details.

It will quickly give you something like the code below. Let's call it v0:

@PostMapping("/order/create")
public Result createOrder(@RequestBody OrderRequest req) {
    // 1. 查商品
    Product product = productMapper.selectById(req.getProductId());
    // 2. 库存不够就返回
    if (product.getStock() < req.getQuantity()) {
        return Result.fail("库存不足");
    }
    // 3. 扣库存
    product.setStock(product.getStock() - req.getQuantity());
    productMapper.updateById(product);
    // 4. 创建订单
    Order order = new Order();
    order.setUserId(req.getUserId());
    order.setProductId(req.getProductId());
    order.setQuantity(req.getQuantity());
    order.setStatus("UNPAID"); // 待支付
    orderMapper.insert(order);
    // 5. 发短信、加积分
    smsService.send(req.getUserId(), "下单成功");
    pointService.add(req.getUserId(), 10);
    return Result.ok(order.getId());
}

@GetMapping("/order/{id}")
public Result getOrder(@PathVariable Long id) {
    return Result.ok(orderMapper.selectById(id));
}

Even if you're not familiar with Java, the comments explain each step. The overall logic is similar to writing a frontend submission function: check, decide, modify, save.

This code works and passes normal flow tests: select product, click submit, stock decreases by one, a new row in the orders table, SMS received.

You might think: "AI is so strong, wouldn't it handle concurrency and idempotency on its own?"

Actually, most of the time it doesn't. Not because AI doesn't know, but because it only knows what you tell it. It doesn't know how much data this table will have, how many people will grab the same product in the same second, or that there are old versions of the app still running. Sometimes it adds a little protection here and there, but whether it did, and whether it's correct, is for you to judge. If you don't mention it, it writes for the simplest case; if you can't see the problem, it goes straight to production.

To make the above code production-ready, you must at least answer these three questions:

  1. If someone clicks repeatedly, simultaneously, or bypasses the frontend, will the order data be wrong?
  2. If the number of orders goes from 100 to 100,000, will the API still hold up?
  3. If dependencies fail or versions update, can you catch problems?

These three questions break down into the 12 backend thinking patterns I'll cover next. Each pattern is simply a question you ask yourself after writing code. For each, I'll start with a familiar frontend analogy, show a counterexample, explain how experienced backend engineers think, and finally give a verification method that doesn't require much code, for deeper understanding.

At the end, I've compiled the 12 patterns into a review checklist. After AI writes backend code, you can go through it. Suggest saving it.

Prerequisites: 6 Differences Frontend Devs Must Recognize When Writing Backend

Before the 12 patterns, three quick notes.

First, when I say "how backend engineers look at it," I mean how an experienced, reliable backend engineer would think—not that backend devs are naturally that careful. Backend devs write v0-like code all the time.

Second, this isn't to say frontend is easy. Frontend difficulties lie elsewhere: browser compatibility, performance optimization, complex interaction states—these might stump a backend engineer. It's just that when you move to full-stack, you'll encounter scenarios rarely seen in the browser, needing a different perspective.

Third, the practices here are mainstream for monolithic services at medium scale. At big-tech scale, many become common components and platform capabilities (like gateway rate limiting, distributed tracing platforms) with more complex solutions. I'll mention these where relevant.

Let's start with the most fundamental: the same feature looks different from the frontend vs. backend. If you don't shift this perspective, many practices will seem like "overthinking."

The Same Order Button: What Frontend vs. Backend See

Frontend views order from the page down: confirmation page, click submit, go to payment page, show result. You care about what the user sees, clicks, and how long they wait.

Experienced backend views order from the data up: which tables will be touched? Orders table, order items table, stock table, payment transaction table. Who reads/writes each table? Could two requests modify the same row simultaneously?

Comparing them:

Difference Frontend faces Backend faces
Users One person in front Hundreds might be grabbing the same product in the same second
Request source Requests from your own page Anyone with any tool can call, possibly twice
State Disappears on refresh Orders stored for years, status goes from unpaid to refunded
Runtime Each user has a page, closes and ends One process serves all users, runs for months
Error impact Show a toast, let user retry Money deducted but order not created, stock goes negative—affects everyone
Debugging Open F12 on the spot Can't set breakpoints online; only logs

Each row in this table will become a concrete problem later. "Request source" corresponds to Pattern 2 (Security) and Pattern 3 (Idempotency); "Users" to Pattern 4 (Concurrency); "Debugging" to Pattern 11 (Observability). "Runtime" is the least tangible for frontend devs; let's expand on that.

Long-Running Processes and Multiple Instances

Frontend pages have short lifespans. Close the tab, memory freed. A small memory leak in an SPA fixes itself on refresh.

Backend services are different: a process starts and runs for days, weeks, or months, serving all users. If every request leaks a little memory, it might be fine initially, but after two weeks it could eat all memory and crash.

More importantly, resources are shared across all requests. CPU, memory, threads, database connections—all in the same pool. For database connections, Spring Boot's default pool (HikariCP) maxes at 10 connections. If one SQL takes 2 seconds and 10 such requests come at once, the pool is exhausted; even simple queries queue up. This rarely happens in frontend: one user's page being slow doesn't slow others' pages.

Also, production services usually have more than one instance. To handle traffic and provide failover, you deploy several identical services behind a load balancer, distributing requests. The same user's consecutive requests might hit two different machines.

This requires services to be "stateless": user-related data can't be stored only on one machine. Many "works locally but weird in production" issues stem from forgetting this. Common ones:

Three pitfalls of multi-instance deployment

Analogy: if you store login state in localStorage, it's gone when you open a different browser. In multi-instance deployment, each machine is like a separate browser.

The Full Flow of a Request

Frontend's impression of a request is just "axios sends, gets response." In the backend, a request passes through several layers:

Layers a request goes through

Each layer has a rough frontend equivalent:

Knowing each layer's responsibility helps you see if logic is in the wrong place. Rough division:

Task Layer
Logged in? Token valid? Filters
Param format: required fields, quantity is number Controller
Business rules: stock enough, order yours, status change allowed Service
Transaction: all-or-nothing Service
Building SQL, reading/writing DB Repository

Looking back at v0, all logic is in the Controller, and there's no check for "who are you." AI isn't incapable of layering; your requirement didn't mention it, so it does whatever is fastest.

Full Map

Experienced backend engineers run through about 12 questions when looking at a feature; each question is a backend thinking pattern. No need to memorize; here's a summary:

Full map: 12 backend thinking patterns

Problem Main Layer Category
1. Data modeling: will data be correct later? Database (table structure) 1. Data must not be wrong
2. Security: what if bypass frontend? Filters, Service 1. Data must not be wrong
3. Idempotency: what if same request twice? Service, Database 1. Data must not be wrong
4. Concurrency: what if two people call simultaneously? Service, Database 1. Data must not be wrong
5. Transaction: what if fail halfway? Service 1. Data must not be wrong
6. Database: what if data volume 1000x? Repository, Database 2. Traffic holds up
7. Cache: same data read repeatedly, DB every time? Service and Database 2. Traffic holds up
8. Async: which steps can wait? Service 2. Traffic holds up
9. Rate limiting: traffic exceeds capacity? Nginx, Filters 2. Traffic holds up
10. Fault tolerance: dependency down? Service calling external 3. Can catch it
11. Observability: can you find problems? Every layer 3. Can catch it
12. Release compatibility: old and new simultaneous? Whole chain 3. Can catch it

Patterns 1–5 keep data correct; 6–9 keep traffic holding; 10–12 handle problems after they occur. The order matters: if data is wrong, handling traffic is useless; if you can't handle traffic, problems are inevitable.

Part 1: Data Must Not Be Wrong

Suppose v0 goes live. In the first week you'll get three tickets:

Looking at the code, every line is correct, syntax fine, logic fine—the problem is it's written assuming "one user, one click, normal flow." So the first thing in backend is to make data correct under abnormal conditions.

Pattern 1: Data Modeling—Will Data Still Be Correct Later?

Frontend state structure can be refactored anytime. E.g., change the structure of Pinia or Redux state, release, user refreshes, done.

Databases are different: once data is stored, it may be used for years. A poorly designed table structure requires changing not just code but millions of rows already in the table.

Look at v0's orders table:

CREATE TABLE orders (
  id         BIGINT AUTO_INCREMENT PRIMARY KEY,
  user_id    BIGINT,
  product_id BIGINT,
  quantity   INT,
  status     VARCHAR(20)
);

Orders only store product ID. To show amount on the order detail page, it queries the product table for current price and multiplies by quantity.

The first month is fine. Then one day the product price increases, and users look back at historical orders and see the amount they paid last month has changed. Users complain to customer service, who can't explain.

Primary keys, foreign keys, one-to-many—AI rarely makes mistakes on these. I'll skip them: one order can contain multiple products, so split into orders and order_items tables. What you really need to judge are the things AI won't consider proactively.

Snapshot: Orders store the moment of purchase

Orders record "what happened at that time." So the product name, unit price, shipping address at the time of purchase must be copied into the order:

CREATE TABLE order_item (
  id           BIGINT PRIMARY KEY,
  order_id     BIGINT NOT NULL,
  product_id   BIGINT NOT NULL,
  product_name VARCHAR(100) NOT NULL,   -- 下单时的商品名
  price        DECIMAL(10,2) NOT NULL,  -- 下单时的单价
  quantity     INT NOT NULL
);

Frontend values single source of truth; seeing the same data stored twice might feel odd. But orders should decouple from the product table's "now." Whatever the price was at order time, it should show that later.

Redundancy: who ensures consistency when stored twice

Snapshots are "store and never change" redundancy. Another type is for faster queries: e.g., storing user nickname in orders to avoid joining the user table for list pages. If user changes nickname, should orders' copy change? Who updates it? What if missed?

Either clearly treat it as a snapshot (showing nickname at order time), or clearly assign responsibility for sync. Before storing an extra field, think which type it is.

State machine: which transitions are allowed

Orders have status: unpaid, paid, shipped, completed, cancelled, refunded. Having these values isn't enough; you need to think about allowed transitions:

Order state machine

Frontend has states too (button loading, disabled), but errors usually affect just one user's one page. Order status errors have real consequences: a cancelled order gets changed to "paid" by a late payment notification—money taken, goods not shipped. So when changing status, don't just write "change to X," also check "what is it now." Details in Pattern 3.

Money: don't use floating point

0.1 + 0.2 = 0.30000000000000004 is a classic frontend problem. Java's double, database FLOAT and DOUBLE are the same. Use them for money, and sooner or later you'll have accounts off by a cent.

Use DECIMAL(10,2) or store integers in cents: 19.90 as 1990. Note: AI-generated entity classes sometimes use Double for price; change it if you see it.

ID: what does exposing to frontend leak?

v0 uses auto-increment order ID, so order detail URL is like /order/10086.

Change to 10085 and you can try to query someone else's order. If backend doesn't verify ownership, you'll actually see it (Pattern 2). Even with verification, auto-increment IDs leak info: order at 8am ID 10086, at 8pm 10986—competitors subtract and know you sold ~900 orders a day.

So use a non-sequential order number externally; keep auto-increment ID internal.

Soft delete: conflicts with unique indexes

Frontend deleting a list item is removing from array. Backend often can't truly delete data; it must be retained for reconciliation and debugging, so we use "soft delete": add a deleted field, set it to 1 on delete.

Trap: unique index. E.g., product code has unique index. A product is soft-deleted when delisted. Later you want to relist with the same code—DB error: duplicate code. Because the old row is still there.

Common solution: include the delete marker in the unique index. E.g., use deletion timestamp instead of 0/1; for non-deleted, set 0; unique index on (code, deleted_time). So non-deleted codes are unique, deleted ones can have many.

Time and time zones

Database, server, and users may be in different time zones. Store in one unified timezone, convert for display. Don't let each place use its own.

Table structure changes, old data remains

Page revamp: release and done. Table structure changes: old data stays old. New fields will be empty in old rows; code must handle nulls. Adding fields/indexes to large tables may take a long time and affect online reads/writes. Details in Pattern 12.

Verification: In the admin panel, change a product's price, then open a historical order that contains that product. If the amount changed, the order didn't store a snapshot.

One-sentence principle: Design table structure based on how data will change, not how the page displays now.

Pattern 2: Security—What If Someone Bypasses the Frontend?

Frontend has many "protections": buttons without permission not shown, quantity input limited to 1–99, phone format validated before submit.

But these only work in the browser. Open F12 and modify request params, or use Postman/curl directly—frontend restrictions vanish. So when writing an API, assume every endpoint will be called directly, bypassing the frontend.

Looking back at v0, two places trust the frontend completely. First, querying order details:

@GetMapping("/order/{id}")
public Result getOrder(@PathVariable Long id) {
    return Result.ok(orderMapper.selectById(id)); // 查到就返回,不管是谁的
}

Second, when ordering, user ID and quantity come directly from the frontend. Using curl:

curl -X POST http://localhost:8080/order/create \
  -H "Content-Type: application/json" \
  -d '{"userId": 1, "productId": 1, "quantity": -1}'

userId can be anything—you can place orders as someone else. quantity = -1 passes stock check, deduct becomes "subtract -1" (i.e., increase stock), and order total is negative.

Authentication vs. Authorization

Authentication is "who you are," solved by login and Token. Authorization is "what you can do." Frontend route guards check "logged in?"—that's only authentication. What you can do after login must be managed per-API on the backend.

There are two types of privilege escalation:

Vertical: normal user calls admin APIs, e.g., price change, refund. Frontend just doesn't show the menu; if the API has no guard, knowing the URL is enough. RBAC solves this: user->role->permissions, each API declares required permission. Ask AI to write "admin price change API," it'll write the endpoint but rarely add permission checks unless you say who can call it.

Horizontal: everyone is a normal user, but you see someone else's data. That's the order number guessing. Fix: include "is it yours" in the query:

-- 反例:只按订单 ID 查
SELECT * FROM orders WHERE id = ?;

-- 修正:同时校验归属,user_id 从 Token 里取
SELECT * FROM orders WHERE id = ? AND user_id = ?;

Horizontal escalation is more common and more insidious because testing with your own account always looks normal. So for every query-by-ID API, ask: is this data the current user's?

What comes from the frontend is just "what the user wants"

User ID comes from Token; price comes from database. Frontend-provided values are "what user wants" (I want product 1, quantity 2), not "facts" (who I am, how much it costs, how much discount).

Validate boundaries for quantity, amount:

if (req.getQuantity() < 1 || req.getQuantity() > 99) {
    return Result.fail("购买数量不合法");
}
Long userId = UserContext.getUserId();   // 从 Token 解析,不用前端传的
BigDecimal price = product.getPrice();   // 从数据库取,不用前端传的

Besides negatives, common boundary issues: using a coupon twice, stacking two non-stackable coupons; using int to store amount in cents, huge quantity overflows int to negative.

Common "I thought it was safe" spots

<!-- 危险:前端传什么就拼什么 -->
ORDER BY ${sortField}

Fix: whitelist allowed fields:

Set<String> allowed = Set.of("create_time", "amount");
if (!allowed.contains(sortField)) {
    sortField = "create_time";
}

Sensitive data and secrets

Phone numbers, ID card numbers: encrypt at rest, mask on display (e.g., 138****1234). Passwords: neither plaintext nor reversible encryption—use salted hash (e.g., BCrypt).

Don't commit database passwords, payment keys in code to Git. Use separate sets for dev/test/prod. New rule in the AI era: when debugging production issues, don't paste production secrets or real user data into AI chat; sanitize first.

Verification: Use your own Token to query someone else's order:

curl http://localhost:8080/order/10085 \
  -H "Authorization: Bearer 你的Token"

Returning 403 or 404 is fine, just don't return the data. Also submit quantity -1 and see if it's blocked.

One-sentence principle: Frontend validation is for UX; backend validation is for security.

Pattern 3: Idempotency—What If the Same Request Is Called Twice?

To prevent duplicate submissions, frontend commonly disables the button after click and shows a loading spinner. That blocks double-clicks, but not:

The last two are beyond frontend control.

After discovering duplicate orders, you ask AI to add "prevent duplicate submission." It might give you: frontend generates a request ID on entering confirmation page, sends it; backend checks if exists, if not insert.

Order exist = orderMapper.selectByRequestId(req.getRequestId());
if (exist == null) {
    orderMapper.insert(order);   // 没下过单,才插入
}

Looks like it prevents duplicates; testing with two clicks yields one order. But it has a vulnerability, addressed at the end of this section.

Duplicate requests are normal

Accept a fact: in backend, duplicate requests are not accidents—they're the norm. The sources above occur anytime; payment platform docs usually say "the same notification may be sent multiple times," so handle it.

So make the API idempotent: the same request called once or ten times has the same result. Note: not "second time errors," but "second time produces no new effect," ideally returning the same result as the first. Otherwise a retry gets an error, user thinks order failed, clicks again.

Per HTTP spec, GET/PUT/DELETE should be idempotent; POST is not. So a POST order API must enforce idempotency itself.

Idempotency Token: frontend-backend coordination

A more complete approach:

  1. When user enters confirmation page, frontend requests a Token from backend; backend generates and stores it (e.g., in Redis).
  2. When submitting, frontend includes this Token.
  3. Backend deletes the Token: if deletion succeeds, first time; continue order. If order fails, put Token back so user can retry with same Token. If deletion fails (Token not found), request is already being processed or done; return "processing" or the first order number.

Note: Frontend must use the same Token for retries; don't generate a new one each time, or backend can't recognize it's the same request.

The key is step 3: "check and delete" must be atomic. If you first check Token exists, then delete, two simultaneous requests both see Token exists and pass. This is Pattern 4's concurrency problem. How to do it in Redis atomically is in Pattern 7.

Unique index: the last line of defense

The most reliable safety net is on the database. Add a unique index on the request ID in the orders table; you can use the Token directly:

ALTER TABLE orders ADD UNIQUE KEY uk_request_id (request_id);

Inserting same request ID twice—DB throws error. Catch that error as "order already exists," query and return the first order.

Same for payments: add unique index on payment transaction number in payment records; ten duplicate notifications only insert one row.

Why call it a safety net? Because code-level checks can have bugs or concurrency gaps; the unique index is DB-guaranteed—no matter how many concurrent requests, only one wins.

Status condition: let status move forward only once

Pattern 1 said when changing status, check "what it is now." Payment callback updating order to paid is typical:

-- 反例:直接改
UPDATE orders SET status = 'PAID' WHERE id = ?;

-- 修正:只有待支付的订单才能改成已支付
UPDATE orders SET status = 'PAID' WHERE id = ? AND status = 'UNPAID';

Check affected rows. If 1, first time; continue with follow-up (notify shipping, add points). If 0, already processed; return success without repeating.

If 0 because order is cancelled but money arrived—need refund. That's reconciliation (Pattern 8).

Why "check-then-insert" fails

Back to AI's code. The problem is "check" and "insert" are two steps with a gap. When two requests arrive milliseconds apart:

Time Request A Request B
1 Query: no such request ID
2 Query: no such request ID
3 Insert order
4 Insert order

Both see "none" and insert. Hard to reproduce with double-clicks because hundreds of milliseconds apart; by the second check, first is done. But online, with many requests and network jitter, this gap gets hit.

So check-then-insert catches duplicates separated in time, not simultaneous ones. The real safety net is the unique index. This "check-then-modify" gap is also the protagonist of the next pattern.

Verification: Send several requests nearly simultaneously with same request ID:

for i in 1 2 3 4 5; do
  curl -X POST http://localhost:8080/order/create \
    -H "Authorization: Bearer 你的Token" \
    -H "Content-Type: application/json" \
    -d '{"requestId": "abc123", "productId": 1, "quantity": 1}' &
done
wait

On Windows, run in Git Bash. If not reproduced once, run more times or increase concurrency. Then check DB:

SELECT COUNT(*) FROM orders WHERE request_id = 'abc123';

If > 1, duplicate protection failed.

One-sentence principle: Frontend can only reduce duplicate requests; only backend can ensure duplicates don't cause errors.

Pattern 4: Concurrency—What If Two People Call Simultaneously?

If you've built a search box, you might have seen this: user types "phone," quickly changes to "phone case," two requests fire. "phone" response arrives late and overwrites "phone case" results—page shows old search results.

That's a race: several things running, outcome depends on order. In browser it's rare; on the server it happens daily.

Look at how v0 deducts stock:

Product product = productMapper.selectById(req.getProductId());  // 查:库存 1
if (product.getStock() < req.getQuantity()) {                    // 判:够
    return Result.fail("库存不足");
}
product.setStock(product.getStock() - req.getQuantity());        // 算:1 - 1 = 0
productMapper.updateById(product);                               // 改:库存写成 0

Stock is 1, two people order simultaneously. Both read stock 1, both judge "enough," both compute 0, both write 0, each creates an order.

Result: 1 item generates 2 orders, stock shows 0, looks perfect. Harder to detect than negative stock.

Why frontend rarely encounters it

JavaScript is single-threaded; only one piece of code runs at a time. Between your if and the next line, no one else can interleave. Races only occur in async contexts (like the search box).

Backend: Spring Boot's embedded Tomcat defaults to 200 threads, one per request, truly parallel. With multiple instances, hundreds of threads across machines execute the same code simultaneously.

Races occur between "read, judge, write"

v0's problem is these are separate steps with gaps. Visual:

Timing diagram of two requests deducting stock

Same problem as Pattern 3's "check-then-insert." Your judgment relies on a value you read earlier, but it may have changed by the time you judge.

Atomic update: let the database do it in one step

Simplest and most common: let the database enforce the condition, one SQL:

UPDATE product SET stock = stock - ?
WHERE id = ? AND stock >= ?;

Meaning: stock enough, then deduct. The DB locks the row during UPDATE; two requests can't modify it simultaneously. Check affected rows: 1 = success, 0 = insufficient.

For most stock deduction, this suffices. But for flash sales, thousands grab the same product—all requests queue on the same row, making it a bottleneck. That needs other approaches; see at the end of Part 2.

Optimistic vs. pessimistic locks: when to use which

Some scenarios can't use a single SQL: read data, complex calculations in code, write back. Then use locks.

Optimistic lock: assume "usually no one contends." Add a version column; read it; on write, check it hasn't changed:

-- 读出来的时候 version 是 5
UPDATE product SET price = ?, version = version + 1
WHERE id = ? AND version = 5;

Affected 0 means someone changed after your read. Re-read and retry, or tell user "data modified, refresh." Many admin systems show that message. Good for low-conflict scenarios: two ops occasionally edit the same product.

Pessimistic lock: assume "someone will contend, I'll lock first":

SELECT stock FROM product WHERE id = ? FOR UPDATE;  -- 锁住这一行
-- 在代码里判断、计算,别人要改这一行只能等着
UPDATE product SET stock = ? WHERE id = ?;
-- 事务提交后才释放锁

Must be in a transaction (Pattern 5). Stable but others wait; use when conflicts are high and read-then-calculate is necessary.

Deadlocks: two transactions, one locks A then B, another B then A, each waits for the other. E.g., an order buys multiple products; deduct stock in a consistent order (e.g., by product ID ascending) to avoid it.

Distributed locks: when multiple machines, local locks are useless

Java's synchronized works only within the current process. With 3 machines, locking on machine A doesn't stop requests on B; they proceed.

To mutually exclude across machines, you need a place everyone sees—commonly Redis. Commands in Pattern 7.

The most overlooked issue: lock expires while business still runs. To prevent a dead process holding the lock forever, distributed locks set expiry (e.g., 10s). If business takes 15s, lock disappears at 10s, another request enters—two inside. Common fix: auto-renew while running (Redisson does this). When releasing, verify it's your lock, don't delete someone else's.

My advice: if a DB atomic update solves it, skip distributed locks—each extra component is another failure mode.

Shared state hidden in frameworks

Two concurrency issues come not from writing "check-then-modify" but from framework defaults.

First: Spring Beans are singletons by default. The whole app has one OrderService object shared by all requests. If you define a member variable:

@Service
public class OrderService {
    private Long currentUserId;   // 所有请求共用这一个变量

    public void create(OrderRequest req) {
        currentUserId = UserContext.getUserId();
        // ……执行到这里时,它可能已经被别的请求改成了别人的 ID
    }
}

Two users order concurrently; later request overwrites earlier user's value. Node/SSR devs might have hit this: module-level variables are shared across requests.

Second: ThreadLocal is like each thread's private pocket, often used for "current logged-in user" (like UserContext). Problem: threads are reused from a pool. Request A finishes but doesn't clear the pocket; thread handles request B, which finds A's user info.

So clear it at request end:

public void afterCompletion(...) {   // 拦截器里,请求结束时执行
    UserContext.clear();             // 不清的话,下一个请求可能拿到上一个用户
}

Verification: Set a product's stock to 1, send 100 concurrent order requests with unique request IDs (avoid Pattern 3 idempotency):

seq 100 | xargs -P 100 -I {} curl -s -o /dev/null \
  -X POST http://localhost:8080/order/create \
  -H "Authorization: Bearer 你的Token" \
  -H "Content-Type: application/json" \
  -d '{"requestId": "req-{}", "productId": 1, "quantity": 1}'

Then count orders for that product. More than 1 means oversold.

One-sentence principle: Wherever there's "check-then-modify," concurrency problems will occur.

Pattern 5: Transactions—What If Execution Fails Halfway?

With Promise.all in frontend, if one request fails, you go to catch. But the other requests already sent aren't rolled back; data is already changed.

Backend operations are also sequences; failures happen. Look at v0's order: deduct stock, create order, send SMS, add points.

With Pattern 3's unique index, a duplicate request comes: stock deducted, then insert fails due to unique index—no order created. Duplicate prevented, but stock deducted unnecessarily.

If SMS step throws, API returns failure, user thinks submission failed—but stock deducted and order created.

Ask AI to fix; it often adds @Transactional. But adding it doesn't guarantee effect:

public Result createOrder(OrderRequest req) {
    return doCreate(req);       // 同一个类里直接调用
}

@Transactional
public Result doCreate(OrderRequest req) {
    // 扣库存、建订单……
}

Outside calls createOrder, which has no transaction; doCreate has annotation but in this call, the transaction won't apply. Reason below.

What transactions do

Pack steps: all succeed or all roll back, no middle state. The textbook ACID (Atomicity, Consistency, Isolation, Durability) matters most here for Atomicity.

Transaction boundary: what goes in, what stays out

Deduct stock, create order, create order items must succeed/fail together—inside the same transaction:

@Transactional
public Long createOrder(OrderRequest req) {
    int rows = productMapper.deductStock(req.getProductId(), req.getQuantity());
    if (rows == 0) throw new BizException("库存不足");  // 自定义的运行时异常,抛出后事务回滚
    orderMapper.insert(order);
    orderItemMapper.insert(item);
    return order.getId();
}
// 事务提交之后,再去发短信、加积分

Don't put SMS, payment, third-party calls inside the transaction. Two reasons.

  1. While a transaction holds, modified rows stay locked. Deducting stock locks that row, others wait. Calling an external API inside the transaction—if it's slow 3s, row locked 3s, DB connection occupied 3s. Pool only has 10 connections.
  2. External calls can't be rolled back. SMS sent; transaction rolls back; SMS doesn't unsend.

@Transactional doesn't guarantee a transaction

Spring transactions use proxies. Frontend analogy: Vue 3 reactivity uses Proxy; modifying the proxy updates the page, bypassing the proxy doesn't. Spring same: calls must go through the proxy.

Cases where annotation is useless:

AI writing transactional code often just adds the annotation and assumes it works. When you see @Transactional, check if it actually applies.

Isolation levels

While two transactions run, how much they see of each other is isolation level. Three classic problems: dirty read (read uncommitted data), non-repeatable read (same query different results in one transaction), phantom read (row count changes). MySQL's default isolation avoids most; usually no need to change. Just know it exists.

Where transactions can't reach

DB transactions only cover operations on the same database. SMS, third-party calls, calls to other services—outside.

What if order created but SMS not sent? Points added failed, should retry? Cross-database consistency needs a different approach (Pattern 8).

Verification: After deducting stock, temporarily add a line to throw an exception:

productMapper.deductStock(req.getProductId(), req.getQuantity());
if (true) throw new RuntimeException("测试回滚");   // 测完记得删掉
orderMapper.insert(order);

Call the order API; check if stock restored. If not, transaction didn't apply; review the above cases.

One-sentence principle: For every write step, ask: if it fails here, what happens to the earlier steps?

v1: What Changed in This Round

After Part 1's 5 patterns, here's what changed from v0:

Change Pattern
Order items store product name and price at purchase time; amount uses DECIMAL; use external order no 1
User ID from Token; check ownership when querying; purchase quantity limited 1–99 2
Request ID unique index; payment callback changes status with original status condition 3
Stock deduction uses UPDATE ... WHERE stock >= ?; ThreadLocal cleared after use 4
Stock deduction and order creation in one transaction; SMS/points moved after commit 5

After this, data won't be wrong.

Part 2: Traffic Holds Up

After v1 goes live, data is finally correct. Then the first big sale.

Normal order API returns in 50ms. At 0:00 of the big sale, it becomes 5 seconds and times out. Users see spinning, smash submit. Thanks to Pattern 3 idempotency, no duplicates.

v1's data is correct, but it's written for "dozens of users." This part covers scale.

Heads up: this part covers indexes, cache, message queues, rate limiting. Except indexes, the others have costs—each adds maintenance. Each pattern will include "when you don't need it."

Pattern 6: Database—What If Data Volume Becomes 1000x?

In frontend, find in an array scans element by element; a Map uses a key to get directly. With 10 elements, no difference; with 1 million, huge.

Same for databases: test data is small, any query is fast.

v1's "My Orders" query:

SELECT * FROM orders
WHERE user_id = ?
ORDER BY create_time DESC;

Test DB has 100 orders, returns in ms. Production after a year: 10 million rows, no index, query scans 10 million rows.

AI can't see your data volume. If you don't tell it the table size, it likely won't create indexes or add pagination.

Index: from scanning rows to checking a catalog

An index is like a book's table of contents or a dictionary's phonetic index: don't flip page by page; look up and jump. For the query above:

CREATE INDEX idx_user_time ON orders (user_id, create_time);

This is a composite index. Rule: "leftmost prefix." The index sorts by user_id, then create_time, so queries must include the leftmost column (user_id) to use it. Querying only by create_time won't. Like a phone book sorted by last name then first name; knowing only first name doesn't help.

Ways an index is created but not used:

Use EXPLAIN to see the plan

Don't guess if an index is used. Prefix with EXPLAIN:

EXPLAIN SELECT * FROM orders WHERE user_id = 123 ORDER BY create_time DESC;

Key columns: type ALL = full scan; key = index actually used; empty = none; rows = estimated rows scanned.

EXPLAIN before/after index

With many SQLs, which to look at? MySQL slow query log logs queries exceeding a threshold. Find slow ones, then optimize; don't add indexes randomly—each has a cost (every write updates the index; more indexes, slower writes).

N+1 and deep pagination: slow queries invisible in test DB

E.g., order list page shows 20 orders, each with items. AI easily writes:

for (Order o : orders) {   // 20 个订单
    o.setItems(orderItemMapper.selectByOrderId(o.getId()));   // 每个再查一次明细
}

Query orders 1 time, items 20 times—N+1. Frontend has the same: each list item makes its own request. Fix: batch query:

SELECT * FROM order_item WHERE order_id IN (1, 2, 3, ...);

Group results by order_id in code and attach.

Deep pagination: admin list page 50,000, SQL:

SELECT * FROM orders ORDER BY id DESC LIMIT 1000000, 20;

DB counts 1 million rows, discards them, returns next 20. Slower as page number grows. Fix: keyset pagination: remember last ID of previous page, continue from there:

SELECT * FROM orders WHERE id < 上一页最后一条的id ORDER BY id DESC LIMIT 20;

If you've done infinite scroll, this is "load more." Trade-off: can't jump to page 500—discuss with product early.

Don't load everything into memory

"Export all orders"—AI might write to query all rows then write to Excel. Test DB hundreds fine; production 1 million rows in memory could OOM and crash. One process serves all users: one user exports, everyone can't order.

Batch read: read 1000 rows, write to file, next batch.

Read-write splitting and replication lag

Read-heavy systems often use one primary for writes and replicas for reads.

Replication has lag: usually ms, under load could be seconds. So: user orders successfully (writes to primary), page jumps to order detail (reads replica), says "order not found."

For write-then-read scenarios (order detail after ordering), force primary read.

What databases are bad at

Full-text search (LIKE '%keyword%' can't use index), large report aggregation—not what OLTP databases excel at. For scale, use Elasticsearch, analytics DBs. Out of scope.

When you don't need it: a single DB with proper indexes handles most small/medium projects. Read-write splitting, sharding don't need upfront; get indexes and SQL right first.

Verification: Have AI write a script to insert 1 million rows into orders. Run EXPLAIN on key queries ("My Orders"), check if type is ALL and rows is hundreds of thousands.

One-sentence principle: Write SQL with production data volume in mind, not the few rows in test.

Pattern 7: Cache—If the Same Data Is Read Repeatedly, Query Every Time?

Frontend knows HTTP caching; SWR/React Query caches API data, shared between components, refreshes in background.

Backend cache is the same: if data is read repeatedly, don't hit DB each time; put a copy somewhere faster. E.g., product detail page opened thousands of times per second during a big sale—DB can't handle it.

But cache adds problems: product detail cached, ops changes price, cache not deleted—detail page shows old price, but order uses DB's new price (Pattern 2 says price from DB). User pays different amount than seen—complaints.

What data is cacheable

Two conditions: read-heavy/write-light, and can tolerate brief inconsistency. Product detail, category, config are good. Account balance (must be exact, often changes) is not.

Where to cache: local cache (in service memory) is fastest, but multiple machines each have their own copy. Ops changes price, machine A's cache cleared, B's still old—price changes with each refresh. So shared data goes to Redis, everyone reads same copy.

Larger systems use both: very hot data in local cache for seconds, rest in Redis—multi-level cache. Cost: accept brief inconsistency or broadcast invalidation to each machine.

Update DB first, then delete cache

Most common pattern: Cache Aside.

public void updatePrice(Long id, BigDecimal price) {
    productMapper.updatePrice(id, price);   // 1. 先改数据库
    redis.delete("product:" + id);          // 2. 再删缓存,下次读时重新加载
}

Similar to SWR's mutate to invalidate cache.

Why delete cache instead of writing new value? Because two concurrent price updates might write to cache in reverse order of DB writes, leaving stale value. Delete avoids that: next read loads fresh.

Why DB first, then delete cache? If delete first, in the gap before DB update, a read sees cache miss, queries DB (old value), writes back to cache. Then DB updates, cache stays old. DB-first then delete is much less likely to fail. Also set TTL; even if something goes wrong, it self-heals.

At larger scale, teams add a safety net: listen to DB binlog, automatically delete cache on data change—not relying on business code to remember.

Redis also has "check-then-modify"

Single Redis commands are atomic, but multiple commands aren't.

E.g., store stock in Redis: GET, judge > 0, SET—same trap as Pattern 4. Fix: use DECR—one command subtracts and returns new value. If < 0, out of stock; add back.

Earlier callbacks now fit:

No need to memorize; AI can generate. The key is judgment: must these steps be atomic?

The moment cache fails

Most dangerous when cache suddenly stops working; all requests hit DB. Three cases:

Redis can't be the only storage

Redis data is in memory; when full, it evicts keys (e.g., LRU). So Redis data may disappear anytime. Orders, which can't be lost, must live in DB; Redis is only for speed.

When you don't need it: small data volume, low traffic—DB is fast enough; adding cache gives no perceptible gains and adds a "cache-DB inconsistency" problem.

Verification: In admin, change product price; immediately refresh detail page; see if price updates. With multiple machines, refresh several times to confirm all return new price.

One-sentence principle: Before adding cache, plan how cache changes when data changes.

Pattern 8: Async—Which Steps Can the User Wait For?

Frontend knows: don't put long computations on the main thread (page freezes); use Web Workers for large parsing, complex calculations.

Backend has its own "main thread": user clicks submit and waits for the API to return. Everything the API does counts toward user wait time.

v1's order API, after transaction commit, sequentially sends SMS, adds points, notifies warehouse. If SMS takes 3s, user waits 3 extra seconds; if SMS fails, API errors and user sees "order failed" even though order exists.

First, separate what must wait

Ask: if this step fails, is the order still a successful order?

Deducting stock, creating order—if fail, order fails. These are core, user must wait. SMS, points, warehouse—if fail, order stands; can be delayed. Non-core steps shouldn't make user wait or fail the order.

Message queue: async, decoupled, peak-shaving

The usual tool to move non-core steps out: message queue (MQ). Order API creates order, sends "order created" message to MQ, returns. SMS, points, warehouse each subscribe, act on receipt.

Think of it as cross-service pub/sub like EventBus: order emits 'orderCreated'; whoever cares, on it.

Three roles:

Accept "eventual consistency"

After async, data isn't immediately consistent. At order success, points aren't added yet; maybe a few seconds. This is eventual consistency: not guaranteed at every instant, but guaranteed eventually.

Most businesses accept this; users won't mind points arriving 2 seconds late. The key is knowing what can be delayed and what can't.

The theory: CAP and BASE. In distributed systems under network problems, you can't have both instant consistency and always-available; most choose availability.

Messages can be lost and duplicated

With MQ, face two issues.

Loss: order created, MQ connection fails when sending; message lost; user never gets points. Common solution: local message table—in the same transaction as order, insert into a "pending messages" table; a scheduled task sends them and marks as sent. If order exists, message exists. Other options: transactional messages, Saga—know the names, look up when needed.

Duplication: most MQs guarantee "at-least-once"; network jitter can deliver twice. Consumers must be idempotent (Pattern 3). E.g., adding points: unique index on (order_no, point_type)—points for same order can only be added once.

Failed messages need retry, but not infinite. After a few retries, put into a dead-letter queue for manual handling; otherwise a bad message blocks forever. Also, messages might arrive out of order ("payment success" before "order created").

Who is the source of truth: reconciliation and compensation

If messages lost, payment callback never came, data is inconsistent. Who wins?

Source of truth: for money, the payment platform's bill; for inventory, the database. Common practice: scheduled reconciliation—daily/hourly pull the payment platform's bill, match against orders. If money received but order still unpaid, mark paid; if order cancelled but money arrived (Pattern 3), issue refund.

Reconciliation is the last safety net: even if everything else fails, it finds and corrects. AI rarely considers this when writing business code.

Two common async scenarios

One: delayed task. Auto-cancel unpaid orders after 30 minutes and restore stock. Use MQ delayed messages or a scheduled task scanning the table. Either way, include the status condition:

UPDATE orders SET status = 'CANCELLED'
WHERE id = ? AND status = 'UNPAID';

Because at minute 30, the user might be paying; cancellation and payment callback arrive simultaneously. Both use "only change from UNPAID"; first wins, second affects 0 rows—no order both cancelled and paid.

Two: long-running task like exporting all orders. Don't keep the request open until done; return a task ID immediately, generate in background, frontend polls progress, then download. Polling and progress bars are familiar frontend; here's the backend half.

When you don't need it: no peak shaving, small volume—a scheduled task scanning a table can do async and retries (e.g., "pending SMS" table, task every few seconds). MQ adds deployment, monitoring, and new problems (pile-up, loss).

Verification: Stop the SMS service; check if you can still place an order. Restart SMS; check if the messages are sent later.

One-sentence principle: Users should only wait for the steps that must happen immediately.

Pattern 9: Rate Limiting—What If Traffic Exceeds Capacity?

Frontend knows debounce/throttle: scroll event fires dozens/sec; throttle to once per 100ms to avoid jank.

Backend rate limiting is like throttling all users' requests together.

v1's order API has no limits. A script hitting thousands/sec will exhaust DB connections; normal users queue and time out. One person's script blocks everyone.

Why rate limit

System capacity has an upper bound; exceeding it doesn't mean "slower," it means "everything crashes."

Idea: reject some requests rather than crashing all. Like a scenic area limiting entry during holidays: disappointed visitors are better than a stampede.

What to limit by

Dimensions:

Also distinguish single-instance vs. distributed limiting. Single-instance: each machine counts its own; with 3 machines each capping 100, total 300—adding a machine changes total. For exact global cap, use Redis to count centrally (INCR from Pattern 7).

Where does the threshold come from

"Max 500/sec" isn't a guess.

Load test: use JMeter to gradually increase load on the endpoint; watch QPS (requests/sec) at which response time degrades or error rate rises. That inflection is the capacity; set threshold with headroom. Before a big sale, estimate expected traffic multiple.

Common algorithms

Don't write from scratch; understand differences:

Algorithm How it works Characteristic
Fixed window Counter per second; reject over Simplest; at window boundary, may allow 2x in an instant
Sliding window Count "last 1 second" Smoother; slightly more complex
Token bucket Tokens added at fixed rate; a request needs a token Allows bursts
Leaky bucket Requests queue, out at fixed rate Smoothest; bursts queue or drop

Frontend cooperation after being limited

Return HTTP 429 (Too Many Requests), optionally with Retry-After header.

Frontend: show friendly "High traffic, please try later," not "system error." Don't auto-retry immediately on 429—everyone retrying makes it worse; wait, ideally with random jitter to spread retries.

When you don't need it: internal admin, tiny systems—basic limiting at gateway/Nginx (Nginx limit_req) is enough; no need for per-user/per-endpoint fine-grained limiting in code.

Verification: Use a load tool to send requests above threshold; check for 429. Also open another page to confirm other endpoints still work.

One-sentence principle: System capacity is finite; reject excess deliberately.

Series: From 100 to 100,000 users—When to Add Each

This part connects index, cache, async, rate limiting. See when each is needed as user base grows.

Flash sale flow:

  1. Gateway rate limiting to block excess.
  2. Redis pre-deduct stock using DECR (fast, in memory); if it fails, return "sold out."
  3. On success, send a message to MQ; tell user "queuing."
  4. Backend services consume at DB-safe pace, create orders slowly.

Flash sale chain

Unavoidable issue: Redis stock vs DB stock diverge. Principle: DB is source of truth. If order creation fails, add stock back to Redis. Also scheduled reconciliation task.

Finally, before adding each layer, ask: is the current bottleneck really here? Many slow systems are slow due to a missing index, not lack of MQ.

v2: What Changed in This Round

After Part 2's 4 patterns:

Change Pattern
Composite index (user_id, create_time) on orders; keyset pagination; batch query for items 6
Redis cache for product detail; change price: update DB then delete cache 7
SMS, points, warehouse become async messages; consumers idempotent; auto-cancel after 30 min unpaid 8
Order API rate-limited per user and globally; return 429 9

Now traffic holds up.

Part 3: Catch Problems

Imagine being woken at 2 AM—users report order failures.

v2 handles traffic, but production issues aren't just "many people." Dependencies fail, new versions deploy, and code always has blind spots. This part: problems will happen; can the system catch them, and can you find them?

The 2 AM scenario returns in Pattern 11.

Pattern 10: Fault Tolerance—What If a Dependency Goes Down?

Frontend handles API failures: fallback messages, Error Boundary wrapping components so one component's error doesn't blank the whole page.

Backend also calls others: payment, SMS, logistics, other teams' services. They fail, they slow. Difference: a frontend page error affects one user; a backend dependency hang can bring down the whole service.

Example: after ordering, user clicks "go pay"; backend calls payment platform to create payment:

RestTemplate rest = new RestTemplate();      // 没设超时
PayResult r = rest.postForObject(payUrl, payReq, PayResult.class);

One day the payment platform has issues; no error, just never returns. Every "go pay" request holds a thread idle. Tomcat defaults 200 threads; quickly exhausted. Now even product detail (unrelated to payment) has no threads—the whole service appears down.

Timeout: set for every external call

RestTemplate defaults to no timeout—waits forever. Frontend same: axios timeout defaults to 0.

Set two timeouts: connect timeout (how long to give up connecting) and read timeout (connected but no response):

SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
f.setConnectTimeout(1000);   // 连接超时 1 秒
f.setReadTimeout(3000);      // 读取超时 3 秒
RestTemplate rest = new RestTemplate(f);

How long? Look at how long the dependency typically takes, add headroom for slow periods. Also consider user: how many seconds will they wait? Beyond that, they're gone even if backend keeps waiting.

Retry: only for idempotent operations

After timeout/failure, retry is natural, but before retrying return to Pattern 3: does calling twice cause problems?

Query-type ops are safe. Creating a payment order—payment platforms usually dedupe by order ID, so retry creates the same payment. But "deduct money" or "issue coupon" without dedupe: first attempt may have succeeded but response lost; retry deducts twice.

Retry with backoff: immediate retry doubles load on an already struggling service. Exponential backoff: wait 1s, then 2s, then 4s; give up after a few. Beware retry storms: each layer retries 3 times; three layers deep, the bottom service gets 27x requests.

Circuit breaker: after too many failures, stop calling

From circuit breakers: too much current, fuse breaks, protects the circuit.

Same: if a dependency's failure rate exceeds a threshold in a window (e.g., 50% in 10s), "open" the circuit: subsequent calls fail fast without hitting it. Threads aren't wasted; dependency gets time to recover. After a while, allow a few trial requests; if they succeed, close the circuit.

Degradation: if non-core fails, turn it off

Same idea as Error Boundary: local failure shouldn't crash the whole.

E.g., product detail page has "you might also like" from a recommendation service. If that service fails, don't block the page; just hide that section or show a pre-set bestseller list.

Which features can degrade and what to show—agree with product beforehand, not at incident time. Same core/non-core classification as Pattern 8.

How one slow service drags down the chain

Back to the payment example: a slow payment platform exhausts threads; the service has none; upstream callers time out; cascades up. One slow dependency can take down the entire chain.

One slow dependency brings down the whole service

Timeout, circuit breaker, degradation keep failures local. Further: resource isolation—allocate separate thread pools to different dependencies; a recommendation service exhausting its threads doesn't affect order threads. Mature libraries exist; out of scope.

Verification: Stop a dependency, or add a sleep to a slow mock. Check two things: how fast does the order API return (within your timeout)? Do unrelated endpoints still work?

One-sentence principle: Every external dependency will fail; plan what to do when it does.

Pattern 11: Observability—Can You Find Problems?

Frontend debugging: open F12—Console has errors, Network shows request params and timing. Sentry collects errors and user actions.

Backend has no F12: online, no breakpoints, can't ask user to reproduce; only logs remain.

Back to 2 AM: open logs, see what this code leaves:

try {
    orderService.create(userId, req);
} catch (Exception e) {
    e.printStackTrace();               // 只往控制台打了一段堆栈
    return Result.fail("下单失败");
}

Logs have a stack trace but don't show which user, product, or order; can't tell if it's the same failure the user describes. Worse, if catch is empty, exception swallowed, no log line at all.

The observability triad

Backend relies on three things to "see" production:

What to log, what not to

First, log levels:

Log the info to reconstruct the scene: traceId, user ID, order number, key params, timing. Fix the previous snippet:

} catch (Exception e) {
    log.error("下单异常 userId={} productId={} requestId={}",
            userId, req.getProductId(), req.getRequestId(), e);  // 最后传入异常,堆栈才会被记下来
    throw e;                                                      // 交给全局异常处理
}

Note: Don't log sensitive info: passwords, tokens, ID numbers, full card numbers. Logs are seen by many, stored long; logging them is leaking.

traceId: connecting all logs of one request

An order request logs in filter, Controller, Service, and calls other services. Thousands of concurrent requests, logs interleaved—how to know which lines belong to one request?

Give each request a unique ID—traceId. Generated on entry, placed in log context (MDC in Java), automatically attached to every line. Pass it in headers when calling other services. Search by traceId to get the full journey.

Frontend can help: return traceId in response header; include it in error reports, or show in error message: "System busy, please retry (error id a1b2c3)." User sends a screenshot; you locate the exact request.

What user sees vs. what logs record

User-facing errors and logged errors are different things.

User needs to know what happened and what to do: "Insufficient stock" or "System busy, please retry." Full stack traces and SQL go only to logs—useless to users, useful to attackers.

Unified error codes plus a global exception handler:

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BizException.class)
    public Result handleBiz(BizException e) {
        return Result.fail(e.getCode(), e.getMessage());   // 业务异常:提示可以直接给用户看
    }
    @ExceptionHandler(Exception.class)
    public Result handleOther(Exception e) {
        log.error("未知异常", e);                           // 完整堆栈只进日志
        return Result.fail(500, "系统繁忙,请稍后再试");      // 用户只看到这一句
    }
}

Frontend gets a unified format like { code, message, traceId }.

Audit logs: AI almost never adds

Another log type: who changed what from old to new when. E.g., "Ops Zhang San changed product 1 price from 99 to 9.9 at 10:03 on 11/11."

Audit logs for price change, refund, permission changes, exporting user data. When problems occur, you can find the operator. Ask AI for a price-change API, it writes the logic but rarely adds audit logging.

Different from business logs: business logs for debugging, kept days to weeks, deleted later. Audit logs for accountability, kept long, immutable, stored separately.

Metrics and alerts: don't let users tell you

Logs are for after the fact; metrics/alerts for first notification.

Technical metrics: QPS, error rate, P99 latency (99% of requests under this time). Why not average? Because average hides slow requests: 99 requests 10ms, 1 request 10s—average 110ms, looks fine, but that 1% is furious.

Business metrics too: orders/minute suddenly drops to zero while QPS and error rate normal—likely something like payment callback not arriving. Technical metrics alone can't catch that.

Set thresholds; alert via group/phone. The 2 AM call should be from an alert, not a user.

Verification: Take a failed request; look only at logs (no code, no breakpoints). Can you explain which step failed and why? If not, logs are insufficient.

One-sentence principle: No breakpoints in production; logs are your only scene.

Pattern 12: Release Compatibility—When Old and New Versions Run Simultaneously

If you've published npm packages, you know semantic versioning: breaking changes require a major version bump, warning users.

Backend APIs are the same, but without version numbers to protect you—change something, every caller is immediately affected.

Example: you think price field name is ambiguous, change to amount:

// 改之前
{ "orderNo": "202611110001", "price": 99.00 }
// 改之后
{ "orderNo": "202611110001", "amount": 99.00 }

Backend releases, new frontend fine, but old app reading price gets empty—order totals blank.

Why old and new coexist

Release isn't instantaneous. Old and new run simultaneously because:

Add only, never remove

APIs must be backward-compatible: add new fields, don't remove or change meaning.

Renaming needs a transition period: return both fields until old versions are negligible, then remove:

{ "orderNo": "202611110001", "price": 99.00, "amount": 99.00 }

Deploy order: backend first, then frontend

Backend releases first, compatible with both old and new frontends; then frontend releases to use new fields. Reverse order breaks the page (frontend uses new field, backend doesn't have it).

Database follows the same order:

  1. Add new column. Old code doesn't know it, unaffected.
  2. Deploy code using new column.
  3. After confirming no old code runs, drop old column.

From Pattern 1, adding columns to large tables can take long and affect online reads/writes. Do it during low traffic; test timing in a similar-size environment.

Graceful shutdown, canary, feature flags

During rolling publish, old processes must stop. If you kill directly, in-flight requests break. Graceful shutdown: stop accepting new requests, let current finish, then exit. Spring Boot old versions: server.shutdown=graceful; some new versions default on—check your version.

Further, canary: send new version to a small percentage of users (5%) or one machine, then full rollout after no issues. Similar to frontend A/B testing.

Feature flags: deploy new code behind a flag, off by default; turn on via config when ready; if issues, turn off without re-deploying.

Code easy to rollback, data hard

Code issue: redeploy previous version, minutes. Data: new code runs half a day, writes new-format data; old code after rollback can't read it. For data corruption, write fix scripts with code review, backup before execution.

Ultimately, only backups save you:

Verification: Use an old frontend to call the new API; see if the page works. During release, keep placing orders; see if any fail. Restore the latest backup in test environment; check data integrity.

One-sentence principle: Release is not an instant swap, but a period where old and new coexist.

Part 4: Hands-On—From Requirement, Build an Order Feature with AI

Now tie the 12 patterns together. From requirement, do the full order feature with AI.

Step 1: Ask Five Questions First

Before letting AI write code, experienced backend asks:

Question Determines
Data volume? Indexes, pagination, batch export (Pattern 6)
Concurrent users? Concurrency handling, cache, rate limiting (4,7,9)
Which data absolutely can't be wrong? Money/stock need transactions, idempotency, reconciliation (3,5,8)
External dependencies? Each needs timeout; plan for failure (8,10)
Who is affected by errors? Alert sensitivity, audit logs, canary (11,12)

AI won't ask these; answers shape the code. An internal procurement system vs. a flash-sale mall have completely different implementations.

Step 2: Design

Tables: orders, order_items, products (stock in this table), payment_transactions, plus local message table and points ledger. Order state machine from Pattern 1.

API design—frontend has a voice here:

Frontend/backend responsibility split:

Task Frontend does Backend does
Param validation Yes, for UX, immediate feedback Yes, must repeat for security
Amount calculation Display only, can estimate Backend is source of truth
Permissions Hide buttons without permission Validate on every endpoint

Page interactions to coordinate:

Step 3: Write Constraints into the Prompt

Earlier prompt only said "what to do," not "what to watch out for," so AI wrote the simplest case.

Put findings into the prompt: "user ID from Token," "stock deduction with conditional update," "all external calls have timeouts." A full example in Appendix 1.

Two tips:

Step 4: Review Generated Code Against 12 Patterns

Take the checklist in Appendix 1. Or have AI self-check, but you confirm.

Most likely missed:

Step 5: You Define Test Cases; AI Writes the Tests

AI writes test code fast, but what to test is yours. If AI defines cases, it tests only normal flow or current behavior, not intended behavior.

Cases mapping to patterns:

Case Expected
Same request ID, send 5 concurrently Only 1 order (3)
Stock=1, send 100 concurrent orders Only 1 sold (4)
Use A's Token to query B's order 404, no data (2)
Throw exception during order creation Stock not deducted (5)
Make payment platform return in 5s API returns within timeout; other endpoints normal (10)

Once cases are set, unit/integration/concurrency test code can be AI-generated.

Step 6: Run Verification and Get v3

All tests pass → v3. Core code, with comments mapping to patterns:

Order API:

@RateLimit(perUser = 1, total = 500)   // 自定义注解:按用户、按接口限流,超出返回 429(思维 9)
@PostMapping("/order/create")
public Result<String> createOrder(@RequestBody @Valid OrderRequest req) {  // @Valid 校验数量 1~99(思维 2)
    Long userId = UserContext.getUserId();    // 用户从 Token 取(思维 2)
    try {
        return Result.ok(orderService.create(userId, req));
    } catch (DuplicateKeyException e) {       // 重复请求被唯一索引挡下,事务已回滚(思维 3、5)
        return Result.ok(orderService.findOrderNo(req.getRequestId()));  // 返回第一次的订单号
    }
}

Business logic:

@Transactional(rollbackFor = Exception.class)                    // 受检异常也回滚(思维 5)
public String create(Long userId, OrderRequest req) {
    int rows = productMapper.deductStock(req.getProductId(), req.getQuantity());  // 条件更新扣库存(思维 4)
    if (rows == 0) {
        throw new BizException("库存不足");
    }
    Product p = productMapper.selectById(req.getProductId());    // 价格读数据库,不读缓存(思维 2、7)
    Order order = Order.create(userId, req.getRequestId(), orderNoGenerator.next());  // 不连续的订单号(思维 1)
    order.setAmount(p.getPrice().multiply(BigDecimal.valueOf(req.getQuantity())));    // 用 BigDecimal 算金额(思维 1)
    orderMapper.insert(order);                                   // request_id 唯一索引兜底(思维 3)
    orderItemMapper.insert(OrderItem.snapshot(order, p, req.getQuantity()));  // 存下单时的商品名和单价(思维 1)
    outboxMapper.insert(Message.orderCreated(order));            // 本地消息表,和订单在同一个事务里(思维 8)
    log.info("下单成功 orderNo={} userId={}", order.getOrderNo(), userId);  // traceId 由 MDC 自动带上(思维 11)
    return order.getOrderNo();
}

Order detail:

@GetMapping("/order/{orderNo}")
public Result<OrderVO> getOrder(@PathVariable String orderNo) {
    Order order = orderMapper.selectByNoAndUser(orderNo, UserContext.getUserId());  // 校验归属(思维 2)
    if (order == null) {
        throw new BizException(404, "订单不存在");
    }
    return Result.ok(OrderVO.from(order));    // 只返回页面需要的字段,不直接返回整条记录
}

Payment callback (signature already verified in Controller, Pattern 2):

@Transactional(rollbackFor = Exception.class)
public void onPaid(PayNotify n) {
    if (payRecordMapper.insertIgnore(n) == 0) {      // 支付流水号唯一索引(思维 3)
        return;                                       // 重复通知,直接忽略
    }
    int rows = orderMapper.markPaid(n.getOrderNo(), n.getAmount());  // 只改待支付、金额一致的订单(思维 2、3)
    if (rows == 0) {
        log.warn("支付通知和订单对不上 orderNo={}", n.getOrderNo());  // 订单已取消或金额不符,等对账退款(思维 8)
    }
}

Points consumer:

@Transactional(rollbackFor = Exception.class)
public void onOrderCreated(OrderCreatedMsg msg) {     // 异步处理,不让用户等(思维 8)
    int rows = pointLogMapper.insertIgnore(msg.getOrderNo(), "ORDER_REWARD");  // (订单号, 类型) 唯一索引
    if (rows == 0) {
        return;                                       // 重复消息,不重复加积分(思维 3、8)
    }
    pointMapper.add(msg.getUserId(), 10);
}

Key SQL and indexes:

-- 扣库存(思维 4)
UPDATE product SET stock = stock - ? WHERE id = ? AND stock >= ?;

-- 支付成功(思维 2、3)
UPDATE orders SET status = 'PAID'
WHERE order_no = ? AND status = 'UNPAID' AND amount = ?;

-- 索引(思维 3、6)
ALTER TABLE orders ADD UNIQUE KEY uk_request_id (request_id);
ALTER TABLE orders ADD UNIQUE KEY uk_order_no (order_no);
CREATE INDEX idx_user_time ON orders (user_id, create_time);
ALTER TABLE pay_record ADD UNIQUE KEY uk_trade_no (trade_no);
ALTER TABLE point_log ADD UNIQUE KEY uk_order_type (order_no, type);

Other parts not in these snippets but part of v3: timeouts for external calls (Pattern 10), product detail cache (7), traceId filter and global exception handler (11), audit logs on price change (11), graceful shutdown and DB backups (12).

Note: v3 is the monolithic pattern: stock deduction and order creation in one DB, one transaction. Larger projects are more complex: inventory may be a separate service with its own DB, using "reserve on order, confirm on payment, release on timeout"; order pricing includes promotions and coupons via a pricing service. But the ideas remain: idempotency, status conditions, compensation on failure.

Finally, compare v0 vs v3:

Problem v0 v3
1. Data modeling Only product ID; price computed live Items store product name/price at purchase; DECIMAL; external order no
2. Security User ID from frontend; no ownership check User ID from Token; ownership check; quantity 1–99; payment callback signature
3. Idempotency None Unique indexes on request ID and payment transaction; status condition
4. Concurrency Check-then-modify Conditional update for stock
5. Transaction None Stock, order, message in one transaction
6. Database No indexes Composite index; keyset pagination; batch query for items
7. Cache None Product detail cache; update DB then delete cache
8. Async Sync SMS/points Local message table + MQ; consumers idempotent
9. Rate limiting None Per-user and per-endpoint; return 429
10. Fault tolerance No timeouts Timeouts; retry only idempotent; degrade non-core
11. Observability Only printStackTrace traceId; logs with business params; global exception handler; audit logs
12. Release compatibility Change fields at will Add-only API; graceful shutdown; regular backups

v0 is AI-written in seconds; most of v3 is also AI-written. The difference is these 12 patterns.

Summary: From "Code Writer" to "Person Responsible for Code"

Looking back, many of these patterns already exist in frontend—just different context:

You already know in frontend Transfers to backend
State structure can be refactored Table structure designed for future changes (1)
Form validation, button permissions Backend validation is security (2)
Button disabled to prevent double-click Idempotency (3)
Search box request races Concurrency (4)
Promise.all failures don't rollback Transactions (5)
Map vs. array traversal Indexes (6)
HTTP cache, SWR Cache and consistency (7)
Web Worker, non-blocking main thread Async and MQ (8)
Debounce/throttle Rate limiting (9)
Error Boundary, fallback data Timeout, circuit breaker, degradation (10)
console, Sentry Logs, metrics, tracing (11)
npm semantic versioning API compatibility and release order (12)

Your frontend experience isn't wasted; the context changes: from "one user in front of me" to "all users simultaneously," from "refresh fixes it" to "data stored for years," from "open F12" to "only logs."

With AI, frontend devs can write backend code now. Java and Spring can be learned on the go—enough to read and modify. The hard part is taking responsibility for that code: being able to explain what happens with duplicate requests, simultaneous access, half-failures, traffic spikes, and old/new versions coexisting. Shifting from code writer to code responsible—that's the real lesson for frontend-to-full-stack.

Final learning path, by "who is responsible":

That's it. If useful, save it; next time AI writes backend code, go through the checklist below. If something is wrong or you have a better approach, feel free to point it out.

Comments

Top 2 of 3 from juejin.cn, machine-translated. The original thread is authoritative.

神小渣

Full-stack is fine, but I don't want to write Java (crying). Which of Node, Go, Rust isn't better than Java?

天天鸭

So what you learn is the thinking and considerations, which are useful no matter what backend you write.

小小程序元

The article is very long.