Client-server architecture means splitting a program so one process, the client, sends requests and another, the server, listens for them, does the work, and returns responses. To make one, you pick a protocol and transport, define the message format, write the server loop and request handlers, build a client that speaks the same contract, then test the whole path from connection to reply under realistic conditions. The key condition is that both sides agree on the wire format and error behavior before you write either side.

That agreement sounds trivial and is where most first attempts fail. A client that expects JSON while the server sends a bare string, or one that assumes a length-prefixed message while the other streams until close, produces the classic hang: both ends are waiting correctly under different rules. This guide walks through the decisions in the order you'd actually make them, with a small worked example, the failure modes to expect, and the point at which you should stop hand-rolling and reach for a framework.

Choose the communication model before writing code

Four patterns cover almost everything you'll build:

Synchronous request-response over a single connection. The client sends one request, blocks, gets one response, and either keeps the connection open for the next request or closes it. Simplest to reason about and the right default for dashboards, forms, and any workflow where a user is waiting. Request-response over HTTP with stateless servers. The server keeps no per-client memory between requests; each request carries all context. This scales horizontally because any server instance can answer any request, but it forces you to design where state actually lives. Long-lived connections for pushes. Server-sent events, WebSocket, or raw TCP where the server needs to notify the client without being asked (chat, live prices, job progress). This is strictly more complex: you now need heartbeats, reconnection logic, and a way to resynchronize after a dropped connection. Asynchronous job submission. The client posts work, receives an identifier immediately, then polls or subscribes for the result. Necessary when a request takes longer than a user or a proxy will tolerate.

Pick the simplest model that meets the requirement. A surprising number of "we need real-time" systems are fine with a poll every few seconds. If your request handler can take longer than about 30 seconds, the synchronous model is the wrong choice because intermediate proxies, load balancers, and impatient clients will drop the connection regardless of what your code does.

The transport follows from this. HTTP over TCP is the default for request-response because it gives you existing tooling, proxies, caching, and observability. Raw TCP or UDP matters for protocols HTTP doesn't fit well; UDP only when losing a message is genuinely acceptable. Notice the model determines whether you can even consider UDP: a request-response contract implies a reply, so UDP's lack of delivery guarantees pushes reliability work into your application.

Define the message contract and error semantics

Before code, write down four things:

1: The message envelope. Framing is the part people underestimate. On a TCP stream there are no message boundaries, so a reader can't tell where one message ends. Either frame each message with a length prefix, use a delimiter that cannot appear in the payload (and escape it if it can), or use a protocol that frames for you. HTTP frames for you via headers and Content-Length; raw TCP does not. 2: The payload schema. JSON is the sane default for debugging and readability; binary formats like Protocol Buffers buy you size and speed at the cost of tooling and human-unreadable traffic. State field names, types, and required versus optional explicitly. Version the schema from day one — a "v": 1 field costs nothing and saves a painful migration. 3: Error representation. A response must distinguish "success with empty result" from "failure." Use a structured envelope like {"ok": true, "data": {...}} and {"ok": false, "error": {"code": "NOT_FOUND", "message": "..."}}. Machine-readable codes let clients branch; human-readable messages let developers debug. Never signal failure only with an HTTP status buried under a 200. 4: Timeouts and limits. A maximum request size, a maximum processing time, and a defined behavior when either is exceeded. Without a size cap, one malformed client can exhaust the server's memory.

A concrete example contract for a small service:

The id field is not decoration: it lets a client that has multiple requests in flight match responses to requests. Include it even if your first version handles one request at a time, because the second version probably won't.

Writing this contract down as a document, a schema file, or even a set of test fixtures is the single highest-leverage step. Both sides can then be developed and tested against the same artifact, and mismatches surface as failing tests rather than mysterious hangs.

Build the server: skeleton, request loop, and handlers

A working server has four jobs: accept connections, decode requests, dispatch to logic, and encode responses. Keep those four separate in the code even in a small project, because each fails for different reasons and you'll want to test them separately.

Prerequisites. A language runtime, a way to listen on a local port, and a client you can run from a terminal (curl, netcat, or your own script). No framework is required for a first version, and starting without one teaches you what the framework actually does for you.

Steps.

