Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 5 · Concept · 25 min · revision 1

Single-deployable styles: layered, modular, microkernel, pipeline

Compare four styles that ship as one deployable unit by structure, deployment unit and data ownership, then run a small plug-in host and a streaming pipeline to see what each style protects you from, and what it does not.

Contentsand lesson path

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

An architecture style is a named family of structures. It says which kinds of parts a system has, how those parts may connect, and what you get in return for keeping to those rules. Saying "this is a pipeline" or "this is a microkernel" tells a new colleague more in one sentence than a page of class diagrams, and it tells you which problems to expect.

This skill describes every style with the same three questions:

  1. Structure. What are the parts, and which connections between them are allowed?
  2. Deployment unit. What is built, released and started together?
  3. Data ownership. Which part may read and change which data?

The four styles in this lesson give the same answer to the second question: everything ships as one deployable unit, a single process (or identical copies of it) that you build, test and release together. Calls between parts are function calls, a change across parts is one release, and one database transaction can cover a whole operation. The styles differ in how they divide the code inside that unit, which decides how well it copes as the code and the team grow.

02. Layered, slices and modules: dividing one deployable

A layered architecture splits code by technical job. A presentation layer handles HTTP or the user interface, a business layer holds the rules, and a persistence layer talks to the database. Each layer may call only layers below it. Many web frameworks and project templates encourage this split, which is why it is the style most developers meet first.

Two details matter. First, a layer can be closed or open. A request must pass through a closed layer; an open layer may be skipped. Closed layers keep a change in a lower layer away from the layers above it, but they produce pass-through code: business methods that only forward a call because a screen needed nothing but a query. Opening a layer removes that code and ties the screen directly to persistence, so it should be a recorded decision, not a quiet shortcut.

Second, a layer is not a tier. Layers organise code; tiers are separate machines or processes, such as a web server and a database server, as Azure's N-tier guide explains. A layered application usually deploys as one unit, and calls between its layers stay in memory.

The weakness shows when you follow one feature. Adding payment by gift card touches a controller, a service and a repository, in three folders that every other feature uses too, so as a team grows everyone edits every layer. Which way dependencies should point is covered in Which way dependencies point; the point here is how the code is partitioned.

Text · the same two features, partitioned two ways
Layered (by technical job)          Vertical slices (by request)
app/                                app/
  controllers/gift_cards.py           features/
  controllers/orders.py                 pay_with_gift_card/
  services/gift_cards.py                  endpoint.py
  services/orders.py                      handler.py
  repositories/gift_cards.py              queries.py
  repositories/orders.py                place_order/
                                          endpoint.py
                                          handler.py
                                          queries.py
                                      shared/   (only what slices truly share)

Vertical slice architecture, described by Jimmy Bogard in 2018, turns this around. Each request, such as place an order or pay with a gift card, gets its own slice that runs from the endpoint to the database, and the rule is to minimise coupling between slices and maximise it inside one. A new feature becomes a new folder instead of edits to three shared ones. The price is some duplication between slices, and the discipline to keep shared/ small.

A modular monolith is still one deployable, but its top-level split follows business capabilities instead of technical jobs: catalogue, ordering, payments. Each module offers a small public interface and hides everything else. Each module also owns its tables, often in a database schema of its own, so other modules ask through the interface instead of reading those tables. Inside a module you can still use layers or slices.

It buys changes that stay inside one module, and seams along which a module could later become a service. It costs enforcement: a boundary that exists only as a folder name erodes under deadline pressure unless a build check rejects forbidden imports. How to find and enforce those boundaries is the subject of the modular monolith skill.

03. Microkernel: a small core and plug-ins

A microkernel, or plug-in, architecture keeps a small, stable core and lets plug-ins add features through a contract that the core defines. The core owns the shared machinery and the data model; each plug-in owns only its own logic and settings. Editors, browsers, build tools and payroll products with one rules package per country follow this shape. It fits when the people who add features are not the core team, or when features vary by customer or region.

The parts are few: a contract that every plug-in must meet, a version for that contract, discovery (how the core finds plug-ins) and a registry (which plug-in handles what). The example has all four in Python 3.12 with only the standard library. The core converts files into rows, and each importer plug-in handles one file type. Create this layout:

Text · folder layout
importer/
  host.py
  plugins/
    csv_importer.py
    tsv_importer.py
    xml_importer.py
Python · importer/host.py
"""host.py: a tiny microkernel. The core knows the contract, not the plug-ins."""
import importlib.util
import pathlib
from typing import Protocol

API_VERSION = 2  # bump when the contract below changes in a breaking way


class Importer(Protocol):
    name: str
    suffixes: tuple[str, ...]

    def parse(self, text: str) -> list[dict]: ...


