跪拜 Guibai
← Back to the summary

Designing Production-Grade Open APIs: From Contract to Rate Limiting, With Every Pitfall Addressed

Last week I helped a friend with a mock interview and was asked a classic scenario question: "If you were to design a set of open API interfaces from scratch, how would you do it?"

This question is almost a must-ask for backend interviews at big companies, but most people answer poorly—either they immediately start stacking @PostMapping, or they recite RESTful boilerplate and stop there. I've built two open platforms from scratch in real projects and rescued many "naked APIs." This article breaks down the complete answer: from design principles and contract specifications to security, idempotency, rate limiting, and observability, each point backed by production-ready code.

Whether you're preparing for an interview or actually need to build an API for your team, this guide is directly usable.

1. Don't rush to write code: four things before you start

In real development, we often see a situation: requirements arrive, open IDEA and just code. The interface ends up with the frontend saying fields are wrong, security saying no auth, operations saying no monitoring—three rounds of rework.

So the first thing is to clarify the scenario. I ask four questions:

  1. Who calls it? Internal services, frontend, or third-party open platform? This directly determines the security level.
  2. Concurrency scale? Is QPS 100 or 100k? Determines whether you need gateway rate limiting, caching, async.
  3. Consistency requirements? Can you tolerate duplicate orders or under-deducted inventory? Determines how far idempotency goes.
  4. Iteration pace? Will the interface change frequently? Determines versioning strategy and compatibility.

If these four points are not clarified before starting, you'll likely rework. In interviews too—clarifying first is a plus, jumping straight to Controller is a minus.

Based on these four questions, I set five design iron rules that all subsequent solutions revolve around:

2. One picture: how many gates a request passes

API design is not writing one endpoint, but covering the full lifecycle of "access → business → governance → operations." A request from client to database must pass through these gates:

image.png

Layer responsibilities:

Architecture Layer Core Responsibility Key Technical Points
Access layer (gateway) Traffic entry, unified control HTTPS, route forwarding, identity auth, global rate limiting, black/white list, gray release
Business layer (service) Business logic, API semantics RESTful norms, unified response envelope, parameter validation, idempotency control, exception handling
Governance layer Stability assurance Rate limiting and circuit breaking, degradation fallback, trace tracing, metrics monitoring
Delivery layer Integration and maintenance OpenAPI docs, SDK, version management, error code norms, change notifications

One-sentence principle: what can go on the gateway don't put in business; what can be blocked at the entry don't hit the database.

Below we break down each layer.

3. Contract design: what the API "looks like," set rules first

The contract is the first face the caller sees; this layer determines whether the API is "easy to use."

3.1 RESTful resource modeling, with one pragmatic exception

Core rules are just a few:

Using orders as an example:

Action Method URL Idempotent
Create order POST /api/v1/orders No, relies on requestId for idempotency
Query order GET /api/v1/orders/{id} Yes
Paginated query GET /api/v1/orders?pageNo=1&pageSize=20 Yes
Cancel order POST /api/v1/orders/{id}/cancel Yes (guaranteed by state machine)
Modify remark PATCH /api/v1/orders/{id} No

I've seen too many anti-patterns:

# ❌ Verb in path, inconsistent naming style
POST /api/v1/getUserInfo
POST /api/v1/createOrder
GET  /api/v1/DeleteUser

💡 Pragmatism beats dogma: pure RESTful gets awkward in complex scenarios. For "actions" like cancel order or payment, using /orders/{id}/cancel is clearer; for complex conditional scenarios like batch queries or exports, degrading to POST /api/v1/orders/batch-query is fine—it also avoids GET parameter length issues.

HTTP method semantics, also commonly tested in interviews:

Method Semantics Idempotent Safe Typical status codes
GET Query resource ✅ ✅ 200 / 404
POST Create resource ❌ ❌ 201 / 409
PUT Full update ✅ ❌ 200 / 412
PATCH Partial update ❌ ❌ 200
DELETE Delete resource ✅ ❌ 204 / 404