1: Open a listening socket. Bind to a specific interface and port; binding to 127.0.0.1 keeps a development server off the network, and 0.0.0.0 makes it reachable from other machines. Choose a high port during development to avoid permission errors. 2: Accept connections in a loop. For each accepted connection, either handle it inline (fine for one user, unusable for two) or hand it to a worker: a thread, a process, or an event loop depending on the language's model. The choice matters less than making it deliberately. 3: Read a complete request using your framing rule. With HTTP, let the library parse headers and body. With raw TCP, read the length prefix first, then exactly that many bytes. Guard against a client that sends a length of two billion. 4: Validate before executing. Check the schema version, the operation name, required argument types, and size limits. Reject unknown operations with a structured error rather than crashing the handler. 5: Dispatch to a handler keyed by operation name. Keep handlers free of socket and framing logic so they can be unit-tested directly. 6: Encode and write the response. Write the full framed response before considering the request done; partial writes on a stream need a loop until everything is flushed. 7: Handle disconnects and timeouts. If the client vanishes mid-request, the handler should be cancellable or at least its result discardable. A read timeout on idle connections prevents resource accumulation. 8: Log each request with the correlation id, operation, duration, and outcome. This log is your primary debugging tool once the client is separate from the server.

Checking success. From a terminal, send a valid request and confirm you get the exact response envelope from the contract. Then send a malformed request (bad JSON, unknown op, oversized body) and confirm you get a structured error and that the server stays up and still answers a subsequent valid request. That second check catches most of the mistakes that make a first server fragile.

When to stop hand-rolling. If you start writing your own connection pooling, TLS termination, retry semantics, or authentication scheme, you've crossed into territory where a framework (Express, Flask, FastAPI, gRPC, or your language's equivalents) is cheaper and safer. A hand-built server is a learning exercise or a very small internal tool; a production service should lean on a battle-tested HTTP stack. The stop condition is concrete: needing TLS, authentication, or graceful restart means adopt a framework rather than extend your loop.

Build the client: connection, send, parse, and recover

The client's job mirrors the server's, and the two most common bugs are in recovery and in parsing.

1: Establish a connection to host and port, with a connection timeout separate from the request timeout. A client that waits forever on connect looks identical to a hung server. 2: Serialize a request using the shared schema, generating an id if the protocol uses them. 3: Write the full request, then read the framed response. With a single request per connection this is straightforward; with pipelining you need to buffer and match by id. 4: Parse the envelope, treating unexpected fields and unknown error codes as errors rather than assumptions. 5: Retry only what is safe to retry. Retrying a read is fine; blindly retrying a write that charges a card is not. Idempotency — where repeating a request has the same effect as sending it once — must be designed into the operation, not bolted onto the client. 6: Surface errors to the caller as distinct types: network failure, timeout, protocol violation, and application error are four different things and deserve different handling.

A small client in pseudocode:

Recovery logic deserves explicit thought. Exponential backoff with jitter prevents a fleet of clients from hammering a recovering server in lockstep. A cap on retry count prevents infinite loops. And a circuit breaker — stop calling a server that keeps failing, check again later — prevents a slow dependency from consuming all your client's capacity.

Handle concurrency, state, and scaling

Concurrency is where a working prototype becomes a real system. Three questions decide your architecture:

How many clients at once, and how long does each request take? A server using one thread per connection handles perhaps a few hundred to a few thousand concurrent connections depending on memory per thread; event-loop servers handle tens of thousands with far less memory but require non-blocking code throughout. Mixed models (a small thread pool serving many connections via an event loop) are common. Estimate before choosing: 1,000 concurrent connections each held for 10 seconds means about 100 requests per second arriving, which is modest; 10,000 connections each doing frequent work is a different problem.

Where does state live? If the server keeps a user's session in memory, that user must return to the same instance or the next request fails. Options are sticky sessions (simple, fragile during deploys), shared storage like a database or cache (adds latency but scales cleanly), or stateless tokens that carry all needed context (scales best, needs careful signing and expiry). Decide explicitly, because "it worked in testing" usually means one instance.

What happens when one server isn't enough? You add a load balancer, and now the balancer needs health checks, the servers need to share state, and any long-lived connection must survive the balancer's idle timeout. This is also the moment to reconsider whether your request is synchronous: a load balancer's default idle timeout on many platforms is in the 30–60 second range, so long polls and lengthy requests get silently cut.

A worked capacity estimate keeps this honest. Suppose each request does one indexed database lookup taking 5 ms, and each server process handles one request at a time with negligible overhead. One process caps at 200 requests per second (1000 ms ÷ 5 ms). Four processes give about 800 per second in theory; expect well under that once connection handling, logging, and the database's own concurrency limits are counted. The point of the estimate isn't precision; it's discovering which resource saturates first.