def load_plugins(folder: pathlib.Path) -> dict[str, Importer]:
    registry: dict[str, Importer] = {}
    for path in sorted(folder.glob("*.py")):
        spec = importlib.util.spec_from_file_location(path.stem, path)
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)  # runs the plug-in's code in THIS process
        wanted = getattr(module, "API_VERSION", None)
        if wanted != API_VERSION:
            print(f"skip   {path.name}: written for API {wanted}, not {API_VERSION}")
            continue
        plugin: Importer = module.plugin
        for suffix in plugin.suffixes:
            registry[suffix] = plugin
        print(f"loaded {plugin.name} for {', '.join(plugin.suffixes)}")
    return registry


def convert(registry: dict[str, Importer], filename: str, text: str) -> str:
    plugin = registry.get(pathlib.Path(filename).suffix)
    if plugin is None:
        return f"{filename}: no importer"
    try:
        rows = plugin.parse(text)
    except Exception as exc:  # one plug-in bug must not stop the whole batch
        return f"{filename}: {plugin.name} failed ({type(exc).__name__})"
    return f"{filename}: {len(rows)} rows via {plugin.name}"


if __name__ == "__main__":
    registry = load_plugins(pathlib.Path(__file__).parent / "plugins")
    batch = {
        "march.csv": "day,amount\n2026-03-01,12.50\n2026-03-02,8.00\n",
        "april.tsv": "day\tamount\n2026-04-01\t3.10\n2026-04-02\t9.90\n",
        "may.tsv": "day\tamount\n2026-05-01\tn/a\n",
        "june.xml": "<rows><row day=2026-06-01 amount=4/></rows>",
    }
    for name, text in batch.items():
        print(convert(registry, name, text))
Python · importer/plugins/csv_importer.py
import csv
import io

API_VERSION = 2


class CsvImporter:
    name = "csv"
    suffixes = (".csv",)

    def parse(self, text: str) -> list[dict]:
        return list(csv.DictReader(io.StringIO(text)))


plugin = CsvImporter()
Python · importer/plugins/tsv_importer.py (has a bug on purpose)
API_VERSION = 2


class TsvImporter:
    name = "tsv"
    suffixes = (".tsv",)

    def parse(self, text: str) -> list[dict]:
        header, *lines = text.strip().split("\n")
        keys = header.split("\t")
        rows = [dict(zip(keys, line.split("\t"))) for line in lines]
        for row in rows:
            row["amount"] = float(row["amount"])  # fails on "n/a"
        return rows


plugin = TsvImporter()
Python · importer/plugins/xml_importer.py (written for an old contract)
API_VERSION = 1  # written against an older contract


class XmlImporter:
    name = "xml"
    suffixes = (".xml",)

    def parse(self, text: str) -> list[dict]:
        raise NotImplementedError


plugin = XmlImporter()
Terminal
cd importer && python3 host.py
Expected output
loaded csv for .csv
loaded tsv for .tsv
skip   xml_importer.py: written for API 1, not 2
march.csv: 2 rows via csv
april.tsv: 2 rows via tsv
may.tsv: tsv failed (ValueError)
june.xml: no importer

Read the output line by line. The core loaded two plug-ins and refused the third, because it declares an older contract version. Adding or removing a plug-in never changed host.py. may.tsv hit the bug in the TSV plug-in (float("n/a")), and the try/except in convert turned it into one failed file instead of a crashed batch. june.xml has no importer, and the core says so instead of guessing.

That protection has a hard limit. The plug-ins run inside the core's own process, so except only catches exceptions. A plug-in that loops forever, uses up the memory or calls os._exit() stops the whole host, and it can read every file and secret the host can; VS Code's documentation says the same of its extension host, which has the same permissions as VS Code itself. Plug-ins from people you do not review belong in a separate process with a timeout, a memory limit and fewer permissions, which is a step towards the distributed styles of lesson 2.

Real Python hosts usually discover plug-ins through package entry points (importlib.metadata.entry_points) rather than a folder scan; the contract, version and registry stay the same.

04. Pipeline: pipes and filters, and the four styles side by side

A pipeline, also called pipes and filters, moves data through a chain of independent steps. Each filter takes input, does one transformation and passes the result on; a pipe connects one filter's output to the next filter's input. A filter knows nothing about its neighbours, so you can reorder, replace or test each one on its own. Shell commands joined with |, compilers (scan, parse, optimise, emit), media processing and data-loading jobs all have this shape. Data ownership is simple: an item belongs to the filter that is working on it, and filters share no state.

Python generators make a small but honest pipeline, because each filter pulls one item at a time from the filter before it. The print calls show the order in which work happens.

Python · pipeline.py
"""pipeline.py: pipes and filters with generators. Each filter knows only its input."""
from collections.abc import Callable, Iterable, Iterator

RAW = ["7,EUR", "x,USD", "3,GBP", "5,EUR"]
RATE_TO_EUR = {"EUR": 1.0, "GBP": 1.2, "USD": 0.9}