3.2 Unified response body: the design frontend developers thank you for

All interfaces return exactly the same format; callers use one parsing logic for everything:

{
  "code": 0,
  "message": "success",
  "data": { "orderId": "1001", "status": "CREATED" },
  "traceId": "a1b2c3d4",
  "timestamp": 1717888888888
}

Java implementation with generics + static factory methods keeps business code minimal:

/**
 * Unified response body
 * Highlights: code is a business code (decoupled from HTTP status), traceId returned with response, a debugging tool
 */
@Data
public class Result<T> {
    private int code;        // business status code
    private String message;  // human-readable message
    private T data;          // business data, null on failure, no ambiguous bare null
    private long timestamp;  // helps time-sequence debugging
    private String traceId;  // 🔥 full-link trace ID

    public static <T> Result<T> ok(T data) {
        return build(ErrorCode.SUCCESS, data);
    }

    public static <T> Result<T> fail(ErrorCode ec) {
        return build(ec, null);
    }

    private static <T> Result<T> build(ErrorCode ec, T data) {
        Result<T> r = new Result<>();
        r.code = ec.getCode();
        r.message = ec.getMsg();
        r.data = data;
        r.timestamp = System.currentTimeMillis();
        r.traceId = MDC.get("traceId");   // from log context, aligned with trace
        return r;
    }
}

Error codes should be segmented, not randomly numbered; the first segment tells you which layer the problem is in:

Range Meaning Example
0 Success SUCCESS
1xxxx Parameter/validation 10001 missing parameter, 10002 duplicate request
2xxxx Permission/security 20001 not logged in, 20002 no permission
3xxxx Business 30001 insufficient inventory
4xxxx System/third-party 40001 system busy, 40002 RPC timeout

Segmenting by module (2xxxx users, 3xxxx orders) or using Alibaba-style A0400/B0500 prefixes also works; the team just needs to be consistent. The core is business codes decoupled from HTTP status codes, each code documented.

💡 Two-layer response code design: HTTP status code expresses transport-layer semantics (200/401/429/500) for gateways and infrastructure; the body's code expresses business semantics for precise caller handling.

3.3 Pagination: cursor pagination, avoid deep-page pitfall

All list interfaces must enforce pagination, with size <= 100 as the upper limit, and no unlimited table queries without LIMIT. But normal pagination has a classic pitfall:

-- ❌ Deep pagination: LIMIT 100000, 20, database must scan and discard first 100k rows
-- ✅ Cursor pagination: use the last row's id as cursor
SELECT * FROM orders
WHERE user_id = ?
  AND id < ?        -- cursor: id of last row in previous page
ORDER BY id DESC
LIMIT 20;

Cursor pagination has no OFFSET; with an index it's a range scan, the performance difference is night and day. Use it for infinite scroll in consumer apps.

3.4 Parameter validation: the first business firewall

Validation principles: dirty parameters must never pass through to Service and hit the database. Implementation:

@Data
public class CreateOrderReq {
    @NotNull(message = "User ID cannot be empty")
    private Long userId;

    @NotBlank(message = "SKU code cannot be empty")
    private String skuCode;

    @Min(value = 1, message = "Purchase quantity must be at least 1")
    @Max(value = 999, message = "Single purchase cannot exceed 999")
    private Integer count;

    @NotBlank(message = "Idempotency token cannot be empty")
    private String requestId;   // 👈 key for idempotency/anti-duplicate, detailed later
}

Group validation is also useful: create doesn't validate id, update requires id; one DTO for two scenarios:

@PostMapping("/users")
public Result<Long> create(@RequestBody @Validated(CreateGroup.class) UserCreateReq req) { ... }

@PutMapping("/users/{id}")
public Result<Void> update(@PathVariable Long id,
        @RequestBody @Validated(UpdateGroup.class) UserUpdateReq req) { ... }