Secure the boundary and keep the two sides compatible

Any server reachable beyond localhost is an attack surface. The minimum viable set:

Never trust client input. Validate size, type, range, and encoding before use. Reject early and cheaply. Authenticate requests, not just connections. An API key, a signed token, or mutual TLS, with the credential checked on every request that needs it. Credentials in URLs leak through logs; prefer headers. Encrypt in transit with TLS whenever traffic crosses an untrusted network. This is not optional for anything carrying credentials. Rate-limit per client to blunt abuse and accidental loops. Return minimal error detail to the client while logging full detail server-side. Stack traces belong in your logs, not in responses.

Compatibility is the other half. Two rules prevent most breakage: additive changes only (new optional fields, new operations) within a schema version, and a version bump with a transition period when a change is breaking. Keep old and new versions running side by side long enough that all clients have migrated. A client field you plan to remove must first become optional and unused in every known caller; otherwise you'll discover a forgotten integration the hard way.

Test the path, then observe it

Test at three levels, because each catches different failures:

Unit tests on handlers with plain function calls, no sockets. These should be fast and cover the logic including error branches. Contract tests that run the same fixtures against both a real server and a real client, confirming the schema is respected. Serialize a known request, send it, and compare the response to an expected structure rather than an exact string. End-to-end and failure tests: kill the server mid-request and confirm the client reports a clear error; send a truncated frame and confirm the server doesn't hang; fill the request size limit and confirm a structured rejection; simulate a slow handler and confirm the timeout fires.

The failure tests matter more than the happy path. A working request-response demo takes an afternoon; a system that behaves predictably when the network lies takes deliberate effort. Fault injection — delaying responses, dropping connections, returning garbage — is cheap to add to a test client and routinely finds the bugs that only appear in production.

Then instrument it. Log the correlation id end to end so a client error can be traced to a server log line. Track request rate, error rate, and latency percentiles (p50, p95, p99) per operation; averages hide the tail that users actually notice. Alert on the error rate and on the highest latency percentile, not on averages.

The recurring failure modes

Most broken client-server systems fail in a small set of recognizable ways:

Framing mismatch. One side assumes message boundaries the transport doesn't provide. Symptom: intermittent hangs or responses arriving glued together. Fix: agree on length-prefixed or delimited framing, and test with two messages sent back to back. Schema drift. A field renamed on one side. Symptom: silent null values or a validation error on a field nobody remembers adding. Fix: generate both sides from one schema, or keep contract tests that fail on mismatch. Retry storms. A transient outage causes every client to retry immediately and continuously, keeping the server down. Fix: exponential backoff with jitter and a retry cap. State loss on restart or scale-out. Sessions held in memory vanish on deploy. Fix: move state out of the process, or make requests self-describing. Half-configured timeouts. Client timeout shorter than server processing time produces duplicate executions. Fix: set timeouts from the outside in, with the client's timeout longer than the server's, and make write operations idempotent. Unbounded queues. Work piles up behind a slow dependency until memory is exhausted. Fix: bounded queue with a defined rejection behavior, and backpressure so clients slow down.

Each fix is cheaper before you launch than after. The framing and schema decisions in particular are nearly free up front and expensive to change once clients are deployed in other people's hands.

FAQ

Do I need a framework to make a client-server architecture?

For learning, no — a few dozen lines in a language with built-in sockets gives you a complete implementation. For anything used by other people, yes: TLS, authentication, and connection management are solved problems and rewriting them introduces risk without benefit.

Is client-server the same as REST?

No. Client-server is the structural split between requester and provider; REST is one set of conventions (resources, HTTP verbs, statelessness) for building the server's interface. You can build client-server systems over gRPC, raw TCP, or a message queue, and each is a different trade-off in tooling, performance, and coupling.

How many clients can one server handle?

There's no universal number; it depends on the concurrency model, per-request work, and memory per connection. Estimate from your own measurements — requests per second per process and bytes per connection — rather than borrowed figures, then load-test before trusting the estimate.

Should I build the client or server first?

Either, as long as the contract exists first. Writing the contract as fixtures and a schema lets both sides be developed against a shared target, and whichever order you choose, contract tests will catch the drift that a manual walkthrough misses.