Distributed styles: from client-server and SOA to actors and serverless
Describe client-server, peer-to-peer, SOA, service-based, microservices, event-driven, actor-based and serverless styles by structure, deployment unit and data ownership, and run an actor and a toy function platform to see where each keeps its state.
Contentsand lesson path
On this page
- Why it matters
- Client-server and peer-to-peer
- Services and events: SOA, service-based, microservices, event-driven
- Actors and reactive systems
- Serverless functions, and all eight styles side by side
- Check your understanding
- Apply it
- Review prompt
Lessons of Architecture Styles
- Single-deployable styles: layered, modular, microkernel, pipeline Concept · 25 min
- Distributed styles: from client-server and SOA to actors and serverless Concept · 30 min
- Style characteristics and the price of distribution Concept · 20 min
- Choosing a style for three product scenarios Worked example · 30 min
- Style selection check Knowledge check · 6 questions
What you will learn
- Describe layered, client-server, peer-to-peer, modular monolith, microkernel, pipeline, service-based, SOA, microservices, event-driven, actor-based and serverless styles by structure, deployment unit and data ownership.
Prerequisites: Quality Attributes & Trade-offs
01. Why it matters
In lesson 1 every part shipped in one deployable unit. Here the parts are deployed, started and scaled separately and talk over a network: you can release one part alone, but calls can now be slow, lost or answered twice, the subject of lesson 3.
The list is not a ladder from worse to better; each style answers a different question. Use the same lenses as before, structure, deployment unit and data ownership, and add one: who starts the conversation, a caller waiting for a reply or a sender who moves on.
02. Client-server and peer-to-peer
In client-server, clients send requests and a server answers. The server is the authority for shared data: a browser or mobile app may cache data, but the server decides what is true. Deployment units are the clients and the server, and they evolve at different speeds: you cannot force every phone to update at once, so the server must accept old clients for a while. Nearly every web application is client-server at its outer edge, whatever it uses inside.
Peer-to-peer removes the central authority: every node, a peer, is both client and server, and shared data is spread over the peers. File distribution is the classic case: a peer that has downloaded part of a large file serves that part to others, so the original source does not have to upload a full copy to every receiver. The costs explain why most business systems avoid it: peers join and leave all the time, so finding data needs a discovery mechanism; peers may be faulty or hostile, so every piece must be checked against a cryptographic hash from a trusted source; and firewalls often block incoming connections to peers.
03. Services and events: SOA, service-based, microservices, event-driven
Service-oriented architecture (SOA), popular in large enterprises in the 2000s, exposed business functions as services that applications across the organisation could reuse. Integration often ran through an enterprise service bus (ESB), a central product that routed, transformed and orchestrated messages, often against a shared data model. Shared data was common, and the typical failure was logic piling up in the bus until every change waited for its owners. James Lewis and Martin Fowler described microservices in 2014 partly as a reaction: smart endpoints and dumb pipes.
Service-based architecture is the pragmatic middle: a handful of coarse services, often one per major business area, each deployed separately and frequently sharing one database (ideally one schema each). You get separate releases and some fault isolation with few moving parts, but the shared database still couples releases when tables change.
Microservices go further: many small services, each aligned with one business capability or bounded context (the part of the domain where one model and its words apply), each owning its data so that no other service reads its tables, and each deployable on its own. The payoff is that many teams can release without waiting for each other; the price is everything lesson 3 describes, which is why the microservices skill starts with when not to use them. Finding the boundaries is a modelling job, described in one model cannot serve everyone.
In an event-driven style, components publish facts such as OrderPlaced to a broker, and any interested component reacts. The publisher does not know who listens, so a new reaction needs no change to it. Deployment units are producers, consumers and the broker. Each consumer owns the data it builds from events, so parts of the system catch up with a change at different moments: eventual consistency.
It shines when many independent reactions hang off the same facts and producers must keep working while consumers are down. It hurts when a sender needs an answer, or when nobody can see the whole flow any more. Brokers are covered in queues, topics and logs, design choices in the event-driven architecture skill.
04. Actors and reactive systems
The actor model, first described by Carl Hewitt and colleagues in 1973, builds a system from actors. An actor has private state that no one else can touch, a mailbox, and a handler that takes one message at a time. To change an account, you send its actor a message and, if needed, wait for the reply. Only the actor touches its state, and it finishes one message, waits included, before taking the next, so there are no locks and no lost updates (Orleans calls this non-reentrant, its default; a reentrant grain gives that up). Because actors only exchange messages, the runtime can place them on any machine in a cluster.
The deployment unit is usually a cluster of identical nodes. Orleans and Akka Cluster Sharding decide where each actor lives; in Erlang and Elixir you choose the node when you spawn a process, or use a library that does. Microsoft Orleans (.NET, MIT licence) adds virtual actors, called grains, which the runtime activates on demand and removes from memory when idle. On the JVM, Akka moved from the Apache 2.0 licence to the Business Source License in 2022, so read its current terms before adopting it; Apache Pekko is an Apache-licensed fork of Akka 2.6.
The script makes two withdrawals of 70 from a balance of 100, with shared state and then with an actor. fraud_check stands in for a network call, an await where other tasks may run. It needs Python 3.12 or newer.
"""actors.py: two withdrawals of 70 from a balance of 100, two ways."""
import asyncio
async def fraud_check() -> None:
await asyncio.sleep(0) # stands in for a network call: other tasks run here
# 1. Shared state: any task may read and write the balance at any time.
balances = {"acc-1": 100}
async def withdraw_shared(account: str, amount: int) -> str:
current = balances[account]
if current < amount:
return "rejected"
await fraud_check()
balances[account] = current - amount
return "ok"
# 2. An actor: private state, a mailbox, one message at a time.
class AccountActor:
def __init__(self, balance: int) -> None:
self._balance = balance # only run() ever touches it
self._mailbox: asyncio.Queue = asyncio.Queue()
async def run(self) -> None:
while True:
kind, amount, reply = await self._mailbox.get()
if kind == "balance":
reply.set_result(self._balance)
elif self._balance < amount:
reply.set_result("rejected")
else:
await fraud_check() # the next message waits until this one ends
self._balance -= amount
reply.set_result("ok")
async def ask(self, kind: str, amount: int = 0):
reply = asyncio.get_running_loop().create_future()
await self._mailbox.put((kind, amount, reply))
return await reply
async def main() -> None:
results = await asyncio.gather(
withdraw_shared("acc-1", 70), withdraw_shared("acc-1", 70)
)
print("shared state:", results, "balance", balances["acc-1"])
actor = AccountActor(100)
worker = asyncio.create_task(actor.run())
results = await asyncio.gather(actor.ask("withdraw", 70), actor.ask("withdraw", 70))
print("actor: ", results, "balance", await actor.ask("balance"))
worker.cancel()
asyncio.run(main())python3 actors.pyshared state: ['ok', 'ok'] balance 30
actor: ['ok', 'rejected'] balance 30With shared state, both withdrawals read 100, pass the check, pause in fraud_check and write 30: 140 left the account and the balance says 30. With the actor, the second message waits in the mailbox until the first has finished, sees 30 and is rejected. Nothing was locked; the order of messages did the work.
The same rule is the style's main cost. Messages for one actor are handled one after another, so a popular actor, such as one auction everybody bids on, becomes a queue while thousands of quiet actors run in parallel. And asyncio.Queue() without a size is an unbounded mailbox: if senders are faster than the actor, memory grows until something breaks. A bounded mailbox makes put wait and so slows the senders: back-pressure, one idea of the Reactive Manifesto (2014), which asks systems to stay responsive under failure and changing load by building on asynchronous messages. Read it as properties to aim for, not a style of its own.
05. Serverless functions, and all eight styles side by side
In the serverless function style (functions as a service) you deploy functions and the platform runs them. When a request or event arrives, the platform starts an execution environment, loads your code, runs it and keeps the environment warm for reuse; when traffic stops, it removes environments and you stop paying for compute. The deployment unit is a function or a small group of them; anything that must survive goes to a managed database, queue or object store.
Limits differ by platform and change over time. AWS's documentation, checked in November 2026, lists for standard Lambda functions a maximum of 15 minutes per invocation, memory from 128 MB to 10,240 MB, 6 MB request and response payloads for synchronous calls, a default of 1,000 concurrent executions per Region (which can be raised), and 10 seconds for the initialisation phase of on-demand functions. Environments are replaced every few hours, even under steady traffic. Variants change parts of this model: SnapStart restores environments from a snapshot, Lambda Managed Instances and Web Functions let one environment serve several requests at once, and durable functions run long workflows.
The two TypeScript files below show the execution model without a cloud account; Node.js 22.18 or newer runs .ts files directly. handler.ts looks like a function handler; local-runtime.ts plays the platform and loads a fresh copy of the module for each new environment.
// handler.ts: shaped like a function-as-a-service handler.
// Code at module level runs once per execution environment (the cold start).
const env = new URL(import.meta.url).searchParams.get('env');
console.log(` [env ${env}] init: load price table, open connections`);
const prices = new Map([['tea', 3], ['cake', 5]]);
let callsHere = 0; // lives exactly as long as this environment
export async function handler(event: { item: string }) {
callsHere += 1;
return { item: event.item, price: prices.get(event.item), callsHere };
}// local-runtime.ts: a toy platform. Each environment is a fresh copy of the module.
type Handler = (event: { item: string }) => Promise<object>;
type Env = { id: number; handler: Handler; busy: boolean };
let envs: Env[] = [];
let started = 0;
async function invoke(item: string): Promise<string> {
let env = envs.find((e) => !e.busy); // reuse an idle, warm environment
if (!env) {
started += 1; // none idle: start a new one (a cold start)
const mod = await import(`./handler.ts?env=${started}`);
env = { id: started, handler: mod.handler, busy: false };
envs.push(env);
}
env.busy = true;
const result = await env.handler({ item });
env.busy = false;
return ` env ${env.id} -> ${JSON.stringify(result)}`;
}
console.log('three requests, one after another:');
for (const item of ['tea', 'cake', 'tea']) console.log(await invoke(item));
console.log('two requests at the same time:');
const both = await Promise.all([invoke('tea'), invoke('cake')]);
both.forEach((line) => console.log(line));
console.log('the platform recycles its environments, then one more request:');
envs = [];
console.log(await invoke('tea'));node local-runtime.tsthree requests, one after another:
[env 1] init: load price table, open connections
env 1 -> {"item":"tea","price":3,"callsHere":1}
env 1 -> {"item":"cake","price":5,"callsHere":2}
env 1 -> {"item":"tea","price":3,"callsHere":3}
two requests at the same time:
[env 2] init: load price table, open connections
env 1 -> {"item":"tea","price":3,"callsHere":4}
env 2 -> {"item":"cake","price":5,"callsHere":1}
the platform recycles its environments, then one more request:
[env 3] init: load price table, open connections
env 3 -> {"item":"tea","price":3,"callsHere":1}The init line appears once per environment, not once per request: that is the cold start, and why platforms advise opening connections at module level. callsHere grows across warm calls in env 1, starts at 1 in env 2, and starts again in env 3 after the platform replaced its environments. Module-level variables are a per-environment cache, not a shared or durable store.
So serverless fits short, stateless work with uneven traffic and a small operations team. It hurts for work that needs a large warm state, long-running jobs, and steady heavy load where per-call pricing adds up.
Style Structure Deployment units Data ownership
-------------- --------------------------- ------------------- ------------------
Client-server clients ask, server answers clients + server server is the
authority
Peer-to-peer equal peers, no centre every peer spread over peers,
checked by hash
SOA enterprise services + bus services + ESB often shared or a
canonical model
Service-based a handful of coarse each service often one shared
domain services database
Microservices many small services, one each service each service owns
capability each its own data
Event-driven producers, broker, producers, each consumer owns
consumers consumers, broker what it builds
Actor-based actors with mailboxes cluster of nodes; each actor owns its
runtime places them private state
Serverless functions run on demand function(s) external managed
by a platform stores only06. Check your understanding
07. Apply it
Extend your lesson 1 notes on the two practice briefs.
- Add the styles of this lesson. For each, write how many deployment units the brief would end up with and who would own which data.
- Note what the team would need to run each style (pipelines and monitoring per unit, on-call, a broker, a platform account) and compare it with what the brief says the team has.
- Mark the styles that clash with a stated constraint, and name the constraint.
08. Review prompt
Without looking back: describe the eight styles of this lesson by structure, deployment unit and data ownership. Explain what went wrong when logic gathered in an enterprise service bus, why an actor needs no locks and what that costs a busy actor, and what survives in a serverless function between calls.
References
- Architecture styles (Azure Architecture Center)
- Microservices (James Lewis and Martin Fowler, 2014)
- Orleans overview: the actor model and grains (Microsoft Learn)
- Why we are changing the license for Akka (Akka, 2022)
- Apache Pekko
- The Reactive Manifesto (2014)
- Lambda quotas (AWS documentation)
- Understanding the Lambda execution environment lifecycle (AWS documentation)
- Node.js: running TypeScript natively
- Request scheduling and reentrancy in Orleans (Microsoft Learn)
- Cluster Sharding (Akka documentation)
- Improving startup performance with Lambda SnapStart (AWS documentation)
- Lambda Managed Instances (AWS documentation)
- AWS Lambda Web Functions (AWS documentation)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.