Keep Controller thin, business logic in Service:

@RestController
@RequestMapping("/api/v1/orders")
@Validated
public class OrderController {

    @Resource
    private OrderService orderService;

    @PostMapping
    @Idempotent(key = "#req.requestId", expire = 30)
    public Result<OrderVO> createOrder(
            @RequestHeader("X-Request-Id") String requestId,
            @Valid @RequestBody CreateOrderReq req) {
        return Result.ok(orderService.createOrder(req, requestId));
    }

    @GetMapping("/{id}")
    public Result<OrderVO> detail(@PathVariable Long id) {
        return Result.ok(orderService.detail(id));
    }
}

3.5 Global exception handling: never throw stack traces at the frontend

All exceptions converge to one response format, and they should be layered:

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /** Parameter validation exception: pinpoints the field, frontend can highlight directly */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValid(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldErrors().stream()
                .map(f -> f.getField() + ": " + f.getDefaultMessage())
                .collect(Collectors.joining("; "));
        log.warn("Parameter validation failed msg={}", msg);
        return Result.fail(ErrorCode.PARAM_ERROR.withMsg(msg));
    }

    /** Business exception: predictable, WARN level, no error stack polluting alerts */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBiz(BusinessException e) {
        log.warn("Business exception traceId={} code={}", MDC.get("traceId"), e.getCode());
        return Result.fail(e.getErrorCode());
    }

    /** Catch-all exception: stack goes to logs only, external response gives traceId only */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleUnknown(Exception e, HttpServletRequest req) {
        String traceId = MDC.get("traceId");
        log.error("System exception uri={} traceId={}", req.getRequestURI(), traceId, e);
        return Result.fail(ErrorCode.SYSTEM_ERROR.withMsg("System busy, please retry later[" + traceId + "]"));
    }
}

⚠️ This is a security red line: returning stack traces to callers in production hands your architecture and dependency versions to attackers on a plate. Stack traces go to logs only; the outside world always gets "system busy + traceId." A user sends you an ID, you look up the full trace log, done.

People who handle parameter/business/system exceptions separately show the interviewer they've done real on-call debugging.

4. Security design: don't just say "add HTTPS"

Many think HTTPS is enough. HTTPS only solves transport-layer eavesdropping; parameter tampering, identity forgery, and replay attacks at the application layer, it handles none of them. Remember:

🔐 Encryption ≠ anti-tamper, signature ≠ secrecy. Encryption only prevents "seeing"; signatures prevent "modifying"; replay protection prevents "sending twice."

My approach is a four-layer defense, progressively: HTTPS transport encryption → JWT/OAuth2 identity authentication → parameter signature anti-tamper → timestamp + nonce anti-replay.

4.1 Full chain of signature + replay prevention

Issue each partner an AppKey + AppSecret; callers sort parameters lexicographically and concatenate, along with timestamp, nonce, and a request-body digest, then compute an HMAC-SHA256 signature:

image.png

Core signature utility code:

public final class SignatureUtil {

    /** 1. Concatenate parameters in lexicographic order: k1=v1&k2=v2 (empty values and sign itself excluded) */
    public static String buildSignContent(Map<String, String> params) {
        return params.entrySet().stream()
                .filter(e -> StringUtils.hasText(e.getValue()) && !"sign".equals(e.getKey()))
                .sorted(Map.Entry.comparingByKey())
                .map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining("&"));
    }

    /** 2. HMAC-SHA256 signature (more resistant to length extension attacks than MD5) */
    public static String sign(String content, String secret) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            return Hex.encodeHexString(mac.doFinal(content.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SIGN_ERROR);
        }
    }

    /** 3. Constant-time comparison, prevents timing attacks ⭐ */
    public static boolean safeEquals(String a, String b) {
        return MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8),
                                     b.getBytes(StandardCharsets.UTF_8));
    }
}

Server-side verification, order matters: identity → freshness → replay → signature, so failures are easy to locate:

