api

API
Design

Building interfaces that are predictable, durable, and a joy to use. The contract between your system and the world.

The Gold Standard: Idempotency

An operation is idempotent if performing it multiple times has the same effect as performing it once.

// POST /payments (Not Idempotent by default)
// Header: Idempotency-Key: abc-123 (Server stores this to prevent double charges)
"In a distributed system, network timeouts are common. Clients WILL retry. If your API isn't idempotent, you will have duplicate data or double-spend errors."

REST vs GraphQL vs gRPC

REST

Standard & Cacheable

Uses HTTP verbs (GET, POST, etc). Best for public-facing APIs where caching is a priority.

GraphQL

Flexible & Precise

Client asks exactly for what it needs. Prevents over-fetching. Great for complex frontends.

gRPC

Fast & Internal

Protocol Buffers over HTTP/2. Extreme performance for internal microservice communication.

Versioning Strategies

Path Versioning
/api/v1/users

Visible, easy to debug, but changes the URL. The most common approach.

Header Versioning
X-API-Version: 2024-03-21

Cleaner URLs. Allows sophisticated "Date-based" versioning (like Stripe's API).

Pagination: Cursor vs Offset

Offset Pagination

`LIMIT 10 OFFSET 100`. Simple but slow on large datasets and unstable if data is added during scroll.

Cursor Pagination

`WHERE id > last_seen_id`. Scales infinitely and handles real-time data shifts perfectly.

Interview Case: Payment API

payments

"Design a system to prevent double-charging a user."

1.

The client generates a unique **request_id** (UUID) for the payment attempt.

2.

Server stores the status of the `request_id` in a database (e.g., "PENDING").

3.

If a duplicate `request_id` arrives, the server returns the existing result immediately without reprocessing.