Lesson 3 of 9 · 25m
Errors, Validation, and Idempotency as Contract Behavior
Specify what failure means, how clients recover, and why retries must be safe before consumers discover the gaps in production.
A payment API once taught me this lesson with duplicate invoices: the client timed out, retried, and the server happily charged twice because nothing in the contract distinguished retry from intent. Teams spend weeks modeling successful payloads and almost no time modeling failure, even though integrations live or die by recovery behavior.
Validation is boundary enforcement
Document input constraints tightly enough that clients can prevalidate obvious mistakes, then enforce exactly what you document — a spec maximum of 100 with a server maximum of 50 is contract drift, not defense in depth:
CreateOrderRequest:
type: object
required: [customerId, items, idempotencyKey]
properties:
customerId: {type: string, format: uuid}
items: {type: array, minItems: 1, maxItems: 100, items: {$ref: '#/components/schemas/OrderItemInput'}}
idempotencyKey: {type: string, minLength: 8, maxLength: 128}Error status codes are semantics, not decoration
Use status codes consistently, and never use 200 with success: false; that habit destroys cache behavior, monitoring, generated client ergonomics, and human debugging:
400 invalid input | 401 unauthenticated | 403 forbidden | 404 absent/invisible
409 state conflict | 422 domain rejection | 429 budget exhausted | 500 server failureIf the operation failed, say so at the HTTP layer.
Retry safety belongs in the contract
Unsafe retries turn transient network failures into duplicate money movement, emails, provisioning jobs, and inventory reservations. Idempotency is often a header rather than a body field, with explicit retention and conflict behavior:
parameters:
- {name: Idempotency-Key, in: header, required: true, schema: {type: string, minLength: 8, maxLength: 128}}A common rule is: same key plus same request fingerprint returns the original result; same key plus different fingerprint returns 409.
Model asynchronous reality honestly
A 200 means complete. If work continues in the background, return 202 and expose status instead of hiding completion behind an informal boolean:
responses:
'202':
description: Export accepted for processing
content:
application/json: {schema: {$ref: '#/components/schemas/ExportJob'}}Consumers need to know whether to poll, wait for a webhook, or treat timeout as final.
Field notes
- Document retryability per error: validation failures are not retryable; some 409s are; most 5xx are, but side effects may still exist.
- Never put secrets or sensitive personal data in error details. Logs leak farther than databases.
- Timeouts are ambiguous outcomes. Design reads or idempotency so clients can recover the truth.
- Rate-limit responses should include enough metadata for disciplined clients to back off correctly.
Was this lesson helpful?