public boolean verify(SignRequest req) {
    // ① Is appKey valid
    String secret = appKeyRepo.getSecret(req.getAppKey());
    if (secret == null) throw new BusinessException(ErrorCode.APP_KEY_INVALID);

    // ② Is timestamp within valid window (±5 minutes), prevents stale replay
    long diff = Math.abs(System.currentTimeMillis() - req.getTimestamp());
    if (diff > 5 * 60 * 1000) throw new BusinessException(ErrorCode.REQUEST_EXPIRED);

    // ③ nonce one-time: Redis SETNX atomic placeholder, same packet only usable once
    String nonceKey = "sign:nonce:" + req.getAppKey() + ":" + req.getNonce();
    Boolean first = redis.opsForValue().setIfAbsent(nonceKey, "1", Duration.ofMinutes(6));
    if (Boolean.FALSE.equals(first)) throw new BusinessException(ErrorCode.REPLAY_ATTACK);

    // ④ Rebuild signature by same rules and compare (signature material includes body digest, prevents body tampering)
    String raw = buildSignContent(req.getParams()) + req.getTimestamp() + req.getNonce()
            + DigestUtils.sha256Hex(req.getBody());
    String expect = SignatureUtil.sign(raw, secret);
    if (!SignatureUtil.safeEquals(expect, req.getSign())) {
        throw new BusinessException(ErrorCode.SIGN_MISMATCH);
    }
    return true;
}

Several easy-to-miss details of high value:

⭐ Technical highlight one: MessageDigest.isEqual for constant-time comparison. Normal equals short-circuits character by character; attackers can infer the signature byte-by-byte from response timing—this is a timing attack. Constant-time comparison closes that path.

⭐ Technical highlight two: nonce must be stored in Redis; verifying signature without checking nonce means no replay protection. Even if the signature is correct, an attacker can replay a captured legitimate request ten thousand times and break you.

⭐ Technical highlight three: don't concatenate the entire large request body into the signature string; CPU spikes. Compute a SHA-256 digest of the body and include that in the signature.

⭐ Technical highlight four: nonce's SETNX is atomic; if you insist on EXISTS + SETEX as two steps, wrap them in a Lua script, otherwise two identical nonces can both pass under concurrency—a classic check-then-act race.

4.2 Other must-answer security points

Risk Solution Key point
Unauthorized access (IDOR) Check data ownership on every query Don't trust the userId from frontend; take from login state and verify owner
SQL injection MyBatis #{}, forbid ${} Code review checkpoint
Sensitive data leakage Mask phone/ID card/bank card Mask in both responses and logs
Malicious request flooding Gateway rate limiting + captcha + IP blacklist Distinguish normal user limiting from malicious attacks
Key security AppSecret managed by config center, rotate periodically No hardcoding, no fixed keys

Don't handle masking in scattered business code; it's easy to miss. Use a Jackson custom serializer + annotation, declarative:

@Sensitive(SensitiveType.PHONE)   // automatically becomes 138****5678 when serialized
private String phone;

5. Idempotency design: where this question separates candidates

Here the "easy" parts end; this is the "does it collapse" part. Idempotency is critical, and interviewers love to dig here.

First clarify a common misconception: Idempotency ≠ concurrency control. Concurrency control handles "simultaneous changes"; idempotency handles "multiple changes." The essence of idempotency: the same request executed once or 100 times leaves the system state exactly the same. Like an elevator button—you press it 10 times, one elevator comes.

Where do duplicate requests come from? Must answer completely:

Consequences of no idempotency: duplicate orders, duplicate charges, duplicate coupons—every one is a P0 incident.

5.1 How to choose among five approaches