def source(lines: list[str]) -> Iterator[str]:
    for line in lines:
        print(f"  read  {line}")
        yield line


def parse(lines: Iterable[str]) -> Iterator[tuple[str, str]]:
    for line in lines:
        amount, currency = line.split(",")
        yield amount, currency


def valid(rows: Iterable[tuple[str, str]]) -> Iterator[tuple[int, str]]:
    for amount, currency in rows:
        if amount.isdigit():
            yield int(amount), currency
        else:
            print(f"  drop  {amount},{currency}")


def to_eur(rows: Iterable[tuple[int, str]]) -> Iterator[float]:
    for amount, currency in rows:
        yield round(amount * RATE_TO_EUR[currency], 2)


def largest_first(values: Iterable[float]) -> Iterator[float]:
    yield from sorted(values, reverse=True)  # must see every value before the first


def sink(values: Iterable[float]) -> None:
    for value in values:
        print(f"  write {value}")


def pipe(data: Iterable, *filters: Callable[[Iterable], Iterable]) -> Iterable:
    for f in filters:
        data = f(data)
    return data


print("streaming:")
sink(pipe(source(RAW), parse, valid, to_eur))
print("with a sorting filter:")
sink(pipe(source(RAW), parse, valid, to_eur, largest_first))
Terminal
python3 pipeline.py
Expected output
streaming:
  read  7,EUR
  write 7.0
  read  x,USD
  drop  x,USD
  read  3,GBP
  write 3.6
  read  5,EUR
  write 5.0
with a sorting filter:
  read  7,EUR
  read  x,USD
  drop  x,USD
  read  3,GBP
  read  5,EUR
  write 7.0
  write 5.0
  write 3.6

In the first run the trace interleaves: 7,EUR is read and written before 3,GBP is even read. Each item travels through every filter on its own, so memory use stays flat and the first result appears at once, however long the input is. The second run adds one filter that sorts. A sort cannot emit its first value until it has seen the last one, so every read now happens before any write, and the whole input sits in memory. One blocking filter changes the whole pipeline, so place such steps on purpose or bound them, for example the top ten values instead of a full sort.

The style strains when a step must talk back to an earlier one, when the flow branches into many independent reactions, or when one item's failure needs coordinated handling across steps; those needs point to the styles of lesson 2. Azure's Pipes and Filters pattern describes the cloud version, with filters as services and queues as pipes.

Text · structure, deployment unit and data ownership
Style             Structure                       Unit   Data ownership
----------------  ------------------------------  -----  ---------------------------
Layered           technical layers, calls go      one    one shared schema, reached
                  down only                              through the lowest layer
Vertical slices   one slice per request           one    shared schema; each slice
                                                         owns its own queries
Modular monolith  business modules with small     one    each module owns its tables
                  public interfaces
Microkernel       stable core + plug-ins behind   one*   core owns the data model;
                  a versioned contract                   plug-ins own their settings
Pipeline          filters joined by pipes         one*   each item belongs to the
                                                         filter working on it

* plug-ins and filters can also run as separate processes, at the price of lesson 3

Real systems combine these: a modular monolith can use slices inside each module, and a microkernel can run a pipeline in its core. Name the style at each level rather than forcing one label onto everything.

05. Check your understanding

Practice check · 3 questions

Single-deployable styles

Three situations from the code and styles in this lesson. Pick the best answer for each.

Q1. You add the `largest_first` filter to a generator pipeline like the one above and feed it a 20 GB file of payments. Compared with the streaming version, what changes?
Q2. A new importer plug-in for `host.py` has a bug: on one malformed file its `parse` method loops forever. The batch has 500 files. What happens?
Q3. In a layered app with closed layers, a report screen needs one read-only query, so the business layer only forwards the call. A developer proposes letting presentation call persistence directly for reports. What does this trade?
Practice only: not graded, not saved, not evidence.

06. Apply it

The practice task of this skill compares styles for two briefs: a startup (one team, a domain that is still unclear) and an enterprise system (eight teams, strict availability goals). Start the comparison now with the four styles of this lesson.

  1. For each brief, write one sentence per style on how it would partition the code, and what it would deploy.
  2. For each brief, note which of the three questions (structure, deployment unit, data ownership) its drivers care about most, and why.
  3. Mark any style you would already rule out, with a one-line reason. For example, a microkernel needs someone outside the core team who will write plug-ins.

Keep the notes: lesson 4 turns them into a scored comparison.

07. Review prompt

Without looking back: describe layered, vertical slices, modular monolith, microkernel and pipeline by their structure, deployment unit and data ownership. Explain why a closed layer produces pass-through code, and why a layer is not a tier. Name the four parts of a plug-in mechanism and the failures that an in-process plug-in host cannot contain. Finally, explain why one sorting filter changes the memory use and latency of a whole pipeline.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check