Design a web service architecture by starting with the constraints that actually bind you, not with a technology list. Write down expected load, latency targets, data consistency needs, team size, budget, compliance obligations, and how the service must behave when a dependency dies. Those constraints decide whether you need one deployable unit or twenty, a single relational database or a partitioned store, and synchronous calls or queues. You then split the system into components with clear responsibilities, define contracts between them, choose data ownership and storage, and design for failure, security, observability, and deployment. The architecture is finished when you can trace a single request end to end and say what happens at each hop under normal load, peak load, and partial outage.
That order matters because architecture is mostly the art of making trade-offs explicit. Two teams can build identical-looking diagrams where one system handles 50 requests per second and the other 50,000, and the diagrams won't tell you which is which. The constraints do. Everything below is organized as a sequence you can actually work through, with the reasoning behind each step and the checks that tell you whether you got it right.
Step 1: Write the constraint sheet before drawing anything
A constraint sheet is one page, and it's the most valuable document in the project. Fill it in with numbers and owners, not adjectives.
List the functional boundary: what the service does and, just as important, what it explicitly does not do. A payments service that also sends marketing email has no boundary. Then list non-functional requirements with numbers attached:
Traffic shape. Average and peak requests per second, peak-to-average ratio, daily and seasonal patterns, and the read/write mix. "Peak" should be a number you can defend, not "Black Friday." Latency targets. Separate them by operation. A product page might tolerate 300 ms at the 95th percentile; a payment authorization might need 800 ms end to end including the card network. Percentile targets are more useful than averages because averages hide the users who suffer. Availability target. 99.9% allows roughly 43 minutes of downtime per month; 99.99% allows about 4.4 minutes. Each nine costs money and design complexity, so pick deliberately. Data consistency. Decide per operation whether stale reads are acceptable. A bank balance and a "likes" counter are not the same problem. Data volume and retention. Current size, growth per month, and legal retention periods. Regulatory and contractual constraints. Data residency, audit logging, encryption requirements, and who may access what. Team and budget. How many engineers will build and operate this, what they already know, and what the hosting budget looks like.
Then write the failure statement: what the business loses per minute of outage, and which degradations are acceptable (read-only mode, delayed notifications, queued writes). This single sentence usually decides more architecture than any framework choice.
Check: hand the sheet to someone outside the team. If they can't state the top three constraints back to you, it isn't specific enough yet.
Step 2: Pick a starting shape and earn your way to complexity
Most new services should start as a modular monolith: one deployable unit with internally separated modules that communicate through explicit interfaces. This is not a compromise. It's the shape with the fewest distributed-system failure modes, the simplest debugging story, and the cheapest operations, and it lets you discover where the real seams are before you pay to cut along them.
A useful decision table for the starting shape:
| Situation | Sensible default | Why |
|---|---|---|
| Small team, unclear domain boundaries, moderate load | Modular monolith | One deployment, one database transaction boundary, easy refactoring |
| Several teams that must deploy independently | Service-oriented split along team ownership | Deployment independence reduces coordination cost |
| Wildly different scaling needs per function (e.g., image processing vs. account lookup) | Separate the hot path into its own service | Scale only what needs scaling |
| Hard isolation or compliance boundary (PCI card data, regulated health data) | Separate service with its own storage and access controls | Limits blast radius and audit scope |
| Event-driven workflows with many consumers | Monolith plus a message broker | Decoupling without a service explosion |
The rule of thumb: split when you can name a boundary that is stable, owns its data, and has a reason to change or scale independently. "It felt cleaner" is not a reason. Every service boundary you add converts an in-process function call into a network call with latency, partial failure, versioning, and authentication concerns attached.
Check: for each proposed service, write one sentence naming its owner, its data, and the reason it must be separate. If you can't, merge it back.
Step 3: Choose the interaction style per operation, not per system
Real systems mix styles. The decision is per call path, and it hinges on whether the caller needs an answer to continue.
Synchronous request/response suits reads and operations where the user is waiting and the result determines the next step: fetching a profile, authorizing a payment. It's simple to reason about but couples availability—if the downstream service is down or slow, the caller is too, unless you add timeouts, retries, and fallbacks.
Asynchronous messaging suits work that can happen later: sending email, updating search indexes, generating reports, propagating events to other teams. A queue or log absorbs bursts, decouples producer and consumer lifecycles, and lets consumers fail and retry without failing the user's request.
Long-running jobs suit anything taking more than a few seconds of user-visible time: exports, media transcoding, bulk imports. Accept the request, return a job identifier, and let the client poll or subscribe.
The classic failure here is making everything synchronous because it's easier to write, then discovering that one slow dependency drags the whole request graph down. The other classic failure is making everything asynchronous and losing the ability to answer "did my write succeed?"
A practical pattern for writes that must be both durable and fast: accept the command synchronously (validate, persist to an outbox table in the same database transaction as the business change), return success, and publish the event from the outbox to the broker asynchronously. This gives you atomicity between state change and event emission without a distributed transaction. Consumers must be idempotent—process the same event twice and get the same result—because delivery is usually at-least-once.
Check: draw an arrow for every interaction and label it sync, async, or job. Any sync arrow crossing a team boundary needs a timeout, a retry policy with backoff and jitter, and a defined degraded response.
Step 4: Assign data ownership and choose storage per access pattern
The most consequential decision in most web service architectures is where data lives and who may write it. The durable rule is: one writer per dataset, and that writer is a single service. Other services read through the owner's API or through an event-fed local copy, never by reaching into its database. Shared databases feel convenient and become the hardest thing to change later, because every schema tweak breaks unknown consumers.
Storage choice follows access pattern, not fashion:
Relational databases (PostgreSQL, MySQL) remain the default for transactional data with relationships, constraints, and multi-row consistency requirements. Modern versions handle surprising scale with proper indexing, connection pooling, and read replicas. Key-value stores suit simple lookups at very high volume with predictable access by key: sessions, feature flags, caches. Document stores suit self-contained records with flexible shape where you rarely need cross-record joins. Search engines suit full-text and faceted queries; treat them as derived indexes rebuilt from a source of truth, never as the primary store. Analytical stores suit aggregation over large histories; feed them from events or change data capture rather than running reporting queries against the transactional database. Blobs (object storage) suit files, images, and backups, with metadata in a database.
For consistency, name it per operation. Strong consistency within one database is cheap. Cross-service consistency requires either a saga (a sequence of local transactions with compensating actions) or accepting eventual consistency with a defined staleness bound. If a user can see their own write, route that user's reads to the primary or pass a version token—don't assume replication lag is zero.
Schema evolution deserves explicit rules. Additive changes (new nullable columns, new event fields) are safe; renames and removals need a deprecation window. For events, version the payload and require consumers to ignore unknown fields.
Check: for every dataset, you should be able to name the single owning service, the backup and restore procedure, the retention rule, and the staleness bound other consumers must tolerate.
Step 5: Design the edge—clients, gateways, and identity
The edge is where most real traffic and most attacks arrive. A typical layout has a CDN and/or load balancer in front, an API gateway handling cross-cutting concerns, and identity handled before business logic.
Put at the edge what every request needs and no service should reimplement: TLS termination, routing, rate limiting per client and per endpoint, request size limits, authentication token validation, CORS policy, and coarse authorization. Push fine-grained authorization (can this user edit this specific record?) into the owning service, which knows the domain rules.
For external APIs, version the surface from day one (a path prefix like /v1 or a media-type version), publish deprecation policy, and treat the contract as a product. For internal APIs, prefer explicit, versioned contracts too, but allow faster movement.
Protocol choice follows clients: REST over JSON is the default for broad compatibility; gRPC is a strong fit for internal service-to-service calls where schema discipline and efficiency matter; GraphQL helps when many client types need to compose varied views over the same data, at the cost of query complexity controls.
Check: simulate an unauthenticated request, an over-limit request, and a malformed payload. Each should be rejected at the edge with a clear error and without reaching a backend.
Step 6: Make failure a designed behavior, not a surprise
Distributed systems fail partially and constantly. Design each dependency interaction with four explicit properties: a timeout, a retry policy, a circuit breaker, and a fallback.
Timeouts must be shorter than the caller's own deadline, and deadlines should propagate down the call chain so a request doesn't keep working after the user has given up. Retries must be bounded, use exponential backoff with jitter, and apply only to idempotent operations or operations protected by an idempotency key. A circuit breaker stops hammering a failing dependency and gives it room to recover. The fallback is the product decision: serve cached data, serve a reduced feature set, or return a clear error.
Bulkheads limit blast radius: separate connection pools and thread/worker budgets per dependency so one slow downstream can't exhaust all capacity. Load shedding—rejecting a fraction of traffic when saturated—keeps the service responsive for the requests it accepts instead of failing everyone. For writes across services, use idempotency keys so a client retry after a timeout doesn't double-charge or double-create.
Then run failure drills: kill a dependency in a staging environment and verify the degraded behavior matches the design. Game days beat optimism.
Check: for each external dependency, you can state the timeout value, the retry count, the breaker threshold, and what the user sees when it's down.
Step 7: Layer security through the whole design, not the perimeter
Security is a property of the architecture, not a checkbox at the end. Start with the data classification from Step 1 and apply controls accordingly.
Encrypt in transit everywhere, including internal hops, and encrypt sensitive data at rest with managed keys. Authenticate users with a standard protocol (OAuth 2.0 / OpenID Connect) rather than custom token schemes. Authorize with least privilege: each service gets only the credentials and permissions it needs, and human access to production data is logged and time-bound. Validate and constrain all input at the boundary, and parameterize database queries to prevent injection.
Secrets belong in a managed secret store with rotation, never in code or environment dumps. Keep dependencies patched and track them. Maintain audit logs for sensitive operations, with retention that meets your obligations. For regulated data, isolate it in its own service and storage so audits and access controls have a small, defensible scope.
Check: list the top three sensitive data flows and, for each, the transport encryption, storage encryption, authorization rule, and audit trail. Any blank is a gap.
Step 8: Build observability and deployment in from the start
You cannot operate what you cannot see. Instrument three signal types: metrics (request rate, error rate, latency percentiles per endpoint and dependency), structured logs (with correlation identifiers so a single request can be traced across services), and distributed traces (spanning the full call graph, with sampled rates tuned to cost). Define service-level objectives with error budgets so "how healthy is it?" has a numeric answer.
Dashboards should mirror the user journey, alerting on symptoms (elevated error rate, latency breach, saturation) rather than causes. Every alert must have an owner and a runbook.
Deployment shapes the architecture too. Container images, infrastructure as code, and automated pipelines make changes routine; database migrations need a backward-compatible pattern (expand, migrate, contract) so rolling deploys never break running code. Blue-green or canary releases with automated rollback reduce risk. Feature flags decouple release from deploy.
Check: can you, right now, answer "what is the p95 latency of the checkout endpoint over the last hour, and which dependency is slowest within it?" If not, observability comes before new features.
Worked estimate: sizing a service from first principles
Suppose a product detail endpoint must serve 3,000 requests per second at peak, with each response assembled from a 4 KB product record plus a 2 KB inventory count fetched from another service.
Read throughput is 3,000 × 6 KB ≈ 18 MB/s of payload, plus protocol overhead—modest for a CDN-cached read path. Assume 95% of requests hit cache; 150 requests per second reach the origin database, each requiring one indexed lookup of roughly 1 ms. That's 0.15 seconds of database work per second—well within one primary's capacity with margin for writes and other traffic.
The inventory call is the real risk: 150 origin requests per second × 5 ms average latency = 0.75 concurrent calls on average, negligible, but a 10× latency spike during a promotion would push response times over target. This is why the inventory count should be cached with a short time-to-live and why the circuit breaker should fall back to a cached value rather than fail the page.
These are illustrative inputs, not measured values; substitute your own. The method is what matters: convert rates and sizes into concurrency and capacity, then identify which number has the least headroom.
Where this design breaks, and when to call for help
Honest architecture names its limits. A modular monolith with a single primary database is a poor fit when write volume exceeds what one machine can absorb, when teams across time zones block each other's deploys, or when a regulatory boundary demands physical isolation of data. Event-driven systems trade coupling for eventual consistency, which is wrong for operations that must be immediately authoritative. Caching introduces staleness bugs that are easy to miss in testing. Every synchronous hop adds latency and a failure mode, so deep call chains need scrutiny.
Escalate to a specialist when the constraints include hard regulatory certification, when you're designing for financial settlement or safety-critical behavior, or when failure consequences are severe enough that a dedicated architecture review with formal threat modeling is warranted. Those situations need named accountable experts, not a blog post.
FAQ
Do I need microservices to scale? No. Most services scale well as a modular monolith with a read replica, caching, and horizontal instances. Split for organizational and isolation reasons first; scale-driven splits are justified by measured bottlenecks.
How many environments do I need? At minimum, production and a pre-production environment that resembles it closely. Ephemeral preview environments per change are valuable for teams with high deploy frequency, but they're a convenience, not a requirement.
When should I introduce a message broker? When work can happen after the response, when multiple consumers need the same events, or when you need to absorb bursts. If none of those apply, a direct call is simpler and easier to reason about.
How do I keep service contracts from breaking each other? Version explicitly, add fields rather than change them, run consumer-driven contract tests in CI, and give consumers a deprecation window with telemetry showing who still calls the old version.