Solution Applicable scenario Advantage Pitfall
🥇 Unique index Creation (orders, payment ledger) Simplest, database backstop is most reliable Depends on business unique key (e.g., biz_no)
🥈 Token pre-claim Frontend duplicate prevention Get token before submit, naturally one-time Requires an extra request
🥉 State machine + optimistic lock Updates (order flow) Conditional UPDATE naturally idempotent, most stable Requires careful state transition design
Redis SETNX / Lua General High performance, can be annotation-based and zero-invasive Watch for failure release, atomicity
Distributed lock General fallback Flexible Watch lock granularity, timeout, reentrancy

My standard combo in practice: Redis front-line interception + database unique index as backstop, double insurance. If Redis dies, the unique index still covers.

5.2 Annotation-based idempotency: AOP + Redis Lua (production-grade implementation)

Writing idempotency logic by hand for each endpoint is foolish; wrap it in an annotation, zero intrusion on business code:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Idempotent {
    String key();                   // idempotency key, supports SpEL: #req.requestId
    long expire() default 30;       // token validity (seconds)
    String message() default "Request is being processed, please do not submit repeatedly";
}

Aspect implementation uses a Lua script to guarantee atomicity and distinguishes "processing" and "done" states:

@Aspect
@Component
@RequiredArgsConstructor
public class IdempotentAspect {

    private final StringRedisTemplate redis;

    // ✅ Lua guarantees atomic "check + place", eliminating check-then-act race
    private static final DefaultRedisScript<Long> SCRIPT = new DefaultRedisScript<>("""
        local v = redis.call('GET', KEYS[1])
        if v == 'PROC' then return -1 end          -- processing
        if v == 'DONE' then return -2 end          -- done
        redis.call('SET', KEYS[1], 'PROC', 'EX', ARGV[1])
        return 1
        """, Long.class);

    @Around("@annotation(idem)")
    public Object around(ProceedingJoinPoint pjp, Idempotent idem) throws Throwable {
        String key = "idem:" + SpelParser.parse(idem.key(), pjp);
        Long r = redis.execute(SCRIPT, List.of(key), String.valueOf(idem.expire()));

        if (r == -1) throw new BusinessException(ErrorCode.REPEAT_PROCESSING, idem.message());
        if (r == -2) return Result.ok(null);   // 🎯 idempotent success: return directly, don't re-execute

        try {
            Object ret = pjp.proceed();
            redis.opsForValue().set(key, "DONE", idem.expire(), TimeUnit.SECONDS);
            return ret;
        } catch (Throwable t) {
            redis.delete(key);   // ⚠️ must release on failure, otherwise interface permanently blocked
            throw t;
        }
    }
}

Usage with one annotation:

@PostMapping("/pay")
@Idempotent(key = "#req.orderNo", expire = 60)
public Result<PayVO> pay(@Valid @RequestBody PayReq req) { ... }

⭐ These three points win the interview: ① Use Lua to guarantee atomic "check + place"; ② Distinguish "processing" and "done" states; ③ Delete the key on exception—this is a real pitfall I hit: after the first request fails, the key remains, and the user's corrected retry is always rejected; the endpoint is effectively dead.

💡 Further UX optimization: cache the full response in the key after success; duplicate requests return the first result. A user clicking order repeatedly gets the same order number instead of a cold "please don't submit repeatedly."

5.3 State-transition scenarios: state machine + optimistic lock

For update-type interfaces (order payment, cancellation), the most stable approach is merging "check state" and "update" into a single conditional SQL:

-- Only transition from 'UNPAID' to 'PAID' when current state is 'UNPAID'
UPDATE orders
SET status = 'PAID', update_time = NOW(), version = version + 1
WHERE id = #{id} AND status = 'UNPAID' AND version = #{version};

-- Affected rows = 0: state already changed (duplicate or illegal request), return directly, don't re-ship

Database guarantees atomicity, handles concurrency naturally, much safer than "check then update."

5.4 Frontend anti-duplicate: Token pre-claim

One variant frequently asked: obtain a one-time token when entering the form page:

image.png

Why use DEL instead of GET + DELETE? One line of Lua does atomic check-and-delete, saving even a distributed lock. Use the right data structure; write ten lines less business code.

