A technical design for a web API in C is a written plan that fixes the API's contract, the C data structures behind it, memory ownership, error mapping, and the operational envelope before code is written. The key condition is alignment: reviewers must agree on the exact HTTP surface and the exact C types it maps to, because in C those two things are easy to let drift. The document does not need to be long, but it needs to be specific enough that a second engineer could implement the same endpoints without asking what a NULL return means or who frees a request buffer. The steps below walk through producing that document in order, from scoping through sign-off, with the checks that tell you each step succeeded.
Step 1: Pin Down Scope and the Binding Constraint Before You Draft
Start with a one-page scope note, not the full design. State which endpoints exist, which client populations call them, and which constraints are non-negotiable. In C the binding constraint is usually not the HTTP library sitting on top — it's memory behavior under concurrency and what happens when allocation fails mid-request.
Write down the operating profile: expected requests per second, peak connections, request body size ceiling, response size ceiling, acceptable latency at the 95th percentile, and the deployment shape (single process behind a reverse proxy, multiple worker processes, an event loop, or a thread pool per core). These numbers drive every later decision, so label them honestly as estimates or measurements and name where each came from. If you don't have measurements, say so and treat the figure as a placeholder to be validated.
Also record what the API will not do. Exclusions are cheaper to negotiate now than after review. A one-page scope note that a reviewer can accept or reject in ten minutes saves a week of rework on a forty-page document.
Success check: a reviewer who has never seen the project can read the scope note and correctly state what the service does, how big it is expected to get, and what it deliberately omits.
Step 2: Write the API Contract First, Independent of C
Draft the HTTP surface as if the implementation language were irrelevant. For each endpoint record the method, path, path and query parameters with types and allowed ranges, request headers that matter, the success status code, the error status codes, and a concrete example request and response body.
Then be explicit about semantics that C implementers get wrong when the contract is vague:
Media type and versioning. State the exact Content-Type accepted and produced, and how versions are signaled (path prefix, header, or media type parameter). Pick one mechanism and say why. Idempotency. Which methods are safe and idempotent, and whether retries with the same idempotency key are deduplicated. Pagination and filtering. Cursor versus offset, the maximum page size, and default ordering, including how ties are broken so ordering is stable. Error body shape. One machine-readable code field, one human-readable message field, and optional field-level detail. Fix the vocabulary of codes now; ad hoc error strings leak into client code. Timestamps and numbers. Use RFC 3339 UTC timestamps and state the integer width for IDs so that 32-bit and 64-bit clients agree. Unknown fields and unknown parameters. Decide whether they are rejected or ignored, and apply that consistently.
The contract is the artifact clients depend on. Everything else in the document exists to support it.
Success check: an engineer can generate a client stub from your examples and have it compile and serialize correctly without reading your prose.
Step 3: Map the Contract to Concrete C Types and Own Them
This is the step that distinguishes a C design document from a language-agnostic one, and it usually deserves the most space. Build a table, or a set of small ones, that maps each wire-level concept to a C type, and record the invariants beside it.
Cover at minimum:
Identifiers. A fixed-width unsigned integer type such as uint64_t, or an opaque string. Do not leave IDs as int, whose width varies by platform. Strings. Decide whether you carry length-prefixed (const char *, size_t) pairs or NUL-terminated strings. Length-prefixed pairs are safer for input that may contain embedded NULs and avoid repeated strlen; choose one and forbid the other in review. Optional values. Do not overload NULL. Model presence explicitly, for example a bool has_foo beside foo, or a tagged union. Otherwise "absent" and "empty" and "invalid" collide. Booleans. Use a fixed-width integer or a dedicated enum, not the C99 bool, if the value crosses a serialization boundary. Timestamps. A struct with seconds and nanoseconds since the Unix epoch, with an explicit "is set" flag. Enumerations. Give every enum a named unknown value (often 0) and handle it explicitly on input. Collections. A pointer plus a count, with defined emptiness (NULL with count 0 is allowed only if documented), and the element type spelled out.
Then specify ownership. For every struct, state who allocates it, who frees it, and whether the API borrows or transfers ownership of any pointer inside it. Use consistent naming to encode it: for instance, functions that transfer ownership into a result struct are named so, and a paired _free function exists for every struct that owns memory. If the API is asynchronous, define the lifetime of request and response objects across callbacks and which thread may free them.
Success check: take two representative request bodies and two responses and write the exact C struct initialization for each by hand. If you cannot do it without inventing a field or guessing an ownership rule, the mapping is incomplete.
Step 4: Decide Error Handling and Allocation-Failure Policy
HTTP status codes are the outer contract, but C needs an inner one. Choose between return codes, an error-out parameter, or a hybrid, and apply it uniformly. A common pattern is an integer return for immediate failures such as a malformed argument, plus an error object with a code, an HTTP status, and a message that is populated when the request reaches business logic.
Write the mapping table: transport or parsing failure to 400, authentication failure to 401, authorization failure to 403, missing resource to 404, conflict to 409, malformed but understood payload to 422, rate limiting to 429, and unexpected internal failure to 500. Reserve 503 for overload or unavailable dependencies.
Allocation failure deserves its own paragraph. State whether allocation failure aborts the request with a 503, returns a 500, or triggers a controlled process-level response, and state the rule for partially constructed responses. The most dangerous pattern in C web services is a half-built response whose cleanup path frees something it does not own, so specify that cleanup functions tolerate NULL and that every allocation is paired with exactly one free on every path, including the error paths.
Log the internal error code and correlation ID for a 500, never the raw message to the client. That keeps implementation details out of the API surface.
Success check: every entry in the error vocabulary in Step 2 has a defined C source of truth and a defined HTTP status, and the design explains what happens on allocation failure during response construction.
Step 5: Specify Processing, Limits, and the Buffer Strategy
Describe the request lifecycle end to end: accept, read headers with a size cap, authenticate, read body with a size cap and a timeout, parse into C structs, run business logic, serialize, write the response, free. Then state the limits that protect the process.
Explicit numbers matter here: maximum header bytes, maximum body bytes, maximum time to receive the full request, idle keep-alive timeout, maximum concurrent requests, and maximum response bytes. On the serialization side, decide whether you build the response in a growable buffer holding the whole body or stream it in chunks. Buffering is simpler to reason about and makes error responses consistent; streaming reduces peak memory but complicates error handling after the first byte has gone out. Whichever you choose, say how back-pressure works — what happens when a client reads slowly and the write buffer fills.
For parsing, choose a parser, state whether it is streaming or requires the full body, and define a maximum nesting depth so hostile payloads cannot exhaust the stack. If you use threads, state the affinity rule: which state is per-request, which is shared, and which mutex or lock-free scheme protects it. If you use an event loop, state which callbacks must never block and which operations are dispatched to a worker.
Success check: the document answers "what happens if a client sends a 10 MB body slowly on a keep-alive connection while the server is at its concurrency limit?" with a specific status code and a specific resource behavior.
Step 6: Settle Data Modeling, Storage, and Caching
If the API persists state, record the storage model at the level a reviewer needs. Name the database or store, the schema or key layout, the uniqueness constraints, the indexes that support your filters and sorts, and the transaction boundaries. Tie each endpoint's query patterns to the indexes that serve them, and note any query that cannot be served without a scan so the cost is visible.
Decide caching behavior and say so per endpoint: cacheable, revalidatable, or private. For GET responses, define the ETag or Last-Modified mechanism and the conditional request handling; for lists, decide whether to expose a total count and how expensive that count is. State the read-your-writes expectations for clients after a mutation.
Also decide where concurrency control lives: optimistic version fields, compare-and-swap on a version column, or row locks, and which HTTP status communicates a conflict.
Success check: for every endpoint that reads or writes storage, you can point to the index or key that makes it efficient, and every mutation has a stated concurrency-control strategy.
Step 7: Cover Security, Observability, and Operations
Security: authentication mechanism with its token lifetime and refresh behavior, authorization rules per endpoint, transport requirements, input size limits from Step 5, rate limiting policy with the scope (per client, per key, per IP) and the response when exceeded, and how secrets are loaded rather than stored. Note any endpoint that produces cross-origin responses and state the exact allowed origins rather than a wildcard.
Observability: structured logs with correlation ID, request ID, path and status, but not secrets or full bodies; metrics for request count, latency histogram, error count by code, in-flight requests, and allocation or connection-pool saturation; health and readiness endpoints with what each checks. If the service exposes traces, say what is sampled.
Operations: configuration through environment or a file with defaults documented, graceful shutdown behavior (stop accepting, drain in-flight requests up to a deadline), and a deployment-time compatibility policy. That policy is worth spelling out for a C service: additive changes are safe, renaming fields and changing types are breaking, and clients must ignore unknown response fields. State the deprecation window for anything removed.
Success check: the on-call engineer can diagnose a 500 burst or a latency spike from the metrics and logs this design produces, and the security section names a control for every unauthenticated entry point.
Step 8: State Concurrency and Memory Limits, Then Validate With a Worked Calculation
Write down the concurrency model and derive a memory budget from it. This is where the design earns credibility, because reviewers can check the arithmetic.
An illustrative calculation, with all inputs flagged as placeholders: suppose the service is designed for 200 concurrent in-flight requests, each with a request buffer capped at 8 KB and a response buffer capped at 64 KB, plus 2 KB per request of bookkeeping. Worst case buffered memory per request is roughly 8 KB + 64 KB + 2 KB = 74 KB, so 200 requests is about 14.8 MB of buffer memory; at 500 concurrent it is about 37 MB. Add per-connection state and per-thread stack, then compare the total against the container limit and leave headroom for allocator overhead and fragmentation. If streaming is chosen instead of buffering, recompute with the high-water mark of the write buffer. State the resulting concurrency ceiling and how the server enforces it.
Add failure limits: per-client request caps, request-accept rate, and behavior when the allocator returns NULL.
Success check: a reviewer can substitute different input numbers and get a defensible budget, and the stated concurrency ceiling is mathematically consistent with the memory limit and the body size caps.
Step 9: Review, Sign Off, and Track the Document
Assign explicit reviewers: someone who owns the C implementation, someone who consumes the API, someone responsible for operations, and a security reviewer for authenticated or data-bearing endpoints. Ask each to review against a short checklist: contract completeness, type-to-wire mapping, ownership rules, error mapping, limits and arithmetic, and operability.
Close the review with a recorded decision: approved, approved with named conditions, or rejected with reasons. Keep the design document in version control alongside the code and reference it from the module header. When the implementation deviates, update the document in the same change rather than letting it rot into fiction. A design that is silently out of date is worse than none, because it trains readers to distrust it.
Success check: sign-off is recorded with named reviewers and any conditions, and the document's version matches the code it describes.
Format and Metadata: The Parts Reviewers Check First
Keep the document in Markdown or an equivalent plain-text format so it diffs cleanly. Put a metadata block at the top: status (draft, in review, approved, superseded), author and reviewers, date, version, and a link to the implementation repository and issue tracker. Follow with an executive summary of ten to fifteen lines that states the goal, the chosen approach with one sentence of rationale, and the main trade-offs. Then the sections in the order above. Include a change log, because reviewers will otherwise argue from stale copies.
Two conventions pay for themselves. First, use stable requirement identifiers (R1, R2) and refer to them in tests and tickets so that requirements are traceable. Second, mark every number as measured, estimated, or a limit, and name the source; mixing the three in one table is how a placeholder latency figure becomes a contractual promise.
Success check: a reviewer opening the file for the first time knows its status, its author, and the single most important decision before scrolling.
Common Failure Modes and How to Catch Them
The classic C-specific failure is defining the C structs and letting the JSON shape be derived from them, which leaks internal field names, sentinel values, and padding into the public contract. Write the contract first and treat the struct as an implementation detail, as Step 2 and Step 3 instruct.
The second is invisible ownership. A response struct that borrows a pointer into the request buffer works until the request buffer is reset on keep-alive reuse; then the response silently references reused memory. The ownership table in Step 3 prevents this only if it is complete, so test the mapping by hand.
The third is unbounded input. A body-size cap that exists in configuration but not in the design document tends to get removed during refactoring because no one knows why it is there. Record the limit and its rationale.
The fourth is unrecorded cost: a list endpoint that sorts without a supporting index, or a synchronous external call inside a request handler on an event loop. Both are cheap to describe and expensive to discover in production.
The fifth is stale documentation. Schedule the update as part of the same commit as the code change and record the review decision.
A Compact Example: One Endpoint Mapped End to End
To make the steps concrete, here is a single endpoint carried through the relevant sections. The API is GET /v1/orders/{id}. The contract says it returns 200 with an order object, 404 when the ID is unknown, and 400 when the ID is not a valid unsigned 64-bit integer. The response body has id, status (an enumerable string), created_at (RFC 3339), total_cents (integer, 64-bit), and an optional note string.
In C, the request ID parses into a uint64_t with a strict conversion that rejects trailing characters. The response struct carries a length-prefixed status string rather than an enum so unknown future values stay representable, an int64_t for cents, and a bool has_note beside the note pointer so absent and empty are distinct. The response builder owns all memory in the struct; a paired order_response_free frees it and tolerates NULL members. A storage lookup by primary key supports the query, and a miss returns 404 with error code order_not_found. The limit that applies is the response body cap from Step 5, and the ETag for caching is derived from the order's version field. That is enough specificity for a reviewer to challenge any single decision without re-litigating the whole document.
Frequently Asked Questions
How long should the document be? Long enough that the C type mapping and ownership rules are unambiguous; typically six to twelve pages of dense text plus tables. Length is not the metric — a reviewer being able to implement a second endpoint without asking questions is.
Should the design include the C code? Include type declarations and short illustrative snippets for the ownership and error patterns. Do not paste the implementation; it will diverge and drag the document out of date.
How is this different from an API specification? The API specification defines the HTTP contract. The technical design adds the C-level realization: types, ownership, allocation failure, concurrency, limits, storage, and operations. Keep both, and let the specification be the normative contract.
Do I need this for a small internal API? Keep the scope note, the contract, the type mapping, and the error mapping at minimum. Those four are where small services usually go wrong first.