Hmm, the user is asking for a doc-driven API style guide covering four specific areas: errors, pagination, timeouts, and idempotency. This suggests they're likely a backend engineer or technical lead designing API standards for their team or organization.
I should structure this as a practical, actionable guide rather than theoretical concepts. The user probably wants clear rules they can implement tomorrow. Since they mentioned "doc-driven," I'll emphasize consistency and machine-readable specs (like OpenAPI).
For errors, I'll focus on standardized formats and severity levels. Pagination needs cursor-based recommendations with real-world constraints. Timeouts should differentiate between network/load balancer vs. application layers. Idempotency requires both technical implementation (headers) and operational patterns (retry workflows).
I'll avoid diving into tangential topics like authentication or rate limiting unless mentioned. The examples must be concrete—maybe show JSON snippets for errors and pagination metadata. Should warn about common pitfalls too, like page number limits causing DB sprawl.
The tone should be authoritative but not academic. No need for lengthy introductions; just deliver the guide with clear sections and "must/should" directives.
Doc-Driven API Style Guide: Core Cross-Cutting Concerns
1. Philosophy & Principles
All APIs in the organization must adhere to these principles:
Documentation-Driven : API contracts (OpenAPI/Swagger) are the single source of truth. Implementation must match spec exactly.
Consistency First : Uniform patterns reduce cognitive load and integration bugs.
Predictability : Clients should be able to anticipate behavior across all endpoints.
Machine-Readable : All conventions must be representable in OpenAPI 3.0+ specifications.
2. Error Handling
2.1 Response Format
All error responses must follow this JSON structure:
json Copy code
{
"error": {
"code": "invalid_parameter",
"message": "Human-readable summary",
"details": [
{
"field": "email",
"issue": "must be a valid email address",
"suggestion": "user@example.com"
}
],
"request_id": "req_abc123",
"timestamp": "2024-01-15T10:30:00Z"
}
}
2.2 HTTP Status Codes
Use standard HTTP semantics:
Code Meaning When to Use 400 Bad Request Validation errors, malformed JSON, missing required fields 401 Unauthorized Missing/invalid authentication credentials 403 Forbidden Authenticated but lacks permission 404 Not Found Resource doesn't exist (don't leak existence info) 409 Conflict Business logic conflict (duplicate email, invalid state transition) 422 Unprocessable Entity Semantic errors (valid JSON but invalid business logic) 429 Too Many Requests Rate limiting 500 Internal Server Error Unexpected server failure (log full details, return generic message) 503 Service Unavailable Scheduled maintenance, dependency outage
2.3 Error Codes
Format : domain.category.specific (e.g., payment.insufficient_funds, user.not_found)
Registry : Maintain a central error_codes.md document mapping codes to:
HTTP status
Description
Retryable? (true/false)
Client-actionable? (true/false)
Never expose stack traces, SQL errors, or internal paths.
2.4 Validation Errors
For 400/422:
Include details array with field-level issues
Use JSON Schema reference paths (#/components/schemas/User/properties/email)
Omit details for non-field errors (e.g., "Invalid operation")
3. Pagination
3.1 Cursor-Based (Required for all list endpoints)
Never use offset-based pagination for new APIs.
Request Parameters
Parameter Type Required Description cursorstring no Opaque base64-encoded cursor from previous response limitint no Items per page (default: 50, max: 100)
Response Structure
json Copy code
{
"data": [...],
"pagination": {
"next_cursor": "eyJpZCI6MTIzfQ==",
"has_more": true,
"limit": 50
}
}
3.2 Rules
Cursors are opaque : Clients must not modify or infer structure
Stable ordering : Sort by id ASC (or creation timestamp) as tiebreaker
has_more is authoritative : Even if next_cursor is empty, has_more=false means end
Maximum limit : Enforce server-side cap (100 items default)
Empty pages : Return data: [], has_more: false when no results
3.3 Anti-Patterns to Avoid
yaml Copy code
# BAD: Offset-based
GET /users?offset=100&limit=20
# BAD: Page numbers
GET /users?page=3&size=20
# BAD: Client-provided sort fields (use fixed sort)
GET /users?sort_by=email # Security risk, inconsistent ordering
4. Timeouts & Retries
4.1 Timeout Definitions
Timeout Type Default Max Where Configured Purpose Connect timeout 2s 5s HTTP client/library TCP handshake/DNS resolution Read timeout 10s 30s HTTP client/library Waiting for response body API-level timeout 30s 120s API gateway/load balancer Total request processing time
4.2 Response Headers
Always include:
http Copy code
X-Timeout-Seconds: 30
X-Retry-After: 120 # Only on 429/503
4.3 Idempotency & Retries
For non-GET requests:
Client Requirements
Generate unique idempotency key (UUID v4+)
Send header: Idempotency-Key: <uuid>
Retry on : 429, 503, network timeouts, 5xx (except 501)
Do NOT retry on : 400, 401, 403, 404, 409, 422
Server Requirements
Store idempotency key + response for 24h (configurable)
Return original response for duplicate key (within key validity)
Key storage must be:
Fast (Redis/Memcached)
Size-limited (max request body hash or 1KB)
Hashed for privacy (SHA-256 of key)
Idempotency Key Scope
yaml Copy code
# Per-tenant + per-endpoint combination
scope: "tenant_id:user_id:endpoint_path"
# Example:
key = hash("acme_corp:/api/v1/users:POST")
5. Implementation Checklist
OpenAPI Spec Requirements
yaml Copy code
# Must include in every operation:
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/StandardResponse'
'400':
$ref: '#/components/responses/BadRequest'
'429':
$ref: '#/components/responses/RateLimited'
'5xx':
$ref: '#/components/responses/ServerError'
# Pagination
parameters:
- $ref: '#/components/parameters/PaginationCursor'
- $ref: '#/components/parameters/PaginationLimit'
# Idempotency
security:
- idempotencyKey: []
Server Middleware Stack Order
Rate limiting (by API key/IP)
Idempotency check
Timeout enforcement
Request validation (JSON schema)
Authentication/authorization
Business logic
Response formatting
6. Testing Requirements
Must Test:
Contract Testing:
Use Pact/Schemathesis to validate against OpenAPI spec
CI must fail on:
Missing required fields in success responses
Undocumented status codes
Response schema drift
7. Deprecation & Evolution
Versioning Strategy
URL versioning : /api/v1/resource
No breaking changes in minor versions
Deprecate via:
Deprecation: true header + Sunset: Tue, 31 Dec 2024 23:59:59 GMT
Document in API changelog with migration guide
90-day minimum deprecation period
Pagination Changes
If changing pagination strategy:
Support both old/new for 6 months
Send Warning: 299 - "Pagination scheme changing to cursor-based in v2"
Update OpenAPI spec with deprecated: true on old parameters
8. Client SDK Generation Rules
From OpenAPI spec, generate SDKs that:
Throw typed exceptions for each error.code
Expose pagination as iterable/generator pattern
Auto-retry on idempotent methods with configurable backoff
Include request ID in all exceptions
9. Monitoring & Alerting
Track per-endpoint :
Error rate by error.code (alert >1% for client errors, >0.1% for server)
P99 latency by endpoint (alert if >80% of timeout)
Idempotency key hit rate (should be near 0% for healthy clients)
Pagination: has_more=false but cursor still provided (client bug)
10. Documentation Requirements
Every endpoint must document:
✅ Idempotency: true/false/conditional
✅ Estimated response time (p50/p99)
✅ Pagination: cursor-based, default/max limit
✅ Retry guidance: which errors are safe to retry
✅ Timeout expectations
✅ Example: full request/response with cursor pagination
Approval Required : Any deviation from this guide must be:
Documented in api-exceptions.md with rationale
Reviewed by Architecture Board
Provisional (6-month review)
Questions? See:
error_codes/registry.yaml
standards/pagination.md
standards/timeouts.md
standards/idempotency.md
Last updated: 2024-01-15 | Next review: 2024-07-15
This document is machine-readable. Generate client SDKs from openapi/*.yaml only.