Finally, clarify the concept: anti-duplicate submission is about reducing duplicate requests in advance; idempotency is about guaranteeing consistent results after the fact. Use them together, not as either/or.

6. Rate limiting and degradation: keeping the API alive is the real principle

A public API without rate limiting is like leaving your front door key hanging outside.

6.1 Distributed rate limiting: Redis + Lua token bucket

For single-machine limiting, Guava RateLimiter is enough; for cluster environments, use Redis + Lua. The token bucket's benefit is smooth limiting with some allowed bursts:

-- KEYS[1]=bucket key  ARGV: rate(per second), capacity, now(ms), requested
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or tonumber(ARGV[2])
local ts     = tonumber(b[2]) or ARGV[3]
local now    = tonumber(ARGV[3])
tokens = math.min(ARGV[2], tokens + (now - ts) / 1000 * ARGV[1])  -- replenish tokens by elapsed time
if tokens < tonumber(ARGV[4]) then
    return 0                                    -- ⛔ not enough tokens
end
redis.call('HMSET', KEYS[1], 'tokens', tokens - ARGV[4], 'ts', now)
redis.call('EXPIRE', KEYS[1], 60)
return 1

All computation happens inside Redis, distributed and error-free. Same trick: wrap in @RateLimit(qps = 100) annotation + AOP, business code unaware.

6.2 Fixed window pitfall: boundary spike

When asked "why not fixed-window counting," draw a picture:

Fixed window defect (boundary spike):
        │← window1 →│← window2 →│
   100  │         │100  │
   requests│█ █ █ █ █│█ █ █ █ █│
────────┴─────────┴─────────┴──→ t
              ↑
        At window boundary: 200 requests may pass within 1 second! 💥
Sliding window: request timestamps recorded in ZSet; any 1-second count never exceeds limit ✅

Sliding window with Redis ZSet, all in Lua:

local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)   -- remove old records outside window
local count = redis.call('ZCARD', key)
if count < tonumber(ARGV[3]) then
    redis.call('ZADD', key, now, now .. '-' .. math.random())
    redis.call('PEXPIRE', key, window)
    return 1
end
return 0

6.3 Rate limiting dimensions and degradation fallback

Rate limiting should be layered: AppKey total → interface level → user level → IP level, returning HTTP 429 + Retry-After header when exceeded. Callers immediately know when to try again. Alert at 80% threshold, prepare for scaling.

Degradation and isolation also needed:

7. Performance design: fast as well as usable

Optimization point Approach
📄 Enforce pagination No unlimited table queries without LIMIT, size <= 100, deep pages switch to cursor pagination
🎯 Return on demand Support fields=id,name field trimming, don't return 50 fields every time
📦 Compress large lists Nginx gzip, response body reduced by 70%+
🚀 Caching Add Redis layered cache for high-frequency reads; watch for penetration, breakdown, avalanche
🖼️ Large files Use OSS direct upload, interface returns only URL
🔗 Batch interfaces POST /users/batch-get, avoid N loop calls
📤 Large data export Process in batches, avoid OOM; async export via file download

8. Compatibility and evolution: today's design shouldn't sabotage tomorrow

Once an API goes live, it's a "product" and a contract; it cannot be changed at will. Versioning options:

Option Example Assessment
URL path (recommended) /api/v1/users → /api/v2/users Most intuitive, easiest to route at gateway, easy log tracing
Header Accept: application/vnd.app.v2+json More "elegant," clean URL, common in open platforms, but harder to debug
Request parameter /users?version=2 Not recommended, easy to miss

Compatibility principles:

Principle Practice
🧷 Only add, never modify or delete Forbid changing field meaning/type, forbid deleting fields; new fields default to nullable
🔄 Version upgrade Minor additions go in v1; breaking changes bump to v2
⏳ Deprecation period Keep old version for at least 3-6 months (at least one quarter); add Deprecation and Sunset headers; announce early via email; monitor old version call volume
🎚 Gray release Gateway routes by AppKey or userId % 100 to new version, supports second-level rollback
🤝 Contract testing Before changing output, run consumer contract tests (e.g., Spring Cloud Contract)
📜 Enum fallback When adding enum values, old callers need fallback branches (else -> UNKNOWN)

Also a hidden trap: use VO for API output, don't return Entity directly.

// ❌ Anti-pattern: returns Entity directly; a new DB field breaks all interfaces, may leak internal fields
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) { ... }

// ✅ Correct approach: VO isolation + Swagger doc annotations
@Operation(summary = "Query user details")
@GetMapping("/api/v1/users/{id}")
public Result<UserVO> getUser(@PathVariable Long id) { ... }

9. Observability: locate problems fast when things break

API going live is just the start; whether you can quickly troubleshoot is the life-or-death line. Three pieces:

Don't neglect documentation: code as documentation, use SpringDoc/Knife4j annotations to auto-generate OpenAPI docs; interface changes update docs automatically, never out of sync. Notify changes in advance; do joint interface review + Mock testing before release. For external open platforms, also provide Java/Python SDKs that encapsulate signing, retry, and idempotency injection—integration takes ten lines, and stickiness naturally rises.

10. Two advanced scenarios to ace the interview

10.1 Interviewer asks: "How do you design a high-concurrency order placement?"

image.png

Core approach in five steps: gateway rate limiting blocks the first wave → Redis pre-deducts inventory to block most invalid requests → MQ async order creation to smooth the spike → database final write for consistency → user polls or queries to get the result. If asked about consistency further, discuss local message table / RocketMQ transactional messages / "state machine + active query + scheduled compensation" for third-party callbacks.

10.2 Interviewer asks: "Exporting a large report takes long; how to design the API?"

Never block synchronously. Return 202 Accepted immediately, with a taskId in the body; callers poll progress via /api/v1/tasks/{taskId}; if the caller has callback capability, support registering a webhook in advance and notify when the task completes. Great experience, no connection usage.

11. Technical difficulty quick-reference table

# Tech difficulty Typical symptom Solution Key points
1 Duplicate submission/idempotency Duplicate charges, duplicate orders, duplicate shipments Token/Lua idempotency + unique index backstop + state machine Lua guarantees atomicity; distinguish processing/done; must delete key on exception
2 Non-atomic idempotency check GET+SET broken through under high concurrency Redis Lua script or SET NX EX single command Eliminate check-then-act race
3 Request replay/tampering Legitimate requests captured and replayed, amounts modified HTTPS + HMAC-SHA256 signature + timestamp + nonce nonce must go to Redis; signature includes body digest; constant-time comparison
4 Vertical/horizontal unauthorized access User A reads user B's data Auth annotation + data ownership check Verify owner on every data query, don't trust frontend id
5 High-concurrency avalanche Flash sale/promotion interface broken, cascading downstream Gateway token bucket rate limiting + Sentinel circuit breaker degradation + thread pool isolation 429 + Retry-After; thresholds from load testing; core interfaces don't degrade
6 Rate limit spike Fixed window double-pass at boundary ZSet sliding window / token bucket Lua Hot key splitting + local short-window pre-occupancy
7 Timeout and retry storm Upstream jitters, retries amplify traffic and crush downstream Staggered timeouts + exponential backoff + jitter retry + circuit breaker Only retry idempotent interfaces
8 Transaction and idempotency consistency Store DB or delete idempotency key first? Idempotency key in same DB/transaction if possible; cross-DB "place first → business → final state mark", delete key on exception Key TTL must exceed max business processing time
9 Deep pagination/large result sets LIMIT 100000,20 drags down DB Cursor pagination + covering index; async export via file List interfaces forbid full return
10 Version incompatibility Changed fields break old clients URL versioning + only add never modify/delete + contract testing + gray release Keep old version during transition, monitor call volume
11 Sensitive data leakage Logs/responses expose phone numbers, ID cards Masking annotation serializer + VO isolation + global exception fallback Mask both responses and logs; never return stack traces
12 Data consistency Inventory deducted but order not created Local message table / RocketMQ transactional messages / eventual consistency Third-party callbacks use state machine + active query + scheduled compensation
13 Cross-service debugging difficulty Logs isolated, locating by guessing Unified traceId throughout (MDC + TTL + MQ header) + full logs + alerts Return traceId in response header to callers

Finally, a panoramic view of the defense system, tying together the core defense lines:

image.png

12. Interviewer high-frequency follow-ups (prepare in advance for bonus points)

Follow-up One-sentence answer
How do you choose GET vs POST? GET for queries/idempotent, POST for changes; GET is cacheable, URL appears in logs/CDN and has length limits (browser implementation, not protocol), never put sensitive parameters in GET
Use HTTP status code or business code? Two layers: HTTP expresses transport semantics (200/401/429/500), body's code expresses business semantics, making gateway processing uniform
API timed out, was the money deducted? Timeout ≠ failure. Use a unique business serial number for idempotency, allow callers to safely retry; also provide a reconciliation query interface as fallback
How to guarantee message/request order? Design business to be order-independent where possible; if order matters, route by bizId to same partition/serial queue
Idempotency key expired but business not finished? Set key TTL greater than max business processing time; for long-running business use "processing" state + async polling result interface
Caller insists on generating their own idempotency key, how to avoid conflicts? Force an AppKey tenant prefix, e.g., app_123:order_submit:xxx, isolating tenants against forgery and collision, while limiting total key length
Sudden 10x traffic? Rate limiting + circuit breaker + degradation (return fallback/cached data) + MQ async smoothing + elastic scaling
How to choose rate limiting algorithm? Single machine: Guava RateLimiter; distributed: Redis + token bucket Lua; for absolute smoothness: ZSet sliding window
Difference between idempotency and anti-duplicate? Anti-duplicate reduces duplicate requests in advance; idempotency guarantees consistent results after the fact; use both together
REST vs GraphQL? GraphQL for many internal aggregate queries and strong field trimming needs; REST for general CRUD is more hassle-free
gRPC vs REST? gRPC/Dubbo for high-throughput, strong contracts between internal services; REST + JSON for cross-team, cross-language, browser-friendly
How to troubleshoot slow API responses? traceId chain → SkyWalking to see which hop is slow → slow SQL / GC / lock contention elimination step by step

Closing: a quick memory card + three honest truths

Three minutes before the exam, glance at this six-character secret:

╔══════════════════════════════════════════════════════╗
║  API Design · Six-Word Secret                        ║
╠══════════════════════════════════════════════════════╣
║  契  → Contract first: OpenAPI documentation is code  ║
║  路  → Resource routing: RESTful plural nouns + /v1   ║
║  核  → Parameter check: DTO + @Valid, no dirty params ║
║  安  → Security: JWT + signature + encryption + anti-replay (four defenses) ║
║  幂  → Idempotency: Token / unique index / state machine ║
║  观  → Observability: TraceID + monitoring + version compatibility ║
╚══════════════════════════════════════════════════════╝

If this article helped you, click "like" and "wow," and follow my public account. This "Scenario Design" series will continue—distributed transactions, flash sale systems, short-link design are all queued.

Finally, three hard-earned honest truths:

  1. Good API design is essentially designing a reliable contract over an untrusted network—friendly to the outside, controllable on the inside;
  2. Idempotency must have a fallback and exception handling must release locks; any change must be backward-compatible—these two I earned through production incidents;
  3. Implementation advice: don't try to do everything at once; first integrate the unified response body + global exception + idempotency annotation trio into your project. It takes an evening and delivers immediate results.

Interaction time: How does your project handle API idempotency? Redis interception, unique index, or no plan and pure luck? Ever been burned by duplicate requests? Leave a comment and I'll reply to each.