{"generated_at":"2026-11-09T06:23:14.832389+00:00","site":"https://www.mikebild.dev","articles":[{"locale":"de","translation_key":"von-der-session-zum-system-zwischenfazit","slug":"von-der-session-zum-system-zwischenfazit","title":"Zwischenfazit und Systemblick: eine Bilanz der Serie","summary":"Monate nach dem Gespräch, mit dem alles begann, ist es Zeit für eine ehrliche Bilanz: welche Erwartungen des Auftakts eingetreten sind, welche nicht, was offen bleibt – und warum die spannendste Frage nicht mehr lautet, was die Modelle können, sondern was Organisationen daraus machen.","tags":["Software","KI","Methodik"],"published_at":"2026-08-17T10:00:00+00:00","updated_at":"2026-08-18T05:16:11.670656+00:00","url":"https://www.mikebild.dev/de/blog/von-der-session-zum-system-zwischenfazit/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/8b34c7f2574232bfaed3a2d2f3d7793624fb3a5259cddf5e0d0c53b8e9f4d667.mp3","audio_duration_secs":697,"text":"Das Gespräch, mit dem [diese Serie begann](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/), liegt im Oktober des vergangenen Jahres; dieser Text zieht mit Stand August 2026 Bilanz. Der Auftakt endete mit einem Vorsatz: der eigenen Begeisterung erst einmal misstrauen, genau hinschauen und jedes Ergebnis an über dreißig Jahren Handwerk messen. Die [letzte Folge](https://www.mikebild.dev/de/blog/hilfsmittel-konzepte-methoden-prozesse/) hat angekündigt, diesen Vorsatz beim Wort zu nehmen. Also: Was von den Erwartungen ist eingetreten, was nicht, was bleibt offen – und welcher Systemblick ist aus den einzelnen Sitzungen des Anfangs inzwischen geworden?\n\n*Teil 13 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\n## Die Begeisterung hat die Prüfung überstanden – knapp\n\nDas Wichtigste zuerst, weil alles andere darauf aufbaut: Aus den paar Tagen Probe im Oktober ist Alltag geworden, und zwar der unspektakulärste Beleg, den ich anbieten kann. Ich denke über diese Werkzeuge nicht mehr nach, so wenig wie über den Editor oder die Versionsverwaltung. Sie sind Infrastruktur. Ein Strohfeuer sieht anders aus – Strohfeuer erkennt man daran, dass man nach drei Monaten wieder davon erzählt statt damit zu arbeiten.\n\nTrotzdem wäre es zu billig, die eigene Wahrnehmung einfach zur Bilanz zu erklären. Im Juli 2025 hat das amerikanische Forschungsinstitut METR – eine gemeinnützige Organisation, die die Fähigkeiten von KI-Systemen mit kontrollierten Experimenten vermisst – eine Studie veröffentlicht, die mich mehr beschäftigt hat als jede Benchmark: Erfahrene Open-Source-Entwickler waren mit KI-Unterstützung in randomisierten Aufgaben messbar langsamer – um rund ein Fünftel – und schätzten hinterher trotzdem, deutlich schneller gewesen zu sein. Genau die Wahrnehmung, auf die ich mich seit dem Auftakt verlassen habe, kann also systematisch täuschen. Das nehme ich ernst, denn es ist dieselbe Warnung, die ich mir im Auftakt selbst gegeben habe: Frische Begeisterung ist ein schlechter Zeuge.\n\nDeshalb prüfe ich an Dingen, die sich nicht schönreden lassen. Was ist abends tatsächlich fertig? Welche der liegen gebliebenen Vorhaben sind heute in Betrieb? Wie oft habe ich in Reviews Fehler gefunden, die ohne die Verschiebung zum Prüfen durchgerutscht wären? Nach diesem Maßstab fällt die Bilanz positiv aus – als Beobachtung, nicht als Messung; belastbare Zahlen dazu fehlen mir. Genau deshalb bleibt die Studie für meine Bewertung wichtig: Solange ich nicht mit vergleichbarer Strenge messe, muss ich einrechnen, dass auch meine Wahrnehmung täuscht. Sie misst allerdings Aufgaben, die den Entwicklern vertraut waren, in Code, den sie gut kannten. Mein größter Gewinn liegt woanders – bei den Vorhaben, die ohne diese Werkzeuge gar nicht erst angefangen worden wären. Das ist keine Widerlegung der Studie, es ist eine andere Rechnung. Beide können gleichzeitig stimmen.\n\n## Was eingetreten ist\n\nDer Auftakt hielt drei Beobachtungen fest. Alle drei haben die Monate seit dem Auftakt überlebt, aber keine ist geblieben, wie sie war.\n\nDie erste – Erzeugen wird billig, Prüfen wird der Engpass – hat sich als die tragende Beobachtung der ganzen Serie erwiesen. Rückblickend ist fast jede Folge eine Antwort auf diese eine Verschiebung: der Harness organisiert das Prüfen um das Modell herum, die [Hausregeln](https://www.mikebild.dev/de/blog/was-ich-kritisch-sehe/) verteidigen es gegen die eigene Bequemlichkeit, [Grounding](https://www.mikebild.dev/de/blog/sauberes-grounding-antworten-erden/) verankert es in echten Quellen, und [Regeln im Pfad](https://www.mikebild.dev/de/blog/eigener-agent-pro-fachdomaene/) machen es unabhängig von der Tagesform des Prüfenden. Was ich im November noch nicht sah: Der Engpass wandert weiter. Erst war das Prüfen knapp, dann das saubere Aufschreiben dessen, was gelten soll – inzwischen ist es das Entscheiden, was überhaupt gebaut wird.\n\nDie zweite Beobachtung – die Schubladen gehen wieder auf – ist eingetreten, mit einer Einschränkung, die ich damals nicht kommen sah. Einiges von dem, was jahrelang liegen geblieben war, ist heute in Betrieb: kleiner als die ursprüngliche Idee, und das ist keine Niederlage, sondern ein Befund. Denn was die Werkzeuge nicht liefern, ist ein Urteil darüber, welche der alten Ideen es wert waren. Zwei Vorhaben habe ich nach wenigen Wochen wieder eingestellt – schneller gescheitert, als es früher möglich gewesen wäre, und genau das ist der unterschätzte Gewinn: Billige Umsetzung macht auch das Verwerfen billig.\n\nDie dritte Beobachtung – der Ton stimmt immer, auch wenn der Inhalt nicht stimmt – war im November ein Bauchgefühl. Daraus ist [eine strukturelle Erklärung](https://www.mikebild.dev/de/blog/sauberes-grounding-warum-ki-raet/) geworden und dann ein Verfahren. Das Misstrauen ist geblieben, aber es ist umgezogen: von meiner privaten Wachsamkeit in Prüfschritte, die nicht davon abhängen, ob ich einen guten Tag habe. Das ist vielleicht die kompakteste Zusammenfassung dessen, was diese Monate mit meiner Arbeitsweise gemacht haben – Sorgfalt wurde von einer Tugend zu einer Eigenschaft des Aufbaus.\n\n## Was ich falsch erwartet hatte\n\nEine Bilanz, die nur Treffer aufzählt, ist Werbung. Zwei Erwartungen haben sich nicht gehalten.\n\nDie teuerste Fehleinschätzung: dass Aufschreiben reicht. Monatelang steckte ich Arbeit in immer bessere Instruktionsdateien, ehe ich die Chronik dieser Versuche ehrlich gezogen habe – aufgeschriebene Regeln bleiben Empfehlungen, egal wie gut sie formuliert sind. Aus dieser Ernüchterung ist die wichtigste Erkenntnis der Serie geworden: Regeln, die gelten sollen, brauchen einen Pfad, der sie durchsetzt – Prüfung vor Wirkung, Freigaben, Nachweise. Wenn ich einen einzigen Satz aus diesen Monaten mitnehmen dürfte, wäre es dieser.\n\nDie zweite Fehleinschätzung ist angenehmer: Erwartet hatte ich, dass die Modellwahl mit der Zeit wichtiger wird – dass sich irgendwann ein Modell absetzt und die Frage „welches?“ doch noch zur Strategiefrage wird. Das Gegenteil ist passiert. Bei meinen Aufgaben wirkten mehrere Modellwechsel seit dem Auftakt wie Qualitätsverbesserungen, und mit jedem Sprung wurde die Wahl [unwichtiger, nicht wichtiger](https://www.mikebild.dev/de/blog/gut-genug-modelle/). Die Arbeitsweise hat die Wechsel kaum bemerkt. Was sich dagegen jedes Mal bemerkbar macht: eine schlecht geschnittene Aufgabe, ein fehlendes Stück Kontext, eine Regel, die nur in Prosa existiert. Der eigene Anteil dominiert das Ergebnis – das war als These früh da, und inzwischen entscheidet sich daran konkret, ob ein Lauf trägt: am Schnitt der Aufgabe, am mitgegebenen Kontext und an den Regeln, die im Pfad durchgesetzt werden.\n\n## Was offen bleibt\n\nDrei Fragen bleiben in diesem Zwischenfazit unbeantwortet.\n\nDie Junior-Frage. Im Auftakt stand ein Verdacht: Der Hebel wirkt, weil drei Jahrzehnte Urteilsfähigkeit dahinterstehen – und ob er für jemanden ohne dieses Fundament genauso wirkt, wisse ich nicht. Auch heute weiß ich es nicht, und die [kritische Folge](https://www.mikebild.dev/de/blog/was-ich-kritisch-sehe/) hat den Verdacht eher geschärft als entkräftet: Wer funktionierenden Code bekommt, bevor der Schmerz einsetzt, aus dem Verständnis entsteht, baut womöglich nie die Substanz auf, von der das Prüfen zehrt. Verdacht ist weiterhin kein Wissen. Aber er ist die Frage, die ich für wichtiger halte als jede Modellfrage.\n\nDie Homogenisierung. Dass Teams, die dasselbe Modell fragen, ähnlichere Lösungen bauen, habe ich seit der einen Beobachtung vom Februar mehrfach wiedererkannt, aber nie gemessen. Es bleibt eine Sorge ohne Beleg, und ich lasse sie bewusst so stehen, statt sie zur These aufzublasen.\n\nDas Verlernen des eigenen Handwerks. Die Hausregeln aus dem Februar halten ungefähr so gut wie Neujahrsvorsätze: besser als nichts, schlechter als behauptet. Der bewusste Lauf ohne KI findet statt, aber seltener, als ich ihn eingeplant hatte. Der Sog der bequemen Variante ist real, jeden Tag. Genau diese Erfahrung hat mich für die zweite Serienhälfte skeptisch gegenüber allem gemacht, was auf Disziplin baut – und empfänglich für alles, was Sorgfalt in den Aufbau verlegt.\n\n## Der Bogen, im Rückblick\n\nDer Dreiklang Ich, Wir, System stand als Absicht schon im Auftakt. Was ich nicht geplant hatte, ist die Mechanik, die sich beim Schreiben zeigte: Jede Ebene erbt das ungelöste Problem der vorherigen. Die Disziplin des Einzelnen [skaliert nicht aufs Team](https://www.mikebild.dev/de/blog/mein-erfolg-laesst-sich-nicht-kopieren/), also schreibt das Team seine Regeln auf; aufgeschriebene Regeln binden niemanden, also braucht es Wissen mit Besitzern und [einen Ort, der die Session überlebt](https://www.mikebild.dev/de/blog/wissen-das-die-session-ueberlebt/); kuratiertes Wissen beantwortet noch keine Verbindlichkeitsfrage, also wandern die harten Regeln [in den Pfad eines eigenen Agenten](https://www.mikebild.dev/de/blog/eigener-agent-pro-fachdomaene/); und damit das kein Reißbrett-Entwurf bleibt, braucht es [Konzepte, Methoden und Prozesse](https://www.mikebild.dev/de/blog/hilfsmittel-konzepte-methoden-prozesse/), die den Anfang klein halten.\n\n```mermaid\nflowchart LR\n    subgraph AKT1[\"Akt 1 · Ich\"]\n        S[\"Session<br/>Erzeugen wird billig\"] --> P[\"Arbeitsweise<br/>Prüfen wird der Engpass\"]\n    end\n    subgraph AKT2[\"Akt 2 · Wir\"]\n        P --> V[\"Team-Varianz<br/>Disziplin skaliert nicht\"] --> D[\"Instruktionsdateien<br/>Empfehlung statt Regel\"]\n    end\n    subgraph AKT3[\"Akt 3 · System\"]\n        D --> W[\"Kuratiertes Wissen<br/>mit Besitzern\"] --> R[\"Regeln im Pfad<br/>Agent pro Fachdomäne\"] --> B[\"Systemarchitektur<br/>Oberfläche, Verträge, Freigaben\"]\n    end\n```\n\nDer Satz, der diesen Bogen zusammenhält, fiel in der Folge über kuratiertes Wissen: Nicht das Modell wird schlauer – die Organisation kuratiert ihr Wissen.\n\n## Der heutige Systemblick\n\nIm Mittelpunkt steht die Eigenschaft, um die es dieser Serie von Anfang an ging: die Trennung von Vorschlag und Wirkung, gebaut als eigene Freigabegrenze, nicht als pauschaler Schalter. Eine Workflow-Engine kann externe Writes bis zur Bestätigung zurückhalten. Ein Publishing-System kann die Promotion einer Vorschau an einen Menschen binden. Ein Wissenssystem kann Änderungen bis zur menschlichen Entscheidung als Vorschlag stehen lassen. Eine Auftragssteuerung kann Ausführung an freigegebene Aufträge binden. Dasselbe Prinzip, jeweils anders geschnitten – weil die Frage, was „wirken“ bedeutet, in jeder Fachdomäne anders beantwortet werden muss. Ein veröffentlichter Inhalt wirkt anders als eine freigegebene Wissensrevision, und beide anders als ein Workflow, der in ein Fremdsystem schreibt.\n\nDamit hat sich auch die Frage verschoben, die der Auftakt stellte. Sie lautete: Was können die Modelle? Sie lautet jetzt: Was macht eine Organisation daraus? Der Zugang zu einer externen Modell-API ist nicht der Teil dieser Architektur, den die Organisation dauerhaft selbst kontrolliert. Eine Oberfläche, hinter der eine sauber geschnittene Fachdomäne steht, maschinelle Verträge, auf die sich andere Systeme verlassen können, und Freigabepfade, die verhindern, dass ein Vorschlag ohne die vorgesehene menschliche Entscheidung wirkt: Das muss eine Organisation selbst aufbauen, und genau darin liegt der Anteil, der ihr unabhängig vom einzelnen Modell bleibt.\n\n## Position statt Prognose\n\nÜber Modellfähigkeiten in einem Jahr, über Produktivitätskurven ganzer Branchen oder über Arbeitsmärkte habe ich keine Urteilsgrundlage, und diese Monate haben mir vor allem beigebracht, wie schnell solche Aussagen altern. Ich formuliere deshalb keine Vision und markiere ausdrücklich, was dieses Zwischenfazit ist: mein begrenzter Erfahrungsstand, keine Prognose über unvermeidliche Markt- oder Organisationsentwicklungen.\n\nWas ich vertreten kann, weil es sich in diesen Monaten wiederholt bestätigt hat: Der dauerhafte Wert liegt weniger im einzelnen Modell als in eigenem Wissen, durchsetzbaren Regeln, klaren Fachdomänen und überprüfbaren Abläufen. Das ist keine Zukunftsaussage, sondern eine Beschreibung dessen, was nach jedem Modellwechsel übrig blieb – und dessen, was jedes Mal fehlte, wenn ein Ergebnis nicht trug.\n\nUnd für meinen eigenen Tisch bleibt eine Erwartung, an der man mich messen kann: der erste Fachdomänen-Agent, der lange genug im Betrieb ist, dass seine Ablehnungen Geschichten erzählen – richtige Neins, zu enge Neins, Sonderfälle, die ein eigenes Verb verdienen. Erst dann zeigt sich, ob der Kreislauf aus der letzten Folge trägt oder nur gut klingt.\n\n## Zwischenfazit, kein Schlusswort\n\nDiese Serie pausiert hier, und zwar aus einem einfachen Grund: Der Vorrat an Beobachtungen ist aufgebraucht. Was jetzt käme, wäre Extrapolation, und davon gibt es genug. Was diesem Zwischenfazit fehlt, ist Betriebszeit. Wenn wieder genug Neues beisammen ist, wenn die Neins des ersten Fachdomänen-Agenten etwas erzählen, schreibe ich weiter. Bis dahin gilt der Vorsatz vom Auftakt unverändert: der eigenen Begeisterung misstrauen, an echten Aufgaben messen, jedes Ergebnis am eigenen Handwerk prüfen. Das Hinschauen lohnt sich, und es hört nicht auf.\n\n## Weiterführende Quellen\n\n- [Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity (METR, Juli 2025)](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/) – die Studie, die gemessene Verlangsamung und gefühlte Beschleunigung nebeneinanderlegt\n- [The Anthropic Economic Index](https://www.anthropic.com/economic-index) – laufende Datenerhebung dazu, wofür KI in der Wirtschaft tatsächlich eingesetzt wird\n- [Things we learned about LLMs in 2024 (Simon Willison)](https://simonwillison.net/2024/Dec/31/llms-in-2024/) – nüchterner Jahresrückblick als Gegenmittel zu Prognosen-Prosa"},{"locale":"de","translation_key":"mcp-http-webhooks-a2a-einfach-erklaert","slug":"mcp-http-webhooks-a2a-einfach-erklaert","title":"MCP, HTTP, Webhooks und A2A einfach erklärt","summary":"MCP, HTTP mit OpenAPI, Webhooks und A2A verbinden Systeme auf unterschiedlichen Ebenen. Entscheidend ist, welche Verantwortung an der jeweiligen Grenze liegt.","tags":["Software","KI","Architektur"],"published_at":"2026-08-17T10:00:00+00:00","updated_at":"2026-08-17T05:36:19.088608+00:00","url":"https://www.mikebild.dev/de/blog/mcp-http-webhooks-a2a-einfach-erklaert/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/eae831362c2ce11a5d6057ede7c48de111635336991481077e3caf29cf5cb649.mp3","audio_duration_secs":630,"text":"Vier Verbindungen können technisch über HTTP laufen und trotzdem vier grundverschiedene Aufgaben erfüllen. Eine Agentenanwendung entdeckt ein Werkzeug. Ein festes Programm ruft einen dokumentierten Endpoint auf. Ein Dienst meldet ein bereits eingetretenes Event. Ein eigenständiger Agent übernimmt einen Auftrag mit eigener Laufzeit.\n\nMCP, HTTP mit OpenAPI, Webhooks und A2A beschreiben diese Grenzen. Keines der Verfahren ersetzt die fachliche Entscheidung darüber, wer lesen, schreiben, freigeben oder veröffentlichen darf. Ein Produkt kann mehrere dieser Maschinenoberflächen anbieten und zusätzlich eine eigene Weboberfläche für Menschen besitzen. Es bleibt trotzdem eine Fachdomäne mit einem maßgeblichen Produktzustand und denselben fachlichen Regeln.\n\n## Vier Fragen statt einer Rangliste\n\nEine Schnittstelle ist eine vereinbarte Grenze zwischen Systemen. Sie legt Eingaben, Ergebnisse und Fehler fest. Der Übertragungsweg beantwortet jedoch noch nicht, welche Verantwortung an dieser Grenze übergeben wird.\n\n| Technik | Leitfrage | Typische Aufgabe |\n| --- | --- | --- |\n| MCP | Welche Fähigkeiten kann eine Agentenanwendung entdecken und verwenden? | Werkzeuge und Kontext für eine offene Aufgabe bereitstellen |\n| HTTP mit OpenAPI | Welchen bekannten Maschinenbefehl kann ein Client ausführen? | Einen stabilen Dienstvertrag aufrufen und prüfen |\n| Webhook | Welches eingetretene Event soll ein anderes System erfahren? | Einen nachgelagerten Ablauf zeitnah anstoßen |\n| A2A | Welchen begrenzten Auftrag kann ein eigenständiger Agent übernehmen? | Zustandsbehaftete Arbeit an ein anderes Agentensystem delegieren |\n\nDie vier Optionen stehen nicht in einer Rangfolge und liegen nicht auf derselben technischen Schicht. HTTP ist ein Übertragungsprotokoll, OpenAPI beschreibt eine Schnittstelle, Webhooks verwenden HTTP für Ereigniszustellungen, und MCP sowie A2A bringen eigene Interaktionsverträge mit. Ein A2A-Agent kann intern MCP-Werkzeuge und normale HTTP-APIs aufrufen.\n\n## MCP stellt Fähigkeiten für Agentenanwendungen bereit\n\nMCP steht für Model Context Protocol. Eine Agentenanwendung kann damit etwa die Suche eines Wissensdienstes als Werkzeug entdecken; die Sichtbarkeit dieses Werkzeugs ist noch keine fachliche Berechtigung und kein Ersatz für einen festen Workflow.\n\nEin Server kann lokal als Prozess oder entfernt als Webdienst laufen. Das Wort „Server“ beschreibt seine Rolle im Protokoll, nicht seinen Standort.\n\n```json\n{\n  \"mcpServers\": {\n    \"knowledge\": {\n      \"type\": \"http\",\n      \"url\": \"https://knowledge.example.com/mcp\"\n    }\n  }\n}\n```\n\nNach dem Verbinden kann die Agentenanwendung das Eingabeschema prüfen und das Werkzeug aufrufen. Das Modell erhält dadurch keine pauschale Berechtigung. Der Host steuert, welche Fähigkeiten sichtbar sind und welche Aufrufe eine Zustimmung verlangen. Der Server authentifiziert und autorisiert den Aufruf. Der zuständige Dienst setzt zusätzlich seine fachlichen Regeln für die Operation durch.\n\nMCP passt zu offenen Aufgaben. Eine Agentenanwendung kann in einem Wissensdienst nach freigegebenem Wissen suchen, Quellen lesen und abhängig vom Ergebnis entscheiden, welcher nächste Schritt sinnvoll ist. Für wiederholte Veröffentlichungen mit identischer Schrittfolge ist diese Freiheit unnötig. Ein gespeicherter, freigegebener Workflow ist dort leichter zu prüfen und zu wiederholen.\n\n## HTTP und OpenAPI bilden einen ausdrücklichen Maschinenvertrag\n\nHTTP regelt Anfrage und Antwort. OpenAPI beschreibt darauf aufbauende APIs maschinenlesbar: Pfade, Methoden, Eingaben, Antworten und Sicherheitsverfahren. Menschen können die Beschreibung lesen, Programme daraus Clients erzeugen und Prüfungen die Implementierung mit dem Vertrag vergleichen.\n\nDer folgende Aufruf ist ein schematisches Beispiel:\n\n```http\nPOST /v1/sites/demo/previews HTTP/1.1\nHost: content.example.com\nAuthorization: Bearer <token>\nContent-Type: application/json\n\n{\n  \"revisionIds\": [\"rev-123\", \"rev-456\"]\n}\n```\n\nDer Aufruf fordert eine Vorschau an. Er sagt nichts darüber aus, wer den Inhalt fachlich geprüft hat oder ob diese Vorschau veröffentlicht werden darf. OpenAPI kann den technischen Vertrag präzisieren. Die Freigaberegel gehört in die Fachdomäne und in den kontrollierten Ablauf.\n\nIn einem Publishing-System kann die HTTP- und OpenAPI-Oberfläche feste Integrationen bedienen, ein Remote-MCP-Endpoint ausgewählte Fähigkeiten an Agentenanwendungen richten und eine Weboberfläche die menschliche Arbeit in derselben Publishing-Domäne tragen. Alle drei Zugänge arbeiten dann mit denselben Revisionen, Vorschauen, Releases und Berechtigungsgrenzen; keiner führt einen zweiten Persistenzpfad ein.\n\n## Ein Webhook meldet ein Event\n\nBei einem normalen API-Aufruf fragt der Client aktiv nach. Bei einem Webhook sendet die Event Source eine HTTP-Anfrage an eine vorher registrierte Adresse. Der Empfänger muss dadurch nicht fortlaufend prüfen, ob sich etwas geändert hat.\n\n```http\nPOST /webhooks/knowledge HTTP/1.1\nHost: orchestration.example.com\nwebhook-id: evt-789\nwebhook-timestamp: 1785585600\nwebhook-signature: v1,<signature>\nContent-Type: application/json\n\n{\n  \"type\": \"proposal.approved\",\n  \"data\": {\n    \"space\": \"product-docs\",\n    \"concepts\": [\"integration-options\"]\n  }\n}\n```\n\nDer Event-Typ im Beispiel ist absichtlich generisch. In diesem Ablauf transportiert der Webhook nur das Event und die Referenz auf den maßgeblichen Stand. Der Empfänger prüft Signatur und Alter, erkennt Mehrfachzustellungen über die Event-ID und liest den Stand anschließend mit eigener Berechtigung aus dem verantwortlichen System.\n\nMehrfache Zustellung gehört zum normalen Fehlerbild. Der Empfänger muss idempotent arbeiten: Dieselbe Event-ID darf fachlich nur einmal wirken. Er antwortet schnell und verschiebt längere Arbeit in einen gespeicherten Ablauf. Ein Wissensdienst kann dafür signierte Standard Webhooks liefern. Eine Workflow-Engine kann einen solchen Eingang signaturgeprüft und gegen Wiederholungen geschützt an genau einen versionierten Workflow binden, ohne die Wissens- oder Publishing-Regeln der beteiligten Systeme zu übernehmen.\n\n## A2A delegiert an ein eigenständiges Agentensystem\n\nA2A steht für Agent2Agent. Das Protokoll verbindet einen aufrufenden Agenten mit einem eigenständigen entfernten Agentensystem. Der Client kennt dessen veröffentlichte Fähigkeiten, aber nicht dessen internen Plan, Speicher oder Werkzeuge. Der entfernte Agent bleibt dafür verantwortlich, wie er den Auftrag innerhalb seiner Grenzen bearbeitet.\n\nEine Agent Card beschreibt Identität, Endpoint, Fähigkeiten und Anforderungen an die Anmeldung. Eine Message überträgt einen Gesprächsschritt aus Text, Dateien oder strukturierten Daten. Länger laufende Arbeit erhält einen Task mit eigener ID und einem Lifecycle. Ergebnisse werden als Artifacts zurückgegeben. Rückfragen und andere notwendige Entscheidungen erscheinen als Zustandsübergänge des Tasks.\n\nDas unterscheidet Delegation von einem Werkzeugaufruf. Bei MCP ruft eine Agentenanwendung eine beschriebene Fähigkeit auf. Bei A2A übergibt ein Agent ein Ziel an ein anderes System, das selbst planen, Werkzeuge verwenden und mehrere Schritte ausführen kann.\n\n## Weboberflächen und Maschinenoberflächen erfüllen verschiedene Aufgaben\n\nEine Weboberfläche für Menschen ist keine fünfte Integrationsart. MCP, HTTP mit OpenAPI, Webhooks und A2A verbinden Maschinen. Weboberfläche und Maschinenoberflächen arbeiten mit dem Zustand derselben Fachdomäne und führen keinen zweiten Persistenzpfad ein.\n\nJede Weboberfläche verwendet dafür die Begriffe und Entscheidungen ihrer eigenen Domäne. In einem Wissensdienst ist eine ausstehende Wissensänderung ein Änderungsvorschlag, in einer Workflow-Engine gehört eine Ausführung zu einer bestimmten Workflow-Version.\n\nAus dieser Trennung folgen zwei Grenzen:\n\n- Eine Weboberfläche wird nicht zum zweiten fachlichen System mit abweichenden Regeln.\n- Ein Maschinenprotokoll wird nicht zur unbeabsichtigten Umgehung der menschlichen Entscheidung.\n\n## Kein Protokoll erteilt von selbst Berechtigungen\n\nAuthentifizierung beantwortet: Wer stellt die Anfrage? Autorisierung beantwortet: Was darf diese Identität tun? Ein gültiger Schlüssel sollte Lesen, Schreiben und Veröffentlichen nicht pauschal zusammenfassen.\n\nEin Agent, der Wissen sucht, braucht nur Leserechte. Ein Schritt, der eine Vorschau baut, braucht die dafür erforderlichen Schreibrechte. Eine Veröffentlichung darf eine eigene Berechtigung und eine sichtbar gebundene menschliche Freigabe verlangen. Wenn eine Operation über mehrere Oberflächen angeboten wird, müssen für sie dieselben fachlichen Freigabegrenzen gelten.\n\nZuverlässigkeit entsteht ebenfalls nicht durch den Namen des Protokolls. Ein HTTP-Aufruf kann nach erfolgreicher Verarbeitung abbrechen, bevor die Antwort beim Client ankommt. Ein Webhook kann mehrfach eintreffen. Ein A2A-Task kann lange auf eine Entscheidung warten. Jeder schreibende Schritt braucht deshalb eine stabile Kennung, eine klare Wiederholungsregel und einen gespeicherten Zustand.\n\nFür schreibende oder freigabepflichtige Integrationen müssen drei Verträge zusammenpassen:\n\n- Der technische Vertrag beschreibt Eingaben, Ergebnisse und Fehler.\n- Der fachliche Vertrag legt fest, welches System Wissen, Freigabe und Veröffentlichung besitzt.\n- Der betriebliche Vertrag regelt Zeitlimits, Wiederholungen, Logging und den Umgang mit Ausfällen.\n\n## Ein Ablauf mit allen vier Grenzen\n\n```mermaid\nflowchart LR\n    U[\"Mensch<br/>formuliert ein Ziel\"] --> A[\"Agentenanwendung<br/>bearbeitet offene Aufgabe\"]\n    A -->|\"MCP<br/>suchen und lesen\"| K[\"Wissensdienst<br/>geprüftes Wissen\"]\n    A -->|\"MCP oder HTTP / OpenAPI<br/>Revision und Vorschau\"| C[\"Publishing-System<br/>Publishing-Domäne\"]\n    K -->|\"signierter Webhook<br/>Freigabeereignis\"| S[\"Workflow-Engine<br/>versionierter Workflow\"]\n    S -->|\"HTTP / OpenAPI<br/>festgelegte Schritte\"| C\n    A -.->|\"A2A<br/>begrenzten Auftrag delegieren\"| R[\"Agentensystem<br/>eigenständiger Task\"]\n    H[\"Mensch in der jeweiligen Weboberfläche\"] -.-> K\n    H -.-> S\n    H -.-> C\n    H -.-> R\n```\n\nDer erste Durchlauf kann begleitet sein. Eine Agentenanwendung liest im Wissensdienst, erzeugt Markdown und baut im Publishing-System eine Vorschau. Ein Mensch sieht die Ergebnisse und kann die Reihenfolge noch verändern.\n\nSobald sich die Folge stabil wiederholt, gehört sie als versionierter Workflow in eine Workflow-Engine. Der Workflow liest eine konkrete freigegebene Wissensrevision, erzeugt eine Content-Revision und baut eine Vorschau. Er veröffentlicht nicht deshalb automatisch, weil ein Webhook ihn gestartet hat. Das Publishing-System behält die Freigabe- und Release-Grenze.\n\nA2A kommt hinzu, wenn tatsächlich ein eigenständiges Agentensystem einen begrenzten Auftrag mit eigener Laufzeit übernimmt. Ein einfacher API-Aufruf wird durch die Bezeichnung „Agent“ nicht zu einer Delegation.\n\n## Die Entscheidung liegt vor dem Protokoll\n\nDie Tabelle hilft erst, wenn drei Fragen beantwortet sind: Welches System besitzt den Zustand? Welche Identität darf ihn verändern? Welche Wirkung benötigt eine menschliche Entscheidung? Daraus folgen die Regeln für Wiederholungen und die Ansicht, in der ein Mensch den aktuellen Stand prüfen kann.\n\nZuerst werden der Besitzer von Zustand und Freigabe festgelegt. Danach folgt das Protokoll.\n\n## Weiterführende Quellen\n\n- [Model Context Protocol: Architektur](https://modelcontextprotocol.io/docs/learn/architecture)\n- [Model Context Protocol: Einführung](https://modelcontextprotocol.io/docs/getting-started/intro)\n- [OpenAPI Specification](https://spec.openapis.org/oas/)\n- [Standard Webhooks](https://www.standardwebhooks.com/)\n- [A2A: zentrale Konzepte](https://a2a-protocol.org/latest/topics/key-concepts/)\n- [A2A und MCP im Vergleich](https://a2a-protocol.org/latest/topics/a2a-and-mcp/)"},{"locale":"de","translation_key":"a2a-agenten-zusammenarbeit","slug":"a2a-agenten-zusammenarbeit","title":"A2A: Wenn Agenten zusammenarbeiten","summary":"Agent Card, Message, Task und Artifact verständlich erklärt: wie A2A 1.0 eigenständige Agentensysteme verbindet, was das Protokoll von MCP unterscheidet und wann sich die Delegation an ein eigenständiges System lohnt.","tags":["Software","KI","Architektur"],"published_at":"2026-07-22T10:00:00+00:00","updated_at":"2026-08-18T18:22:46.983957+00:00","url":"https://www.mikebild.dev/de/blog/a2a-agenten-zusammenarbeit/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/ff952355488811c160d6a793a3334543ee0ccefc7fcf72f832060a239ee9e80f.mp3","audio_duration_secs":691,"text":"Ein Agentensystem braucht eine begrenzte Codeänderung in einem fremden Repository. Es könnte selbst Werkzeuge laden, den Code lesen und die Änderung entwerfen. Es kann den Auftrag aber auch an ein eigenständiges System übergeben, das in einer anderen Umgebung läuft, eigene Berechtigungen besitzt und später ein prüfbares Ergebnis zurückmeldet.\n\nA2A 1.0 – die Abkürzung steht für Agent2Agent – beschreibt für diesen zweiten Fall die Übergabe und Verfolgung eines Auftrags zwischen eigenständigen Systemen. Die veröffentlichte Spezifikation des offenen Protokolls behandelt, wie ein Auftraggeber einen entfernten Agenten findet, ihm Messages übermittelt, länger laufende Aufgaben verfolgt und Ergebnisse entgegennimmt. Welches Sprachmodell, welche Programmiersprache oder welches Framework intern arbeitet, schreibt sie nicht vor.\n\n## Eigenständig ist das entscheidende Wort\n\nNicht jede benannte Rolle ist ein eigener Agent. Wenn eine Anwendung nacheinander drei Prompts ausführt und alle Werkzeuge, Zugangsdaten und Zustände zentral verwaltet, sind das aus Sicht der Architektur drei Arbeitsschritte in einem Agentensystem. A2A bringt dort wenig.\n\nEin entfernter A2A-Agent ist dagegen ein eigenständiger Dienst. Er entscheidet innerhalb seines Auftrags selbst, wie er arbeitet. Der aufrufende Agent sieht die angebotenen Fähigkeiten und die ausgetauschten Daten, aber nicht automatisch den internen Speicher, die Überlegungen oder die Werkzeuge des anderen Systems. Diese Kapselung trennt die Berechtigungs- und Task-Grenzen beider Systeme: Der entfernte Agent arbeitet mit eigenen Zugriffsrechten, und ausgetauscht werden sollte nur, was der Auftrag vorsieht.\n\nIm Protokoll nimmt ein A2A-Client im Auftrag des Benutzers Kontakt auf. Der A2A-Server stellt den entfernten Agenten bereit. Client und Server sind Kommunikationsrollen, keine Systemklassen: Bei einem anderen Auftrag kann dasselbe System die andere Rolle einnehmen.\n\n```mermaid\nflowchart LR\n    U[\"Benutzer<br/>gibt ein Ziel vor\"] --> C[\"Aufrufender Agent<br/>A2A-Client\"]\n    C -->|\"Agent Card lesen\"| S[\"Entfernter Agent<br/>A2A-Server\"]\n    C -->|\"Message<br/>Auftrag und Kontext\"| S\n    S -->|\"Task<br/>Zustand und Rückfragen\"| C\n    S -->|\"Artifacts<br/>Ergebnisse\"| C\n    S --> M[\"Interne Modelle, Tools<br/>und Datenquellen\"]\n    C -.->|\"kein automatischer Zugriff\"| M\n```\n\n## Die Agent Card ist die Beschreibung, nicht die Berechtigung\n\nBevor ein Client einen Auftrag sendet, muss er wissen, was der andere Agent anbietet und wie er erreichbar ist. Dafür dient die Agent Card, ein JSON-Dokument mit Metadaten. Die veröffentlichte A2A-1.0-Spezifikation beschreibt darin unter anderem Identität, unterstützte Schnittstellen und angebotene Skills; als Bezugswege nennt sie eine standardisierte Adresse (`https://{domain}/.well-known/agent-card.json`), daneben Kataloge oder eine feste Konfiguration.\n\nDas folgende fiktive Publishing-Beispiel ist auf die hier benötigten Felder reduziert und beansprucht keine vollständige A2A-1.0-Agent-Card.\n\n```json\n{\n  \"name\": \"Publishing Agent\",\n  \"description\": \"Builds previews and prepares approved releases\",\n  \"supportedInterfaces\": [\n    {\n      \"url\": \"https://publishing.example.com/a2a\",\n      \"protocolBinding\": \"HTTP+JSON\",\n      \"protocolVersion\": \"1.0\"\n    }\n  ],\n  \"version\": \"1.0.0\",\n  \"capabilities\": {\n    \"streaming\": true,\n    \"pushNotifications\": true,\n    \"extendedAgentCard\": true\n  },\n  \"defaultInputModes\": [\"text/plain\", \"application/json\"],\n  \"defaultOutputModes\": [\"text/markdown\", \"application/json\"],\n  \"skills\": [\n    {\n      \"id\": \"prepare-publication\",\n      \"name\": \"Prepare publication\",\n      \"description\": \"Creates a preview from approved knowledge\",\n      \"tags\": [\"publishing\", \"preview\", \"content\"]\n    }\n  ]\n}\n```\n\nDie Agent Card ist mit einer öffentlichen Leistungsbeschreibung vergleichbar. Dass dort ein Skill aufgeführt ist, erlaubt noch keinen Aufruf. Anmeldung und Autorisierung bleiben eigene Sicherheitsentscheidungen: Der Server muss bei jedem Auftrag prüfen, wer anfragt und was dieser Auftraggeber tun darf. Eine öffentliche Agent Card sollte außerdem keine internen Fähigkeiten oder vertraulichen Endpoints verraten.\n\n## Message, Part, Task und Artifact\n\nMessage, Part, Task und Artifact bezeichnen unterschiedliche Bausteine eines Auftrags.\n\n| Begriff | Bedeutung | Beispiel bei delegierter Arbeit |\n| --- | --- | --- |\n| Message | Ein Gesprächsbeitrag des Benutzers oder Agenten | „Analysiere diese Abhängigkeit und schlage eine Änderung vor.“ |\n| Part | Ein Bestandteil einer Message oder eines Artifacts | Anweisung als Text, eine Datei oder strukturierte Daten |\n| Task | Eine zustandsbehaftete Arbeitseinheit mit eindeutiger ID | Der Auftrag wartet auf eine Rückfrage oder arbeitet weiter |\n| Artifact | Ein vom Agenten erzeugtes Ergebnis | Analysebericht, vorbereitete Änderung, Vorschau-URL |\n\nEine Message kann sofort mit einer anderen Message beantwortet werden. Das passt zu einer kurzen Unterhaltung ohne dauerhaften Arbeitszustand. Muss die Arbeit weiterlaufen oder über mehrere Gesprächsrunden erhalten bleiben, antwortet der entfernte Agent mit einem Task.\n\nDer Task ist mehr als eine technische Anfrage-ID. Er hält den Zustand einer fachlichen Arbeitseinheit. Der Client kann ihn später lesen, auf eine Rückfrage antworten oder eine Stornierung anfordern. Nach der Spezifikation können mehrere Messages über eine `contextId` zu demselben Gesprächszusammenhang gehören; eine `taskId` bezeichnet die konkrete Arbeit. Ein vereinfachtes, nicht normatives Beispiel:\n\n```http\nPOST /message:send HTTP/1.1\nHost: agents.example.com\nAuthorization: Bearer <token>\nContent-Type: application/a2a+json\nA2A-Version: 1.0\n\n{\n  \"message\": {\n    \"role\": \"ROLE_USER\",\n    \"messageId\": \"msg-123\",\n    \"parts\": [\n      {\n        \"text\": \"Prepare a limited change proposal. Do not merge it.\"\n      },\n      {\n        \"data\": {\n          \"repository\": \"product-service\",\n          \"scope\": [\"dependency-upgrade\"]\n        },\n        \"mediaType\": \"application/json\"\n      }\n    ]\n  }\n}\n```\n\nDie Parts trennen unterschiedliche Inhalte innerhalb derselben Message: Text trägt eine Anweisung, eine Datei übergibt ein Dokument, strukturierte Daten erlauben ein vereinbartes Schema ohne erneutes Auslesen aus Prosa. Der Empfänger muss Medientyp, Größe, Herkunft und Berechtigung jedes Inhalts prüfen.\n\nArtifacts sind die Arbeitsergebnisse, nicht bloß Gesprächsbeiträge. Laut Spezifikation kann ein Task mehrere Artifacts liefern, und ein Artifact kann während eines Datenstroms schrittweise ergänzt werden. Der Client sollte deshalb Artifact-ID und Task-ID speichern, statt nur den letzten sichtbaren Text zu kopieren. Eine typische erste Antwort sieht so aus – der Server hat angenommen, aber noch nicht abgeschlossen:\n\n```json\n{\n  \"task\": {\n    \"id\": \"task-456\",\n    \"contextId\": \"context-789\",\n    \"status\": {\n      \"state\": \"TASK_STATE_WORKING\",\n      \"timestamp\": \"2026-08-07T10:05:00Z\"\n    },\n    \"artifacts\": []\n  }\n}\n```\n\n## Der Lifecycle macht längere Arbeit sichtbar\n\nA2A ist auf asynchrone Aufgaben ausgelegt. Ein Server kann sofort einen Task zurückgeben und im Hintergrund weiterarbeiten. Für Aktualisierungen sieht die Spezifikation drei Zustellwege vor: Queries, einen fortlaufenden Datenstrom oder Push Notifications.\n\n```mermaid\nstateDiagram-v2\n    [*] --> SUBMITTED\n    SUBMITTED --> WORKING\n    WORKING --> INPUT_REQUIRED: Rückfrage\n    INPUT_REQUIRED --> WORKING: weitere Message\n    WORKING --> AUTH_REQUIRED: zusätzliche Freigabe\n    AUTH_REQUIRED --> WORKING: Berechtigung erteilt\n    WORKING --> COMPLETED\n    WORKING --> FAILED\n    SUBMITTED --> REJECTED\n    WORKING --> CANCELED\n    COMPLETED --> [*]\n    FAILED --> [*]\n    REJECTED --> [*]\n    CANCELED --> [*]\n```\n\nDas Diagramm vereinfacht den in der Spezifikation von Version 1.0 definierten Zustandsraum. `INPUT_REQUIRED` bedeutet, dass der Agent weitere fachliche Angaben braucht. `AUTH_REQUIRED` signalisiert eine während des Auftrags nötige Autorisierung; Zugangsdaten gehören dabei nicht als Klartext in eine Message, sondern laufen über einen getrennten, zuvor vereinbarten Weg. Als Endzustände definiert die Spezifikation `COMPLETED`, `FAILED`, `CANCELED` und `REJECTED`. Ein Client darf einen Endzustand nicht durch blindes Wiederholen wiederbeleben, sondern muss bewusst einen neuen Task anlegen.\n\nPolling, Streaming und Push lösen dasselbe Zustellungsproblem auf unterschiedliche Weise. Beim Polling fragt der Client in sinnvollen Abständen nach dem Task – einfach, bei langen Pausen aber verschwenderisch. Beim Streaming bleibt eine Verbindung offen und der Server sendet Status- und Artifact-Updates als Events; nach einer Unterbrechung muss der Client den gespeicherten Task erneut lesen, denn ein Datenstrom ist kein Archiv. Push Notifications ersparen die dauerhafte Verbindung, verlangen dafür einen abgesicherten HTTP-Endpoint beim Client, inklusive Authentifizierung, Schutz vor internen Zieladressen und Behandlung mehrfacher Zustellungen.\n\n## Delegation erzeugt keine neue Berechtigung\n\nA2A nimmt einem System keine Sicherheitsentscheidung ab. Ein aufrufender Agent sollte einer gefundenen Agent Card nicht allein deshalb vertrauen, weil sie formal korrekt ist. Vor einem Auftrag muss feststehen, welchem Anbieter das eigene System vertraut, welche Daten es verlassen dürfen und welche Wirkung der entfernte Agent auslösen kann.\n\nDer A2A-Server steht in derselben Pflicht: Er muss bei jedem Auftrag prüfen, wer anfragt und was dieser Auftraggeber tun darf, und Messages als nicht vertrauenswürdige Eingaben behandeln. Der wichtigste Grundsatz dahinter: Delegation darf keine neue Berechtigung erzeugen. Wer einen Auftrag übermittelt, darf dadurch nicht mehr Rechte im Zielsystem erhalten, und der ausführende Agent darf nicht stillschweigend die Rechte seines Auftraggebers erben. Der Auftrag bleibt begrenzt.\n\nEin Zielsystem kann diese Begrenzung explizit machen: Ein delegierter Auftrag ist dann an einen aktiven, menschlich freigegebenen Auftragsstand gebunden. Was dieser Stand nicht erlaubt, kann auch ein technisch korrekter A2A-Aufruf nicht auslösen. Ein menschlicher Freigabeschritt bleibt damit eine fachliche Entscheidung im Zielsystem – ein Agent darf eine Freigabe nicht aus einer freundlichen Formulierung in einer Message ableiten.\n\n## MCP, A2A und Weboberfläche sind verschiedene Zugänge, keine Etiketten\n\nMCP stellt einer Agentenanwendung Werkzeuge und Kontext bereit; die Verantwortung für die offene Aufgabe bleibt in der Anwendung. A2A verbindet eigenständige Agentensysteme: Der Auftraggeber übergibt ein Ziel, der entfernte Agent verantwortet die Ausführung und führt einen eigenen Task-Lifecycle. MCP und A2A modellieren damit unterschiedliche Verantwortlichkeiten und Lifecycles.\n\n| Frage | MCP | A2A |\n| --- | --- | --- |\n| Gegenüber | Fähigkeitsserver | Eigenständiges Agentensystem |\n| Auffindbare Beschreibung | Werkzeuge und Kontextquellen | Agent Card mit Skills und Schnittstellen |\n| Typische Arbeit | Werkzeug auswählen und aufrufen | Ziel oder Teilaufgabe delegieren |\n| Länger laufender Zustand | Durch die Anwendung modelliert | Task-Lifecycle ist Protokollkonzept |\n| Ergebnis | Tool-Ergebnis oder Resource | Message oder ein oder mehrere Artifacts |\n| Interne Umsetzung | Fähigkeit mit definiertem Schema | Entfernter Agent bleibt intern eigenständig |\n\nDazu kommt eine Weboberfläche als Zugang für Menschen. Diese Zugänge haben unterschiedliche Aufgaben, und ein System kann mehrere davon anbieten, ohne dass daraus mehrere Fachmodelle werden.\n\nEin System kann etwa begrenzte Analyse- und Änderungsaufträge über A2A 1.0 anbieten, während REST, MCP, A2A und Weboberfläche denselben strukturierten Task- und Ergebnisdatensatz lesen.\n\n## Wann A2A sinnvoll ist\n\nA2A lohnt sich, wenn mehrere Bedingungen gleichzeitig zutreffen: Die beteiligten Agenten werden unabhängig entwickelt oder betrieben. Die Arbeit dauert möglicherweise länger als eine einzelne Anfrage, benötigt Rückfragen oder erzeugt mehrere Ergebnisse. Der Auftraggeber legt Ziel und zulässige Wirkung fest, der entfernte Agent verantwortet die interne Ausführung.\n\nFür eine bekannte Folge fester Schritte ist ein deterministischer Workflow meist einfacher. Bloß verschiedene Rollennamen, mehrere Sprachmodelle oder getrennte Prompts rechtfertigen noch keine verteilte Agentenarchitektur – sie erzeugen nur eine zusätzliche Netzgrenze ohne zusätzliche Verantwortungsgrenze.\n\nDie Entscheidung lässt sich daran festmachen, wer die Verantwortung für die offene Aufgabe trägt. Bleibt sie in der eigenen Anwendung und benötigt sie lediglich Werkzeuge oder Kontext, kann MCP genügen. Übernimmt ein unabhängiges System einen begrenzten Auftrag mit eigenem Task-Lifecycle, ist A2A der passende Vertrag. Wer diese Ebenen auseinanderhält, baut keine unnötigen Agenten – und erkennt, welche Merkmale die hier beschriebene Delegation besitzt: eine Agent Card, ein authentifizierter Aufruf, ein nachverfolgbarer Task und ein begrenzter Auftrag.\n\n## Weiterführende Quellen\n\n- [A2A Protocol Specification 1.0](https://a2a-protocol.org/latest/specification/)\n- [A2A: Core Concepts](https://a2a-protocol.org/latest/topics/key-concepts/)\n- [A2A: Life of a Task](https://a2a-protocol.org/latest/topics/life-of-a-task/)\n- [A2A und MCP im Vergleich](https://a2a-protocol.org/latest/topics/a2a-and-mcp/)\n- [Model Context Protocol: Architektur](https://modelcontextprotocol.io/docs/learn/architecture)\n- [MCP, HTTP, Webhooks und A2A einfach erklärt](https://www.mikebild.dev/de/blog/mcp-http-webhooks-a2a-einfach-erklaert/)"},{"locale":"de","translation_key":"stuendlich-ist-nicht-echtzeit","slug":"stuendlich-ist-nicht-echtzeit","title":"Stündlich ist nicht Echtzeit","summary":"Ein abgeschlossener Stundenreport beantwortet andere Fragen als laufende Betriebsbeobachtung – und wird einfacher, sobald Zeitfenster, Verspätung und Messlücken ausdrücklich modelliert sind.","tags":["Software","Architektur","Observability","Delivery"],"published_at":"2026-07-20T10:00:00+00:00","updated_at":"2026-08-18T15:35:19.820644+00:00","url":"https://www.mikebild.dev/de/blog/stuendlich-ist-nicht-echtzeit/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/b45ed288a8d569fdb4c59829523ded08e78925e4a33d135146699a3d8b88a416.mp3","audio_duration_secs":779,"text":"Ein stündlicher Report fragt nicht nach dem aktuellen Zustand, sondern nach der gerade abgeschlossenen Stunde. Was um 14:00:00 UTC passiert, gehört bereits in das nächste Zeitfenster. Der Lauf beginnt deshalb erst, wenn das Zeitfenster geschlossen ist, und veröffentlicht seinen Stand einige Minuten später. Für einen Alarm wäre das viel zu spät. Für eine verlässliche Zusammenfassung ist es genau die gewünschte Verzögerung.\n\nDiese zeitliche Entscheidung trennt den Stundenreport von laufender Betriebsbeobachtung. Ein abgeschlossener Report beantwortet eine andere Frage als Monitoring: Er hält einen begrenzten Zeitraum als prüfbaren Stand der Beobachtungen fest, während Monitoring auf neue Signale reagieren muss. Der Unterschied liegt nicht zuerst in Prometheus, Grafana oder Markdown. Er liegt darin, wie schnell ein neuer Wert eine Reaktion auslösen muss und ob sich die betrachtete Aussage später noch verändern darf.\n\nDer Beitrag [„Markdown Reports statt Dashboard-Zwang“](https://www.mikebild.dev/de/blog/markdown-reports-statt-dashboard/) beschreibt bereits den Unterschied zwischen flüchtiger Ansicht und prüfbarem Stand. Hier geht es enger um die Zeitmechanik eines regelmäßigen Produktreports: geschlossene Zeitfenster, verspätete Daten, Wiederholungen und die Grenze zu echter Betriebsbeobachtung.\n\n## Zwei Zeitachsen, zwei Aufgaben\n\nMonitoring arbeitet möglichst nah am Event. Eine Fehlerrate steigt, ein Alarm wird ausgewertet, jemand öffnet Logs und Traces. Neue Daten verändern die Darstellung fortlaufend. Ein Report wartet dagegen, bis sein Zeitraum beendet ist. Er kann dann feststellen, welche Quellen vollständig vorlagen, seine Fakten hashen und denselben Stand später erneut ausliefern.\n\n```mermaid\nflowchart LR\n    E[\"Ereignis\"] --> M[\"Live-Metrik<br/>Sekunden bis Minuten\"]\n    M --> A[\"Alarm oder Untersuchung\"]\n    E --> W[\"geschlossenes Stundenfenster\"]\n    W --> R[\"unveränderlicher Report\"]\n    R --> V[\"Vergleich und Einordnung\"]\n```\n\nBeide Wege dürfen dasselbe Event sehen und trotzdem zu verschiedenen Ergebnissen kommen. Das Monitoring kann um 13:42 auf fünf Fehler in zwei Minuten reagieren. Der Stundenreport hält später fest, dass im Zeitfenster von 13 bis 14 Uhr fünf Fehler bei 1.200 Ausführungen auftraten, welche Quellen abgedeckt waren und ob die Häufung im Vergleich zu früheren Zeitfenstern auffällt.\n\nEine laufend aktualisierte Oberfläche für die zweite Aufgabe würde unvollständige Zwischenstände zeigen. Während des laufenden Zeitfensters sind Zähler unvollständig. Ein Wert von null um 13:01 sagt fast nichts über die Stunde aus. Ein wachsender Balken lädt dazu ein, Zwischenstände ungekennzeichnet mit abgeschlossenen Stunden zu vergleichen. Ohne Berücksichtigung der unterschiedlichen Abdeckung ist dieser Vergleich nicht belastbar.\n\n## Die Grenzen des Zeitfensters\n\nDie Sammlung verwendet halboffene UTC-Intervalle. Anfang eingeschlossen, Ende ausgeschlossen. Diese Schreibweise verhindert, dass ein Event an der Grenze in zwei Reports landet.\n\n```ts\ntype ClosedWindow = {\n  from: string; // inclusive RFC 3339 timestamp\n  to: string;   // exclusive RFC 3339 timestamp\n  bucket: \"hour\";\n};\n\nconst window: ClosedWindow = {\n  from: \"2026-07-18T13:00:00.000Z\",\n  to: \"2026-07-18T14:00:00.000Z\",\n  bucket: \"hour\"\n};\n```\n\nUTC vermeidet einen unangenehmen Sonderfall: In Europa hat der Tag der Sommerzeitumstellung nicht immer 24 lokale Stunden. Speicherung und Sammlung bleiben deshalb in UTC. Die Reportseite kann ein Datum später für ihre Leser lokalisieren, ohne die fachliche Grenze zu verändern.\n\nZwischen dem Ende des Zeitfensters und der Frischeprüfung sieht dieser Ablauf eine ausdrücklich festgelegte Reserve vor. Wird die Sammlung umfangreicher, müssen Startzeitpunkt, Timeout und Prüfgrenze gemeinsam angepasst werden. Eine heimlich verlängerte Reserve würde echte Verzögerungen nur später sichtbar machen.\n\n## Verspätete Daten und fehlende Läufe getrennt halten\n\nEin HTTP-Aufruf kann vorübergehend fehlschlagen. Ein Workflow kann nach dem Schreiben des Artefakts abbrechen, bevor er seinen Status aktualisiert. Ein Release kann erfolgreich sein, obwohl die Antwort beim Client nicht mehr ankommt. Darum darf ein Retry nicht einfach „noch einmal alles“ bedeuten.\n\nJeder Lauf hat ein eindeutiges Zeitfenster. Cadence-markierte Reports werden hier als immutable Veröffentlichungen behandelt: Ein einmal veröffentlichter Stundenstand ändert sich nicht mehr. Ein wiederholter erfolgreicher Versuch darf deshalb keinen zweiten, abweichenden Stundenreport für dasselbe Zeitfenster sichtbar machen.\n\nErst nach der vorgesehenen Reserve wird zwischen verspätet und fehlend unterschieden. Ein verspäteter Lauf kann noch erfolgreich abschließen und denselben Report veröffentlichen. Ein fehlender Lauf hinterlässt eine Lücke in der erwarteten Stundenfolge. Verspätung, Messlücke und geschlossenes Zeitfenster bleiben damit drei getrennte Sachverhalte, die der Report getrennt benennen sollte.\n\n## Was aus einer fehlenden Beobachtung folgt\n\nEin kritischer Fall für einen Stundenreport ist eine Stunde ohne Daten. Ein Beobachtungsdienst sollte dafür ausdrücklich vier Zustände unterscheiden: Eine Quelle wurde noch nie beobachtet, sie wurde geprüft und der erwartete Inhalt ist nicht vorhanden, sie ist zugangsgeschützt, oder sie ist tatsächlich fehlerhaft. Eine fehlende Beobachtung darf dabei weder als gesunder Zustand noch als Zahlenwert null ausgegeben werden.\n\nFür einen Stundenreport heißt das: Liegt für eine Stunde keine Messung vor, existiert für diese Stunde kein Wert. Der Report darf dann nicht behaupten, es habe null Events gegeben, denn diese Aussage würde eine Messung unterstellen, die nie stattgefunden hat. Er muss stattdessen ausweisen, dass die Quelle im betrachteten Zeitraum nicht beobachtet wurde und die Aussage offen bleibt. Wurde die Quelle dagegen geprüft und der erwartete Inhalt nicht gefunden, ist dieser Zustand beobachtet; daraus folgt aber nicht automatisch ein allgemeiner Fehlerzähler von null.\n\n## Wann Prometheus und Grafana fehlen würden\n\nWerkzeuge wie Prometheus und Grafana unterstützen unter anderem die laufende Untersuchung: Eine Query lässt sich während der Analyse anpassen und der Zeitraum verschieben. Diese Arbeitsweise ist wertvoll, wenn die Frage nicht vorab feststand.\n\nEine Oberfläche für Stundenreports kann dagegen auf abgeschlossene Reportzeiträume ausgerichtet sein. Diese Ausrichtung passt, solange die Oberfläche abgeschlossene Zeiträume erklären soll. Für eine Incident-Analyse kämen Warnungen dagegen zu spät, und die stündliche Auflösung reicht für eine Ursachensuche bis auf einzelne Requests nicht aus. Ein stündlicher Report ersetzt weder Alarmierung noch laufende Betriebsbeobachtung; er setzt beides als eigenständige Aufgaben voraus.\n\n## Vier Fragen vor der Werkzeugwahl\n\n„Dashboard oder Report?“ ist zu grob. Vier Fragen trennen die Anforderungen: Reaktionszeit, Veränderlichkeit, Untersuchung und Auflösung.\n\nDie erste betrifft die Reaktionszeit. Muss jemand innerhalb von Sekunden oder wenigen Minuten handeln, gehört die Beobachtung in ein Monitoring- und Alerting-System. Darf ein Team den Stand im nächsten regelmäßigen Arbeitszyklus prüfen, kann ein stündlicher oder täglicher Report reichen.\n\nDie zweite betrifft die Veränderlichkeit. Soll dieselbe URL morgen neue Werte zeigen, ist eine Live-Query passend. Muss später noch genau der Stand vom 18. Juli lesbar sein, braucht es ein immutable Artefakt oder einen ausdrücklich gespeicherten Snapshot.\n\nDie dritte betrifft die Untersuchung. Sind die Fragen vorab bekannt – Anzahl Releases, Fehler, Quellenabdeckung –, kann ein begrenztes Schema sie präzise abbilden. Entstehen die Fragen erst beim Blick auf eine Auffälligkeit, werden Query Language, variable Zeiträume und Drill-down wichtig.\n\nDie vierte betrifft die Auflösung. Ein stündlicher Zähler kann zeigen, dass etwas häufiger fehlschlug. Er kann nicht erklären, welcher einzelne Request langsam war oder welche Logzeile zu einem Trace gehört. Für diese Untersuchung müssen die hochaufgelösten Daten in ihrem Betriebswerkzeug bleiben.\n\n```yaml\ndecision:\n  reaction_time: next_work_cycle\n  immutable_history: required\n  questions_known_in_advance: true\n  per_request_drilldown: false\nresult: scheduled_report\n```\n\nSobald eine Antwort kippt, kann auch das passende Werkzeug wechseln. Ein Report und ein Live-System dürfen denselben Dienst beobachten, solange sie nicht vortäuschen, dieselbe Aufgabe zu erfüllen.\n\n## Der Scheduler ist Teil der Aussage\n\nEin manuell erzeugter Report belegt nur, dass irgendwann jemand einen Knopf gedrückt hat. Ein geplanter Lauf macht zusätzlich sichtbar, ob die erwartete Regelmäßigkeit eingehalten wurde. Eine Prüfung dieser Regelmäßigkeit muss deshalb zwischen geplanten und manuell ausgelösten Läufen unterscheiden: Manuelle Läufe dürfen eine ausgefallene geplante Stunde nicht verdecken, sonst zählt die Prüfung Erfolge, die nichts über die Zusage der Regelmäßigkeit aussagen.\n\nAuch eine Pause ist kein Fehler, wenn sie während eines Releases ausdrücklich gesetzt wurde. Sie muss jedoch sichtbar sein und nach dem Rollout bewusst aufgehoben werden. Ein vergessener Pause-Schalter ist kein Datenproblem, sondern eine unterbrochene Zusage über Regelmäßigkeit.\n\n## Was ein Stundenreport erklären muss\n\nOhne ausgewiesene Quellenabdeckung kann ein Operator eine Messlücke als Ergebnis lesen. Ein Stundenreport muss deshalb selbst erklären, worauf er sich stützt. Überblick, Frage, Schlussfolgerung und nächste Handlung lassen sich aus demselben semantischen Report-Dokument ableiten; ein zweiter, parallel gepflegter Dashboard-Datensatz ist dafür nicht nötig. Eine passende Oberfläche zeigt diese Antwort in abnehmender Wichtigkeit: zuerst Zustand und Ausnahme, dann wenige Signale, danach Evidenz und Provenienz.\n\nEine Seite mit dreißig Metrics ohne Frage ist schwerer zu prüfen als eine Seite mit einer klaren Frage, einem belegten Stand und einer benannten nächsten Entscheidung. Die Faktendefinition muss dafür auch Datenlücken abbilden: Sie sollte vorhandene, fehlende und veraltete Quellen getrennt nennen, damit eine offene Aussage nicht wie eine beantwortete aussieht.\n\n```md\n## Data quality\n\nThe source window is complete for four product APIs.\nExternal acquisition data is not connected yet and is shown as unavailable.\nNo value is inferred from missing input.\n```\n\nAuch die Aggregation braucht eine Erklärung. Eine wöchentliche Median-Laufzeit beantwortet eine andere Frage als das Maximum der langsamsten Stunde. Der Report nennt Zeitraum, erwartete und vorhandene Unterfenster sowie die verwendete Verdichtung. Sonst sieht eine präzise Zahl geprüfter aus, als sie ist.\n\n## Verdichtung über größere Zeiträume\n\nTages-, Wochen-, Monats- und Jahresreports entstehen aus bereits abgeschlossenen Artefakten. Ein Tagesreport kann auf den immutable Stundenständen aufsetzen, statt dieselben Quellen für jede Stunde erneut abzufragen, und dabei ausweisen, welche Stundenfenster ihm fehlen. Cadence-markierte Reports bleiben immutable Veröffentlichungen; ein Rollup ersetzt keinen Stundenstand, er verdichtet ihn.\n\n```mermaid\nflowchart TD\n    H[\"24 Stundenartefakte\"] --> D[\"Tagesreport\"]\n    D --> W[\"Wochenreport\"]\n    W --> M[\"Monatsreport\"]\n    M --> Y[\"Jahresreport\"]\n    H --> Q[\"Abdeckung und fehlende Fenster\"]\n    Q --> D\n```\n\nEin Tagesreport, dem einzelne Stundenfenster fehlen, kann trotzdem hilfreicher sein als gar kein Report – aber nur, wenn er sich klar als unvollständig ausweist. Er darf nicht dieselbe visuelle Sicherheit ausstrahlen wie ein vollständig abgedeckter Zeitraum. Die Datenqualität gehört neben die Kennzahlen, nicht in eine Fußnote.\n\nEine Oberfläche kann den neuesten abgeschlossenen Zeitraum vor weiteren Entscheidungshorizonten und einer begrenzten Historie anordnen. Welche Frage jeder gröbere Report beantwortet, ist eine Gestaltungsentscheidung. Eine naheliegende Aufteilung: Die Stunde prüft den Datenfluss und frische technische Signale. Der Tag beantwortet, was heute Aufmerksamkeit braucht. Die Woche vergleicht Tagesverläufe und wiederkehrende Ausnahmen. Der Monat ordnet Aktivitätsmuster, Betriebsrisiken und Messlücken für die nächste Planung ein. Das Jahr verdichtet nur jene Evidenz, die eine strategische Entscheidung tragen kann. Nur den Datumsfilter zu verbreitern wäre formal korrekt und inhaltlich schwach.\n\nAuch Zahlen sind dabei nicht bloß Werte. Eine Faktendefinition sollte Zähler, Bestände, Laufzeiten, Verhältnisse und Datenmengen unterscheiden, die Einheit nennen und festlegen, ob ein Rollup Summe, letzten Wert oder Mittelwert bevorzugt. Eine Maschine muss dann nicht aus einem Metriknamen raten, wie der Wert über mehrere Intervalle gelesen werden soll.\n\n## Einfache Technik braucht eine klare Grenze\n\nDer stündliche Ansatz kann ohne zusätzliche, dauerhaft laufende Auswertungsplattform auskommen, wenn vorhandene Systeme Sammlung, Planung und Veröffentlichung übernehmen. Seine Fragen stehen vor dem Lauf fest, und sein Ergebnis erscheint als immutable Veröffentlichung. Entscheidend ist die Verantwortungsgrenze: Der Report sammelt, schließt ab und veröffentlicht; die laufende Beobachtung bleibt bei den dafür gebauten Systemen.\n\nDiese Einfachheit bleibt nur erhalten, wenn das System zu seiner Aufgabe steht. Ein Report darf eine fehlende Datenquelle zeigen, statt eine neue Datenerfassung heimlich einzubauen. Er darf auf eine externe Incident-Ansicht verweisen, statt selbst zur Leitstelle zu werden. Und er darf eine Frage unbeantwortet lassen, wenn dafür weder Fakt noch Connector vorhanden ist.\n\nStündlich bedeutet hier nicht „fast live“. Es bedeutet: regelmäßig, abgeschlossen, wiederholbar und langsam genug, um einen vollständigen Stand zu prüfen. Wer schneller reagieren muss, braucht Monitoring und Alarmierung. Wer später nachvollziehen will, was in einem klaren Zeitraum bekannt war, braucht einen Stundenreport. Beide bestehen nebeneinander, mit klar zugeordneten Aufgaben: Monitoring liefert laufende Signale, Alarmierung stößt daraus eine Reaktion an, und der Stundenreport bewahrt den abgeschlossenen, prüfbaren Beobachtungsstand.\n\n## Weiterführende Quellen\n\n- [Prometheus Overview](https://prometheus.io/docs/introduction/overview/)\n- [Grafana Dashboards](https://grafana.com/docs/grafana/latest/visualizations/dashboards/)\n- [W3C Trace Context](https://www.w3.org/TR/trace-context/)"},{"locale":"de","translation_key":"claims-klein-belegt-pruefbar","slug":"claims-klein-belegt-pruefbar","title":"Claims: klein, belegt, prüfbar","summary":"Claims zerlegen Wiki-Seiten in einzelne Aussagen mit Subjekt, Prädikat, Objekt, Confidence, Status und wörtlichem Beleg. Dadurch werden Zustimmung und Widerspruch präzise.","tags":["Software","KI","Methodik"],"published_at":"2026-07-20T10:00:00+00:00","updated_at":"2026-08-18T06:39:59.272448+00:00","url":"https://www.mikebild.dev/de/blog/claims-klein-belegt-pruefbar/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/1f809af816f67e9351b254759bb71f152c836d42d3111514399aff3db6f09450.mp3","audio_duration_secs":736,"text":"„Unser Publishing ist sicher, schnell und zuverlässig.“ Der Satz klingt gut und taugt kaum als Claim. Drei Bewertungen stecken darin, keine besitzt ein Kriterium, und eine Quelle könnte höchstens Teile davon belegen. Eine prüfende Person müsste den ganzen Satz annehmen oder ablehnen, obwohl sie vielleicht nur einen belegten Rollback-Mechanismus als Teil der Zuverlässigkeit bestätigen kann.\n\nEine Wissensbasis sollte deshalb kleine Aussagen als `subject / predicate / object` speichern. Der Seitentext bleibt für Menschen lesbar. Claims bilden darunter jene Einheiten, die einzeln zitiert, geprüft, bestritten und stillgelegt werden können. Confidence und Status beantworten dabei verschiedene Fragen.\n\n## Ein Claim sagt genau eine Sache\n\nDas Subjekt benennt den Gegenstand, das Prädikat die Beziehung oder Eigenschaft und das Objekt den konkreten Wert. Ein guter Claim lässt sich ohne den restlichen Seitenabsatz verstehen.\n\n```json\n{\n  \"subject\": \"content-release\",\n  \"predicate\": \"rollback_mechanism\",\n  \"object\": \"switch the active pointer to an immutable revision\"\n}\n```\n\nDie Form ähnelt einem einfachen RDF-Triple, ist aber kein Zwang, die gesamte Fachlichkeit als universellen Graphen zu modellieren. Innerhalb eines Space entsteht ein kontrolliertes Vokabular, das zu dessen Fragen passt. `rollback_mechanism` kann dort sinnvoll sein, wo Releases verglichen werden; in einem HR-Space wäre es ohne Bedeutung.\n\nZu große Claims verbinden mehrere prüfbare Aussagen. Zu kleine Claims verlieren ihren Sinn. `content-release / uses / pointer` wäre zwar atomar, erklärt aber nicht, wofür der Pointer verwendet wird. Die Formulierung sollte eng genug für einen Widerspruch und vollständig genug für einen Leser sein.\n\n```mermaid\nflowchart TD\n    A[\"Aussage aus Quelle\"] --> Q{\"eine fachliche<br/>Behauptung?\"}\n    Q -->|mehrere| S[\"in mehrere Claims teilen\"]\n    Q -->|eine| C{\"ohne Absatz<br/>verständlich?\"}\n    C -->|nein| E[\"Objekt präzisieren\"]\n    C -->|ja| V[\"Zitat und Status ergänzen\"]\n```\n\n## Das Zitat trägt die Aussage\n\nJeder Claim verweist über Citations auf eine oder mehrere Quellen. Die Citation enthält einen wörtlichen Ausschnitt und optional einen Locator. Eine Zitatprüfung kann sicherstellen, dass das Zitat wörtlich im archivierten Quelltext vorkommt. Ein Claim, dessen Beleg nur paraphrasiert oder erfunden ist, sollte verworfen werden, bevor er den Review erreicht.\n\n```json\n{\n  \"subject\": \"content-release\",\n  \"predicate\": \"rollback_mechanism\",\n  \"object\": \"switch the active pointer to an immutable revision\",\n  \"confidence\": 0.94,\n  \"citations\": [\n    {\n      \"source_id\": \"source_release_docs\",\n      \"quote\": \"Rollback changes the active release pointer to a previous immutable revision.\",\n      \"locator\": \"Rollback\"\n    }\n  ]\n}\n```\n\nEin Zitat muss die Aussage in ihrem Geltungsbereich stützen. Wenn die Quelle nur von einer Preview-Umgebung spricht, darf der Claim daraus keine allgemeine Produktionsregel machen. Diese Prüfung kann nicht allein über Zeichenketten erfolgen. Die prüfende Person liest den Kontext.\n\nMehrere Citations sind nützlich, wenn eine Aussage aus Vertrag und beobachtetem Verhalten gemeinsam gestützt wird. Die API-Dokumentation kann den vorgesehenen Mechanismus beschreiben, ein Produktionsreport seine tatsächliche Nutzung belegen. Viele schwache Quellen machen einen Claim jedoch nicht automatisch stärker.\n\n## Confidence ist keine Wahrheitsskala\n\n`confidence` beschreibt, wie sicher die erzeugende Synthese bei ihrer Zuordnung war. Sie kann der prüfenden Person helfen, unsichere Vorschläge zuerst anzusehen. Sie ist kein Ersatz für Status und keine Wahrscheinlichkeit, dass eine Aussage in der Welt wahr ist.\n\n```ts\ntype ClaimStatus = \"proposed\" | \"verified\" | \"disputed\" | \"deprecated\";\n\ntype Claim = {\n  subject: string;\n  predicate: string;\n  object: string;\n  confidence: number;\n  status: ClaimStatus;\n};\n```\n\nEin Claim mit `confidence: 0.99` bleibt vor der Freigabe `proposed`. Ein freigegebener Claim mit `confidence: 0.78` kann `verified` sein, weil ein Mensch Quelle und Formulierung geprüft hat. Später kann ein neuer Beleg ihn `disputed` machen, ohne den alten Confidence-Wert umzudeuten.\n\nDiese Trennung verhindert eine bequeme Abkürzung. Eine Grenze wie „ab 0.9 automatisch freigeben“ würde Modellselbstsicherheit mit fachlicher Verbindlichkeit verwechseln. Sinnvoller ist es, aus jeder Wissensänderung einen Änderungsvorschlag zu machen, unabhängig vom Wert in `confidence`. Er wird erst nach menschlicher Freigabe übernommen.\n\n## Status bildet den Lifecycle ab\n\n`proposed` ist Staging und für normale Leser unsichtbar. `verified` bezeichnet eine freigegebene Aussage. `disputed` macht einen nachvollziehbaren Konflikt sichtbar. `deprecated` hält eine überholte Aussage in der Geschichte, ohne sie als aktuellen Stand zu behandeln.\n\nDer Lifecycle erlaubt präzisere Antworten als Löschen. Wenn ein Dienst bis Version 2 einen statischen Retry-Wert verwendete und seit Version 3 ein Budget teilt, sind beide Aussagen historisch relevant. Die alte wird nicht aus allen Revisionen entfernt. Sie erhält einen Status und bleibt mit ihrer Quelle verbunden.\n\n```mermaid\nstateDiagram-v2\n    [*] --> proposed\n    proposed --> verified: human approval\n    proposed --> [*]: rejection\n    verified --> disputed: conflicting evidence\n    disputed --> verified: conflict resolved\n    verified --> deprecated: superseded\n    disputed --> deprecated: superseded\n```\n\nDer Übergang von `proposed` zu `verified` geschieht nicht automatisch, sondern erst nach einer menschlichen Entscheidung. Der sichtbare Seitentext kann den aktuellen Stand anschließend flüssig erklären. Die Claims darunter bewahren, welche Einzelaussagen diese Erklärung tragen und welche Konflikte noch offen sind.\n\n## Funktionale Prädikate machen Konflikte exakt\n\nManche Beziehungen dürfen gleichzeitig mehrere Objekte haben. Ein System kann mehrere Exportformate unterstützen. `supports_format=markdown` widerspricht `supports_format=okf` nicht. Andere Beziehungen sollen für ein Subjekt nur einen aktuellen Wert besitzen, etwa `primary_database`.\n\nEin Space kann solche funktionalen Prädikate deklarieren. Treffen dort zwei unterschiedliche Objekte für dasselbe Subjekt und Prädikat aufeinander, kann die Wissensbasis beide Claims als `disputed` markieren und über `contradicts` verbinden.\n\n```json\n{\n  \"settings\": {\n    \"functional_predicates\": [\n      \"primary_database\",\n      \"current_owner\",\n      \"default_retention_days\"\n    ]\n  }\n}\n```\n\nDiese Regel bleibt deterministisch. Ein Modell muss nicht entscheiden, ob zwei frei formulierte Absätze semantisch kollidieren. Das kontrollierte Prädikat benennt vorher, wo genau ein einzelner aktueller Wert erwartet wird.\n\nZu viele funktionale Prädikate wären schädlich. `supports_format` als funktional zu markieren würde ergänzende Fakten fälschlich in Konflikt setzen. Das Vokabular ist deshalb eine fachliche Entscheidung des Space und gehört ins Review.\n\n## Einen Absatz in Claims zerlegen\n\nEin praktisches Beispiel zeigt die Größenentscheidung. Angenommen, eine Quelle sagt: „The service runs as a single binary, migrates PostgreSQL on startup, and exposes health and readiness endpoints.“ Daraus sollte kein Claim mit dem Objekt `single binary with migrations and probes` entstehen. Drei Eigenschaften ändern sich unabhängig voneinander.\n\n```json\n[\n  {\n    \"subject\": \"service-runtime\",\n    \"predicate\": \"distribution\",\n    \"object\": \"single self-contained binary\"\n  },\n  {\n    \"subject\": \"service-runtime\",\n    \"predicate\": \"database_migration\",\n    \"object\": \"runs automatically on startup\"\n  },\n  {\n    \"subject\": \"service-runtime\",\n    \"predicate\": \"exposes_probe\",\n    \"object\": \"/health and /ready\"\n  }\n]\n```\n\nWenn später ein Sidecar hinzukommt, betrifft das den Distribution-Claim. Die Migration und die Probes können unverändert bleiben. Eine prüfende Person sieht genau den kleinen Diff. Ein Agent kann weiterhin die beiden bestätigten Aussagen verwenden, während die erste geprüft wird.\n\nDie Gegenprobe hilft: Würde eine Änderung des Objekts automatisch die anderen Teile der Aussage ändern? Falls nein, sind mehrere Claims angemessen. Würde ein Claim ohne Nachbarsatz missverständlich, braucht er ein genaueres Subjekt oder Objekt.\n\nAuch Zeit und Geltungsbereich gehören in die Formulierung. `uses PostgreSQL` passt zu einer aktuellen Architektur, wenn die Quelle den gesamten Dienst beschreibt. Bezieht sie sich nur auf die Produktionsbereitstellung, sollte das Subjekt `service-production-deployment` lauten. Präzision entsteht oft besser über ein engeres Subjekt als über einen langen Objekttext.\n\nEin Claim ist kein vollständiger Satz für die Blogprosa. Er darf maschinenlesbar und knapp bleiben. Die Konzept-Seite erklärt anschließend, wie die drei Eigenschaften zusammenwirken.\n\n## Ein Konzept ist mehr als seine Claims\n\nClaims allein ergeben keine gut lesbare Erklärung. Ein Konzept besitzt weiterhin Titel, Zusammenfassung, Markdown und Beziehungen zu anderen Konzepten. Die Seite kann ein Beispiel, Einschränkungen und den historischen Zusammenhang erklären.\n\nDie Claims erfüllen eine andere Aufgabe. Sie erlauben:\n\n- eine einzelne Aussage bis zum Originalzitat zurückzuverfolgen;\n- einen Widerspruch ohne Ablehnung der ganzen Seite zu markieren;\n- bei einer neuen Revision nur die tatsächlich veränderten Behauptungen zu prüfen;\n- Suchtreffer und Agentenantworten auf sichtbare, freigegebene Einheiten zu begrenzen.\n\nSeitentext und strukturierte Ebene sollten gemeinsam revisioniert werden. Ein Vorschlag darf nicht bereits neuen Text zeigen, während seine Claims für Leser unsichtbar oder unvollständig sind. Die atomare Freigabe macht die neue Revision als Einheit aktuell.\n\n## Beziehungen verbinden, Claims belegen\n\nNeben Claims kann eine Wissensbasis gerichtete Beziehungen zwischen Konzepten kennen: `related`, `part_of`, `depends_on`, `contradicts` und `supersedes`. Eine Relation beantwortet, wie zwei Seiten zusammenhängen. Sie ersetzt keinen Claim und keine Citation.\n\n```json\n{\n  \"from_slug\": \"content-release\",\n  \"kind\": \"depends_on\",\n  \"to_slug\": \"immutable-revision\"\n}\n```\n\nDie Relation macht Navigation und Kontext möglich. Der belegte Sachverhalt bleibt als Claim auf einer der Seiten. Sonst würde ein bloßer Link eine fachliche Aussage tragen, ohne ihren Wortlaut oder ihre Quelle zu nennen.\n\n`contradicts` kann als Folge der funktionalen Prädikatlogik entstehen. `supersedes` eignet sich für eine nachvollziehbare Ablösung, bei der der neue Begriff oder die neue Regel den alten Stand ersetzt. Beziehungen selbst werden mit der Konzept-Revision geprüft und veröffentlicht.\n\n## Revisionen beantworten die Zeitfrage\n\nEin aktueller Claim erklärt nicht allein, wann er eingeführt wurde. Eine Konzept-History sollte freigegebene, abgelehnte und vorgeschlagene Revisionen mit ihrer Herkunft führen: Welches Modell und welche Prompt-Version haben den Vorschlag erzeugt, welche Quellen wurden verwendet und welche Person hat freigegeben.\n\nDiese Angaben machen ein Modell nicht zum Autor im rechtlichen oder fachlichen Sinn. Sie dokumentieren, welcher technische Syntheseweg den Vorschlag erzeugte. Prüfende Person, Notiz und Zeitstempel erklären die menschliche Entscheidung. Freigabe, Status und Revision zusammen machen sichtbar, wie eine Aussage in den gültigen Wissensstand gelangt ist – und wie sie ihn wieder verlassen kann.\n\nDie History erlaubt eine zeitbezogene Frage: Welche Aussage war im März sichtbar, bevor die Retention-Regel geändert wurde? Ein Wissensdienst, der immer nur den aktuellen Absatz zurückgibt, kann sie nicht zuverlässig beantworten. Revisionen erhalten den damaligen Stand, ohne alte Claims als heute gültig auszugeben.\n\nFür Teams wird diese Spur besonders nach Modell- oder Promptwechseln nützlich. Wenn eine neue Syntheseversion auffällig andere Claims vorschlägt, lassen sich betroffene Revisionen identifizieren und gezielt prüfen. Damit lässt sich neben der Quelle auch nachvollziehen, welches Modell und welche Prompt-Version den Vorschlag erzeugt haben.\n\n## Ein Schritt über „Sauberes Grounding II“ hinaus\n\n[Sauberes Grounding II](https://www.mikebild.dev/de/blog/sauberes-grounding-antworten-erden/) sortierte Grounding in Konventionen, Dokumente und API-Beschreibungen. Die zentrale Frage lautete, welches Material für eine konkrete Aufgabe in den knappen Kontext gehört und wie teuer seine Wiederbeschaffung wäre. Das war ein Arbeitsmodell für einzelne Sessions.\n\nHinzu kommt eine kleinere, dauerhafte Einheit zwischen Dokument und Kontext: der Claim. Ein Agent muss nicht jedes Mal eine ganze Seite als gleichmäßig verbindlich behandeln. Er kann die aktuelle Konzept-Revision lesen, sichtbare Claims samt Status prüfen und bei Bedarf ihre Citations öffnen. Aus „passendes Dokument in den Kontext“ wird „passende, freigegebene Aussage mit Rückweg zur Quelle“.\n\nDer ältere Artikel [Fuzzy Matching mit expliziten Grenzen](https://www.mikebild.dev/de/blog/fuzzy-matching-mit-grenzen/) trennte eine Behauptung mit Confidence von einem Fakt. Dieselbe Vorsicht gilt hier. Confidence hilft beim Sortieren eines Vorschlags. Erst Beleg, Review und Status bestimmen, wie die Aussage in der Wissensbasis erscheint.\n\n## Claims im Review prüfen\n\nBei einem neuen Vorschlag genügen vier Fragen. Behauptet der Claim genau eine Sache? Ist er ohne den umgebenden Absatz verständlich? Trägt das Zitat genau diesen Geltungsbereich? Würde ein abweichender neuer Wert als klarer Widerspruch erkennbar?\n\nWenn eine Antwort nein lautet, wird der Claim geteilt, enger formuliert oder abgelehnt. Das ist keine formale Wortübung. Kleine Claims senken später den Aufwand. Eine geänderte Retention-Regel erfordert dann keine komplette Neufassung der Seite über Storage. Nur die betroffene Aussage und ihre Erklärung werden angepasst.\n\nStrukturiert werden nur Behauptungen, die für Suche, Review, Konflikte oder Herkunft relevant sind. Es geht nicht darum, jeden Satz als universelle Ontologie abzubilden. Alles andere bleibt Prosa; dafür entsteht kein Claim.\n\n## Weiterführende Quellen\n\n- [W3C RDF 1.1 Concepts](https://www.w3.org/TR/rdf11-concepts/)\n- [W3C PROV-O](https://www.w3.org/TR/prov-o/)\n- [Sauberes Grounding II](https://www.mikebild.dev/de/blog/sauberes-grounding-antworten-erden/)\n- [Fuzzy Matching mit expliziten Grenzen](https://www.mikebild.dev/de/blog/fuzzy-matching-mit-grenzen/)"},{"locale":"de","translation_key":"produkte-berichten-ueber-ihre-api","slug":"produkte-berichten-ueber-ihre-api","title":"Produkte berichten über ihre API","summary":"Produktstatistiken bleiben verständlich, wenn jedes System seine Daten selbst verdichtet und über einen kleinen, zeitlich einheitlichen HTTP-Vertrag anbietet.","tags":["Software","Architektur","API","Delivery"],"published_at":"2026-07-19T10:00:00+00:00","updated_at":"2026-08-18T06:39:59.272448+00:00","url":"https://www.mikebild.dev/de/blog/produkte-berichten-ueber-ihre-api/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/6658d74f36059d7606e0037540fafdcbdf20f4f8c14502c97c9180ba38e9086c.mp3","audio_duration_secs":871,"text":"Eine Statistik-API ist eine Produktfunktion. Dieser Satz klingt selbstverständlich, wurde in der Arbeit an einem produktübergreifenden Reporting aber erst nach zwei schlechteren Entwürfen klar. Zunächst sollte ein zentraler Sammler direkt auf mehrere PostgreSQL-Datenbanken zugreifen. Danach standen besondere private Reporting-Endpoints und eigene Schlüssel im Raum. Beides hätte den Report tiefer in die Produkte eingebaut, als es für seinen Zweck nötig ist.\n\nÜbrig blieb ein kleinerer Vertrag. Ein Publishing-System, eine Wissensbasis und ein Orchestrator verdichten ihre eigenen Daten selbst und bieten ihre Sicht über normale, authentifizierte HTTP-Endpoints an. Ein nachgelagerter Ablauf führt die Aggregate für ausdrücklich begrenzte Zeitfenster zusammen – er sieht weder Tabellen noch Markdown, Namen, Schlüssel oder interne IDs.\n\nDiese Aufteilung ist kein spezieller Kniff für Dashboards. Jeder autorisierte Verbraucher kann dieselben Statistikressourcen verwenden: ein Kapazitätsreport, eine Qualitätsprüfung, eine lokale Auswertung oder ein späteres Exportwerkzeug.\n\n## Datenbesitz ist mehr als Speicherort\n\nWer eine Tabelle besitzt, kennt ihre Bedeutung. Ein Publishing-System weiß, wann eine Revision erstellt und ein Release tatsächlich aktiviert wurde. Eine Wissensbasis unterscheidet einen gestarteten Ingest von einem geprüften Wissensstand. Ein Orchestrator verdichtet seine Ausführungsdaten dort, wo die Läufe tatsächlich stattfinden. Ein zentraler Sammler müsste diese Bedeutungen nachbauen und bei jeder Produktänderung mitziehen.\n\nDirektes SQL macht diesen Nachbau besonders leicht – und damit gefährlich. Eine Query funktioniert, obwohl sie vielleicht einen Zwischenstatus mitzählt, den das Produkt selbst niemals als abgeschlossen anzeigen würde. Eine neue Migration kann den Report brechen, ohne dass sich die öffentliche Produkt-API geändert hat. Der Datenbankzugriff umgeht außerdem die normale Rechteprüfung und zieht Credentials mehrerer Systeme an eine Stelle.\n\nMit einer Produkt-API liegt die fachliche Verdichtung dort, wo auch die Zustandsänderung implementiert ist:\n\n:::process{title=\"Fachliche Verdichtung bleibt im Produkt\" role=\"primary\" preferredPattern=\"connected-process\"}\n1. Produktaktion · erzeugt einen fachlich definierten Zustandsübergang\n2. Eigener Datenspeicher · bewahrt den fachlich maßgeblichen Zustand des Produkts\n3. Aggregation · übersetzt interne Zustände in begrenzte fachliche Kennzahlen\n4. Statistik-API · liefert authentifizierte Werte mit Zeitraum und Bedeutung\n5. Collector · führt kompatible Antworten zusammen, ohne sie neu zu definieren\n6. Report · erklärt den eingefrorenen gemeinsamen Stand\n:::\n\nDer Sammler darf die Antworten zusammenführen, aber nicht neu deuten, was ein erfolgreicher Release oder ein verifizierter Claim ist. Diese Begriffe gehören dem Produkt.\n\n## Einheitlich ist die Zeit, nicht die Fachlichkeit\n\nEin gemeinsamer Vertrag bedeutet nicht, dass alle Produkte dieselben Kennzahlen liefern. Das wäre künstliche Gleichmacherei. Gemeinsam sind nur die Eigenschaften, die ein Collector für zuverlässige Zeitfenster benötigt:\n\n- `bucket` bestimmt die Auflösung: Stunde, Tag, Monat oder Jahr.\n- `from` ist der eingeschlossene Anfang des Fensters.\n- `to` ist das ausgeschlossene Ende.\n- `tz` macht die Zeitzone ausdrücklich, hier durchgehend UTC.\n- `buckets` enthält eine dichte Reihe einschließlich leerer Intervalle.\n- `totals` fasst genau das angefragte Fenster zusammen.\n\nDie Nutzlast bleibt fachlich benannt. Ein Publishing-System kann etwa auf eine Site begrenzte Aggregate für Releases, Inhalte und Leserzugriffe bereitstellen, eine Wissensbasis auf einen Space begrenzte Aggregate für Nutzung, Abdeckung und Reviews, ein Orchestrator auf einen Tenant begrenzte Laufzeitstatistiken für Ausführungen und Connectoren. Kein Produkt muss die Begriffe eines anderen Produkts übernehmen; alle müssen denselben Zeitvertrag erfüllen.\n\n```json\n{\n  \"bucket\": \"hour\",\n  \"tz\": \"UTC\",\n  \"from\": \"2026-07-18T10:00:00.000Z\",\n  \"to\": \"2026-07-18T12:00:00.000Z\",\n  \"buckets\": [\n    { \"ts\": \"2026-07-18T10:00:00.000Z\", \"items_created\": 2 },\n    { \"ts\": \"2026-07-18T11:00:00.000Z\", \"items_created\": 0 }\n  ],\n  \"totals\": { \"items_created\": 2 }\n}\n```\n\nDie halboffene Schreibweise `[from,to)` verhindert Doppelzählungen. Das Fenster von 10 bis 11 Uhr enthält ein Event um 10:59:59, aber keines um 11:00:00. Das nächste Fenster beginnt genau dort. Ein Retry fragt dasselbe Zeitfenster erneut ab und erhält dieselbe Bedeutung.\n\n## Gemessene Null, fehlende Beobachtung, unvollständiges Fenster\n\nEine dichte Zeitreihe enthält auch leere Buckets. Das ist praktisch, weil der Collector keine fehlenden Stunden erraten oder auffüllen muss. Eine Null ist dabei ein gemessener Wert: Das Produkt hat das Fenster ausgewertet und kein entsprechendes Event gefunden.\n\nDavon zu unterscheiden sind zwei andere Zustände. Fehlend bedeutet, dass für die Kennzahl keine Beobachtung vorliegt – etwa weil eine Quelle nicht angeschlossen ist oder eine Quote ohne Grundmenge nicht berechnet werden kann. Im hier beschriebenen Reporting-Ablauf bestimmt der nachgelagerte Report außerdem die Unvollständigkeit: Ein erwarteter Snapshot fehlt, oder das Fenster war zum Zeitpunkt der Erfassung noch nicht abgeschlossen. Diese drei Fälle dürfen im Report nicht gleich aussehen, denn sie tragen verschiedene Konsequenzen: Null technische Fehler sind beruhigend, null Seitenaufrufe können stimmen, ein fehlender Analytics-Anschluss ist eine offene Verbindung und keine Messung.\n\nEin Produkt kann die Unterscheidung zwischen gemessen und fehlend zum Teil der Antwort machen und Messwerte etwa mit `value_state` und `value_kind` kennzeichnen. Eine Quote ohne Beobachtungen trägt den Zustand `missing` und wird nicht als gemessene Null ausgegeben:\n\n```json\n{\n  \"metric\": \"engagement_rate\",\n  \"value_kind\": \"ratio\",\n  \"value_state\": \"missing\"\n}\n```\n\nFür jemanden, der einen Report liest, ist dieser Zustand wichtiger als eine weitere Nachkommastelle. Zeitfenster, Datenzustand und Messbedeutung gehören deshalb in den Vertrag selbst – nicht in eine Fußnote der Reportseite.\n\n## Datenschutz beginnt bei der Antwortform\n\nAggregate sollten Informationen weglassen, die der Zweck nicht benötigt. Eine Statistik kann erfolgreiche, fehlgeschlagene und rate-limitierte Leserzugriffe zählen, ohne dafür Benutzernamen, IP-Adresse, Session-ID, Markdown-Inhalte, URLs, Job-IDs oder Credentials in der Statistikstabelle zu speichern. Eine Wissensbasis muss über ihre Statistikressourcen keine Quellentexte ausgeben.\n\nEine solche Negativliste gehört in die Dokumentation und in Vertragstests. „Wir geben aktuell keine Namen zurück“ ist schwächer als ein Schema, in dem es für Namen gar kein Feld gibt. Der Collector kann dann keinen sensiblen Wert versehentlich in ein JSON-Artefakt oder eine Reportseite übernehmen.\n\nAuch Trace-Daten bleiben auf ihren Zweck begrenzt. W3C Trace Context standardisiert `traceparent` und `tracestate`, damit ein Aufruf über mehrere Dienste korreliert werden kann. Die W3C-Empfehlung warnt ausdrücklich davor, personenbezogene oder andere sensible Informationen in diesen Headern zu transportieren. Eine Trace-ID verbindet technische Schritte; sie beschreibt keinen Menschen.\n\n```http\nGET /v1/sites/example/stats/releases?bucket=hour&from=2026-07-18T10:00:00Z&to=2026-07-18T11:00:00Z\nAuthorization: Bearer <site-read-key>\ntraceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\n```\n\n## Zero-config heißt: vorhandene Begriffe verwenden\n\nVollständig konfigurationslos ist Telemetrie selten. Ein Dienst braucht zumindest eine dauerhafte Ablage und eine Information darüber, ob er in Entwicklung, Test oder Produktion läuft. „Zero-config“ ist hier enger gemeint: Für den Reporting-Ablauf wird im Produkt kein Sondermodus aktiviert, kein besonderer Schlüssel erzeugt und kein Reportziel eingetragen.\n\nDie Statistik-Endpoints können vorhandene Produktgrenzen verwenden: ein Publishing-System etwa die Site und einen normalen Lese-Key, eine Wissensbasis den Space und ihren Lese-Scope, ein Orchestrator den Mandanten.\n\nOpenTelemetry liefert dafür ein brauchbares gemeinsames Vokabular. `service.name` benennt den logischen Dienst, `deployment.environment.name` unterscheidet `development`, `staging`, `production` und `test`; Stand August 2026 ist der ältere Schlüssel `deployment.environment` in den OpenTelemetry-Konventionen als veraltet markiert. Solche standardisierten Felder verhindern, dass ein Dienst `prod`, ein anderer `live` und ein dritter `production-eu` als dasselbe Konzept behandelt. Das Produkt setzt diese Werte einmal für seine Laufzeit; der Reporting-Collector muss keine Etiketten reparieren.\n\nDie gemeinsame Bezeichnung allein genügt allerdings nicht. Liest ein Aggregator andere Feldnamen, als ein älterer Schreibpfad noch liefert, können erfolgreiche Aufrufe als Fehler erscheinen. Ein solcher Übergang lässt sich in beide Richtungen kompatibel machen: Der Leser versteht alte und neue Felder, der Schreiber liefert vorerst beide, und Tests verwenden echte Auditzeilen statt handgebauter Idealobjekte.\n\n## Begrenzte Queries statt versteckter Last\n\nEine allgemeine Statistik-API braucht harte Grenzen, etwa eine maximale Fensterlänge je Auflösung. Ungültige oder zu große Fenster liefern `422`, statt die Produktdatenbank mit einer unerwarteten Vollauswertung zu belasten.\n\nDiese Grenzen gehören zum Produktvertrag, weil nur das Produkt seine Kosten kennt. Ein Collector sollte nicht versuchen, sie mit vielen überlappenden Queries zu umgehen. Für einen langen Zeitraum verwendet er die gröbere Auflösung oder arbeitet in eindeutigen, nicht überlappenden Seiten.\n\nDasselbe gilt für Aufbewahrung. Anonyme Rohereignisse können im Produkt eine eigene Aufbewahrungsfrist haben. Ein Reportartefakt kann länger bestehen, wenn sein verdichteter Inhalt dafür vorgesehen ist. Rohereignis, Produktaggregat und veröffentlichter Report haben verschiedene Lifecycles; sie müssen nicht in einem Speicher enden.\n\n## Bestehende Schlüssel statt einer Hintertür\n\nEin eigener „Reporting-Key“ wirkt zunächst ordentlich, schafft aber eine zweite Sicherheitslogik. Was darf dieser Schlüssel lesen? Gilt er für eine Site, einen Space oder das ganze Produkt? Wer rotiert ihn? Sobald jedes Produkt darauf eine andere Antwort gibt, wird aus dem vermeintlich einfachen Collector ein Sonderfall mit weitreichenden Rechten.\n\nDie Statistik-APIs sollten deshalb vorhandene Scopes verwenden. Ein reiner Lese-Key einer Site darf dann genau die Statistiken der Site lesen, für die er ausgestellt wurde. Ein Lese-Key der Wissensbasis bleibt auf seinen Space begrenzt. Ohne passenden Schlüssel bleibt jeder dieser Endpoints geschlossen.\n\nFür den Collector gilt damit dieselbe Regel wie für andere API-Nutzer: pro Produkt ein eigener, möglichst enger Schlüssel; Secrets ausschließlich in der Credential-Ablage; keine Schlüssel in Workflowdefinition, JSON-Artefakt, Log oder Report. Der Workflow kennt nur eine `credential_ref`; der tatsächliche Wert wird beim HTTP-Aufruf eingesetzt und erscheint weder im gespeicherten Ablauf noch in dessen Ergebnis. Diese Trennung lässt sich testen: Ein Aufruf ohne Schlüssel muss `401` liefern, ein Schlüssel ohne passenden Scope `403`, ein korrekter Schlüssel `200`.\n\n## PostgreSQL ist intern, nicht verboten\n\nDie Ablehnung direkter Datenbankabfragen bedeutet nicht, dass Aggregate außerhalb der Produktdatenbank liegen müssen. Für ein Publishing-System oder eine Wissensbasis kann PostgreSQL gerade der passende Ort sein. Event und fachlicher Zustand lassen sich dort transaktional erfassen, nach Site oder Space begrenzen und mit denselben Migrationen weiterentwickeln wie der Rest des Produkts.\n\nWichtig ist die Richtung der Abhängigkeit. Das Produkt darf seine eigene Datenbank kennen. Ein fremder Collector darf sie nicht kennen müssen. Ob eine Antwort aus einer vorberechneten Tabelle, einer begrenzten SQL-Aggregation oder einem Cache entsteht, bleibt eine interne Entscheidung. Entscheidend ist, dass jedes Produkt seine interne Ablage nach dem eigenen Betriebsmodell gestalten kann und nach außen denselben verlässlichen Zeitvertrag erfüllt.\n\n## Dokumentation gehört zum Vertrag\n\nEin neuer Endpoint ist erst fertig, wenn OpenAPI, `llms.txt`, `llms-full.txt`, README und die ausführliche Produktdokumentation dasselbe erzählen. Sonst findet ein Mensch einen Scope in der README, ein Client generiert aus einer älteren OpenAPI-Datei und ein Agent liest eine dritte Variante.\n\nDarum prüfen die Repositories ihre generierten Dokumente auf Drift. Vertragstests schicken gültige, ungültige, zu große und nicht autorisierte Fenster an die Handler. Integrationstests verwenden die echte Produktablage. Ein Binärtest stellt sicher, dass die ausgelieferte Datei dieselben Routen und dieselbe Versionsnummer enthält wie der Quellstand. Diese Prüfungen verhindern, dass der Collector von einer veralteten oder nur intern bekannten Antwortform abhängt.\n\n## APIs machen Austausch möglich\n\nDer unmittelbare Effekt dieser Trennung zeigt sich beim Testen. Jede Produkt-API lässt sich mit einem festen Fenster gegen ihr eigenes Schema prüfen. Der Collector erhält Fixtures ohne Zugriff auf die Datenbank. Ein Produktrelease lässt sich auf API-Ebene unabhängig zurückrollen, solange der veröffentlichte Vertrag erhalten bleibt.\n\nEin neuer Verbraucher braucht keine neue Tabelle im Produkt. Ein anderes Reporting-Werkzeug kann dieselbe API ebenso aufrufen. Ein Produkt darf seine interne Ablage ändern, ohne dass die Statistikressource neu erfunden wird.\n\nDas hält auch die Produkte verständlich. Jedes Produkt behält seine Rolle – als Publishing-System, Wissensbasis oder Orchestrator. Ihre Statistikressourcen beschreiben die eigene Arbeit als begrenzte, fachlich benannte Aggregate. Alles Weitere geschieht außerhalb ihrer Grenzen. Solange der veröffentlichte Vertrag erhalten bleibt, kann ein Teil ersetzt werden, ohne die anderen anzupassen.\n\n## Was sich seit damals geändert hat\n\nDer Beitrag [HTTP-APIs: klein, stabil, lesbar](https://www.mikebild.dev/de/blog/http-apis-klein-stabil-lesbar/) formulierte 2014 einen Endpoint als langfristiges Versprechen an unbekannte Clients. Kleine Ressourcen, eindeutige Zeitstempel, stabile Bedeutungen und lesbare Fehler sollten verhindern, dass jeder Client eine eigene Abwehrschicht baut. Diese Anforderungen gelten weiterhin.\n\nNeu ist der Blick auf interne Produktstatistiken. Ein Statistikpfad wird nicht für ein bestimmtes Dashboard gebaut, sondern als begrenzte Projection der eigenen Produktdaten. Er verwendet bestehende Schlüssel und Scopes, liefert Zeitgrenzen und Datenzustand mit und veröffentlicht nur Aggregate. Damit bleibt die API klein, unabhängig davon, ob ein Mensch, ein Workflow oder ein Agent sie aufruft.\n\n## Weiterführende Quellen\n\n- [W3C Trace Context](https://www.w3.org/TR/trace-context/)\n- [OpenTelemetry Service Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/resource/service/)\n- [OpenTelemetry Deployment Attributes](https://opentelemetry.io/docs/specs/semconv/registry/attributes/deployment/)\n- [HTTP-APIs: klein, stabil, lesbar](https://www.mikebild.dev/de/blog/http-apis-klein-stabil-lesbar/)"},{"locale":"de","translation_key":"vom-organigramm-zum-arbeitsfluss","slug":"vom-organigramm-zum-arbeitsfluss","title":"Vom Organigramm zur Produktverantwortung","summary":"KI macht den Weg vom Kundenproblem bis zur Wirkung durchgängiger.","tags":["Software","KI","Methodik"],"published_at":"2026-07-18T10:00:00+00:00","updated_at":"2026-08-18T06:39:59.272448+00:00","url":"https://www.mikebild.dev/de/blog/vom-organigramm-zum-arbeitsfluss/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/709ee89e98f6dcab9390632ddf2c285dff0aeb1474956056141dda882d4c5f92.mp3","audio_duration_secs":745,"text":"Ein KI-Assistent erzeugt einen Entwurf – und danach wartet der Vorgang auf Freigabe, Review und Release wie zuvor. Wer trägt ihn vom beobachteten Kundenproblem bis zur messbaren Wirkung? Diese Frage beantwortet keine noch so schnelle Entwurfserzeugung. KI kann den Arbeitsfluss vom ersten Kundensignal über Plan und Umsetzung bis zu Review und Wirkung durchgängiger machen – wenn die Verantwortung für Problem, Entscheidung, Prüfung und Wirkung an einer Stelle zusammengeführt wird.\n\nKI beseitigt Organisationsgrenzen nicht automatisch. Sie senkt die Kosten, sich in den nächsten Schritt einzuarbeiten. Ob daraus ein zusammenhängender Vorgang wird oder nur ein schnellerer Zulauf auf dieselben Wartepunkte, entscheidet die Organisation, nicht das Modell.\n\n## Der Arbeitsfluss vom Kundenproblem bis zur Wirkung\n\nMit Arbeitsfluss meine ich hier eine konkrete Kette: Ein Kundensignal wird beobachtet, daraus entsteht eine Hypothese, aus der Hypothese ein Plan, aus dem Plan eine Umsetzung, aus der Umsetzung ein Review mit fachlicher Abnahme, danach ein Release und schließlich eine beobachtbare Wirkung, die wieder als Signal in den nächsten Durchlauf einfließt.\n\n```mermaid\nflowchart LR\n    S[Kundensignal] --> H[Hypothese und Plan]\n    H --> E[Entwurf und Umsetzung]\n    E --> Q[Review und Abnahme]\n    Q --> R[Release]\n    R --> W[Wirkung beobachten]\n    W --> S\n    A[KI: Kontext, Varianten,<br/>Tests und Dokumentation] --> H\n    A --> E\n    A --> Q\n```\n\nDie Ausgangshypothese lautet, dass diese Kette in arbeitsteiligen Organisationen selten durchgängig ist: Ein Ticket beschreibt den Wunsch, ein anderer Mensch entscheidet über das Design, ein dritter baut die Schnittstelle, ein vierter prüft den Release. Jede Rolle kann ihre Aufgabe sehr gut erledigen, während das Ergebnis für den Kunden trotzdem unvollständig bleibt. Wer nur einen kleinen Ausschnitt sieht, kann kaum beurteilen, ob eine neue Funktion das Kundenproblem löst oder lediglich einen Teilprozess sauberer macht.\n\nKI verändert an dieser Kette vor allem einen Kostenfaktor: das Einarbeiten in den jeweils nächsten Schritt. Ein Assistent kann einen unbekannten Service erklären, vorhandene Entscheidungen zusammentragen, einen Datenfluss skizzieren und passende Tests vorschlagen. Er ersetzt dabei kein Fachwissen. Er senkt die Hürde, Fachwissen aus anderen Teilen der Organisation rechtzeitig einzubeziehen – bevor eine Entscheidung getroffen ist, nicht nachdem eine fertige Lösung abgeliefert wurde.\n\n## Übergaben verkürzen sich nicht automatisch\n\nMeine These ist: KI kann Übergaben verkürzen, wenn die Verantwortung für Problem, Entscheidung, Prüfung und Wirkung zusammengeführt wird. Das ist eine Hypothese über Organisation, kein nachgewiesenes Gesetz. Bleibt die Verantwortung verteilt wie zuvor, beschleunigt KI lediglich die Produktion von Zwischenständen, die weiterhin auf dieselben Freigaben warten.\n\nDer [Beitrag über schnellere Entwicklung und unveränderte Prozesse](https://www.mikebild.dev/de/blog/ki-im-konzern-schnellere-entwicklung-andere-prozesse/) beschreibt diese Kehrseite: Wenn eine Organisation denselben alten Ablauf nur schneller füllt, verschiebt sich der Stau. Mehr Entwürfe warten auf dieselben Reviewer, und mehr Dokumente widersprechen sich. Der Gewinn entsteht erst, wenn die frei gewordene Zeit in das Verständnis des gesamten Vorgangs fließt.\n\nZusammengeführte Verantwortung bedeutet dabei nicht, dass ein Mensch gleichzeitig Produktmanager, Designer, Sicherheitsfachmann und Betriebsverantwortlicher sein muss. Gemeint ist, dass ein klar begrenzter Ausschnitt des Produkts von derselben Stelle weiterverfolgt wird: vom beobachteten Problem über eine Hypothese und eine Änderung bis zur Rückmeldung aus der Nutzung. Spezialdisziplinen bleiben unverzichtbar. Der Unterschied liegt im Zeitpunkt: Spezialisten werden früher und gezielter einbezogen, statt am Ende einer langen Kette eine fertige Lösung entgegenzunehmen.\n\nDas Organigramm verschwindet dadurch nicht. Menschen brauchen klare Zuständigkeiten, Entwicklungsperspektiven und Entscheidungen, die nicht zwischen Teams verloren gehen. Aber der durchgängige Arbeitsfluss kann wichtiger werden als die Grenzen zwischen den Kästchen – dort, wo Verantwortung tatsächlich zusammengeführt ist.\n\n## Vertikale Schnitte als überprüfbare Hypothese\n\nVertikale Arbeitspakete machen diese These überprüfbar. Statt eine Änderung nach technischen Schichten zu zerlegen – zuerst Datenmodell, dann API, dann Oberfläche – wird ein kleiner, nutzbarer Ausschnitt durch alle Schichten geführt. Ein solcher Schnitt hat einen klaren Zweck, eine sichtbare Wirkung und eine überschaubare Zahl offener Entscheidungen.\n\nBereits ohne generative KI war diese Arbeitsweise sinnvoll. Ein möglicher Hinderungsgrund war der Aufwand, sich in fremde Teile des Systems einzuarbeiten: Ein Entwickler kannte etwa das Frontend, nicht die Regeln im Backend. Das Produktteam kannte die Wirkung für Anwender, nicht die Folgen für Betrieb oder Datenmodell. Also wurden Arbeitspakete entlang von Zuständigkeiten geschnitten und anschließend über viele Meetings wieder zusammengesetzt.\n\n```mermaid\nflowchart TD\n    P[Produktproblem] --> V[Vertikaler Schnitt]\n    V --> U[Oberfläche]\n    V --> F[Fachlogik]\n    V --> D[Daten und Verträge]\n    V --> B[Betrieb und Beobachtung]\n    U --> X[Ein überprüfbares Ergebnis]\n    F --> X\n    D --> X\n    B --> X\n    K[KI: Abhängigkeiten und<br/>Vorschläge sichtbar machen] --> V\n```\n\nKleinere vertikale Schnitte sind eine überprüfbare Organisationshypothese, keine pauschale Aussage über jedes Team. Die Hypothese lautet, dass ein Team mit KI-Unterstützung mehr von diesem Zusammenhang selbst erkunden kann – welche Services betroffen sind, welche Verträge sich ändern, welche Testfälle fehlen, welche Dokumentation angepasst werden muss. Ob die Beobachtungen im konkreten Kontext für diese Hypothese sprechen, lässt sich anhand von Wartezeit, Zahl der Übergaben, Nacharbeit und Zeit bis zum Nutzerfeedback prüfen. Die Werte werden mit identischer Definition vor und nach einem begrenzten Piloten erhoben; andere Prozessänderungen müssen festgehalten werden, weil ein solcher Vergleich keine eindeutige Ursache beweist. Fällt die Messung anders aus als erwartet, ist die Hypothese für diesen Kontext zunächst nicht bestätigt, nicht das Team gescheitert.\n\nEin vertikaler Schnitt darf nicht zum Vorwand werden, jede Spezialdisziplin auf wenige Menschen abzuwälzen. Wo Sicherheit, Regulierung oder tiefe Fachkenntnis nötig sind, bleibt Zusammenarbeit Pflicht. Der Schnitt verändert die Reihenfolge der Beteiligung, nicht ihre Notwendigkeit.\n\n## Technologie wird wieder zur Option\n\nViele Technologiewahlen entstehen aus dem, was ein Team gerade kennt. Das ist verständlich: Eine unbekannte Plattform verlangt Recherche, kleine Versuche und die Sorge, später allein damit dazustehen. Darum werden Anforderungen gelegentlich an die vorhandenen Werkzeuge angepasst, obwohl ein anderer Weg besser passen könnte.\n\nKI verändert diese Rechnung. Sie kann Dokumentation durchsuchen, Beispiele aus einem Repository erklären, Varianten gegenüberstellen und einen kleinen Prototypen vorbereiten. Aus einer unbekannten Technologie wird dadurch noch keine gute Entscheidung. Aber es wird günstiger, die Entscheidung auf Basis eines echten Versuchs zu treffen statt auf Basis der Gewohnheit.\n\nEine brauchbare Untersuchung hält dabei mehrere Möglichkeiten offen:\n\n- Was ist die kleinste Änderung, mit der wir etwas über das Kundenproblem lernen?\n- Welche vorhandenen Systeme, Daten und Verträge müssen wir wirklich verstehen?\n- Welche Annahme übernimmt die KI, und wie lässt sie sich prüfen?\n- Welche Wirkung erwarten wir nach dem Release, und woran merken wir das Gegenteil?\n\nDie Antworten müssen nicht immer wie eine Architekturentscheidung dokumentiert werden. Bei einer kleinen Änderung reicht oft ein sauberer Pull Request mit Tests und einer kurzen Begründung. Entscheidend ist, dass die KI nicht bloß mehr Optionen produziert, sondern hilft, Optionen schneller zu bewerten und schlechte Ideen früher zu verwerfen.\n\n## Erstellen wird billiger, Review und Abnahme werden wichtiger\n\nDas sichtbarste Ergebnis von KI ist oft ein Entwurf: Code, ein Test, eine Zusammenfassung, eine API-Beschreibung, ein Release-Hinweis. Der Entwurf kann erstaunlich gut sein. Er kann aber auch eine falsche Voraussetzung mit großer Überzeugung weitertragen. Je günstiger das Erstellen wird, desto stärker wächst deshalb der Wert von Review und fachlicher Abnahme.\n\nReview meint hier mehr als den Pull Request. Es umfasst die fachliche Prüfung einer Anforderung, den Blick auf Widersprüche im vorhandenen Wissen, den Test unter realistischen Bedingungen und die Frage, ob der Release das Produkt verbessert. Qualitätssicherung ist damit kein letztes Tor vor dem Ausrollen. Sie begleitet den gesamten Schnitt.\n\n```yaml\nreview_focus:\n  product_question: \"Does this solve the observed customer problem?\"\n  domain_question: \"Which business rule could make this wrong?\"\n  technical_question: \"Which contract or dependency can break?\"\n  quality_signal: \"What evidence would change our decision?\"\n  release_check: \"Can we observe the result and recover safely?\"\n```\n\nDieses Beispiel ist keine neue Checkliste für jede Kleinigkeit. Es zeigt die Verschiebung: Bei KI-gestützten Entwürfen kann sich der Engpass von der Erzeugung zur Prüfung verschieben. Wichtiger wird dann, schnell und zuverlässig zu entscheiden, was von einem Entwurf behalten, geändert oder verworfen werden muss.\n\nDie NBER-Studie „Generative AI at Work“ liefert dazu einen begrenzten empirischen Hinweis. Bei mehr als 5.000 Beschäftigten im Kundensupport erhöhte ein KI-Assistent die Zahl gelöster Fälle pro Stunde im Mittel um 14 Prozent, wobei weniger erfahrene Beschäftigte besonders profitierten. Diesen Befund zu den weniger erfahrenen Beschäftigten lese ich als Hinweis darauf, dass KI bewährte Vorgehensweisen verbreiten kann – das ist meine Interpretation, kein direkter Studienbefund. Ein Beleg für dieselbe Wirkung in jeder Aufgabe oder gar in der Produktentwicklung ist die Studie ohnehin nicht. Für die Produktarbeit bleibt daraus vor allem: Der erste Entwurf wird zugänglicher. Erfahrung entwertet das nicht. Erfahrung wird sichtbarer dort, wo sie zählt – bei der Auswahl einer Richtung, beim Erkennen eines untypischen Falls und beim Urteil über Qualität.\n\n## Verantwortung technisch verankern\n\nWenn diese These ernst gemeint ist – zusammengeführte Verantwortung für Problem, Entscheidung, Prüfung und Wirkung –, dann muss sie sich auch in den Systemen wiederfinden, durch die Arbeit fließt. Sonst bleibt sie ein Vorsatz. Zwei Beispiele zeigen, wie eine solche Verankerung aussehen kann.\n\nEine Auftragssteuerung kann HTTP, MCP, A2A, Webhooks und Chat in denselben Planungspfad führen und Ausführung an explizite Auftragsautorität, Budgets, Verträge, Evidenz und Review binden. Das ist die technische Form dieser Verantwortungsbündelung: Egal über welchen Kanal ein Auftrag eintrifft, er läuft durch dieselbe Planung, und die Ausführung ist an explizite Autorität gebunden.\n\nEine Workflow-Engine kann wiederkehrende Arbeit über mehrere Systeme als genehmigten, protokollierten Workflow modellieren und Schritte mit Außenwirkung bis zur Bestätigung zurückhalten. Auch hier trennt das Design Vorbereitung und Ausführung von der bestätigten Außenwirkung: Ein Vorgang darf vorbereitet, geprüft und wiederholt werden, aber der Schritt, der nach außen wirkt, wartet auf die Abnahme.\n\nDie Übertragung auf die Organisation ist eine Hypothese, keine Garantie. Wenn Wissen auffindbar ist, wenn Releases so vorbereitet sind, dass ein Team eine Änderung kontrolliert bis zur Wirkung verfolgen kann, und wenn Produkt- und Serviceinformationen aus denselben geprüften Quellen entstehen statt in getrennten Kopien zu altern – dann kann ein Vorgang mehr Lücken auf einmal schließen: Eine Produktänderung liefert zugleich Testfälle, Betriebsinformationen und einen Entwurf für die Kundendokumentation. Wiederkehrende Supportfragen zeigen früh, welche Produktregel oder Erklärung fehlt. Fehler und Rückfragen fließen zurück in Regeln, Tests und spätere Arbeitspakete. Ob diese Bedingungen erfüllt sind, muss jede Organisation an ihrem eigenen Arbeitsfluss prüfen.\n\n## Ein vollständiger Schnitt als Test\n\nDie Veränderung beginnt nicht mit einem neuen Organigramm. Sie beginnt mit einem echten, begrenzten Produktproblem. Ein Team nimmt einen Vorgang, der heute mehrere Übergaben hat, und führt ihn einmal vollständig durch: Kundenfrage verstehen, Annahme prüfen, Änderung bauen, Qualität bewerten, veröffentlichen und die Wirkung ansehen.\n\n```yaml\nvertical_slice:\n  customer_problem: \"Describe the observed problem\"\n  smallest_change: \"Deliver one useful outcome\"\n  ai_support:\n    - \"Find relevant context\"\n    - \"Prepare tests and documentation\"\n  human_review:\n    - \"Validate domain assumptions\"\n    - \"Accept quality and release risk\"\n  outcome_signal: \"Measure customer use and failures\"\n```\n\nDanach ist die Diskussion über Rollen und Struktur konkreter. Vielleicht zeigt sich, dass ein Team eine Schnittstelle selbst verantworten kann. Möglicherweise fehlt eine gemeinsame Wissensquelle. Oder ein Spezialist bleibt dauerhaft Teil des Ablaufs. Entscheidend ist, dass die Organisation aus beobachteter Arbeit lernt und nicht aus einem abstrakten Umbauplan – und dass sie die Hypothese verwirft, wo die Messung dagegen spricht.\n\nKI macht vollständige Produktentwicklung nicht einfach. Sie macht sie dort öfter möglich, wo Verantwortung, Review und Wirkung zusammengehören und nicht über viele Stationen verteilt sind. Recherche, Entwurf, Tests, Dokumentation und Release-Vorbereitung rücken näher zusammen. Das Organigramm bleibt. Aber die Entscheidung, die jede Organisation jetzt treffen kann, ist konkret: einen ausgewählten, begrenzten Arbeitsfluss einmal durchgängig verantworten und an seiner Wirkung messen, ob die Hypothese trägt.\n\n## Weiterführende Quellen\n\n- [NBER: Generative AI at Work](https://www.nber.org/papers/w31161)\n- [KI im Enterprise-Umfeld: Schnellere Entwicklung braucht andere Prozesse](https://www.mikebild.dev/de/blog/ki-im-konzern-schnellere-entwicklung-andere-prozesse/)"},{"locale":"de","translation_key":"llms-txt-und-llms-full-txt","slug":"llms-txt-und-llms-full-txt","title":"llms.txt: Doku für Maschinen","summary":"Kontext für Modelle, nicht fürs Ranking: warum llms.txt und llms-full.txt Coding-Agenten helfen – und was ein MCP-Server daraus macht.","tags":["Software","KI","Methodik"],"published_at":"2026-07-15T10:00:00+00:00","updated_at":"2026-08-18T05:16:11.670656+00:00","url":"https://www.mikebild.dev/de/blog/llms-txt-und-llms-full-txt/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/aafa9dbe6e0b20c8d98403a06961eac6b3e4515fd6ebb904366e505a23ad0d9d.mp3","audio_duration_secs":803,"text":"`llms.txt` liegt im Wurzelverzeichnis einer Website und sieht damit aus wie das nächste Signal für Suchmaschinen – ein Nachbar von `robots.txt` und `sitemap.xml`, angelegt in der Hoffnung auf Sichtbarkeit. Genau dieser Schluss geht am Zweck vorbei. Die Datei war nie als Ranking-Signal gedacht, und für eine Ranking-Wirkung liegt kein Beleg vor. Ihr Nutzen liegt nicht in Crawler-Signalen, sondern darin, Agenten kuratierten Dokumentationskontext bereitzustellen.\n\nEs gibt zwei Dateien, `llms.txt` und `llms-full.txt`. Sie sehen nach Marketing-Infrastruktur aus, und ihr Nutzen liegt an einer anderen Stelle: bei der Frage, wie ein Modell an sauberen, kuratierten Kontext kommt, ohne sich vorher durch Navigationsleisten, Cookie-Banner und JavaScript zu arbeiten. Beide Dateien sind maschinenlesbare Selbstdokumentation eines Produkts.\n\n## Zwei Dateien, ein Problem\n\nDen Vorschlag hat Jeremy Howard, Mitgründer von Answer.AI, am 3. September 2024 veröffentlicht; die Beschreibung steht unter `llmstxt.org`. Der Ausgangspunkt ist eine nüchterne Beobachtung: Modelle stützen sich zunehmend auf Webinhalte, aber ihr Kontextfenster ist zu klein, um eine ganze Website am Stück aufzunehmen. Und rohes HTML in brauchbaren Text zu verwandeln, ist mühsam und ungenau – zwischen dem eigentlichen Inhalt steckt jede Menge Beiwerk, das nur Platz frisst.\n\nDie Antwort besteht aus zwei Bausteinen, die man sauber auseinanderhalten sollte.\n\n`llms.txt` liegt im Wurzelverzeichnis einer Site und ist ein kuratierter Index in Markdown. Das Format ist bewusst eng: eine H1-Überschrift mit dem Projektnamen, darunter ein Zitatblock mit einer kurzen Zusammenfassung, optional ein paar Sätze Kontext, danach H2-Abschnitte mit Linklisten. Jeder Link trägt eine knappe Beschreibung. Ein eigener Abschnitt `## Optional` markiert, was ein Modell bei knappem Platz zuerst weglassen darf. So kompakt sieht das aus:\n\n```markdown\n# Orderflow API\n\n> Orderflow is a REST API for creating, tracking, and refunding orders.\n> These docs are written for LLMs and coding agents.\n\nEvery write endpoint accepts an `Idempotency-Key` header, so retries stay safe.\n\n## Core Documentation\n\n- [Quick Start](https://docs.example.com/quickstart.md): Authenticate and create your first order\n- [API Reference](https://docs.example.com/api.md): Endpoints, parameters, and error codes\n- [Webhooks](https://docs.example.com/webhooks.md): Event types and signature verification\n\n## Optional\n\n- [Changelog](https://docs.example.com/changelog.md): Version history and breaking changes\n```\n\n`llms-full.txt` ist der zweite Baustein und konzeptionell schlichter: der vollständige Text der wichtigen Seiten, in einer einzigen Markdown-Datei aneinandergehängt. Kein Index mehr, sondern der ganze Inhalt am Stück, ohne HTML-Rauschen. Ein Agent oder Client kann den gebündelten Inhalt mit einer einzigen Anfrage laden, statt sich Seite für Seite durchzuhangeln – ob davon alles zur konkreten Aufgabe passt, ist eine andere Frage.\n\nErgänzend schlägt Howard vor, einzelne Seiten zusätzlich als saubere Markdown-Fassung unter derselben Adresse mit angehängtem `.md` bereitzustellen – aus `.../api` wird `.../api.md`. Das ist der Klebstoff zwischen Index und Inhalt: Der Index verweist auf Seiten, die schon in der Form vorliegen, die ein Modell ohnehin am besten verarbeitet.\n\nWichtig ist die Abgrenzung, weil hier viel durcheinandergeht. `robots.txt` regelt, was ein Crawler anfassen darf. `sitemap.xml` hilft beim Indexieren. `llms.txt` tut keines von beidem: Die Datei ordnet ein und kuratiert, gedacht für den Moment der Inferenz, nicht für den Crawl. Ein Agent, der sie liest, bekommt eine redaktionelle Aussage darüber, was an einem Produkt zählt – kein Versprechen an eine Suchmaschine. Die drei Dateien schließen sich nicht aus, sie beantworten verschiedene Fragen.\n\n```mermaid\nflowchart TD\n    A[Coding-Agent] -->|kennt llms.txt| B[llms.txt<br/>kuratierter Index]\n    B --> C{Welche Seite<br/>brauche ich?}\n    C -->|gezielt| D[seite.md<br/>saubere Markdown-Fassung]\n    C -->|alles auf einmal| E[llms-full.txt<br/>gesamter Inhalt]\n    A -.->|Alternative ohne llms.txt| F[HTML-Seite crawlen<br/>Navigation, Werbung, JS]\n    F -.->|viel Rauschen| G[Kontextfenster voll,<br/>Inhalt verwässert]\n```\n\n## Warum das etwas bringt\n\nBeim Anbinden einer fremden Bibliothek lädt ein Agent ohne Markdown-Sicht häufig die vollständige HTML-Seite oder improvisiert fehlende Signaturen. Im ersten Fall zieht er Menü, Fußzeile und drei Codebeispiele herein, die er gar nicht braucht – ein spürbarer Teil des Fensters ist weg, bevor die eigentliche Aufgabe beginnt. Im zweiten Fall rät er. Mir ist in einem Code-Review aufgefallen, dass ein Agent eine API-Signatur schlicht erfunden hatte, plausibel und falsch, weil ihm die exakte Referenz zu teuer war, sie sich zu holen. Beides sind Symptome desselben Problems: zu viel Rauschen pro Token, zu wenig verlässliche Substanz.\n\n`llms.txt` setzt genau dort an. Kuratiertes Markdown ohne Layout-Ballast bedeutet, dass mehr vom Fenster für den eigentlichen Inhalt übrig bleibt. Der Index zwingt außerdem zu einer Entscheidung: Nicht jede Seite ist gleich wichtig, und jemand mit Domänenwissen muss benennen, welche dreißig bis hundert Seiten den Kern ausmachen. Und wenn das Modell die genaue Fehlermeldung oder den exakten Parameter braucht, holt es sich die passende `.md`-Seite, statt zu improvisieren.\n\nDer Punkt mit der Kuratierung wird oft übersehen. Eine gute `llms.txt` ist keine beliebige Linkliste, sondern eine redaktionelle Aussage darüber, was an einem Produkt zählt. Diese Festlegung ist die eigentliche Arbeit – nicht die Datei selbst.\n\n## Wo es sich lohnt\n\nFür ein Blog oder eine Marketing-Seite bringt `llms.txt` wenig: Für eine Ranking-Wirkung liegt kein Beleg vor, und wer die Datei in der Hoffnung auf bessere Sichtbarkeit anlegt, wird enttäuscht. Wer eine solche Wirkung verspricht, verspricht zu viel.\n\nDie Ausnahme ist eng, aber real: technische Dokumentation und Coding-Agenten. Eine API-Referenz, eine Komponentenbibliothek, ein SDK – Inhalte, die ohnehin in Markdown gepflegt werden und die ein Agent in der IDE gezielt nachschlägt.\n\nFür reine Marketingseiten ohne nachweisbare Agentennutzung rechtfertigt der Pflegeaufwand die Datei meist nicht; bei regelmäßig abgefragter technischer Dokumentation kann er sich lohnen. Server-Logs mit Anfragen auf `/llms.txt` liefern dafür einen Nutzungshinweis, tragen die Entscheidung aber nicht allein: Ausbleibende direkte Zugriffe belegen nicht zwingend fehlende Nutzung, etwa wenn dieselben Inhalte über andere Wege wie MCP-Ressourcen abgerufen werden.\n\n## Aus der Quelle erzeugt, nicht von Hand gepflegt\n\nEin zentrales Risiko beim Einsatz ist organisatorisch, nicht technisch: zwei Fassungen desselben Inhalts, die getrennt gepflegt werden. Die Seite für Menschen hier, die Markdown-Fassung für Modelle dort. Läuft die `llms-full.txt` der echten Doku hinterher, füttert man Modelle mit veralteten Ständen – und das ist schlimmer als gar keine Datei, weil es falsches Vertrauen erzeugt. Ohne automatische Erzeugung aus derselben Quelle ist Drift nur eine Frage der Zeit.\n\nDeshalb gehören beide Dateien in den Build, nicht in den Editor. Der Build kann pro Site und Locale `llms.txt`, `llms-full.txt` und Markdown-Zwillinge aus dem veröffentlichten Stand erzeugen. Entscheidend ist die gemeinsame Quelle für menschliche und maschinenlesbare Ausgaben; eine zweite, von Hand gepflegte Dokumentation würde erneut Drift ermöglichen.\n\nDas ist die zweite Hälfte der Kuratierungsarbeit. Die redaktionelle Entscheidung, was in den Index gehört, trifft ein Mensch. Die Erzeugung der Dateien übernimmt der Build. Wer beides von Hand macht, hat sich eine zweite Doku eingehandelt, die leicht vom veröffentlichten Stand abweicht.\n\n## Was ein MCP-Server daraus macht\n\nBis hierhin ist `llms.txt` eine statische Datei, die jemand irgendwann abholt. MCP ergänzt den statischen Index um gezielten Zugriff auf Ressourcen und Operationen. Das Model Context Protocol ist das offene Protokoll, das Anthropic Ende 2024 vorgestellt hat und über das ein Agent standardisiert mit externen Werkzeugen und Datenquellen spricht.\n\n`llms.txt` beschreibt als Index, welche Inhalte es gibt und wo sie liegen; ein MCP-Server stellt Ressourcen und Operationen gezielt bereit. Das LangChain-Team hat mit `mcpdoc` genau so einen Doku-Server gebaut. Er bekommt eine Liste von `llms.txt`-Adressen und stellt dem Agenten zwei Werkzeuge bereit: eines, das die registrierten Quellen aufzählt, und eines, das eine bestimmte Seite daraus nachlädt.\n\nEin darauf ausgelegter MCP-Doku-Server kann Kontext gezielt nachladen, Aufrufe protokollierbar machen und Zugriffe beschränken – drei Verbesserungen gegenüber dem bloßen Herunterladen der Datei.\n\nErstens die Dosierung. Statt `llms-full.txt` komplett ins Fenster zu kippen, fragt der Agent über den Index nur die eine Seite ab, die zur Aufgabe passt – der Bereich zwischen „gar kein Kontext“ und „alles auf einmal“.\n\nZweitens die Nachvollziehbarkeit. Bei einem Doku-Server wie `mcpdoc` läuft das Nachladen über Werkzeugaufrufe, die man prüfen kann: welche Adresse geladen wurde und was zurückkam. Für Ressourcenabrufe gilt das nicht automatisch; dort braucht es eine eigene Logging auf der Serverseite. Ein direkter Download der Datei hinterlässt diese Spur im Agenten-Workflow nicht zwangsläufig. Bei interner oder geschützter Dokumentation kann diese Prüfbarkeit den zusätzlichen Betriebsaufwand rechtfertigen.\n\nDrittens die Zugriffskontrolle. Der Server lässt sich auf erlaubte Domains beschränken, und für interne oder geschützte Doku legt man Authentifizierung davor. Wer berechtigungsgebundenen Zugriff braucht, kann die Dokumentation über einen authentifizierten MCP-Server als Ressource anbieten und dort Berechtigungen für jeden Abruf prüfen. Damit trägt die Konvention auch hinter der Firmen-Firewall: Der Server zeigt auf eine private `llms.txt`, und Modelle im Team bekommen kuratiertes Wissen, ohne dass die Inhalte offen im Netz stehen.\n\nKommt beides aus einem Produkt, kann es neben den erzeugten Dateien eine Remote-MCP-Oberfläche anbieten. In einem solchen Aufbau sind MCP-Ressourcen anwendungsverwalteter Kontext, den der Server dem Client als Dokumentation anbietet. Werkzeuge bleiben davon getrennt: Sie bilden domänenbezogene Operationen ab und sollten erst mit dem passenden Scope sichtbar werden. Ein solches System kann seine eigene `llms.txt`-Dokumentation zusätzlich als MCP-Ressource bereitstellen, sodass ein Client Werkzeugmodell und API-Grenzen lesen kann, ohne eine Webseite zu erraten. MCP ergänzt die statische Dokumentation also um gezielten Zugriff und um Operationen; berechtigungsgebunden wird dieser Zugriff erst, wenn der Server Ressourcenabrufe authentifiziert und autorisiert. Die Dokumentation ersetzt MCP nicht – ohne erzeugte, aktuelle Maschinensichten fehlte diesen Dokumentationsressourcen eine verlässliche Grundlage.\n\n```mermaid\nflowchart LR\n    H[Agent-Host<br/>Cursor, Claude Code] --> M[MCP Docs-Server<br/>z. B. mcpdoc]\n    M -->|Quellen auflisten| L[llms.txt<br/>registrierte Indizes]\n    M -->|Seite nachladen| P[nur die benötigte<br/>.md-Seite]\n    P --> H\n```\n\nBesonders `llms-full.txt` gewinnt in dieser Kombination. Man kann die Datei direkt als Wissensquelle an einen MCP-Server hängen – ohne Embedding-Pipeline, ohne Vektordatenbank. Treffender als „Ersatz für RAG“ ist die Beschreibung als werkzeuggestützte, prüfbare Variante davon: kein unvorhersehbares Ziehen aus einem großen Vektorindex, sondern nachvollziehbarer Zugriff auf kuratierte Seiten.\n\n## Wo es hakt\n\n`llms.txt` ist ein Vorschlag, kein verabschiedeter Standard. Es gibt kein Gremium dahinter und keine Garantie, dass ein bestimmtes Modell die Datei liest. Man stellt sie bereit; erzwingen lässt sich der Konsum nicht.\n\nDie Größe ist eine echte Grenze. Eine mehrere Megabyte große `llms-full.txt` kann je nach Tokenisierung, Modell und Clientlimit nicht vollständig in den verfügbaren Kontext passen und wird dann nur in Bruchstücken geladen – womit der Vorteil „alles in einer Anfrage“ dahin ist. Für große Sites bleibt es beim kuratierten Index auf die wirklich zentralen Seiten, ergänzt um gezieltes Nachladen einzelner `.md`-Fassungen.\n\nUnd schließlich die Vertrauensfrage. Sobald ein Agent eine fremde `llms-full.txt` ungeprüft übernimmt, übernimmt er Inhalt, den er nicht kontrolliert. Das ist dieselbe Angriffsfläche wie bei jeder externen Datenquelle, die in den Kontext wandert – ein guter Grund, über einen MCP-Server mit Domain-Beschränkung zu gehen, statt beliebige Adressen einzusammeln.\n\n## Fazit\n\n`llms.txt` und `llms-full.txt` sind maschinenlesbare Selbstdokumentation. Der Index sagt, was zählt und wo es liegt; die Vollfassung liefert den Inhalt am Stück; die `.md`-Spiegel geben einzelne Seiten in der Form, die Modelle bevorzugen. Ein belastbarer Ranking-Faktor ist keines davon, und wer die Dateien mit dieser Erwartung anlegt, misst am falschen Ziel. Ihr Wert entsteht dort, wo Dokumentation auf Agenten trifft – bei SDKs, API-Referenzen und Coding-Werkzeugen.\n\nDaraus folgen zwei Entscheidungen. Erstens: Die Dateien werden aus derselben Quelle erzeugt wie die Dokumentation für Menschen, oder man lässt sie weg – ein handgepflegter Doppelbestand driftet und untergräbt genau das Vertrauen, das er stiften soll. Zweitens: Wer gezielten oder berechtigungsgebundenen Zugriff braucht, kann die Dokumentation über einen authentifizierten MCP-Server als Ressource anbieten und dort Berechtigungen prüfen. MCP kann die statischen Sichten so um dosierten, prüfbaren und – bei serverseitiger Autorisierung – berechtigungsgebundenen Zugriff ergänzen; es bleibt darauf angewiesen, dass die Dokumentation dahinter stimmt.\n\n## Weiterführende Quellen\n\n- Der ursprüngliche Vorschlag und die Formatbeschreibung: [llmstxt.org](https://llmstxt.org/)\n- Repository zum Vorschlag: [AnswerDotAI/llms-txt](https://github.com/answerdotai/llms-txt)\n- MCP-Doku-Server, der `llms.txt` als Quelle liest: [langchain-ai/mcpdoc](https://github.com/langchain-ai/mcpdoc)\n- Model Context Protocol: [modelcontextprotocol.io](https://modelcontextprotocol.io/)"},{"locale":"de","translation_key":"hilfsmittel-konzepte-methoden-prozesse","slug":"hilfsmittel-konzepte-methoden-prozesse","title":"Hilfsmittel, die tragen: Konzepte, Methoden, Prozesse","summary":"Einen Agenten für die eigene Fachdomäne kann man nicht installieren – den Weg dorthin aber sehr wohl lernen. Welche Konzepte tragen, welche Methoden den Anfang klein halten und welche Prozesse verhindern, dass Regeln veralten.","tags":["Software","KI","Methodik","Delivery"],"published_at":"2026-07-15T10:00:00+00:00","updated_at":"2026-08-18T05:16:11.670656+00:00","url":"https://www.mikebild.dev/de/blog/hilfsmittel-konzepte-methoden-prozesse/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/85c6b39b0ba8daf83a88bdf1232b28c9d8e82e9ca43ba5afea716a459aec19fc.mp3","audio_duration_secs":892,"text":"Für einen Agenten, der eine Fachdomäne verbindlich vertritt, gibt es kein Installationspaket. Installieren lassen sich verfügbare Modellgewichte und Laufzeiten; Protokolle lassen sich implementieren oder anbinden. Modellgewichte und Laufzeiten allein erzwingen jedoch keine fachliche Freigabe und erzeugen keinen fachlich aussagekräftigen Nachweis darüber, wer was entschieden hat. Der verbindliche Teil entsteht erst in der Auseinandersetzung mit der eigenen Domäne – mit ihren Begriffen, ihren Regeln und den Menschen, die für beides einstehen. Der Weg dorthin ist allerdings lernbar, und er ist unspektakulärer, als viele Framework-Debatten vermuten lassen.\n\n*Teil 12 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nDie [letzte Folge](https://www.mikebild.dev/de/blog/eigener-agent-pro-fachdomaene/) hat beschrieben, was so ein Agent können muss: Pläne prüfen, bevor sie wirken; Freigaben, die kein Modell wegformulieren kann; Nachweise, die Fragen von übermorgen beantworten. Offen geblieben ist der Weg dorthin. Er führt über drei Sorten von Hilfsmitteln: Konzepte, die tragen. Methoden, die den Anfang klein halten. Und Prozesse, die das Ganze im Betrieb am Leben erhalten, wenn die Aufmerksamkeit weiterzieht. Der Reihe nach.\n\n## Konzepte: nichts davon ist neu\n\nWer die Fähigkeiten-Liste aus der letzten Folge durchgeht, findet darin keine einzige KI-Erfindung. Fachsprache und Domänenschnitt – dass ein System die Begriffe seiner Domäne sprechen soll und dass diese Begriffe nur innerhalb eines abgesteckten Zusammenhangs eindeutig sind – hat Eric Evans vor gut zwanzig Jahren in „Domain-Driven Design“ als ubiquitous language und Bounded Context beschrieben. Die Trennung von Vorschlag und Wirkung kennt jede Organisation, die Änderungen erst prüft und dann ausrollt, vom Vier-Augen-Prinzip in der Buchhaltung bis zu `terraform plan` und `apply`. Validierung, Autorisierung, Audit sind das Handwerkszeug jeder ernsthaften Fachanwendung. Und dass Antworten [auf echten Quellen stehen müssen statt auf plausiblem Raten](https://www.mikebild.dev/de/blog/sauberes-grounding-antworten-erden/) und [kuratiertes Wissen einen Kreislauf mit Besitzern braucht](https://www.mikebild.dev/de/blog/wissen-das-die-session-ueberlebt/), haben die mittleren Folgen dieser Serie behandelt – auch das ist im Kern Dokumentations- und Bibliotheksarbeit, kein Hexenwerk.\n\nNeu ist allein der Abnehmer: eine Schleife, in der ein Modell handelt, statt einer Oberfläche, in der Menschen klicken. Für die Konzeptauswahl ist das eine kleine Verschiebung. Mir hilft seither eine einfache Prüffrage: Hat dieses Konzept schon getragen, bevor es KI gab? Domänenschnitt, Freigabe-Workflows, Versionierung, Audit – ja, jahrzehntelang. Ein Orchestrierungs-Framework, das es seit vier Monaten gibt – eher nicht. Das ist keine Abwertung von allem Neuen; irgendwo entsteht gerade tatsächlich das nächste tragende Konzept. Aber die Beweislast liegt beim Neuen, nicht beim Bewährten.\n\nDass sich die alten Konzepte direkt in Agentensysteme übertragen lassen, zeigt ein naheliegender Baustein: Eine Workflow-Engine kann Mission, Plan, Lauf und die dazu erteilte Autorität trennen – und für HTTP, MCP, A2A, Webhooks und Chat denselben Planungspfad nutzen. Das ist die alte Trennung von Vorschlag und Wirkung, konsequent auf jeden Eingangskanal angewendet: Egal, woher ein Vorhaben kommt, es nimmt denselben Planungspfad.\n\nFür den Reflex, gleich die ganze Organisation als Agenten-Landschaft zu entwerfen, gibt es ebenfalls ein altes Konzept, und es trifft härter als jede Technikfrage. John Gall hat es in den Siebzigern als Beobachtung über Systeme formuliert: Ein komplexes System, das funktioniert, ist ausnahmslos aus einem einfachen System hervorgegangen, das funktioniert hat. Ein komplexes System, das am Reißbrett entworfen wurde, funktioniert nicht und lässt sich auch nicht reparieren – man muss von vorn anfangen, mit einem einfachen System. Zwölf verbundene Agenten auf einem Whiteboard sind der Reißbrett-Entwurf. Der erste Vorgang, der wirklich läuft und ein prüfbares Ergebnis liefert, ist der Anfang des Systems.\n\n## Methode: erst die Regeln inventarisieren\n\nDie erste der drei Fragen vom Ende der letzten Folge lautete: Welche Regeln gehören in den Pfad, welche dürfen Prosa bleiben? Die Antwort beginnt nicht bei der Technik, sondern bei einer Bestandsaufnahme, die unbeliebter ist, als sie sein müsste. Für die Inventur würde ich zunächst vier Fundorte prüfen: das Wiki, Instruktionsdateien wie CLAUDE.md oder AGENTS.md, Code-Review-Kommentare – und Köpfe, als das Wissen der einen Kollegin, die man sicherheitshalber vor jeder Preisänderung fragt. Vollständig ist diese Liste nicht; je nach Organisation kommen Tickets, Richtlinien, Konfiguration oder Fachverfahren hinzu. Die Inventur holt die Regeln an einen Ort und notiert zu jeder vier Dinge: Wo steht sie? Wie verbindlich ist sie gemeint? Was passiert bei einem Verstoß? Und wie oft wurde sie zuletzt tatsächlich verletzt?\n\nDie letzte Spalte ist die wichtigste, denn sie ersetzt Meinung durch Befund. In der Chronik meiner Instruktionsdateien war die Ernüchterung, dass aufgeschriebene Regeln Empfehlungen bleiben; in der [Folge über Tools](https://www.mikebild.dev/de/blog/agent-modell-fachdomaene/) wurde daraus ein Übergangskriterium: Wenn dieselbe Regel zum dritten Mal in einer Instruktionsdatei auftaucht und zum zweiten Mal ignoriert wurde, ist sie ein Kandidat für die Durchsetzung im Pfad. Die Inventur macht aus diesem Bauchgefühl eine Liste:\n\n```yaml\n# rule inventory, one entry per rule\n- rule: \"Credit notes above 500 EUR require team lead approval\"\n  source: wiki, AGENTS.md\n  violation_impact: money leaves the company\n  violated_recently: twice in Q2\n  decision: enforce   # goes into the path\n\n- rule: \"Use the customer number, not the invoice number, in replies\"\n  source: onboarding notes\n  violation_impact: confusion, no damage\n  violated_recently: unknown\n  decision: prose     # stays a convention\n```\n\nFür die Einordnung halte ich drei Fragen für einen tragfähigen Startpunkt, und sie decken sich mit den Kriterien, die sich in dieser Serie nach und nach herausgeschält haben: Bewegt ein Verstoß Geld, personenbezogene Daten oder Wirkung nach außen? Muss hinterher jemand nachweisen können, wer was wann entschieden hat? Wurde die Regel trotz sauberer Dokumentation wiederholt gebrochen – von Menschen oder vom Modell? Ein Ja bei einer dieser Fragen ist für mich der Ausgangspunkt, die Regel in den Pfad zu nehmen: Prüfung, Freigabe, Nachweis. Eine Startheuristik bleibt das allerdings – wo der mögliche Schaden gering ist, ein Fehler sich leicht zurücknehmen lässt oder bestehende Kontrollen ihn ohnehin abfangen, kann eine Regel auch bei einem Ja Prosa bleiben. Dreimal Nein, und sie bleibt Prosa – als Konvention, die das Modell liest und meistens befolgt, und deren verbleibendes Risiko ausdrücklich akzeptiert wurde.\n\nDie Inventur hat einen zweiten Ertrag, der leicht übersehen wird: Sie findet tote Regeln. Vorgaben, die seit Jahren niemand mehr braucht, deren Anlass längst verschwunden ist, die aber weiter in jedem Dokument mitgeschleppt werden. Die fliegen raus – nicht in den Pfad, sondern ganz. Ein Agent, der eine Fachdomäne vertritt, ist auch eine Gelegenheit, die Domäne selbst zu entrümpeln.\n\n## Methode: die erste Domäne klein schneiden\n\nDie zweite Frage: Wie schneidet man die erste Domäne, ohne sich zu verheben? Die kurze Antwort: einen Vorgang, keine Abteilung. Eine Abteilung bündelt viele Zustände und Verantwortlichkeiten, die nie gleichzeitig fertig sind; ein Vorgang hat einen prüfbaren Anfang und ein prüfbares Ende. „Rechnungswesen“ ist deshalb kein Schnitt, sondern ein Organigramm-Kästchen. „Gutschriften und Mahnstopps“ ist einer – ein abgrenzbarer Vorgang mit Anfang, Ende und einer Handvoll Verben.\n\nWoran man einen tauglichen ersten Kandidaten erkennt:\n\n- Der Vorgang hat einen klaren Anfang und ein klares Ende – kein Dauerzustand, kein Sammelbegriff.\n- Eine Handvoll Verben genügt: Spätestens wenn die Tool-Liste beim Modellieren zweistellig wird, würde ich den Schnitt erneut prüfen.\n- Es gibt heute schon eine fachlich zuständige Person – die Rolle, die auch ohne KI freigibt und entscheidet.\n- Der Schmerz ist dokumentiert: Verstöße sind in der Vergangenheit tatsächlich passiert und haben nachweislich geärgert.\n- Das Schadenspotenzial rechtfertigt den Aufwand, bleibt aber überschaubar – Gutschriften ja, Zahlungsverkehr mit dem Ausland vielleicht erst im zweiten Jahr.\n\nDer letzte Punkt verdient einen Moment. Der erste Domänen-Agent ist nicht nur ein Werkzeug, er ist auch das Stück, an dem ein Team die drei Fähigkeiten – Prüfung, Freigabe, Nachweis – zum ersten Mal baut und betreibt. Solche ersten Stücke wählt man so, dass Fehler lehrreich sind, nicht existenzbedrohend.\n\nZum kleinen Schnitt gehört auch ein kleiner Übergang. Niemand reißt die bestehende Arbeitsweise ab und ersetzt sie durch den Agenten; die Prosa-Variante bleibt der Prototyp, aus dem Regeln einzeln in den Pfad wandern, sobald ihre Verbindlichkeit sich erwiesen hat. Martin Fowler hat für dieses Muster – das Neue wächst am Alten entlang, bis das Alte entbehrlich ist – das Bild der Würgefeige geprägt, die einen Baum umwächst. Auf Regeln übertragen: Erst gilt die 500-Euro-Regel als Satz in der Instruktionsdatei, dann zusätzlich als Prüfung im Pfad, und irgendwann ist der Satz nur noch Dokumentation der Prüfung. Kein großer Umstellungstag, keine riskante Migration über ein Wochenende.\n\nDer Rest der großen Skizze stirbt dabei nicht – er wird Backlog, sortiert nach genau den Kriterien oben. Das kann sich wie ein Rückzug anfühlen. Es ist das Gegenteil: der erste Schritt, der tatsächlich gegangen werden kann und ein überprüfbares Ergebnis liefert.\n\n## Prozesse: Besitzer, Änderungsweg, Rhythmus\n\nBleibt die dritte Sorte Hilfsmittel, und sie ist die am leichtesten unterschätzte. Konzepte kann man lernen, Methoden kann man anwenden – Prozesse muss man im Betrieb durchhalten. Drei halte ich für tragend.\n\nErstens: Jede Regel hat einen Besitzer, und der sitzt im Fachbereich. Die Entwicklung besitzt die Durchsetzung – den Code, der prüft, das Gatter, das wartet, das Protokoll, das schreibt. Aber ob 500 Euro die richtige Schwelle ist, ob „Kulanz“ und „Preisfehler“ verschiedene Wege gehen, entscheidet die Fachseite, die diese Verantwortung schon immer trug. Die Diskussion über das Vorschlagen, Prüfen und Freigeben von Regeln ist dabei kein Hindernis auf dem Weg zum Prozess. Sie ist der Prozess – wer sie überspringt, hat Regeln ohne Legitimation, und die erodieren beim ersten Konflikt.\n\nZweitens: Regeländerungen gehen denselben Weg wie Regeln. Vorschlag, Prüfung, Freigabe, Versionierung – dieselbe Sorgfalt, die für Code selbstverständlich ist. Dass der Nachweis die geltende Regelversion festhält, war in der letzten Folge ein Detail am Rand; im Betrieb wird es zur Voraussetzung dafür, dass man Regeln überhaupt anfassen kann, ohne die Vergangenheit umzudeuten. Wie das aussehen kann, zeigen zwei Bausteine: Ein Wissenssystem kann fachliche Leitlinien in einem versionierten, menschenverantworteten Charter halten und Änderungen am abgeleiteten Wissensbestand durch einen Review-Prozess führen. Eine Workflow-Engine kann genehmigte Abläufe als wiederholbar ausgeführte Workflows beschreiben und jeden Lauf protokollieren – nicht beschriebene und nicht genehmigte Arbeit wird nicht improvisiert. Beides sind Ausprägungen desselben Prinzips: Der Änderungsweg ist in das System eingebaut.\n\nDrittens, und am wichtigsten: aus den Neins lernen, in festem Rhythmus. Der Agent erzeugt im Betrieb zwei Ströme – Ausführungen und Ablehnungen. Für zu enge oder fehlende Regeln sind die Ablehnungen oft der ergiebigere Ausgangspunkt; Stichproben erfolgreicher Läufe bleiben trotzdem nötig, weil auch eine durchgewunkene Ausführung eine falsche Entscheidung enthalten kann. Das Ablehnungsprotokoll gehört deshalb regelmäßig auf den Tisch – anfangs in einem festen Abstand von wenigen Wochen, später abhängig von Ablehnungsrate und Schadenspotenzial – mit drei Fragen: Welche Neins waren richtig und bleiben? Welche waren zu eng und brauchen eine angepasste Schwelle oder einen neuen Gutschriftsgrund? Und welche Sonderfälle tauchen so regelmäßig auf, dass sie ein eigenes Verb verdienen? Das ist derselbe Kreislauf, den [die Folge über kuratiertes Wissen](https://www.mikebild.dev/de/blog/wissen-das-die-session-ueberlebt/) beschrieben hat, nur mit Regeln statt Erkenntnissen: Der Betrieb liefert Kandidaten, die Kuration macht Verbindliches daraus – die Organisation ändert dabei Regeln und Schnittstellen; das Modell bleibt unverändert.\n\n```mermaid\nflowchart LR\n    I[\"Inventur<br/>Regeln sammeln und bewerten\"] --> K[\"Einordnung<br/>Pfad oder Prosa\"]\n    K --> B[\"Bauen<br/>Verben · Prüfung · Freigabe\"]\n    B --> O[\"Betrieb<br/>Ausführungen und Ablehnungen\"]\n    O --> S[\"Sichtung im Rhythmus<br/>aus den Neins lernen\"]\n    S --> I\n```\n\nZusammen ergeben die drei Prozesse das, was in der letzten Folge nur behauptet wurde: dass so ein Agent ein Produkt mit Lebenszyklus ist. Ein Produkt hat Besitzer, einen Änderungsweg und einen Takt, in dem es besser wird. Fehlt eines davon, verfällt es – bei Regeln schneller als bei Code, weil eine veraltete Schwelle keinen Build fehlschlagen lässt und deshalb gezielt durch Review oder Betriebsmetriken erkannt werden muss.\n\n## Moden, die man auslassen kann\n\nUnd die Gegenliste? Vier Muster halte ich für Aufmerksamkeitsfresser, die weder Prüfung noch Freigabe oder Nachweis verbessern – das ist ein Urteil, kein Messergebnis.\n\nDas Multi-Agenten-Orchester ab Tag eins: viele Agenten, die einander Messages schicken, bevor auch nur einer eine einzige verbindliche Regel durchsetzt – der Reißbrett-Entwurf in Software gegossen. Der häufige Framework-Wechsel, bei dem die Fachlogik jedes Mal ein Stück tiefer in Anbieter-Konventionen einsinkt; das Gegenmittel – Fachlogik in eigene Dienste, Tool-Schicht als dünner Adapter – stand schon [in der Folge über Agent, Modell und Fachdomäne](https://www.mikebild.dev/de/blog/agent-modell-fachdomaene/). Die Modell-Vergleichstabelle als Strategieersatz, gegen die [diese Serie früh argumentiert hat](https://www.mikebild.dev/de/blog/gut-genug-modelle/): Ob mehrere Modelle die eigenen Aufgaben gut genug lösen, zeigt eine konkrete Prüfung gegen genau diese Aufgaben – und dort, wo das der Fall ist, gehört die Energie in den eigenen Anteil, nicht in die Tabelle. Und das endlose Feilen an Formulierungen: Wenn dieselbe Anweisung zum dritten Mal umformuliert wird, damit das Modell sie „endlich versteht“, ist das kein Schreibproblem. Es ist das Signal, dass die Regel in den Pfad gehört, nicht in schönere Worte.\n\nDie Prüffrage ist immer dieselbe, und sie macht die Liste kurz: Hilft es, Prüfung, Freigabe oder Nachweis zu bauen – oder fühlt es sich nur nach Fortschritt an? Viele derzeit diskutierte Frameworks und Agentenmuster kann man in Ruhe reifen lassen. Sie laufen nicht weg, und was davon trägt, ist in einem Jahr noch da.\n\n## Zwischenstand\n\nDamit sind die drei Fragen vom Ende der letzten Folge beantwortet, so gut ich es nach diesen Monaten kann: mit einer Inventur, die Befunde statt Meinungen liefert, einem Schnitt von der Größe eines Vorgangs und Prozessen, die Besitzer, Änderungsweg und Rhythmus festlegen. Beginnen würde ich deshalb mit einem belegten Regelverstoß in einem bereits klein geschnittenen Vorgang – dort ist der Schmerz dokumentiert, der Schnitt klein und das Ergebnis prüfbar. Die Konzepte dahinter sind alt, und das ist ihre wichtigste Eigenschaft: Sie haben schon einmal gehalten.\n\nVor gut acht Monaten begann diese Serie mit einer Session auf meinem Rechner und der Beobachtung, dass sich meine Arbeit verändert; jetzt endet der Weg vorläufig bei Organisationen, die Regeln, Wissen und Verantwortung in eigene Agenten legen. Die nächste Folge prüft die Erwartungen aus dem Auftakt: Was davon ist eingetreten, was nicht – und wohin führt das alles?\n\n## Weiterführende Quellen\n\n- [Domain-Driven Design Reference (Eric Evans)](https://www.domainlanguage.com/ddd/reference/) – ubiquitous language und Bounded Context als Entwurfsarbeit\n- [John Gall: Systemantics](https://en.wikipedia.org/wiki/John_Gall_%28author%29) – warum funktionierende komplexe Systeme aus einfachen funktionierenden Systemen entstehen\n- [Martin Fowler: Strangler Fig Application](https://martinfowler.com/bliki/StranglerFigApplication.html) – das Muster für Übergänge ohne großen Umstellungstag\n- [Building Effective AI Agents (Anthropic)](https://www.anthropic.com/engineering/building-effective-agents) – der Rat, mit dem einfachsten funktionierenden Aufbau zu beginnen"},{"locale":"de","translation_key":"eigener-agent-pro-fachdomaene","slug":"eigener-agent-pro-fachdomaene","title":"KI-Agenten pro Fachdomäne: Regeln, Freigaben und Nachweise","summary":"Wie ein KI-Agent fachliche Regeln über mehrere Tool-Aufrufe hinweg durchsetzt: mit Vorgangszustand, geprüften Plänen, Freigaben und nachvollziehbarer Ausführung.","tags":["Software","KI","Methodik","Delivery"],"published_at":"2026-07-14T10:00:00+00:00","updated_at":"2026-11-08T13:00:00+00:00","url":"https://www.mikebild.dev/de/blog/eigener-agent-pro-fachdomaene/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/70f30f9c15d391ac21e974541fb6236207eb633fc60bb961e78f6c3e54d5ffdf.mp3","audio_duration_secs":996,"text":"Ein KI-Agent pro Fachdomäne verbindet die Werkzeuge eines Arbeitsfelds mit dessen Regeln, Rechten und Vorgangszustand. Entscheidend ist nicht ein weiterer Chat, sondern ein ausführbarer Pfad, der zusammengehörige Aktionen prüft, bevor sie wirken. Dieser Artikel zeigt, welche Verantwortung dafür beim Modell, beim Tool und beim betriebenen Agentensystem liegt.\n\nEin konstruiertes Beispiel: Ein Agent soll 740 Euro Kulanz erstatten. Über 500 Euro braucht es die Freigabe der Teamleitung. Der Tool-Aufruf über 740 Euro wird abgelehnt; zwei Aufrufe über je 370 Euro würden eine rein aufrufbezogene Prüfung dagegen bestehen. Jeder Aufruf wäre einzeln zulässig, die gemeinsame Wirkung nicht. Genau diese Lücke muss eine Regel über den gesamten Vorgang schließen.\n\n*Teil 11 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nDas Beispiel beschreibt eine mögliche Schwachstelle, keinen beobachteten Vorfall. Ob ein Modell tatsächlich zwei Teilbeträge vorschlägt, ist offen. Die Architektur muss eine solche Umgehung trotzdem verhindern: Eine Vorgangsregel lässt sich nicht allein als isolierte Prüfung einzelner Aufrufe ausdrücken.\n\nDiese Folge löst damit zwei Versprechen ein, die in der Serie offen sind. Die Chronik meiner Instruktionsdateien endete mit dem Befund, dass nur das eine Regel ist, was die Umgebung erzwingt. Die [letzte Folge](https://www.mikebild.dev/de/blog/agent-modell-fachdomaene/) schloss mit der Frage, warum verbindliche Regeln auf einen eigenen, an die Fachdomäne gebundenen Agenten hinauslaufen – und was der können muss. Die Gutschriften-Konstruktion gibt die Antwort in Kurzform: Regeln brauchen einen Ort, an dem der Zusammenhang sichtbar ist.\n\n## Ein Tool sieht den Aufruf, nicht den Vorgang\n\nZur Erinnerung, wo die Serie steht: Die letzte Folge hat die Fachdomäne aus dem Prompt in die Tools verlegt – typisierte Operationen, deren Namen aus der Fachsprache kommen, deren Eingaben validiert und deren Aufrufe autorisiert werden. Die Prüfung läuft damit im ausführbaren Pfad statt im Prompt: Die 500-Euro-Regel wurde von einer Empfehlung, die das Modell lesen und abwägen kann, zu Code, der bei jedem Aufruf gleich entscheidet.\n\nIn diesem Beispiel sieht die Prüfung nur einen Aufruf. Ein Tool kann auch Vorgangszustand laden und prüfen; entscheidend ist, dass diese Verantwortung ausdrücklich umgesetzt wird. Ohne sie bleiben drei Dinge verborgen.\n\nDer Zusammenhang. Fachliche Regeln sind selten Regeln über Aufrufe – sie sind Regeln über Vorgänge. „Nicht mehr als 500 Euro Kulanz“ meint: pro Fall, pro Kunde, pro Zeitraum. Zwei Gutschriften à 370 Euro zum selben Vorgang verletzen die Regel, ohne dass irgendein einzelner Aufruf sie verletzt. Eine Autorisierung, die nur die Eingabe des aktuellen Aufrufs erhält, kann das nicht bemerken – nicht weil das Tool technisch unfähig wäre, sondern weil ihr der gebundene Vorgangszustand fehlt.\n\nDie Wirkung. Manche Fehler erkennt man nicht am einzelnen Schritt, sondern erst am Gesamtbild – an dem, was nach zwanzig Schritten entstanden sein wird. Wer erst nach der Ausführung prüft, prüft zu spät; die Gutschrift ist dann schon beim Kunden.\n\nDas Gedächtnis. Ob ein Muster auffällig ist, entscheidet sich über Sessions hinweg: dieselbe Rechnung, dreimal in zwei Wochen, von zwei verschiedenen Personen angestoßen. Der einzelne Aufruf weiß davon nichts, und das einzelne Tool ebenso wenig.\n\nWas dem einzelnen Tool-Aufruf fehlt, kann der Agent zusammenführen: den Verlauf, einen materialisierten Plan und persistenten Vorgangszustand – vorausgesetzt, diese Zustände werden explizit gespeichert und an den Vorgang gebunden. Deshalb wandert die Durchsetzung eine Ebene nach oben – aus dem Tool in den Agenten, der die Schleife betreibt. Damit ist der Agent kein austauschbares Zubehör mehr, sondern der Ort, an dem die verbindlichen Regeln einer Fachdomäne liegen: ein betriebenes Softwaresystem mit Plan, Rechten, Freigaben, Nachweisen und klarer Zuständigkeit.\n\n## Vom Vorschlag zum Nachweis: fünf Stationen\n\nWie sieht diese Durchsetzung aus? Der tragende Gedanke ist alt und stammt nicht aus der KI-Welt: Bauen und Ausführen trennen. Wer Infrastruktur als Code betreibt, kennt ihn als `terraform plan` und `terraform apply` – erst entsteht eine vollständige Vorschau dessen, was sich ändern würde, dann entscheidet sich getrennt davon, ob das auch geschieht. Zwischen Vorschlag und Wirkung liegt eine Prüfung, und die sieht nicht den einzelnen Handgriff, sondern das ganze Vorhaben.\n\nAuf Agenten übertragen umfasst der Weg von der Idee zur Wirkung fünf Stationen.\n\nAm Anfang steht der Modellvorschlag: eine textuelle oder strukturierte Ausgabe, so eloquent wie unverbindlich. Ob das Modell Prosa liefert oder fertig formatierte Tool-Aufrufe – es erzeugt damit zunächst nur eine Absichtserklärung ohne autorisierte Wirkung. Daraus wird zweitens ein ausführbarer Plan: eine geordnete Folge typisierter Operationen mit konkreten Parametern, als immutable Revision gespeichert und an den geprüften Zustand gebunden; die Operationen und Parameter sind maschinell auswertbar, eine Begründung kann ergänzend Freitext bleiben. Drittens die fachliche Autorisierung: Der Plan wird als Ganzes gegen die Regeln der Fachdomäne geprüft. Hier fallen zwei Gutschriften zum selben Vorgang auf, hier greifen Summen- und Häufigkeitsregeln, hier entscheidet sich, ob das Vorhaben zulässig, abzulehnen oder freigabepflichtig ist. Viertens, wo die Regeln es verlangen, die menschliche Freigabe: eine Bestätigung durch eine Rolle der Fachdomäne, die das Modell weder erteilen noch ersetzen kann – es darf Vorschläge machen, aber keine menschliche Entscheidung selbst bestätigen. Und fünftens der Nachweis, in zwei Formen: ein Entscheidungsnachweis für jede Ablehnung und jede Freigabe, ein Ausführungsnachweis für jede tatsächlich ausgeführte Operation – wer, was, wann, mit welchem Ergebnis, unter welcher Regelversion.\n\n```mermaid\nflowchart LR\n    M[\"Modellvorschlag<br/>textuell oder strukturiert, unverbindlich\"] --> P[\"Plan<br/>alle geplanten Operationen\"]\n    P --> R{\"fachliche Autorisierung<br/>Regeln der Fachdomäne\"}\n    R -- \"verletzt\" --> N[\"Ablehnung<br/>begründet und protokolliert\"]\n    R -- \"freigabepflichtig\" --> H[\"menschliche Freigabe\"]\n    R -- \"zulässig\" --> D{\"gebundener Zustand<br/>noch aktuell?\"}\n    H -- \"bestätigt\" --> D\n    H -- \"abgelehnt\" --> A\n    D -- \"ja\" --> E[\"Ausführung\"]\n    D -- \"nein\" --> R\n    E --> A[\"Entscheidungs- oder Ausführungsnachweis<br/>wer · was · wann · Regelversion\"]\n    N --> A\n```\n\nIm Kleinen kennt das jeder, der mit Coding-Agenten arbeitet: erst der Diff, dann der Commit. Der Unterschied ist, dass dort ein Mensch freiwillig hinschaut – und am Freitagnachmittag eben auch mal nicht. In einem Agenten, der eine Fachdomäne verantwortet, ist die Prüfung keine Gewohnheit, sondern Teil des Pfads. Sie findet statt, ob jemand daran denkt oder nicht.\n\n## Ein Nein, das ein Nein bleibt\n\nDie zweite Fähigkeit folgt direkt aus der Konstruktion vom Anfang. Ein Modell, das auf eine Ablehnung trifft, kann umformulieren, verhandeln, Umwege suchen. Das wäre keine Böswilligkeit: Weitersuchen ist genau das Verhalten, das wir an anderer Stelle schätzen, wenn ein Modell einen Testfehler dreimal anders angeht, bis der Build grün ist. Statt diese Beharrlichkeit wegtrainieren zu wollen, kann man ihr eine Grenze setzen, die nicht mitverhandelt.\n\nDafür muss die Freigabe außerhalb des Gesprächs liegen. Eine freigabepflichtige Operation wartet, bis ein Mensch sie bestätigt – und kein noch so eloquenter Text im Kontext bewegt dieses Gatter, weil das Gatter den Text gar nicht liest. Das Modell kann seine zwei 370-Euro-Gutschriften vorschlagen, so oft es will: Die Summenregel schlägt beim Plan an, die Freigabe bleibt offen, der Vorgang liegt beim zuständigen Menschen. Wichtig ist dabei, wer dieses Ja gibt: nicht „irgendein Admin“, sondern eine Rolle aus der Fachdomäne – die Teamleitung, die auch ohne KI über 500-Euro-Kulanzen entscheidet. Die Freigabe bildet eine bestehende fachliche Verantwortung ab, sie erfindet keine neue.\n\nSkizziert an der Tool-Definition aus der letzten Folge sieht die Erweiterung ungefähr so aus. Der Codeblock ist eine vereinfachte, illustrative Skizze: Die API `defineTool` und die Rolle `billing_team_lead` sind frei gewählte Platzhalter.\n\n```ts\nconst issueCreditNote = defineTool({\n  name: \"issue_credit_note\",\n  input: z.object({\n    invoiceId: z.string(),\n    amount: z.number().positive(),\n    reason: z.enum([\"complaint\", \"goodwill\", \"pricing_error\"]),\n  }),\n  approval: {\n    required: ({ input, history }) =>\n      input.amount + history.totalCreditedFor(input.invoiceId) > 500,\n    approvers: [\"billing_team_lead\"],\n  },\n  audit: { record: [\"user\", \"input\", \"approval\", \"result\"] },\n});\n```\n\nDie entscheidende Zeile ist die mit `history`. Die Freigabepflicht hängt nicht am einzelnen Betrag, sondern an der Summe über den Vorgang. Autoritativ liegt dieser Zustand in der Fachdomäne, nicht im Gespräch: Der Agent bindet einen geprüften Stand des Vorgangs an den Plan und reicht ihn als Eingabe in die Autorisierung – genau die Sicht, die der isolierten Einzelaufrufprüfung fehlt. Eine Bindung allein genügt allerdings nicht: Damit parallele Aufrufe die 500-Euro-Grenze nicht doch überschreiten, muss die Ausführung den gebundenen Stand vorab erneut gegen den aktuellen Domänenzustand prüfen und bei zwischenzeitlichen Änderungen abbrechen oder neu autorisieren.\n\n## Nachweis statt Erinnerung\n\nDie dritte Fähigkeit ist die unscheinbarste: Jede Ausführung hinterlässt einen Nachweis. Wer hat den Vorgang angestoßen, welche Planrevision wurde geprüft, was genau wurde ausgeführt, mit welchen Eingaben, was kam heraus, wer hat freigegeben – und, leicht zu übersehen: welche Fassung der Regeln galt dabei. Fachregeln ändern sich. Aus 500 Euro werden 300, ein Freigabeweg wird umgebaut. Wenn drei Monate später jemand fragt, warum eine Gutschrift damals durchging, muss die Antwort lauten können: nach Regelstand vom März war sie zulässig, hier ist der Eintrag.\n\nEin solches Protokoll existiert nicht, weil jemand daran gedacht hat mitzuschreiben. Es existiert, weil der Pfad es erzeugt – Ablehnungen eingeschlossen. Auch das Nein hinterlässt eine Spur, und gerade die Neins zeigen, wo Regeln zu eng oder Tools zu grob geschnitten sind. Auditierbarkeit ist keine Compliance-Übung, die man hinterher anbaut. Sie ist eine Eigenschaft des Pfads, oder sie ist nicht.\n\n## Warum pro Fachdomäne\n\nBis hierher ist begründet, warum verbindliche Regeln in prüfbare Zustandsübergänge und Autorisierungsgrenzen gehören statt nur in Prompt-Prosa. Offen ist der zweite Teil der Frage aus der letzten Folge: Warum ein *eigener* Agent pro Fachdomäne – und nicht ein großer, der alles kann?\n\nWeil jede der drei Fähigkeiten Fachlichkeit voraussetzt. Eine Plan-Prüfung kann nur bewerten, was sie versteht: Dass zwei Gutschriften zum selben Vorgang gehören, dass ein Kunde im Mahnverfahren steckt, dass „Kulanz“ und „Preisfehler“ verschiedene Folgen haben – das sind Begriffe und Zusammenhänge einer Domäne, keine generischen Konzepte. Die Freigabe braucht Rollen, die es nur dort gibt. Der Nachweis muss in der Sprache geführt werden, in der später jemand fragt. Ein generischer Agent kann Dateien lesen und Kommandos ausführen; er kann nicht wissen, was eine unzulässige Gutschrift ist.\n\nDazu kommen die Rechte. Ein Agent, der die Tools aller Domänen trägt, kann einen entsprechend breiten Berechtigungsumfang benötigen, wenn Rechte nicht pro Aufruf delegiert und begrenzt werden – und wird mit solchen dauerhaften Rechten zu einem lohnenden Angriffsziel. Die OWASP führt „Excessive Agency“ in ihren Top-10-Risiken für LLM-Anwendungen: zu viele Tools, zu weite Berechtigungen, zu viel Autonomie in einem einzigen System. Simon Willison hat mit seiner „lethal trifecta“ die giftigste Kombination benannt – Zugriff auf private Daten, Kontakt mit nicht vertrauenswürdigen Inhalten und die Fähigkeit, nach außen zu kommunizieren, in einem Agenten vereint. Der Zuschnitt nach Fachdomänen ist deshalb auch eine Sicherheitsentscheidung – eine durchsetzbare Grenze wird er allerdings erst mit getrennten Identitäten, Rechten, Zuständen und Schnittstellen: wenige Tools, eng gefasste Berechtigungen, klarer Wirkungskreis. Der Gutschriften-Agent kann keine Deployments anstoßen, und der Deployment-Agent kennt keine Kundendaten.\n\nUnd schließlich das Wissen. Kuratierte Erkenntnisse, [geerdete Antworten](https://www.mikebild.dev/de/blog/sauberes-grounding-antworten-erden/), [Wissen, das die Session überlebt](https://www.mikebild.dev/de/blog/wissen-das-die-session-ueberlebt/) – all das gehört immer zu einer bestimmten Domäne. Ein Agent, der eine Fachdomäne verantwortet, trägt ihre Quellen, ihre Konventionen, ihre Sonderfälle. Nicht als domänenübergreifendes Sammelsurium, sondern als gepflegter, überschaubarer Bestand mit Besitzern.\n\nAn dieser Stelle schließt sich auch der Bogen zur [Varianz aus dem Team-Teil dieser Serie](https://www.mikebild.dev/de/blog/mein-erfolg-laesst-sich-nicht-kopieren/). Damals war der Befund: Zwischen Personen, Aufgaben und Sessions streut das Ergebnis, und Dateien mit Regeln ändern daran wenig. Der Domänen-Agent löst dieses Problem nicht, indem er Menschen gleich macht. Er verschiebt die Grenze, unterhalb derer Varianz Schaden anrichten kann. Oberhalb bleibt alles verschieden: Wie jemand formuliert, erkundet, delegiert, welchen Weg eine Session nimmt. Unterhalb ist es gleich: Was am Ende wirkt, geht durch dieselbe Autorisierung, dieselbe Freigabe, denselben Nachweis – bei der erfahrenen Kollegin genauso wie beim Praktikanten, am Freitagnachmittag genauso wie am Dienstagmorgen.\n\n## Was der eigene Agent können muss\n\nDamit lässt sich die Frage aus der letzten Folge kompakt beantworten. Ein Agent, der eine Fachdomäne verbindlich vertreten soll, braucht:\n\n- Tools in der Fachsprache der Domäne – typisiert, validiert, autorisiert\n- die Trennung von Modellvorschlag und Wirkung, mit Prüfung des ganzen Plans statt einzelner Aufrufe\n- Regeln über Vorgänge: Summen, Häufigkeiten, Zusammenhänge über Aufrufe und Sessions hinweg\n- Freigaben im Pfad, außerhalb des Gesprächs, durch Rollen der Fachdomäne\n- Nachweis jeder Ausführung und jeder Ablehnung – mit Planrevision, Regelrevision, Freigabeentscheidung, Aufrufer, Ergebnis und Fehlerstatus\n- die Rechte des jeweiligen Aufrufers statt eigener Allmacht – eng geschnitten, domänenbezogen\n- kuratierte Wissensquellen der Domäne, mit Besitzern und Pflege\n\nAuf dieser Liste steht nichts, was ein erfahrenes Team nicht längst gebaut hätte: Validierung, Autorisierung, Workflow, Audit, Berechtigungsmodell. Neu ist allein, wofür – nicht für eine Oberfläche, in der Menschen klicken, sondern für eine Schleife, in der ein Modell handelt. Wer so einen Agenten baut, legt gewöhnliche, solide Software um variable Modellvorschläge herum. Genau deshalb ist die Aufgabe zu schaffen.\n\nZu schaffen heißt nicht nebenbei. Was hier entsteht, ist ein betriebenes Softwaresystem mit Lebenszyklus, kein Wochenendprojekt – die Gegenrechnung aus der letzten Folge gilt unverändert, vom Pflegeaufwand bis zur Gefahr, aus lauter Vorsicht ein Formular mit Chat-Oberfläche zu bauen. Und es gehört niemandem allein: Die Regeln kommen aus dem Fachbereich, die Durchsetzung aus der Entwicklung, und keiner von beiden kann den Teil des anderen übernehmen. Unabhängig vom Implementierungsaufwand muss das Team klären, wer solche Regeln künftig vorschlagen, prüfen und freigeben darf – das ist Organisationsarbeit.\n\n## Zwischenstand\n\nDer Weg dieser Serie lässt sich jetzt in drei Stationen erzählen. Regeln als Prosa: gelesen, gewichtet, gelegentlich überstimmt – Empfehlungen, wie ich sie ein halbes Jahr lang vergeblich verschärft habe. Regeln im Tool: geprüft bei jedem Aufruf, verlässlich im Einzelnen, blind für den Zusammenhang. Und Regeln im Pfad: ein eigener Agent, der die Fachdomäne kennt, Pläne prüft, bevor sie wirken, Freigaben einholt, die kein Modell wegformulieren kann, und Nachweise erzeugt, die Fragen von übermorgen beantworten. Erst auf dieser Stufe ist aus der Empfehlung eine Regel geworden, die auch dann hält, wenn niemand hinschaut.\n\nWas diese Folge bewusst offenlässt: den Weg dorthin. Die Regeln einer Fachdomäne liefert kein installiertes Produkt automatisch mit – sie entstehen in der Auseinandersetzung mit der Domäne selbst, und die wirft sofort praktische Fragen auf. Wie findet ein Team heraus, welche Regeln in den Pfad gehören und welche Prosa bleiben dürfen? Wie schneidet man die erste Domäne, ohne sich zu verheben? Welche Konzepte, Methoden und Prozesse tragen dabei – und welche Moden kann man getrost auslassen? Von diesen Hilfsmitteln handelt die nächste Folge.\n\n## Was SubKit dazu beiträgt\n\n[SubKit](https://subkit.mikebild.dev/de/) ist mein Werkzeug für wiederkehrende Abläufe: Ein Assistent entwirft den Workflow, eine Person prüft ihn und gibt seine Reichweite frei. Die Ausführung folgt den festgelegten Schritten; Rechte und Ergebnisse werden nachvollziehbar. KI-Clients können freigegebene Workflows über MCP als Werkzeuge nutzen.\n\nDas ersetzt nicht die Modellierung der Fachdomäne. Eine fallbezogene Kulanzgrenze, gemeinsam genutzter Vorgangszustand und der Umgang mit parallelen Anfragen müssen im jeweiligen Ablauf und den angebundenen Systemen ausdrücklich umgesetzt werden. SubKit liefert dafür nicht automatisch die Geschäftsregeln. Die [Anwendungsfälle](https://subkit.mikebild.dev/de/anwendungsfaelle/) zeigen mögliche Einstiege; die Rolle der Schnittstelle erläutert der Artikel [MCP: Wenn Software Fähigkeiten anbietet](https://www.mikebild.dev/de/blog/mcp-softwarefaehigkeiten-agenten/).\n\n## Weiterführende Quellen\n\n- [Terraform: plan und apply](https://developer.hashicorp.com/terraform/cli/commands/plan) – die Trennung von Vorschlag und Wirkung im Infrastruktur-Alltag\n- [OWASP Top 10 für LLM-Anwendungen: Excessive Agency](https://genai.owasp.org/llmrisk/llm062025-excessive-agency/) – zu viele Tools, zu weite Rechte, zu viel Autonomie\n- [Simon Willison: The lethal trifecta](https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/) – warum die Kombination aus Datenzugriff, Fremdinhalten und Außenkommunikation gefährlich ist\n- [Domain-Driven Design Reference (Eric Evans)](https://www.domainlanguage.com/ddd/reference/) – Fachsprache und Domänenschnitt als Entwurfsarbeit"},{"locale":"de","translation_key":"mcp-softwarefaehigkeiten-agenten","slug":"mcp-softwarefaehigkeiten-agenten","title":"MCP-Sicherheit: Tools, Rechte und Freigaben für KI-Agenten","summary":"Wie du MCP-Tools sicher in Anwendungen einbindest: serverseitige Rechteprüfung, menschliche Freigaben, Schutz vor Prompt Injection und nachvollziehbare Aufrufe.","tags":["Software","KI","Architektur"],"published_at":"2026-07-13T10:00:00+00:00","updated_at":"2026-11-09T06:23:14.832389+00:00","url":"https://www.mikebild.dev/de/blog/mcp-softwarefaehigkeiten-agenten/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/c4ef3d567945612c3bc3cbaff94a961e16e47f096c6e921630ccea1ed0062962.mp3","audio_duration_secs":874,"text":"# MCP-Sicherheit: Tools, Rechte und Freigaben für KI-Agenten\n\nEin MCP-Tool kann Daten lesen, eine Revision veröffentlichen oder einen externen Dienst aufrufen. Damit wird aus einer Modellantwort eine Handlung mit Folgen. Für Entwickler und Betreiber lautet die Sicherheitsfrage deshalb: Wer darf welche Operation ausführen, an welchen Daten und nach welcher Freigabe?\n\nDas Model Context Protocol standardisiert die Verbindung zu solchen Fähigkeiten. Die Regeln deiner Anwendung musst du weiterhin selbst durchsetzen. Dieser Artikel zeigt das an einem konstruierten Publishing-Beispiel: dieselben Rechte über Weboberfläche, HTTP und MCP, eine überprüfbare Freigabe vor der Veröffentlichung und ein nachvollziehbarer Umgang mit Wiederholungen und fremden Inhalten.\n\nZur Einordnung der Schnittstellen findest du hier die [Unterschiede zwischen MCP, HTTP, Webhooks und A2A](/de/blog/mcp-http-webhooks-a2a-einfach-erklaert/).\n\n## Nicht die App, sondern die Fähigkeit\n\nDas Model Context Protocol ist ein offener Standard, mit dem KI-Anwendungen externe Systeme anbinden können. Die offizielle Dokumentation beschreibt MCP als Verbindung zwischen KI-Anwendungen und Datenquellen, Tools und Workflows. Die Spezifikation spricht von Hosts, Clients und Servern: Eine LLM-Anwendung ist der Host, darin sitzt ein Client, und ein Server stellt Kontext oder Fähigkeiten bereit.\n\nDas klingt zunächst nach Integrationsinfrastruktur. Tatsächlich steckt darin eine größere Verschiebung. Eine Anwendung ist dann nicht mehr allein eine Oberfläche für Menschen. Sie ist zugleich eine Menge adressierbarer Fähigkeiten für Agenten.\n\nDer klassische Bedienpfad sieht so aus:\n\n```mermaid\nflowchart LR\n  Human[Mensch] --> UI[Benutzeroberfläche]\n  UI --> App[Anwendung]\n  App --> Result[Ergebnis]\n```\n\nDer Mensch öffnet eine Oberfläche, sucht die richtige Stelle, füllt Felder aus, klickt auf Vorschau, klickt auf Veröffentlichen, prüft danach Feed und Suche. Die Anwendung ist das sichtbare Bündel aus Bedienung, Fachlogik und Zustand.\n\nMit einem Agenten kommt ein zweiter Pfad hinzu:\n\n```mermaid\nflowchart LR\n  Human[Mensch] --> Agent[Agent]\n  Agent --> Validate[validate_markdown]\n  Agent --> Preview[create_preview]\n  Agent --> Publish[publish_revision]\n  Agent --> Rollback[rollback_release]\n  Agent --> Search[rebuild_search_index]\n```\n\nDie Oberfläche verschwindet dadurch nicht, und sie wird auch nicht zweitrangig. Aber sie ist nicht mehr der einzige Zugang zur Arbeit. Ein Agent muss nicht wissen, wo der Button sitzt. Er muss wissen, welche Fähigkeit existiert, welche Eingaben sie erwartet, welche Ergebnisse zurückkommen und welche Regeln gelten.\n\nDas ist der Kern: MCP macht Softwarefähigkeiten für Agenten adressierbar. Was es nicht tut: die Produktdomäne ersetzen oder ihre menschliche Bedienoberfläche verdrängen.\n\n## Ein Publishing-System als Beispiel\n\nDas folgende Publishing-System ist ein konstruiertes Architekturbeispiel, keine fertige Integration und kein Kundenfall. Der Ablauf ist vertraut: Markdown kommt hinein, eine Vorschau wird gebaut, jemand prüft sie, danach wird eine Revision veröffentlicht. Im Fehlerfall braucht es Rollback. Nach dem Release müssen Index, Feed und Cache stimmen.\n\nIn einer klassischen Oberfläche sind diese Schritte an Seiten und Buttons gebunden. Für Menschen ist das sinnvoll: Eine gute GUI zeigt Kontext, kann ungültige Eingaben blockieren und macht Zustände wie Freigabestände sichtbar. Für einen Agenten ist dieselbe Oberfläche dagegen Umweg und Fehlerquelle. Er müsste klicken, warten, aus HTML lesen, interpretieren, wieder klicken. Das ist Automatisierung auf der falschen Ebene.\n\nAls MCP-Fähigkeit sähe derselbe Arbeitsschritt anders aus:\n\n```ts\nconst publishRevision = defineTool({\n  name: \"publish_revision\",\n  description: \"Publish an approved content revision\",\n  inputSchema: {\n    type: \"object\",\n    properties: {\n      site: { type: \"string\" },\n      revisionId: { type: \"string\" },\n      reason: { type: \"string\" }\n    },\n    required: [\"site\", \"revisionId\", \"reason\"]\n  }\n});\n```\n\nDer wichtige Teil ist nicht die konkrete Syntax. Der wichtige Teil ist die Verschiebung: Aus einem Bedienpfad wird eine benannte Fähigkeit. `publish_revision` ist nicht „klicke auf den grünen Button“. Es ist eine fachliche Operation mit Eingaben, Ergebnis, Rechten und Fehlern.\n\nSobald die Operation so vorliegt, kann ein Agent damit arbeiten. Er kann vorher `validate_markdown` aufrufen, bei Warnungen zurückfragen, eine Vorschau anfordern, den Freigabestand prüfen und erst danach veröffentlichen. Der Agent bedient dabei keinen Bildschirm. Der hier beschriebene MCP-Server stellt ihm fachliche Werkzeuge mit Eingabeschema und Berechtigungsprüfung bereit.\n\n## Drei Zugänge, eine Domäne\n\nEin solches Publishing-System kann unter `/mcp` eine domänenorientierte Werkzeugoberfläche bereitstellen, die über dieselbe Veröffentlichungsdomäne läuft wie REST und die Weboberfläche. Die MCP-Werkzeuge bleiben dabei an die Produkt-Scopes gebunden.\n\nEntscheidend ist, was diese Konstruktion nicht ist: MCP ist kein zweites System neben dem Produkt. Weboberfläche, HTTP und MCP greifen auf dieselbe Veröffentlichungsdomäne mit ihren Revisionen und Berechtigungsgrenzen zu. Die gemeinsame Domänenlogik entscheidet, was gilt – nicht der Kanal, über den die Anfrage kam.\n\nDas hat eine praktische Folge für die Werkzeugliste selbst. Werkzeuge, die der aktuelle Principal nicht verwenden darf, müssen gar nicht erst in der Liste erscheinen. Der Agent entdeckt also nur Fähigkeiten, die seine Scopes hergeben. Und wo eine menschliche Freigabe vorgesehen ist, liefert der Agent diese Freigabe nicht selbst – sie bleibt ein eigener Schritt außerhalb seiner Reichweite.\n\nDiese Filterung ist mehr als Komfort, aber sie ist Sichtbarkeit, nicht der eigentliche Schutz. Ein Agent, der ein Werkzeug nicht in der Liste sieht, entdeckt es nicht auf regulärem Weg. Der Schutz vor unberechtigten Aufrufen entsteht durch die serverseitige Autorisierung; die Werkzeuge bleiben an die Scopes des jeweiligen Produkts gebunden. Ein fehlendes Release-Recht lässt sich deshalb auch nicht dadurch beschaffen, dass man von der Weboberfläche zu MCP wechselt. Der Zugang wechselt, die Berechtigung nicht.\n\n## Tool-Zugriff ist eine Berechtigung\n\nEin Agent, der Text schreibt, kann Unsinn produzieren. Ein Agent, der Tools aufruft, kann Wirkung erzeugen. Er kann Daten lesen, Dateien ändern, Releases auslösen oder externe Systeme benachrichtigen. Deshalb ist Tool-Zugriff kein Komfortfeature, sondern eine Berechtigung. Dass ein Werkzeug auffindbar ist, ist noch keine Erlaubnis zur Wirkung; der Aufruf bleibt eine autorisierte Operation, die das System prüft. In einem Remote-MCP-Zugang sind diese Aufgaben verteilt: Die Zustimmung des Nutzers vor einem Tool-Aufruf ist nach der MCP-Spezifikation Sache des Hosts, während das Produkt jeden Aufruf serverseitig gegen die Scopes des Principals prüft.\n\nDie MCP-Spezifikation sagt selbst, dass solche Fähigkeiten Sicherheits- und Vertrauensfragen mitbringen: Nutzer müssen Datenzugriff und Operationen verstehen und kontrollieren können, Tools sind mit Vorsicht zu behandeln, Hosts müssen Zustimmung vor Tool-Aufrufen einholen. Zustimmung und Zugriffskontrolle gehören deshalb in den Ausführungspfad jedes Tool-Aufrufs.\n\nIn einem produktiven System reicht deshalb eine Tool-Definition nicht aus. Daneben gehört eine Policy:\n\n```ts\ntype ToolPolicy = {\n  tool: string;\n  allowedRoles: string[];\n  requiresApproval: boolean;\n  requiresIdempotencyKey: boolean;\n  maxRuntimeMs: number;\n};\n\ntype ToolAuditEntry = {\n  tool: string;\n  inputHash: string;\n  idempotencyKey?: string;\n  decision: \"allowed\" | \"blocked\" | \"approved\";\n  outcome: \"succeeded\" | \"failed\" | \"unknown\";\n  actorId: string;\n  runId: string;\n};\n```\n\nDamit wird aus „der Agent darf veröffentlichen“ eine überprüfbare Regel. Wer durfte welchen Aufruf machen? Welche Eingabe wurde verwendet? War eine Freigabe nötig? Wurde der Aufruf ausgeführt oder blockiert? Bei schreibenden Operationen kommt eine weitere Frage hinzu: Was passiert, wenn der Agent nach einem Timeout denselben Aufruf wiederholt? Ein Idempotenzschlüssel hilft nur, wenn der Server ihn an die Operation und ihre Eingaben bindet, konkurrierende Wiederholungen abfängt und das Ergebnis zuverlässig speichert. Bei externen Nebenwirkungen muss auch der nachgelagerte Dienst Wiederholungen erkennen oder das System den unklaren Ausgang abgleichen. Ein Schlüssel allein garantiert keine einmalige Ausführung.\n\nMCP standardisiert Auffindbarkeit und Aufruf eines Tools. Es macht die Operation weder fachlich sicher noch automatisch idempotent oder auditierbar. Diese Eigenschaften muss die angebotene Fähigkeit selbst tragen.\n\n## Prompt Injection: Inhalte dürfen keine Rechte vergeben\n\nEin eingelesener Artikel kann Anweisungen enthalten, etwa eine andere Revision zu veröffentlichen oder Daten an eine fremde Adresse zu schicken. Behandle solche Inhalte als nicht vertrauenswürdige Daten. Ein Prompt, der das Modell zum Ignorieren auffordert, ist keine ausreichende Zugriffskontrolle. Die erlaubten Operationen, Zieladressen und Freigaben müssen außerhalb des gelesenen Dokuments geprüft werden.\n\nAuch Tool-Beschreibungen und Kennzeichnungen wie „nur lesend“ sind kein Beweis für das tatsächliche Verhalten eines fremden Servers. Prüfe, welchen Server du verbindest und welche Rechte du ihm gibst. Die [Sicherheitsgrundsätze der MCP-Spezifikation](https://modelcontextprotocol.io/specification/2025-06-18#security-and-trust--safety) benennen diese Vertrauensgrenze ausdrücklich.\n\nFür einen Remote-MCP-Server kommt die Absicherung der Anmeldung hinzu: Prüfe, ob ein Zugriffstoken für deinen Server bestimmt ist; reiche empfangene Tokens nicht ungeprüft an nachgelagerte Dienste weiter. Fordere nur die benötigten Rechte an. Diese Maßnahmen und die Risiken von Token-Weitergabe beschreibt die offizielle Dokumentation zu [MCP Security Best Practices](https://modelcontextprotocol.io/docs/2025-11-25/tutorials/security/security_best_practices).\n\nFür das Publishing-Beispiel würde ich vor dem Betrieb mindestens folgende Fälle prüfen:\n\n- Ein Nutzer ohne Veröffentlichungsrecht ruft das Tool direkt auf: Der Server lehnt ab, auch wenn der Tool-Name bekannt ist.\n- Eine Freigabe gilt für Revision A, der Aufruf nennt Revision B: Der Server lehnt ab.\n- Ein Dokument verlangt den Versand an eine fremde Adresse: Die konfigurierte Grenze bleibt wirksam.\n- Ein Aufruf läuft in einen Timeout: Vor einem erneuten Schreibversuch wird sein Ergebnis geklärt oder die Wiederholung wirksam dedupliziert.\n- Eine fehlgeschlagene oder abgelehnte Operation erscheint im Verlauf mit ihrem tatsächlichen Ergebnis.\n\nDas ist eine Prüfliste für dieses Architekturbeispiel, kein vollständiger Sicherheitsnachweis.\n\n## Der falsche und der richtige Schnitt\n\nIch glaube nicht, dass Anwendungen in kleine MCP-Dienste zerfallen und danach keine Produkte mehr sind. Eine gute Anwendung bündelt mehr als Funktionen: Sie bündelt Verständnis, Bedienung, Datenmodell, Rechte, Feedback und Verantwortung. Aber an den Rändern werden Fähigkeiten einzeln adressierbar, die bisher an Bedienpfade gebunden waren.\n\nEine Fähigkeit ist gut geschnitten, wenn sie fachlich verständlich, technisch prüfbar und betrieblich verantwortbar ist. Der falsche Schnitt wäre ein generisches `run_sql` oder `click_button` – ein Werkzeug, das die Fachregeln umgeht, statt sie zu tragen. Der bessere Schnitt ist eine Operation mit Fachabsicht: `publish_revision`, `rollback_release`, `create_preview`. Der Agent soll nicht an der Datenbank vorbeiarbeiten. Er soll innerhalb derselben Regeln arbeiten, die auch für Weboberfläche und HTTP gelten.\n\nEin Standard nimmt dabei Integrationsarbeit weg, aber keine Produktverantwortung. Anthropic hat MCP Ende 2024 gegen genau das Problem eingeführt, dass jede neue Datenquelle eine eigene Anbindung brauchte. Die Spezifikation standardisiert den Austausch über JSON-RPC und beschreibt Resources, Prompts und Tools. Schlechte Fähigkeiten bleiben schlecht, auch wenn sie standardisiert angeboten werden.\n\n## Was mit Bedienoberflächen passiert\n\nDie stärkste Version der Zukunftsthese lautet: Wenn Agenten Software bedienen, werden GUIs zweitrangig. Ich halte das für falsch.\n\nRoutinepfade werden sich verschieben. Wenn ich einem Agenten sagen kann, er soll einen Entwurf prüfen, eine Vorschau bauen und mir nur die Abweichungen zeigen, dann will ich dafür nicht durch fünf Masken klicken. Das gilt besonders für wiederkehrende Arbeit, die gut beschrieben und sauber begrenzt ist.\n\nAber Menschen brauchen Oberflächen für Exploration, Kontrolle, Ausnahmefälle und Vertrauen. Eine Vorschau ist eine GUI. Ein Diff ist eine GUI. Ein Audit-Log ist eine GUI. Ein Freigabedialog ist eine GUI. Gerade wenn Agenten mehr ausführen, werden gute Kontrolloberflächen wichtiger. Die Kontrolloberfläche dient dazu, dass ein Mensch versteht, was ein Agent getan hat, und dort eingreift, wo sein Urteil gefragt ist.\n\nKontrolloberfläche und MCP konkurrieren also nicht um dieselbe Aufgabe. Die Kontrolloberfläche richtet sich an menschliche Bedienung und Kontrolle, MCP an agentische Aufrufe. Für beide gelten die Berechtigungsgrenzen derselben Domäne.\n\n## Was ich daraus mitnehme\n\nMCP ist für mich weniger eine spektakuläre Technik als ein guter Anlass, Software anders zu beschreiben. Nicht allein über die Daten, die ein System hält, und nicht allein über die Oberfläche, die es anbietet – sondern über die Arbeit, die es sicher, nachvollziehbar und prüfbar erledigen kann.\n\nDas ist eine Architekturfrage. Wer Fähigkeiten nur als dünne Hülle um interne Funktionen veröffentlicht, baut wahrscheinlich neue Risiken. Ein fachlicher Schnitt, Rechte, Idempotenz und Auditierbarkeit schaffen eine kontrollierbare Grundlage für Agenten – eine Qualitätsgarantie sind sie nicht.\n\nNicht jede Anwendung braucht sofort einen MCP-Server. Viele Systeme sind mit einer guten API, einem CLI oder einer klaren Oberfläche besser bedient. Wo es passt, gilt aber: Software, die von Agenten genutzt werden soll, muss ihre Fähigkeiten explizit machen – und sie muss dieselben Berechtigungsgrenzen über jeden Zugang durchsetzen.\n\n## Wo SubKit dazu passt\n\nBei [SubKit](https://subkit.mikebild.dev/de/) hilft die KI beim Entwerfen eines Workflows. Eine Person prüft die Vorschau und gibt seine Reichweite frei. Danach läuft der festgelegte Workflow; die KI entscheidet beim Ausführen nicht über den weiteren Weg. Jeder Lauf wird auf Rechte geprüft und aufgezeichnet.\n\nMCP wird in beide Richtungen genutzt: Ein Workflow kann als Tool für einen KI-Client dienen; ein externer MCP-Server kann als Konnektor angebunden werden. Welche externen Tools verwendet werden dürfen, wird dabei gesondert festgelegt. Der zusätzliche Zugang ersetzt weder die Freigabe noch die Rechte der aufrufenden Person.\n\nDas ist ein konkreter Produktbezug, keine Behauptung, dass SubKit jeden MCP-Server sicher macht oder fachliche Regeln automatisch kennt. Die Regeln deiner Domäne und die Rechte externer Systeme bleiben zu prüfen. Wie solche Regeln von Modellentscheidungen getrennt werden können, vertieft der Artikel [KI-Agenten pro Fachdomäne: Regeln, Freigaben und Nachweise](/de/blog/eigener-agent-pro-fachdomaene/).\n\n:::note\n**Einordnung und Quellenstand**\n\nDas Publishing-System und die Codeausschnitte sind konstruiert und illustrieren Architekturentscheidungen. Der Beitrag verwendet die MCP-Spezifikation vom 18. Juni 2025 und die verlinkten Security Best Practices. Die Sicherheitsabschnitte wurden am 9. November 2026 gegen diese Primärquellen geprüft; daraus folgt keine Aussage über die Sicherheit einer konkreten Installation. Der SubKit-Abschnitt beruht auf der bestätigten Produktbeschreibung vom 8. November 2026.\n:::\n\n## Weiterführende Quellen\n\n- [Model Context Protocol: Spezifikation 2025-06-18](https://modelcontextprotocol.io/specification/2025-06-18)\n- [Model Context Protocol: Security Best Practices](https://modelcontextprotocol.io/docs/2025-11-25/tutorials/security/security_best_practices)\n- [Model Context Protocol: Einführung](https://modelcontextprotocol.io/docs/getting-started/intro)\n- [SubKit: Workflows, Freigaben und Betrieb](https://subkit.mikebild.dev/de/)"},{"locale":"de","translation_key":"agent-modell-fachdomaene","slug":"agent-modell-fachdomaene","title":"Agent, Modell, Fachdomäne","summary":"Das Modell ist gemietet, der Agent kann unter eigener Kontrolle stehen – entscheidend ist, ob die Fachdomäne als Prosa im Prompt liegt oder als geprüfte Schnittstelle im Agenten.","tags":["Software","KI","Methodik","Delivery"],"published_at":"2026-07-13T10:00:00+00:00","updated_at":"2026-08-17T17:34:45.985779+00:00","url":"https://www.mikebild.dev/de/blog/agent-modell-fachdomaene/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/3e0e35359b093a19a35f870d05b2c12e1da9b740e9f004e68375982acb764d0a/agent-modell-fachdomaene-vorlesen.mp3","audio_duration_secs":861,"text":"Vor einiger Zeit saß ich in einem großen Konzern in einer Runde, die eine „Agenten-Strategie“ für das kommende Jahr beschließen sollte. An der Wand eine Folie mit drei Spalten: drei Anbieter, darunter Häkchen für Funktionen, Preise pro Nutzer, Compliance-Siegel. Eine Stunde lang drehte sich das Gespräch um die Frage, welcher Agent der beste sei. Irgendwann habe ich eine andere Frage gestellt: Was von alledem gehört uns hinterher eigentlich? Wenn wir in drei Jahren den Anbieter wechseln – was nehmen wir mit? Es wurde still. Nicht, weil die Frage besonders originell gewesen wäre, sondern weil die Folie auf sie keine Antwort hatte.\n\n*Teil 10 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nDie [letzte Folge](https://www.mikebild.dev/de/blog/wissen-das-die-session-ueberlebt/) endete mit der Frage, wem ich kuratiertes Wissen in die Hand gebe – und wo der generische Agent an seine Grenzen kommt. Um sie zu beantworten, muss ich zuerst auseinandernehmen, was in dem Wort „Agent“ alles zusammengepackt wird. Denn die stille Minute im Konferenzraum hatte einen einfachen Grund: Die Runde hat über Agenten gesprochen wie über ein Gerät, das man kauft, aufstellt und benutzt. Dieses Bild führt in die Irre – und zwar genau an der Stelle, an der es fürs Unternehmen teuer wird.\n\n## Ein Agent ist Software\n\nWas ein Agent wirklich ist, lässt sich in einem Satz sagen. Simon Willison formulierte im Herbst 2025 eine dafür brauchbare Arbeitsdefinition: Ein Agent ist ein Modell, das in einer Schleife Tools aufruft, um ein Ziel zu erreichen. Mehr steckt nicht dahinter. Kein Bewusstsein, keine Absicht, keine Magie.\n\nDa ist eine Schleife: Das Modell bekommt eine Aufgabe und den bisherigen Verlauf, schlägt den nächsten Schritt vor, der Agent führt ihn aus, das Ergebnis fließt zurück – bis eine Stoppbedingung greift. Da sind Tools: Funktionen, die der Agent dem Modell anbietet und deren Aufrufe er ausführt. Da ist Kontext: alles, was der Agent dem Modell mitgibt, von Dateien über Suchergebnisse bis zu Instruktionen. Da ist Zustand: was zwischen den Schritten und über die Session hinaus erhalten bleibt. Und da sind Rechte: was der Agent überhaupt ausführen darf, mit wessen Berechtigungen, mit welchen Nachweisen.\n\nJedes einzelne dieser fünf Dinge ist gewöhnliche Software. In Folge 3 habe ich beschrieben, dass genau dieser Rahmen – der Harness – den Unterschied zwischen einem beeindruckenden und einem brauchbaren Werkzeug ausmacht. Damals meinte ich das persönlich: mein Rechner, meine Werkzeuge, meine Arbeitsweise. Heute lese ich denselben Satz organisatorisch. Was für meine Kommandozeile gilt, gilt für das Unternehmen erst recht: Das Modell erzeugt Ausgaben, etwa Vorschläge, Klassifikationen und Formulierungen. Der Agent bestimmt Schleife, Kontext, Zustand, Rechte und Tool-Anbindung. Diese Teile lassen sich gestalten.\n\n## Was man mietet und was man kontrollieren kann\n\nDiese Arbeitsteilung lohnt einen genauen Blick, weil sie ökonomisch zwei völlig verschiedene Dinge beschreibt.\n\nEin proprietäres Modell, das man über die API eines Anbieters bezieht, mietet man: Es gehört dem Anbieter, und über Versionswechsel bestimmt man nur in dem Rahmen mit, den API-Vertrag und Anbieter vorgeben. Man besitzt daran nichts – und das ist verkraftbar, wenn mehrere Modelle die eigenen, konkret geprüften Aufgaben hinreichend gut lösen. Wer seine Strategie auf „das beste Modell“ baut, baut auf etwas, das er weder besitzt noch kontrolliert. Den ausführlichen Gedanken dazu habe ich [früh in dieser Serie](https://www.mikebild.dev/de/blog/gut-genug-modelle/) beschrieben.\n\nDer Agenten-Layer kann dagegen unter eigener Kontrolle stehen. Die Schleife, der Kontextaufbau, der Zustand, die Rechte, vor allem die Tools – all das kann eigener Code und eigene Konfiguration sein, versionierbar, testbar und überprüfbar. Auch die Anbindung wird weniger proprietär: MCP liegt seit Dezember 2025 zusammen mit AGENTS.md und goose bei der Agentic AI Foundation unter dem Dach der Linux Foundation. Eine Garantie, dass jeder Anbieter dieselben Fähigkeiten auf dieselbe Weise bereitstellt, ist das nicht.\n\n```mermaid\nflowchart TB\n    subgraph rented[\"gemietet – austauschbar\"]\n        M[\"Modell<br/>Vorschläge · Klassifikation · Sprache\"]\n    end\n    subgraph owned[\"gestaltbar – unter eigener Kontrolle\"]\n        A[\"Agent<br/>Schleife · Kontext · Zustand · Rechte\"]\n        W[\"Tools und Schnittstellen<br/>typisierte Operationen\"]\n        F[\"Fachdomäne<br/>Begriffe · Regeln · Abläufe\"]\n        A --> W\n        W --> F\n    end\n    A -- \"fragt an\" --> M\n    M -- \"schlägt Schritte vor\" --> A\n```\n\nWenn das Modell gemietet und die Anbindung zunehmend standardisiert ist, bleibt ein besonders wichtiger eigener Anteil: das, was ein Unternehmen in den Agenten hineinlegt. Seine Begriffe, seine Regeln, seine Abläufe, seine Daten – kurz: seine Fachdomäne. Damit steht die Frage dieses Beitrags im Raum. Wo liegt die Fachdomäne?\n\n## Variante A: die Fachdomäne als Prosa\n\nDer naheliegende Ort ist der Prompt. In der Praxis heißt das: Instruktionsdateien wie CLAUDE.md oder AGENTS.md, Systemprompts, angehängte Richtlinien-Dokumente. Dort steht dann so etwas wie: „Gutschriften über 500 Euro darf nur eine Teamleitung auslösen. Kunden im laufenden Mahnverfahren erhalten keine Kulanzgutschrift. Preisänderungen gelten erst ab dem Folgemonat.“\n\nIch will diese Variante nicht kleinreden. Sie ist schnell: Wenn es einen freigegebenen Pflegeweg gibt, kann die Fachabteilung den Text ändern, ohne die Fachanwendung anzufassen. Die geänderte Fassung steht dem Modell zur Verfügung, sobald der Agent sie lädt. Für exploratives Arbeiten reicht das oft – und am Anfang ist es fast immer der richtige Weg, weil man erst einmal herausfinden muss, welche Regeln überhaupt gebraucht werden.\n\nAber sie ist fragil, und zwar strukturell, nicht bloß handwerklich. Erstens ist Prosa ungeprüft: Niemand validiert sie, kein Compiler meldet, dass Satz 12 und Satz 47 sich widersprechen, keine Typprüfung merkt, dass „500 Euro“ an einer Stelle brutto und an der anderen netto gemeint war. Zweitens ist Prosa für das Modell eine Empfehlung, kein verlässlicher Enforcement-Mechanismus – das war die zentrale Ernüchterung meiner vergeblichen Versuche mit Instruktionsdateien: Das Modell kann Anweisungen befolgen, ihre Einhaltung lässt sich damit aber nicht erzwingen. Drittens greift die Session-Lotterie: Derselbe Satz wird heute beachtet und morgen überlesen, je nachdem, was sonst noch im Kontext liegt. Und viertens – im Unternehmen wiegt das am schwersten – lässt sich zwar die Datei versionieren, aber nicht das Verhalten. Die Instruktionsdatei allein stellt keine deterministische, blockierende Prüfung bereit, die eine regelwidrige Gutschrift verhindert; ohne zusätzliche Prüfung fällt der Verstoß erst hinterher auf.\n\nProsa skaliert mit der Menge des Wissens. Sie skaliert nicht mit dessen Verbindlichkeit.\n\n## Variante B: die Fachdomäne als Schnittstelle\n\nDie Alternative: das Fachwissen nicht neben den Agenten legen, sondern in seine Tools einbauen. Statt dem Modell generischen Datenbank- und Dateizugriff zu geben und die Regeln als Text daneben zu stellen, bekommt der Agent typisierte Operationen, deren Namen aus der Fachsprache kommen und deren Eingaben geprüft werden:\n\n```ts\nconst issueCreditNote = defineTool({\n  name: \"issue_credit_note\",\n  description: \"Issue a credit note for an existing invoice\",\n  input: z.object({\n    invoiceId: z.string(),\n    amount: z.number().positive(),\n    reason: z.enum([\"complaint\", \"goodwill\", \"pricing_error\"]),\n  }),\n  authorize: ({ user, input }) =>\n    input.amount <= 500 || user.hasRole(\"team_lead\"),\n  execute: (input, ctx) => billing.issueCreditNote(input, ctx.audit),\n});\n```\n\nDer Unterschied ist grundsätzlicher, als der kurze Codeblock aussieht. Die 500-Euro-Regel ist keine Bitte mehr, sondern Code: Sie wird bei jedem Aufruf geprüft, in jeder Session gleich, unabhängig von Tagesform und Kontextlage des Modells. Es gibt sie genau einmal, sie hat einen Besitzer, ein Review, einen Test. Die KI formuliert, die Schnittstelle entscheidet, was überhaupt möglich ist.\n\nDas ist die konsequente Fortsetzung von zwei Gedanken aus den letzten Folgen. In [Folge 8](https://www.mikebild.dev/de/blog/sauberes-grounding-antworten-erden/) ging es darum, Antworten zu erden: nachschlagen statt raten, echte Quellen statt plausibler Vermutungen. Ein Tool ist geerdetes Wissen in ausführbarer Form – der Agent muss die Gutschriften-Regeln nicht erraten, er kann nur innerhalb von ihnen handeln. Und in [Folge 9](https://www.mikebild.dev/de/blog/wissen-das-die-session-ueberlebt/) ging es um Wissen, das die Session überlebt: Eine Tool-Definition überlebt sie von selbst, weil sie Teil des Systems ist und nicht Teil des Gesprächs.\n\nDie Tool-Namen schließen dabei direkt an Domain-Driven Design an: Sie werden zur verbindlichen Fachsprache. Was Eric Evans vor gut zwanzig Jahren „ubiquitous language“ nannte – eine gemeinsame, präzise Sprache zwischen Fachbereich und Entwicklung – bekommt eine sehr handfeste Existenzform. Wenn `issue_credit_note` und `waive_dunning_fee` die einzigen Verben sind, die der Agent kennt, muss die Organisation sich einigen, was diese Verben genau bedeuten. Das Modellieren der Tools ist Domänenarbeit, keine Infrastrukturarbeit. Die Schnittstelle kann Eingaben und Berechtigungen einzelner Aufrufe verlässlich prüfen; Ablaufregeln über mehrere Aufrufe brauchen zusätzliche Zustandsprüfung und gegebenenfalls eine Prüfung des geplanten Ablaufs.\n\n## Die Gegenrechnung\n\nSo weit die Chance. Zur selben Rechnung gehören Lock-in, Pflegeaufwand, Verantwortung und Übersteuerung.\n\nDa ist zuerst der Lock-in. Tool-Definitionen, Skill-Formate, Agent-Konfigurationen folgen heute Anbieter-Konventionen. MCP normt den Transport, nicht die Semantik: Das Protokoll legt fest, wie ein Tool aufgerufen wird, nicht, wie meine Gutschriften-Logik strukturiert ist. Wer seine Fachlogik direkt in die Formate eines Agent-Frameworks gießt, hat sie in drei Jahren genau dort liegen – und der Umzug kostet. Das Gegenmittel ist ein altes: die Fachlogik in eigene Dienste legen und die Tool-Schicht als dünnen Adapter bauen. Aber das muss man tun, es passiert nicht von allein, und unter Termindruck passiert regelmäßig das Gegenteil.\n\nDann der Pflegeaufwand. Eine eigene Tool-Schicht verursacht dauerhaften Pflege- und Betriebsaufwand. Fachregeln ändern sich: Aus der 500-Euro-Schwelle werden 300, ein neuer Gutschriftsgrund kommt dazu, eine Rolle wird umgebaut. Jemand muss das pflegen, priorisieren, testen und ausrollen – neben allem anderen. Die Prosa-Variante war auch deshalb so verführerisch, weil sie diesen Aufwand versteckt hat. Die Tool-Variante macht ihn sichtbar, und Sichtbarkeit fühlt sich zunächst wie Verteuerung an, obwohl der Aufwand vorher nur woanders lag: in den Korrekturen hinterher.\n\nDrittens Prüfbarkeit und Verantwortung. Wer haftet für eine Tool-Definition? Die Frage klingt juristisch, ist aber vor allem organisatorisch. Bei rein beratender Nutzung kann ein Mensch die Antwort verwerfen. Darf der Agent Tools ohne Freigabe ausführen, kann ein Fehler in deren Autorisierung unmittelbar wirken: Eine falsche Obergrenze gilt dann verlässlich falsch, in jeder Session, für jeden Nutzer. Tool-Definitionen brauchen deshalb dieselbe Sorgfalt wie jede produktive Schnittstelle: Review, Tests, klare Zuständigkeit, Änderungshistorie. Und die Verantwortung verschiebt sich spürbar: weg vom Einzelnen, der einen Prompt formuliert hat, hin zum Team, das das Tool definiert hat. Das ist konsequent und richtig – aber eine Organisation muss das wollen, entscheiden und aushalten.\n\nUnd schließlich die Übersteuerung. Es ist verlockend, nach dem ersten Zwischenfall jede denkbare Abweichung wegzudefinieren, bis der Agent nur noch einen einzigen, engen Pfad kennt. Dann hat man ein Formular gebaut, mit einer Chat-Oberfläche davor – teurer, langsamer und launischer, als das Formular es gewesen wäre. Die Stärke des Modells liegt gerade im Unvorhergesehenen: im Sonderfall, in der Rückfrage, im Zusammenhang zwischen zwei Vorgängen, an den beim Entwurf niemand gedacht hat. Wer dem Agenten nur Tools für das Erwartbare gibt, hätte klassische Automatisierung billiger haben können. Zu enge Tools können Risiken begrenzen, aber auch so viel Handlungsspielraum nehmen, dass klassische Automatisierung die passendere Lösung wäre.\n\n## Wann generische Tools reichen – und wann nicht\n\nFür meine Entscheidung sind vier Kriterien maßgeblich: die Art der Arbeit, die Verantwortlichen, das Schadenspotenzial und der Reifegrad des Fachwissens. Generische Tools – Dateizugriff, Shell, Suche – reichen erstaunlich weit, solange ein paar Bedingungen zusammenkommen:\n\n- Die Arbeit ist explorativ: analysieren, prototypisieren, recherchieren, migrieren – Aufgaben, deren Ergebnis ohnehin ein Mensch begutachtet.\n- Es arbeitet eine Einzelperson, die das Ergebnis selbst verantwortet und selbst beurteilen kann.\n- Das Schadenspotenzial ist klein: alles reversibel, nichts verlässt das Haus, kein Geld bewegt sich.\n- Das Fachwissen ist noch im Fluss – es wäre schlicht zu früh, es in Schnittstellen zu gießen.\n\nUmgekehrt gehört die Fachdomäne in den Agenten, sobald sich das Bild dreht:\n\n- Ein Ablauf wiederholt sich im Team: dieselbe Operation, viele Personen, unterschiedliche Sorgfalt und Erfahrung.\n- Regeln sind verbindlich, nicht empfohlen – sie müssen auch am Freitagnachmittag um 17 Uhr gelten.\n- Es gibt Audit- oder Nachweispflichten: Wer hat wann was ausgelöst, mit welcher Begründung?\n- Das Schadenspotenzial ist hoch: Geld, personenbezogene Daten, Wirkung nach außen.\n\nDazwischen nutze ich einen pragmatischen Übergang: Die Prosa-Variante ist der Prototyp der Schnittstelle. Wenn dieselbe Regel zum dritten Mal in einer Instruktionsdatei auftaucht – und zum zweiten Mal ignoriert wurde –, ist sie für mich ein Kandidat für ein Tool. So wandert die Fachdomäne Stück für Stück von der Empfehlung in die Struktur, entlang ihrer tatsächlichen Verbindlichkeit statt entlang eines großen Vorabplans.\n\n## Zwischenstand\n\nFür mich verschiebt die bisherige Serie die Verantwortung von der Session zum System. Am Anfang stand die Session: die Erfahrung, dass die Modelle für meine Arbeit gut genug sind und der Unterschied in meinem eigenen Rahmen liegt – Tools, Kontext, Arbeitsweise. Dann kam das Team: die Ernüchterung, dass sich mein Arbeitserfolg nicht per Datei kopieren lässt und Instruktionsdateien Empfehlungen bleiben, so sorgfältig man sie auch schreibt. Dann das Wissen: sauberes Grounding statt überzeugendem Raten, kuratierte Erkenntnisse, die Sessions überleben. Und jetzt das System: die Einsicht, dass das Modell gemietet ist und gemietet bleibt – und dass der dauerhaft kontrollierbare Anteil im Agenten liegt. Genauer: in den Tools, mit denen der Agent die Fachdomäne berührt.\n\nOffen bleibt die Frage, wie verbindliche Regeln über einzelne Tool-Aufrufe hinweg durchgesetzt werden. Tools entscheiden, was in einem einzelnen Aufruf möglich ist – darüber hinaus braucht es Freigaben, bevor etwas wirkt; Nachvollziehbarkeit, nachdem es gewirkt hat; ein Nein, das ein Nein bleibt, auch wenn das Modell freundlich weiterformuliert. Warum das am Ende auf einen eigenen, an die Fachdomäne gebundenen Agenten hinausläuft – und was der können muss –, ist einen eigenen Beitrag wert.\n\n## Weiterführende Quellen\n\n- [Building Effective AI Agents](https://www.anthropic.com/engineering/building-effective-agents) – Anthropics Unterscheidung von Workflows und Agenten\n- [Writing effective tools for AI agents](https://www.anthropic.com/engineering/writing-tools-for-agents) – Tool-Design für Agenten aus der Praxis\n- [Designing agentic loops](https://simonwillison.net/2025/Sep/30/designing-agentic-loops/) – Simon Willison über Schleifen, Tools und Stoppbedingungen\n- [Model Context Protocol](https://modelcontextprotocol.io/) – Spezifikation und Dokumentation des Tool-Protokolls\n- [Gründung der Agentic AI Foundation](https://www.linuxfoundation.org/press/linux-foundation-announces-the-formation-of-the-agentic-ai-foundation) – MCP, AGENTS.md und goose unter dem Dach der Linux Foundation"},{"locale":"de","translation_key":"wissen-das-die-session-ueberlebt","slug":"wissen-das-die-session-ueberlebt","title":"Wissen, das die Session überlebt","summary":"Session-Wissen verdampft, wenn niemand es kuratiert – warum Teams ihr KI-Arbeitswissen wie Code behandeln sollten und dabei nicht das Modell schlauer wird, sondern die Organisation lernt.","tags":["Software","KI","Methodik","Delivery"],"published_at":"2026-06-23T10:00:00+00:00","updated_at":"2026-08-17T17:34:45.985779+00:00","url":"https://www.mikebild.dev/de/blog/wissen-das-die-session-ueberlebt/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/b306e810309aeef8c9cc026bd69992b31f33e4dfcd273dd99dfbecbda8a4a7e8.mp3","audio_duration_secs":943,"text":"Dienstagvormittag, dritte Session in dieser Woche. Ich tippe zum dritten Mal dieselbe Erklärung. Unser Fehlermodell unterscheidet zwischen erwartbaren und unerwarteten Fehlern; erwartbare Fehler kommen als Werte zurück, und um Serviceaufrufe sollen keine try/catch-Kaskaden entstehen. Die Session davor wusste das. Sie hatte es verstanden, angewendet und sogar einen Grenzfall sauber gelöst, auf den ich selbst nicht gekommen wäre. Jetzt sitze ich wieder in einer neuen Session ohne diese Erklärung und schreibe sie noch einmal, mit anderen Worten, etwas ungeduldiger als beim letzten Mal.\n\n*Teil 9 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nDas ist die Session-Amnesie als Alltagserfahrung. Nicht als theoretisches Problem von Kontextfenstern und Token-Budgets, sondern als das leise Ärgernis, dass ich mit einem Werkzeug arbeite, das jeden Morgen zum ersten Mal von mir hört. Die Anbieter arbeiten daran. Stand August 2026 gibt es dafür unterschiedliche Speichermechanismen: Anthropics Memory Tool erlaubt Agenten, Informationen außerhalb des unmittelbaren Kontextfensters dateibasiert abzulegen und später wieder zu laden; Claude Code stellt Projektanweisungen über hierarchische CLAUDE.md-Dateien und persönliche Notizen über Auto Memory bereit, beides über Sessions hinweg. Persönliches Auto Memory setzt dabei bei der einzelnen Person an; gemeinsam gepflegte CLAUDE.md-Dateien wären davon zu unterscheiden. Die Variante des Problems, die mich wirklich beschäftigt, löst keine dieser Funktionen von allein.\n\nDenn die Team-Variante ist schlimmer. Mittwoch erzählt mir ein Kollege, er habe „seiner“ Session unser Fehlermodell erklärt. Ich frage nach, wie. Er hat es anders erklärt als ich. Nicht falsch – anders. Andere Begriffe, andere Beispiele, eine Nuance, die ich weglassen würde, eine, die mir fehlt. Ein dritter Kollege hat es gar nicht erklärt, weil er nicht wusste, dass es da etwas zu erklären gibt; seine Session hat try/catch-Kaskaden gebaut, und der Pull Request sah entsprechend aus. Vier Leute, vier private Erklärungen derselben Konvention, vier leicht verschiedene Ergebnisse. Das ist exakt das Varianzproblem, das ich in [„Mein Erfolg lässt sich nicht kopieren“](https://www.mikebild.dev/de/blog/mein-erfolg-laesst-sich-nicht-kopieren/) beschrieben habe – nur dass es hier nicht um Arbeitsweisen geht, sondern um Wissen. Jeder von uns füttert seine Sessions mit einer eigenen, mündlichen Überlieferung dessen, was das Team eigentlich gemeinsam wissen sollte. Persönliches Auto Memory ändert daran nichts: Es merkt sich meine Version der Erklärung, nicht unsere. Versionierte, gemeinsam gepflegte CLAUDE.md-Dateien wären der Ort für eine geteilte Version – aber nur, wenn das Team sie bewusst kuratiert.\n\nDie Kernfrage dieser Folge ist also: Wie wird aus Session-Wissen Team-Wissen – und irgendwann Unternehmenswissen? Wie kommt das, was in einer guten Session entsteht, in die nächste Session eines anderen Menschen?\n\n## Zwei Sorten von Wissen\n\nUm darüber vernünftig zu reden, hilft mir eine Unterscheidung, die ich lange nur implizit mit mir herumgetragen habe: kuratiertes Wissen und emergentes Wissen.\n\nKuratiertes Wissen ist bewusst destilliert. Jemand hat sich hingesetzt, eine Erfahrung oder eine Entscheidung in Worte gefasst, jemand anderes hat es gegengelesen, und das Ergebnis steht an einem Ort, an dem es gefunden wird. Architektur-Entscheidungen in ADRs, Konventionen in einer CLAUDE.md oder AGENTS.md, ein Runbook für den Deployment-Sonderfall, der alle sechs Monate zuschlägt. Kuratiertes Wissen ist teuer – es kostet die Zeit eines Menschen, der es aufschreibt, und die eines zweiten, der es prüft. Dafür ist es adressierbar: Ich kann darauf zeigen, es verlinken, es einer Session mitgeben.\n\nEmergentes Wissen entsteht nebenbei. In der Session vom Dienstag ist ein halbes Dutzend kleiner Erkenntnisse angefallen: dass unser Test-Setup eine Eigenheit beim Mocken des Message-Brokers hat, dass eine bestimmte Bibliothek in Version 4 ein anderes Default-Verhalten hat als in unserer Doku steht, dass mein Prompt-Zuschnitt für Refactorings besser funktioniert, wenn ich das Zielbild vor die Einschränkungen stelle. Nichts davon habe ich aufgeschrieben. Die Session endete, und mit ihr verdampfte alles, was nicht in Code oder Commit-Message gerann. Emergentes Wissen ist billig in der Entstehung – und für spätere Sessions nicht verlässlich verfügbar, sofern es nicht gespeichert wurde.\n\nDas Gefälle zwischen beiden ist das eigentliche Problem. Teams produzieren in KI-Sessions heute mehr emergentes Wissen als je zuvor – jede Session ist ja ein kleines Labor, in dem jemand ausprobiert, formuliert, scheitert, nachjustiert. Und fast nichts davon überlebt. Was überlebt, ist der Code. Aber der Code enthält nur das Ergebnis, nicht die Begründung, nicht den verworfenen Irrweg, nicht die Formulierung, die den Knoten gelöst hat.\n\n## Wissen wie Code behandeln\n\nDas destillierte Arbeitswissen eines Teams verdient dieselbe Behandlung wie sein Code. Versioniert. Reviewt. Mit Ownership. Und mit einem Lebenszyklus, der auch das Sterben vorsieht. Darauf läuft diese Folge hinaus.\n\nDas klingt erst einmal nach einer Banalität – Docs as Code bezeichnet die Behandlung von Dokumentation mit denselben versionierten Arbeitsweisen wie Quellcode, einschließlich Review und automatisierter Prüfungen. Aber im KI-Kontext bekommt jede dieser vier Eigenschaften eine neue Schärfe:\n\n- Versioniert, weil das Wissen jetzt maschinell konsumiert wird. Wenn eine Instruktionsdatei sich ändert, kann sich das Verhalten der Sessions ändern, die sie laden. Solche Änderungen wirken auf das Verhalten des Systems – und Verhaltensänderungen gehören in die Historie, mit Diff und Datum und der Möglichkeit, zurückzugehen.\n- Reviewt, weil eine falsche Konvention jetzt neben menschlichen Lesern auch mehrere Sessions in die Irre führt. Ein Mensch, der einen schlechten Wiki-Artikel liest, merkt oft, dass etwas nicht stimmt. Eine Session kann den Fehler nicht erkennen und die falsche Konvention anwenden, wie ich es in [„Sauberes Grounding II: Antworten erden“](https://www.mikebild.dev/de/blog/sauberes-grounding-antworten-erden/) beschrieben habe: Was im Kontext steht, wird zur Realität der Session, ob es stimmt oder nicht.\n- Mit Ownership, weil herrenloses Wissen niemand pflegt. Jede Konventionsdatei, jedes Runbook braucht einen Menschen, der sich zuständig fühlt. Das ist keine Bürokratie – es ist die schlichte Antwort auf die Frage „Wen frage ich, ob das noch gilt?“.\n- Mit Lebenszyklus, weil veraltetes Wissen schlimmer ist als keins. Das ist der Punkt, den ich am häufigsten unterschätzt sehe. Eine Session ohne passende Quelle kann raten oder nachfragen; eine Session mit veraltetem Grounding rät mit Quellenangabe. Sie zitiert die Konvention von 2024, die wir im Herbst gekippt haben, und klingt dabei so belegt, dass niemand nachprüft.\n\nDer letzte Punkt verdient einen eigenen Absatz, weil er kontraintuitiv ist. Wir sind darauf trainiert, Dokumentation als „besser als nichts“ zu betrachten. Im KI-Kontext stimmt das nicht mehr. Falsches, altes, halbgares Wissen im Grounding einer Session ist aktiv schädlich, weil es die Ratlosigkeit des Modells in falsche Sicherheit verwandelt. Ein leeres Verzeichnis zwingt mich, nachzudenken, was die Session wissen muss. Ein volles, nie ausgemistetes Verzeichnis gaukelt mir vor, das sei erledigt. Deshalb gehört zum Lebenszyklus auch die regelmäßige Kontrolle gegen die Quellen: Gilt die Konvention noch? Beschreibt das Runbook noch das System, das läuft?\n\n## Der Kreislauf\n\nWenn man die Sortierung ernst nimmt – emergentes Wissen entsteht ständig, kuratiertes Wissen wirkt – dann ergibt sich fast zwangsläufig ein Kreislauf. Aus diesen Beobachtungen leite ich vier Stationen ab.\n\nErstens: aus echten Läufen lernen. Nicht aus Meinungen, nicht aus Blogposts, sondern aus dem, was in den eigenen Sessions tatsächlich passiert ist. Welche Erklärung hat funktioniert? An welcher Stelle taucht dieselbe Rückfrage wiederholt auf? Welcher Fehler kommt in mehreren Pull Requests unabhängig voneinander vor? Das Rohmaterial liegt herum – man muss es nur als Rohmaterial erkennen.\n\nZweitens: ein Mensch kuratiert und gibt frei. Das ist die entscheidende Station, und sie ist bewusst nicht automatisiert. Destillieren heißt auswählen, verdichten, wegwerfen. Aus zehn Beobachtungen wird ein Absatz; aus einem Absatz wird vielleicht eine Zeile in der Konventionsdatei; acht der zehn Beobachtungen werden verworfen, weil sie Einzelfälle waren. Diese Entscheidung muss das Team treffen, weil nur es festlegen kann, was künftig verbindlich gilt: was bei uns Regel ist, was eine Ausnahme war und was ab morgen gelten soll. Und die Freigabe – ein zweites Paar Augen, ein echtes Review – macht aus einer privaten Notiz eine geteilte Verbindlichkeit.\n\nDrittens: das Destillat fließt ins Grounding der nächsten Session. Es steht in der Datei, die jede Session liest, oder in der Wissensquelle, die beim Arbeiten herangezogen wird. Ab diesem Moment muss nicht mehr jeder Kollege „seiner“ Session das Fehlermodell mündlich und verschieden erklären – die Erklärung ist dieselbe, für alle, geprüft.\n\nViertens: die nächste Arbeit kann besser werden. Nicht dramatisch, nicht auf einen Schlag. Ob der Kreislauf wirkt, lässt sich an konkreten Fragen prüfen: Kommt die Rückfrage, die sich zuletzt wiederholt hat, seltener? Taucht der wiederkehrende Fehler in neuen Pull Requests noch auf? Und die nächsten Läufe produzieren neues Rohmaterial – idealerweise auf einem etwas höheren Niveau.\n\n```mermaid\nflowchart LR\n    A[\"Echte Läufe<br/>und Erfahrungen\"] --> B[\"Beobachten und<br/>Rohmaterial sammeln\"]\n    B --> C[\"Mensch kuratiert,<br/>Review gibt frei\"]\n    C --> D[\"Destillat im Grounding<br/>der nächsten Session\"]\n    D --> A\n```\n\nDas ist kein Framework und keine Zeremonie. Als Einstieg reicht ein regelmäßiger, kurzer Durchgang, in dem das Team bespricht, was hängen geblieben ist, plus die Disziplin, Änderungen an den Wissensdateien wie Code-Änderungen zu behandeln: Branch, Review, Merge. Wie viel Aufwand angemessen ist, hängt von Team, Umfang und Risiko ab.\n\n## Nicht das Modell wird schlauer\n\nDie Pointe dieses Kreislaufs ist mir erst mit der Zeit klar geworden, und sie hat meinen Blick auf die ganze Modell-Debatte verändert: In diesem Kreislauf wird nicht das Modell schlauer. Die Organisation lernt: Menschen wählen Erkenntnisse aus, begründen sie und machen sie für andere wiederverwendbar. Die ausgewählten Erkenntnisse schlagen sich als versionierte Änderungen des kuratierten Wissens nieder – nicht darin, dass ein Modell mehr Kontext behält.\n\nAm Ende des Quartals hat das Modell von unseren Sessions nichts automatisch als Teamwissen behalten. Die angebotene Version kann sich in dieser Zeit durchaus geändert haben – unser Fehlermodell kennt sie deshalb noch lange nicht. Verbessert hat sich die Schicht darum herum: unser kuratiertes Wissen, unsere Erklärungen, die Qualität dessen, was wir jeder Session mitgeben. Und – das ist der entscheidende Unterschied – diese Schicht gehört uns. Wir können sie lesen, prüfen, korrigieren, zurückrollen. Wir können sie steuern. Welche Modellversion ein Anbieter ausliefert und wie sie sich verhält, können wir weit weniger beeinflussen.\n\nWer die Lernfähigkeit seiner KI-Arbeit im Modell verortet, hat deshalb ein Steuerungsproblem: Er wartet auf Fortschritt, den er nicht beeinflussen kann. Wer sie in der Kuratierung verortet, hat ein Arbeitsproblem – anstrengender, aber lösbar. Ich halte das für die nüchternste Antwort auf die Frage, wo ein Team investieren sollte: in den Teil, den es besitzt.\n\n## Die Anti-Pattern\n\nWas ich an Versuchen gesehen habe, Session-Wissen festzuhalten, ist überwiegend gescheitert. Und zwar auf drei wiedererkennbare Arten.\n\nDie Prompt-Sammlung im Wiki. Irgendwer legt eine Seite an: „Unsere besten Prompts“. Drei Wochen lang wird eingezahlt, dann nie wieder. Nach einem halben Jahr enthält die Seite veraltete Prompts ohne Einsatzkontext: für Modelle, die keiner mehr benutzt, für Probleme, die keiner mehr hat, ohne Angabe, wann sie funktionieren und wann nicht. Niemand traut sich zu löschen, niemand mag pflegen. Der Fehler steckt schon in der Form: Ein Prompt ohne die Situation, für die er destilliert wurde, ist kein Wissen, sondern ein Souvenir.\n\nDie Instruktionsdateien-Halde. Das habe ich in „Vergebliche Versuche: Skills, AGENTS.md und die Grenze der Empfehlung“ schon von einer anderen Seite beleuchtet: Konventionsdateien, in die jeder mal etwas hineinschreibt und aus denen nie etwas herausfällt. Nach einem Jahr sind es zweitausend Zeilen, in denen sich Regeln widersprechen, weil die von März die von Oktober nicht kennt. Die Sessions lesen alles und gewichten irgendwie – das Ergebnis ist Lotterie. Eine Wissensdatei ohne Löschdisziplin ist keine Wissensdatei, sondern ein Sedimentbecken.\n\nDas Einmal-Aufgeschriebene. Die dritte Variante ist die leiseste: Ein motivierter Kollege schreibt in einer guten Woche alles auf – gründlich, strukturiert, wirklich brauchbar. Dann wird es nie wieder angefasst. Kein Ownership, kein Review-Rhythmus, kein Anlass, es zu aktualisieren. Zwölf Monate später können Teile davon veraltet sein, und weil niemand weiß, welche, traut niemand mehr dem Rest. Der einmalige Kraftakt ist der natürliche Feind des Kreislaufs: Er fühlt sich wie eine Lösung an und verhindert genau die Routine, die eine wäre.\n\nAllen drei Mustern fehlt dasselbe: der Rückweg von der echten Arbeit ins Wissen. Sie behandeln Aufschreiben als Event statt als Kreislauf.\n\n## Die Chance, die Arbeit kostet\n\nUnd trotzdem – oder gerade deshalb – halte ich diesen Moment für eine ungewöhnliche Gelegenheit. Organisationen reden seit Jahrzehnten davon, implizites Wissen zu explizieren. Wissensmanagement-Initiativen, Wikis, Communities of Practice: Meine These ist, dass ein fehlender unmittelbarer Abnehmer zum Versanden vieler dieser Initiativen beigetragen hat. Wer sein Wissen aufschrieb, schrieb für ein abstraktes „später“ und ein hypothetisches „jemand“. Die Rückkopplung fehlte; das Aufschreiben blieb ein Opfer ohne sichtbaren Ertrag.\n\nDas ändert sich gerade. KI-Sessions bilden einen zusätzlichen unmittelbaren Abnehmer für explizites Wissen. Wer heute eine Konvention sauber destilliert, kann es in der nächsten Session prüfen: Verhält sich die KI anders? Hält der Pull Request die Konvention ein? Bleibt die bekannte Rückfrage aus? Die Rückkopplungsschleife, die in diesen Fällen fehlte, kann sich in solchen Arbeitsabläufen deutlich verkürzen. KI schafft damit einen unmittelbaren Anreiz, implizites Wissen zu explizieren – und die nächste Session liefert früh Hinweise darauf, ob das Aufgeschriebene trägt.\n\nIch will die Kritik daran nicht unterschlagen. Kuratieren kostet die Zeit genau der Leute, die am wenigsten davon haben. Es besteht die reale Gefahr, dass der Kreislauf ausufert und jede Zeile Konvention ein eigenes Freigabegremium durchlaufen muss. Und nicht jedes Wissen will eingefroren werden – manches ist absichtlich im Fluss, und wer es zu früh destilliert, zementiert einen Zwischenstand. Die Antwort darauf ist Maß, nicht Verzicht: klein anfangen, nur destillieren, was sich wiederholt hat, und das Löschen genauso ernst nehmen wie das Schreiben.\n\nWas mich am Ende dieser Folge umtreibt, ist eine Frage, die eine Ebene tiefer liegt. Angenommen, der Kreislauf steht: Das Team kuratiert, das Wissen überlebt die Session, die Organisation lernt. Dann liegt da ein wachsender Bestand aus destillierten Konventionen, Fachbegriffen, Entscheidungen – und ich gebe ihn Session für Session einem generischen Assistenten in die Hand, der von meiner Fachdomäne nichts weiß und jedes Mal alles aus dem Kontext rekonstruiert. Irgendwann stellt sich die Frage, wem ich dieses Wissen eigentlich anvertraue: Reicht der generische Agent mit gutem Grounding – oder braucht die Fachdomäne ein Gegenüber, das für sie gebaut ist? Wo genau der generische Agent endet, ist die Frage der nächsten Folge.\n\n## Weiterführende Quellen\n\n- [AGENTS.md – das offene Format für Agenten-Instruktionen](https://agents.md/)\n- [Anthropic: Memory Tool – Wissen über Sessions hinweg](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool)\n- [Claude Code: How Claude remembers your project](https://code.claude.com/docs/en/memory)\n- [Ikujiro Nonaka: The Knowledge-Creating Company (Harvard Business Review)](https://hbr.org/2007/07/the-knowledge-creating-company)\n- [Write the Docs: Docs as Code](https://www.writethedocs.org/guide/docs-as-code/)"},{"locale":"de","translation_key":"sauberes-grounding-antworten-erden","slug":"sauberes-grounding-antworten-erden","title":"Sauberes Grounding II: Antworten erden","summary":"Mein Arbeitsmodell für Grounding unterscheidet Konventionen, Dokumente und API-Beschreibungen. Was im knappen Kontext bleibt, priorisiere ich nach Aufgabe und Wiederbeschaffungskosten.","tags":["Software","KI","Methodik","Delivery"],"published_at":"2026-06-03T10:00:00+00:00","updated_at":"2026-08-17T17:34:45.985779+00:00","url":"https://www.mikebild.dev/de/blog/sauberes-grounding-antworten-erden/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/3a3c91bf6c3b3fd52a36848dae71e5ea6e149d6ff41fa2a097c3497933a6ab22.mp3","audio_duration_secs":792,"text":"Vor ein paar Wochen saß ich mit einem Kollegen vor einem halbfertigen Integrationsstück. Die KI sollte einen Client für eine interne API schreiben, und sie tat, was sie immer tut: Sie schlug `customerId` vor. Das Feld heißt bei uns `customer_ref` – aus historischen Gründen, die niemand mehr verteidigt, aber jeder kennt. Wir hatten das dem Assistenten in dieser Woche schon zweimal erklärt. Diesmal habe ich etwas anderes gemacht: Ich habe ihm nicht widersprochen, sondern die OpenAPI-Beschreibung der API in den Kontext gegeben. Der nächste Vorschlag stimmte. Nicht ungefähr, sondern exakt – inklusive der etwas eigenwilligen Paginierung, die sich kein Modell der Welt hätte ausdenken können, weil sie schlicht eine Entscheidung von uns war. Gleiches Modell, gleicher Tag, gleiche Aufgabe. Der Unterschied: Es musste nicht mehr raten.\n\n*Teil 8 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nIn der [letzten Folge](https://www.mikebild.dev/de/blog/sauberes-grounding-warum-ki-raet/) habe ich beschrieben, warum die KI so überzeugend rät: Ein Sprachmodell verweist mit Symbolen auf Symbole, nicht auf meine Systeme. Es kennt tausend APIs, die so ähnlich aussehen wie meine – und genau deshalb erfindet es plausibel. Das war die Diagnose. Diese Folge ist die konstruktive Seite: Wie gebe ich der KI meine Realität mit? Ich nenne das für mich sauberes Grounding – Antworten erden, statt sie in der Schwebe zu lassen. Und wie so oft ist der Kern weniger ein Werkzeug als eine Sortierung: Welches Wissen gibt es überhaupt, wo kommt es her, und wann gehört es in den Kontext?\n\n## Mein Arbeitsmodell: drei Wissensschichten\n\nWenn ich mir anschaue, was meinen Antworten in der Praxis Boden gibt, lande ich immer wieder bei drei Schichten. Das ist meine Sortierung für diese Arbeit, keine allgemeine Taxonomie von Wissen. Die Schichten unterscheiden sich nicht allein im Inhalt, sondern in ihrem Charakter – und das ist der eigentliche Punkt.\n\n```mermaid\nflowchart TB\n    subgraph Schichten[\"Drei Wissensschichten\"]\n        K[\"Konventionen<br/>wie wir arbeiten<br/>präskriptiv, kuratiert\"]\n        D[\"Dokumente<br/>Runbooks, Specs, Entscheidungen<br/>deskriptiv, alternd\"]\n        S[\"Schnittstellenbeschreibungen<br/>OpenAPI, GraphQL-Introspection, Schemas<br/>maschinell prüfbar\"]\n    end\n    K --> E[\"Erdung beim Bauen<br/>und Vorbereiten\"]\n    D --> E\n    S --> E\n    E --> A[\"Geprüftes Arbeitsergebnis<br/>Dokument, Plan, Code, konfigurierter Ablauf\"]\n```\n\nDie erste Schicht sind unsere **Konventionen und Arbeitsweisen**. Das ist präskriptives Wissen: nicht „so ist die Welt“, sondern „so machen wir das hier“. Error Handling gehört an den Aufrufer, Migrationen laufen nie automatisch, Commit-Botschaften erklären das Warum, Reviews prüfen zuerst die Schnittstelle. Nichts davon steht in einer API-Beschreibung, und nichts davon kann ein Modell erraten – es sind Entscheidungen, keine Fakten. In Folge 6 habe ich erzählt, wie ich versucht habe, genau dieses Wissen in Instruktionsdateien wie AGENTS.md oder CLAUDE.md zu packen – und wo Empfehlungen an ihre Grenzen kommen. Aufgeben war daraus nicht die Lehre. Diese Schicht muss klein, dicht und kuratiert sein: Eine kurze Liste von Regeln, hinter denen das Team steht, lässt sich befolgen und im Review einfordern. Eine lange Sammlung von Hinweisen konkurriert mit sich selbst um Aufmerksamkeit.\n\nDie zweite Schicht sind unsere **Dokumente**: Runbooks, Spezifikationen, Architekturentscheidungen, Betriebsnotizen. Das ist deskriptives Wissen – es beschreibt, was bei uns gilt und warum es so gekommen ist. Eine festgehaltene Architekturentscheidung kann verhindern, dass die KI mit ihrem Vorschlag drei Jahre alte Systemgrenzen übergeht. Ein Runbook erklärt, was bei einem bestimmten Alarm wirklich zu tun ist, statt was generisch sinnvoll klingt. Aber ich habe gelernt, dieser Schicht mit einer gewissen Skepsis zu begegnen: Dokumente altern. Sie beschreiben den Zustand von damals, nicht von heute. Ein Runbook, das seit zwei Jahren niemand angefasst hat, kann die KI genauso in die Irre führen wie ihr eigenes Raten – nur klingt die Antwort dann noch überzeugender, weil sie sich auf „unsere Doku“ beruft.\n\nDie dritte Schicht sind **echte API-Beschreibungen** – und sie ist meine liebste, weil sie einen Charakter hat, den die anderen beiden nicht haben: Werkzeuge können ihre Struktur lesen, auch wenn Schema und Laufzeitverhalten auseinanderlaufen können. Eine OpenAPI-Beschreibung, ein per [Introspection](https://graphql.org/learn/introspection/) abgefragtes GraphQL-Schema, ein JSON-Schema, ein Datenbankschema – das ist nicht die Erinnerung eines Kollegen an das System, sondern eine maschinenlesbare Struktur- oder API-Beschreibung. Introspection zeigt das angebotene Schema dieser Umgebung zu diesem Zeitpunkt: Wenn das Feld `customer_ref` heißt, steht es dort. Das beweist weder korrekte Resolver noch die Übereinstimmung mit anderen Deployments oder mit datenabhängigen Antworten. Je nach Artefakt kann ich daraus Feldnamen, Typen oder Endpoints ablesen, statt sie aus Konventionen oder Dokumenten zu erraten.\n\nDie drei Schichten beantworten unterschiedliche Fragen, und sie ersetzen einander nicht:\n\n- Konventionen sagen, **wie** etwas gebaut werden soll – Stil, Schnitt, Verantwortlichkeiten.\n- Dokumente sagen, **warum** die Dinge so sind, wie sie sind – Kontext und Geschichte.\n- Die jeweilige API-Beschreibung nennt Felder, Typen oder Endpoints. Ob die Implementierung diesem Stand entspricht und funktioniert, muss separat geprüft werden.\n\nWer nur die dritte Schicht liefert, bekommt Code, der zum beschriebenen Vertrag passt, aber nicht zwingend zur Laufzeit funktioniert. Wer nur die erste liefert, bekommt stilistisch sauberen Code gegen eine erfundene API. Erst zusammen erden sie eine Antwort.\n\n## Nachschlagen statt Raten\n\nDas Prinzip hinter allen drei Schichten ist dasselbe, und es ist so unspektakulär, dass man es leicht überliest: **nachschlagen statt raten**. Am leichtesten versteht man es an einer Analogie, die jeder aus dem Editor kennt: IntelliSense.\n\nWenn ich in meinem Editor `customer.` tippe, rät der Editor nicht, welche Felder ein Kunde vermutlich hat. Er schlägt nach. Ein typbasierter Editor leitet Vorschläge aus der verfügbaren Typdefinition ab, nicht aus statistischer Ähnlichkeit. Genau diese Ableitung fehlt einem Sprachmodell, wenn wir es ohne Erdung arbeiten lassen.\n\nEin Agent mit passenden Werkzeugen und Leserechten kann nachschlagen. Er kann eine OpenAPI-Datei lesen, ein GraphQL-Schema per Introspection abfragen, eine Typdefinition im Repository aufschlagen. Das [Model Context Protocol](https://modelcontextprotocol.io/) stellt dafür Tools und Kontextquellen über einen Protokollvertrag bereit. Und ein solcher Agent kann noch einen Schritt weitergehen, der über IntelliSense hinausreicht: Er kann Endpoints **probieren**. Ein lesender Aufruf gegen die echte API, die tatsächliche Antwortstruktur anschauen, und der nächste Vorschlag basiert auf beobachteten Daten statt auf Erfindung. Aus „dieses Feld gibt es wahrscheinlich“ wird „dieses Feld habe ich gesehen – in dieser Antwort, mit diesen Rechten, in dieser Umgebung und zu diesem Zeitpunkt“. Das ist ein kategorialer Unterschied, kein gradueller, auch wenn eine einzelne Antwort nicht das Verhalten für andere Daten, Rechte, Umgebungen und Zeitpunkte belegt.\n\nErkundende Lesezugriffe müssen autorisiert sein; ihre fachliche Freiheit von Side Effects muss vorher geklärt werden. Solche Aufrufe sind für die Recherche wertvoll. Schreibende Aufrufe „zum Ausprobieren“ sind ein eigenes Thema mit eigenen Sicherungen – dazu komme ich in dieser Serie noch. Für das Erden von Antworten reicht die lesende Seite fast immer aus.\n\n## Grounding wiederholbarer Abläufe gehört ans Bauen\n\nDas zweite Prinzip hat länger gebraucht, bis es bei mir angekommen ist, und es ist das mit den größten Konsequenzen: **Wann** wird geerdet? Überall dort, wo ein wiederholbarer Ablauf ein vorab prüfbares Artefakt hat, gehört die Erdung ans Bauen und Vorbereiten – nicht in den kritischen Pfad der Ausführung. Entsteht die Frage dagegen erst zur Laufzeit, muss auch die Erdung dort stattfinden.\n\nDie Grafik oben zeigt diesen Fall für ein vorab prüfbares Artefakt.\n\nAn dieser Stelle muss ich RAG einordnen, weil es das erste Wort ist, das im Raum steht, sobald jemand „eigenes Wissen“ und „KI“ im selben Satz sagt. Retrieval-Augmented Generation – 2020 von [Lewis und Kollegen](https://arxiv.org/abs/2005.11401) beschrieben – bedeutet: Zum Zeitpunkt der Anfrage werden passende Textstücke aus einem Korpus gesucht und dem Modell mitgegeben. Das ist genau richtig, wenn die Frage erst zur Laufzeit entsteht und die Antwort aus einem Dokumentbestand kommen muss – ein Assistent, der Fragen zum Handbuch beantwortet, eine Suche über interne Notizen, Support-Fälle. Solche Fälle entsprechen dem im RAG-Papier beschriebenen Muster aus Retrieval und Generierung.\n\nSchief wird es, wenn RAG zum Reflex für alles wird. Denn Retrieval zur Laufzeit hat zwei Eigenschaften, die im Tagesgeschäft wehtun: zusätzliche Latenz und mögliche Ergebnisänderungen bei verändertem Index, Ranking oder Suchverfahren. Jede Ausführung sucht neu, und was gefunden wird, hängt an Einbettungen, Rankings, am Zustand des Index – derselbe Ablauf kann heute andere Textstücke sehen als gestern und sich deshalb anders verhalten. Für eine explorative Frage ist das verschmerzbar. Bei einem Ablauf, der jede Nacht läuft und auf dessen Ergebnis sich Leute verlassen, können wechselnde Treffer zu nicht reproduzierbaren Ergebnissen führen.\n\nDeshalb ziehe ich für solche wiederholbaren Abläufe die Erdung nach vorn. Das Wissen – die Konventionen, die Dokumente, die API-Beschreibungen – fließt ein, während etwas **entsteht**: ein Dokument, ein Plan, ein Stück Code, ein konfigurierter Ablauf. Dieses Arbeitsergebnis wird geprüft, von mir oder von einem Kollegen, und ab dann steht es fest. Die spätere Ausführung würfelt nicht neu, sie führt aus, was geprüft wurde. Der Unterschied ist derselbe wie zwischen einem Programm, das bei jedem Start seine Abhängigkeiten aus dem Netz rät, und einem Build mit festgeschriebenen Versionen: In den flüchtigen, kreativen Moment gehört die ganze Unsicherheit – in das, was danach jede Nacht wieder abläuft, gehört sie nicht.\n\nDas ist keine Absage an RAG, sondern eine Zuständigkeitsklärung. Suche über Dokumente zur Laufzeit, wo die Frage zur Laufzeit entsteht. Erdung beim Bauen, wo das Ergebnis ein Artefakt ist, das Bestand haben soll. In meiner Arbeit ist der zweite Fall der häufigere – diskutiert wird er trotzdem mit dem Vokabular des ersten.\n\n## Kontext-Ökonomie: was zuletzt fliegt\n\nDas dritte Prinzip klingt banal und entscheidet in der Praxis erstaunlich viel: Der Kontext ist knapp. Ja, die Fenster sind groß geworden. Aber wer länger mit Agenten-Sessions arbeitet, weiß, dass „groß“ nicht „unerschöpflich“ heißt – lange Sitzungen, gelesene Dateien, Tool-Ausgaben und Zwischenstände füllen jedes Fenster, und irgendwann wird getrimmt, zusammengefasst, weggelassen. Anthropic hat das unter dem Begriff Context Engineering auf den Punkt gebracht: Kontext ist eine endliche Ressource, relevante Informationen werden gezielt gefunden und nur bei Bedarf geladen. Ein großer, ungefilterter Kontext ist kein Qualitätsmerkmal – die für die Aufgabe maßgebliche Quelle gehört zum Zeitpunkt der Bearbeitung hinein.\n\nFür mein Grounding folgt daraus eine Priorisierungsregel: Wenn unter Druck etwas aus dem Kontext fliegen muss, entferne ich zuerst Material, das sich gezielt erneut nachschlagen lässt. Ein langes Runbook bleibt nur mit den gerade relevanten Absätzen im Kontext. Kleine, aufgabenrelevante Konventionen halte ich länger fest, weil ihr Verlust schwerer zu bemerken ist. Bei einer anderen Aufgabe kann diese Reihenfolge anders aussehen; entscheidend sind Relevanz und Wiederbeschaffungskosten, nicht die Bezeichnung der Schicht.\n\nDeshalb halte ich Konventionsdokumente klein und auf die Aufgabe zugeschnitten. Ein ausuferndes Dokument konkurriert mit Quellen und Tool-Ausgaben um Platz. Kuratieren heißt hier, bewusst zu entscheiden, was für den nächsten Schritt im Kontext bleiben muss.\n\n## Was Grounding nicht leistet\n\nZur Ehrlichkeit gehört die Gegenrechnung, und ich will sie nicht ans Ende quetschen, als wäre sie eine Fußnote. Grounding beseitigt das Raten nicht. Beim nächsten Vorschlag traten mit der geladenen OpenAPI-Beschreibung keine erfundenen Feldnamen oder Strukturen auf. Aber ein Sprachmodell bleibt ein Sprachmodell: Es kann eine korrekte Spezifikation im Kontext haben und trotzdem einen Schluss daraus ziehen, der nicht trägt. Es kann zwei Dokumente zusammenlesen, die sich widersprechen, und den Widerspruch elegant überbrücken, statt ihn zu melden. Und es kann an einem gealterten Runbook geerdet sein – dann ist die Antwort sauber begründet und trotzdem falsch, nur schwerer als falsch zu erkennen.\n\nPrüfen bleibt deshalb Pflicht. Das geerdete Arbeitsergebnis ist ein besserer Kandidat, kein fertiges Urteil. Was sich für mich geändert hat, ist die Art der Prüfung: Ich suche seltener nach frei erfundenen Feldern und häufiger nach falschen Schlüssen aus richtigen Quellen. Das ist ein besseres Problem – dieselbe Sorte Problem, die ich auch bei einem menschlichen Kollegen hätte, der sich gewissenhaft eingelesen hat. Aber es ist ein Problem, und Grounding ersetzt weder Konsistenzprüfung noch Tests – ohne solche Prüfungen können falsche Schlüsse unentdeckt bleiben.\n\nEine Frage lässt mich seither nicht los. Alles, was ich hier beschrieben habe, erdet eine Session: Die Konventionen, die Dokumente, die Schnittstellen fließen in einen Arbeitszusammenhang ein, und am Ende steht ein geprüftes Ergebnis. Aber die Session endet. Das Fenster schließt sich, der Kontext ist weg – und mit ihm alles, was die KI in diesen zwei Stunden über unser System, unsere Eigenheiten, unsere Korrekturen gelernt hat. Morgen erkläre ich `customer_ref` zum dritten Mal, oder ich habe einen Weg gefunden, dass Wissen die Session überlebt. Wie das aussehen kann – ohne veraltete, unauffindbare oder unbelegte Einträge anzusammeln – davon handelt die nächste Folge.\n\n## Weiterführende Quellen\n\n- [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) – Anthropics Engineering-Beitrag zu Kontext als endlicher Ressource\n- [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401) – das RAG-Originalpapier von Lewis et al. (2020)\n- [GraphQL Introspection](https://graphql.org/learn/introspection/) – wie ein GraphQL-Schema über sich selbst Auskunft gibt\n- [OpenAPI Specification](https://spec.openapis.org/oas/latest.html) – der Standard für maschinenlesbare HTTP-API-Beschreibungen\n- [Model Context Protocol](https://modelcontextprotocol.io/) – offener Standard, um KI-Werkzeugen echte Datenquellen und Systeme zugänglich zu machen"},{"locale":"de","translation_key":"ki-im-konzern-schnellere-entwicklung-andere-prozesse","slug":"ki-im-konzern-schnellere-entwicklung-andere-prozesse","title":"KI im Enterprise-Umfeld: Schnellere Entwicklung braucht andere Prozesse","summary":"KI verkürzt Recherche, Entwurf und Implementierung. Bleiben Übergaben, Ticket-Hierarchien und Freigaben unverändert, verlagert sich der Engpass – Großunternehmen müssen deshalb Arbeitsfluss und Governance gemeinsam neu ordnen.","tags":["Software","KI","Architektur","Delivery"],"published_at":"2026-05-19T10:00:00+00:00","updated_at":"2026-08-17T17:34:45.985779+00:00","url":"https://www.mikebild.dev/de/blog/ki-im-konzern-schnellere-entwicklung-andere-prozesse/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/442b997a3bb1e71dc90aae7da2c38199a3c3dbec6adf788b81c2f5499646041b.mp3","audio_duration_secs":928,"text":"Wenn die Implementierung statt fünf Tagen nur noch zwei dauert, die Änderung danach aber zwölf Tage auf Reviews, Freigaben und ein gemeinsames Testfenster wartet, ist das Produkt kaum früher beim Nutzer. Die lokale Arbeit wurde schneller. Der Gesamtprozess nicht.\n\nGenau diese Verschiebung macht KI in großen Unternehmen sichtbar. Ein Entwickler kann Code, Tests und eine erste Dokumentation in einem Bruchteil der bisherigen Zeit vorbereiten. In Forschung und Entwicklung (R&D) lassen sich Hypothesen schneller prüfen und Prototypen früher zeigen. Gleichzeitig bleiben Abhängigkeiten zwischen Teams, widersprüchliche Dokumentation und gewachsene Freigaberunden unverändert. Der Engpass rückt aus der Implementierung in die Organisation.\n\nDas ist kein Argument gegen große Unternehmen. Ihre Formalitäten sind selten aus reiner Freude an Bürokratie entstanden. Regulierung, Produkthaftung, wechselnde Mitarbeiter, verteilte Systeme und jahrzehntelang betriebene Software brauchen Nachvollziehbarkeit. Problematisch wird es, wenn niemand mehr unterscheiden kann, welche Formalität ein echtes Risiko beherrscht und welche nur eine frühere Unsicherheit verwaltet.\n\n## KI verstärkt den vorhandenen Arbeitsfluss\n\nDie Zahlen zur Produktivität passen nur auf den ersten Blick nicht zusammen. Drei Feldexperimente bei Microsoft, Accenture und einem weiteren Fortune-100-Unternehmen mit insgesamt 4.867 Entwicklern ergaben für Nutzer eines Coding-Assistenten rund 26 Prozent mehr erledigte Aufgaben; die Wirkung unterschied sich nach Erfahrung und Kontext. Eine randomisierte METR-Studie mit erfahrenen Open-Source-Entwicklern kam dagegen für frühe 2025er-Werkzeuge auf 19 Prozent längere Bearbeitungszeiten. Im Februar 2026 berichtete METR von Hinweisen auf bessere Ergebnisse mit neueren agentischen Werkzeugen, hielt die Daten wegen Auswahleffekten aber selbst für zu unsicher, um die Größe des Nutzens zu beziffern.\n\nDie Befunde widersprechen sich weniger, als es scheint. Aufgabe, Codebasis, Erfahrung, Werkzeug und Abnahmekriterium verändern das Ergebnis. Der [DORA-Report 2025](https://dora.dev/research/2025/dora-report/) fasst den organisatorischen Teil treffend zusammen: KI wirkt als Verstärker. Gute Feedbackschleifen, gepflegte interne Daten und kleine Änderungen profitieren. Unklare Zuständigkeiten und schwerfällige Abläufe werden ebenfalls verstärkt.\n\nIn dieselbe Richtung weist ein Befragungsergebnis aus dem [Atlassian State of Developer Experience Report 2025](https://www.atlassian.com/teams/software-development/state-of-developer-experience-2025): Entwickler berichteten dort von Zeitersparnis durch KI und zugleich von wöchentlichen Zeitverlusten durch organisatorische Reibung. Solche Selbstauskünfte sind keine Stoppuhr. Als Diagnose sind sie trotzdem nützlich: Schnellerer Code beseitigt keine Wartezeit.\n\n## Der Ticketbaum ist nicht das Produkt\n\nIn einem großen Unternehmen kann aus einer Produktidee zunächst eine Initiative werden, darunter ein Epic, mehrere Features, Stories und Subtasks. Die Fachbeschreibung liegt in Confluence, eine Architekturentscheidung in einem Kommentar, die Abnahmebedingung in einem Ticket und die tatsächliche Regel im Code. Jede Ebene ist für sich nachvollziehbar. Zusammen entstehen mehrere Wahrheiten.\n\nDaraus entsteht häufig ein halb agiles, halb wasserfallartiges Vorgehen. Das Team arbeitet in Sprints, muss den Inhalt aber Monate vorher für Budget, Abhängigkeiten und Gremien festlegen. Rückfragen landen als Ticketkommentare, weil das gesprochene Wort nicht als belastbar gilt. Also wird mehr geschrieben, ohne dass die Dokumentation dadurch konsistenter wird. Bei der Integration mehrerer Systeme wächst die Zahl der Abstimmungen schneller als die Zahl der fachlichen Entscheidungen.\n\nKI sollte diesen Apparat nicht automatisch befüllen. Sonst entstehen nur mehr Epics, längere Zusammenfassungen und noch überzeugender klingende Kommentare. Der bessere Ansatz beginnt mit einer einzigen, kleinen Beschreibung der Absicht. Alles Weitere wird daraus abgeleitet und bleibt mit der Änderung versioniert.\n\n```yaml\nchange:\n  id: customer-address-v2\n  outcome: reduce failed deliveries\n  constraints:\n    - preserve existing API clients\n    - keep customer consent auditable\n  owners:\n    product: customer-experience\n    technical: customer-platform\n  evidence:\n    - contract-tests\n    - migration-report\n    - rollback-plan\n  risk: medium\n```\n\nDas ist kein neues Pflichtformular. Es ist ein Beispiel für ein kleines, versioniertes Änderungsartefakt, über das man sinnvoll streiten kann. Mit lesendem Zugriff auf einen indexierten Code- und Entscheidungsbestand darf ein Agent daraus betroffene Repositories, frühere Entscheidungen, Verträge und Tests zusammensuchen. Er darf einen Plan, Akzeptanzbeispiele und Dokumentationsänderungen vorschlagen. Outcome, Einschränkungen, Risiko und Eigentümer bestimmt weiterhin das Team.\n\nDer Unterschied zum Ticketbaum liegt in der Richtung: Menschen pflegen nicht fünf Darstellungen derselben Änderung. Die unterschiedlichen Sichten werden aus wenigen versionierten Quellen erzeugt. Das Ticket verweist auf das Artefakt, der Pull Request zeigt den Diff, und die Dokumentation verweist auf die Entscheidung. Eine Zusammenfassung für das Management darf anders aussehen als die technische Sicht, aber beide müssen auf denselben Stand zurückführbar sein.\n\n## Integration braucht Verträge statt mehr Abstimmung\n\nKomplexe Integration wird durch KI nicht automatisch einfach. Ein Agent kann einen unbekannten Service schnell lesen und trotzdem eine fachliche Annahme übersehen, die nur das betreibende Team kennt. Gerade deshalb sollte die Zusammenarbeit weniger von Prosa und stärker von überprüfbaren Verträgen abhängen.\n\nBeim Beispiel der geänderten Kundenadresse könnte das relevante Event als Schema vorliegen:\n\n```json\n{\n  \"$id\": \"CustomerAddressChanged.v2\",\n  \"type\": \"object\",\n  \"required\": [\"customerId\", \"address\", \"consentId\"],\n  \"properties\": {\n    \"customerId\": { \"type\": \"string\" },\n    \"address\": { \"$ref\": \"Address.v2.json\" },\n    \"consentId\": { \"type\": \"string\" }\n  }\n}\n```\n\nDie KI kann im Code nach Produzenten und Konsumenten suchen, einen Kompatibilitätsbericht erstellen, Contract Tests ergänzen und Testdaten vorbereiten. Der Kompatibilitätsbericht muss für jede Aussage Repository, Revision und Fundstelle ausweisen – etwa dafür, dass das CRM `consentId` bereits liefert, der Versandservice das Feld ignoriert und ein alter Export mit `Address.v1` arbeitet. So lässt sich die Recherche prüfen, bevor daraus eine Entscheidung entsteht.\n\nEntscheiden muss sie nicht. Ob eine alte Adresse noch verarbeitet werden darf, ist eine fachliche Frage. Ob beide Versionen parallel laufen oder ein Adapter nötig ist, ist eine Architekturentscheidung. Der Agent sammelt Evidenz; die beteiligten Teams verantworten den Vertrag. Genau dafür sind [ADRs](https://www.mikebild.dev/de/blog/adr-entscheidungen-die-man-versteht/) und ausführbare Spezifikationen wertvoll: Sie halten nicht jedes Gespräch fest, sondern das Ergebnis und seine Gründe.\n\n## Dokumentation wird abgeleitet, nicht abgeschafft\n\nConfluence bleibt für Erklärungen, Entry Points und Übersichten nützlich. Es sollte nur nicht länger die dritte manuell gepflegte Kopie dessen sein, was Ticket und Code ebenfalls beschreiben. Eine Seite braucht einen benannten Eigentümer, einen überprüfbaren Bezug zu Vertrag, ADR oder Repository und ein sichtbares Aktualisierungsdatum. Fehlt diese Verbindung, darf ein Agent die Seite als möglicherweise veraltet markieren, aber nicht stillschweigend zur Wahrheit erklären.\n\nKI kann aus einer freigegebenen Änderung verschiedene Sichten erzeugen: Release Notes für Nutzer, einen technischen Integrationshinweis und eine kurze Zusammenfassung für das Portfolio. Der jeweilige Text bleibt überprüfbar, weil er auf dieselben Artefakte verweist. Menschen müssen dann nicht jeden Satz dreimal schreiben. Sie prüfen, ob die abgeleitete Sicht für ihre Leser stimmt. Die Dokumentation wird dadurch konsistenter und die Pflicht zugleich kleiner: Festgehalten werden Entscheidung, Vertrag und Betriebsfolge – nicht jede Zwischenstufe der Diskussion.\n\n```mermaid\nflowchart LR\n  Idea[Produktidee] --> Ticket[Ticket-Hierarchie]\n  Ticket --> Docs[Separate Dokumentation]\n  Docs --> Meetings[Abstimmungsrunden]\n  Meetings --> Build[Große Umsetzung]\n  Build --> Test[Gemeinsames Testfenster]\n  Test --> Approval[Externe Freigabe]\n\n  Intent[Versionierte Absicht] --> SmallChange[Kleine Änderung]\n  SmallChange --> Evidence[Tests, Vertrag und Diff]\n  Evidence --> Review[Peer Review]\n  Review --> Release[Release]\n  Release --> Feedback[Nutzer- und Betriebssignal]\n  Feedback --> Intent\n```\n\n## Agil wird man durch die Kosten einer Änderung\n\nAgilität ist kein bestimmtes Board und keine Zahl von Meetings. Das ursprüngliche Agile Manifesto stellt funktionierende Software über umfassende Dokumentation und die Reaktion auf Veränderung über das Befolgen eines Plans. Beide Aussagen verlangen keine Sorglosigkeit. Sie verlangen, dass neue Information den Arbeitsstand tatsächlich verändern kann.\n\nOb KI Recherche, Prototyping oder Testentwurf in einem konkreten Wertstrom verkürzt, muss dort gemessen werden. Wenn das gelingt, sinken die Kosten kleiner Experimente. R&D kann dann stärker mit Hypothesen arbeiten: Was wollen wir lernen, welches kleinste Experiment liefert Evidenz, und welches Ergebnis würde unsere Richtung ändern? Produktentwicklung kann denselben Rhythmus nutzen.\n\nDie Voraussetzung sind kleine Batches. Mehr parallel erzeugter Code verschlechtert den Fluss, wenn die Review-Kapazität gleich bleibt. Die Folge wäre eine neue Form von Lagerbestand – halbfertige Pull Requests statt halbfertiger Tickets. Wie bei [Developer Productivity](https://www.mikebild.dev/de/blog/developer-productivity-verkuerzte-zyklen/) zählt deshalb nicht die Tippgeschwindigkeit, sondern die Zeit bis zu belastbarem Feedback. [DORA-Metrics](https://www.mikebild.dev/de/blog/dora-metriken-was-zyklen-verkuerzt/) helfen beim Diagnostizieren; sie dürfen nicht zum Ziel für einzelne Mitarbeiter werden.\n\n## Governance ohne pauschale Queue\n\nKontrolle bleibt nötig, aber nicht jede Änderung verdient denselben Weg. Eine Textkorrektur, eine rückwärtskompatible API-Erweiterung und ein neues Berechtigungsmodell haben verschiedene Schadenspotenziale. Gute Governance macht diesen Unterschied ausführbar. Das NIST AI Risk Management Framework verfolgt denselben Gedanken auf der Ebene der KI-Systeme selbst: Es strukturiert Risikomanagement über Governance, Messung und laufende Steuerung statt über eine einzelne pauschale Freigabe.\n\n```yaml\napproval_policy:\n  - risk: low\n    requires: [tests, policy-checks, peer-review]\n    decision: peer-approved\n  - risk: medium\n    requires: [tests, contract-checks, owner-review, rollback-plan]\n    decision: peer-approved\n  - risk: high\n    requires: [security-review, compliance-review, business-owner, audit-record]\n    decision: manually-approved\n```\n\nAuch diese YAML-Datei ist nur eine Skizze, keine fertige Policy-Sprache. Automatisierte Kontrollen erzeugen bei jeder Änderung dieselbe Evidenz. Menschen prüfen dort, wo Kontext, Haftung oder schwer rückbaubare Wirkung hinzukommen. DORA empfiehlt, schwere externe Change Approvals durch Peer Review, kontinuierliche Tests, Monitoring und gezielte Zusatzprüfung riskanter Änderungen zu ersetzen. Das ist weniger Bürokratie und zugleich präzisere Kontrolle.\n\n```mermaid\nflowchart TD\n  Change[Änderung mit Evidenz] --> Risk{Risikoklasse}\n  Risk -->|niedrig| Guardrails[Automatische Guardrails]\n  Guardrails --> Peer[Peer Review]\n  Peer --> Release[Release]\n  Risk -->|mittel| Owner[Fachlicher und technischer Owner]\n  Owner --> Release\n  Risk -->|hoch| Specialist[Security, Compliance und Business]\n  Specialist --> Approval{Freigabe}\n  Approval -->|ja| Release\n  Approval -->|nein| Rework[Überarbeiten oder verwerfen]\n```\n\nDer EU AI Act macht eine zweite Unterscheidung wichtig. Artikel 4 der [Verordnung (EU) 2024/1689](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX%3A32024R1689) zur KI-Kompetenz gilt seit dem 2. Februar 2025: Anbieter und Betreiber müssen Maßnahmen treffen, damit Menschen, die in ihrem Auftrag mit KI-Systemen arbeiten, über ein ausreichendes Maß an KI-Kompetenz verfügen. Anhang III Nr. 4 der Verordnung erfasst – abhängig vom bestimmungsgemäßen Verwendungszweck – unter anderem Systeme, die Beschäftigte bewerten oder überwachen oder Aufgaben anhand persönlichen Verhaltens oder persönlicher Merkmale zuweisen. Ein Produktivitätsranking aus Prozessdaten fällt nicht automatisch darunter. Wird es jedoch für Personalentscheidungen, Leistungsbewertung oder Aufgabenzuweisung genutzt, liegt es in einem rechtlich besonders sensiblen Bereich. Governance soll die Arbeit absichern, nicht Menschen unter Generalverdacht stellen.\n\n## Die Organisation muss dem Arbeitsfluss folgen\n\nEin neuer Assistent allein ändert kein Organigramm. Auf Dauer passt aber eine Organisation mit vielen Übergaben schlecht zu einer Arbeitsweise, die in kurzen Schleifen lernen soll. Für Wertströme mit häufigen teamübergreifenden Änderungen werden drei Strukturen wichtiger:\n\n- langlebige, funktionsübergreifende Produktteams, die eine Wirkung von der Idee bis zum Betrieb verantworten und kleine Änderungen selbst freigeben können\n- eine interne Plattform, die sicheren Zugriff auf Code, Dokumentation, Testumgebungen und freigegebene KI-Modelle als Standardweg anbietet\n- Governance-, Security- und Architekturgruppen, die Regeln, Referenzlösungen und Ausnahmen gestalten, statt jede normale Änderung einzeln durchzuwinken\n\nDas entspricht dem Muster, das ich schon bei [einfacherem Entwurf und weniger Prozess](https://www.mikebild.dev/de/blog/einfach-schlagen-elegant-statt-prozess/) beschrieben habe: Erst die Änderung klein und ihre Erwartungen explizit machen, dann den Prozessschritt entfernen, der dadurch überflüssig wird. Eine lokal gemessene Zeitersparnis ersetzt diese Architekturarbeit nicht.\n\nFür die beteiligten Rollen verschiebt sich der Schwerpunkt:\n\n| Rolle | Neuer Schwerpunkt |\n| --- | --- |\n| Entwickler | Aufgaben schneiden, Kontext bereitstellen, generierte Änderungen prüfen, Tests und Betriebssignale entwerfen |\n| Architekten | Systemverträge, automatisierte Architekturregeln, Rückbaubarkeit und sichere Standardwege gestalten |\n| Product Owner | Outcomes, Akzeptanzbeispiele und Nutzerfeedback schärfen, statt den Ticketbestand zu verwalten |\n| Projektmanagement | Abhängigkeiten, Risiken, Wartezeiten und Work in Progress verringern, statt Tätigkeiten im Detail vorzuplanen |\n\nKeine dieser Rollen verschwindet. Im Gegenteil: Je billiger die Erzeugung von Vorschlägen wird, desto wertvoller werden Auswahl, Urteil und Verantwortung. Das [Ergebnis eines einzelnen KI-Power-Users lässt sich nicht einfach auf ein Enterprise übertragen](https://www.mikebild.dev/de/blog/mein-erfolg-laesst-sich-nicht-kopieren/). Teams brauchen gemeinsame Prüfkriterien, Lernzeit und einen Arbeitsfluss, der Unterschiede sichtbar macht.\n\n## Klein anfangen und den Gesamtzyklus messen\n\nEin unternehmensweites Transformationsprogramm wäre ein widersprüchlicher Anfang. Besser ist ein einzelner Wertstrom mit einer wiederkehrenden Änderung, deren Risiko bekannt ist. Dort lässt sich der heutige Weg vom Wunsch bis zum Betrieb aufzeichnen: Wie lange wird gearbeitet, wie lange gewartet, wie oft wird dieselbe Information übertragen, und an welcher Stelle entsteht Nacharbeit?\n\nFür einen ersten Versuch reichen wenige Schritte:\n\n- ein versioniertes Änderungsartefakt und die führenden Quellen festlegen\n- der KI nur lesenden Zugriff geben und ihren Kontext nachvollziehbar protokollieren\n- Tests, Contract Checks und Dokumentations-Diffs automatisch als Evidenz erzeugen\n- zunächst ausschließlich kleine, reversible Änderungen durch den neuen Pfad schicken\n- Lead Time, Wartezeit, Zahl der Übergaben, Nacharbeit, Change Fail Rate und Zeit bis zum Nutzerfeedback vergleichen\n\nNicht messen würde ich erzeugte Codezeilen, geschlossene Tickets oder individuelle Prompt-Aktivität. Solche Zahlen belohnen Volumen. Messen würde ich den Bestand halbfertiger Arbeit, den Anteil einer vorab festgelegten Dokumentstichprobe, der einem benannten Vertrag, ADR oder Repository-Stand widerspricht, und die Zeit vom Öffnen einer Review-Anfrage bis zur ersten Freigabe oder konkreten Änderungsanforderung. Der Anteil der Releases, die über den kontrollierten Pfad laufen, misst die Prozessabdeckung und nicht die Wirkung.\n\n## Fazit\n\nDie schwerfälligen Abläufe großer Unternehmen sind kein Naturgesetz, aber auch nicht bloß Dummheit aus der Vergangenheit. Sie bewahren Zuständigkeit, Wissen und Kontrolle dort, wo technische Mittel lange nicht ausgereicht haben. KI verändert diese Rechnung, weil sie Kontext schneller zusammentragen, Evidenz vorbereiten und wiederkehrende Prüfungen unterstützen kann.\n\nDer Gewinn entsteht erst, wenn die Organisation die frei werdende Zeit nicht mit mehr Output füllt. Dann werden Änderungen kleiner, Verträge ersetzen einen Teil der Abstimmung und versionierte Artefakte vermeiden widersprüchliche Kopien. Freigaben richten sich nach dem Risiko statt nach einer pauschalen Queue. Menschen behalten die Entscheidungen, bei denen Fachlichkeit, Haftung und Folgen zählen.\n\nSo kann KI Entwicklung und R&D tatsächlich agiler machen: nicht indem sie den alten Prozess schneller ausfüllt, sondern indem sie hilft, seine Umwege überflüssig zu machen.\n\n## Weiterführende Quellen\n\n- [DORA – State of AI-assisted Software Development 2025](https://dora.dev/research/2025/dora-report/)\n- [DORA – Capability Catalog](https://dora.dev/capabilities/)\n- [DORA – Streamlining Change Approval](https://dora.dev/capabilities/streamlining-change-approval/)\n- [DORA – Working in Small Batches](https://dora.dev/capabilities/working-in-small-batches/)\n- [DORA – Repository](https://github.com/dora-team/dora.dev)\n- [Microsoft Research – The Effects of Generative AI on High-Skilled Work](https://www.microsoft.com/en-us/research/publication/the-effects-of-generative-ai-on-high-skilled-work-evidence-from-three-field-experiments-with-software-developers/)\n- [METR – Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/)\n- [METR – We Are Changing Our Developer Productivity Experiment Design](https://metr.org/blog/2026-02-24-uplift-update/)\n- [Atlassian – State of Developer Experience Report 2025](https://www.atlassian.com/teams/software-development/state-of-developer-experience-2025)\n- [Manifesto for Agile Software Development](https://agilemanifesto.org/)\n- [NIST – AI Risk Management Framework](https://airc.nist.gov/airmf-resources/airmf/5-sec-core/)\n- [Europäische Kommission – AI Literacy: Questions & Answers](https://digital-strategy.ec.europa.eu/en/faqs/ai-literacy-questions-answers)\n- [Verordnung (EU) 2024/1689 – Artificial Intelligence Act](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX%3A32024R1689)"},{"locale":"de","translation_key":"sauberes-grounding-warum-ki-raet","slug":"sauberes-grounding-warum-ki-raet","title":"Sauberes Grounding I: Warum die KI so überzeugend rät","summary":"Warum Sprachmodelle plausible Dinge erfinden, weshalb mehr Training das Problem nicht zuverlässig beseitigt und was Grounding damit zu tun hat.","tags":["Software","KI","Methodik","Delivery"],"published_at":"2026-05-06T10:00:00+00:00","updated_at":"2026-08-17T16:28:14.564928+00:00","url":"https://www.mikebild.dev/de/blog/sauberes-grounding-warum-ki-raet/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/dc9891b2fd00b8bc42f7a52453cf4dea79b198a40f96c8eb178b49501009946c/sauberes-grounding-warum-ki-raet-vorlesen.mp3","audio_duration_secs":679,"text":"Vor ein paar Wochen saß ich in einem Review über generiertem Code. Der Assistent hatte eine Retry-Logik für unseren internen HTTP-Client vorgeschlagen – einen Client, den es nur bei uns gibt, eine dünne TypeScript-Schicht über `fetch` mit ein paar hauseigenen Konventionen. Der Vorschlag: `client.withRetry({ backoff: \"exponential\", maxAttempts: 3 })`. Sauber benannt, im Stil unserer Codebasis, mit einem Kommentar, warum exponentielles Backoff hier die richtige Wahl sei. Dazu eine kurze Erklärung im Chat, wie sich die Methode zu unserem Timeout-Handling verhält.\n\nDie Methode existiert nicht. Sie hat nie existiert. Unser Client konfiguriert Retries an einer ganz anderen Stelle, beim Erzeugen der Instanz, nicht am Aufruf. Aber das Erschreckende war nicht der Fehler. Fehler mache ich auch. Das Erschreckende war die Qualität der Erfindung: Der Name passte perfekt zu unseren Konventionen, die Signatur sah aus wie von uns, die Begründung war fachlich einwandfrei. Wäre die Methode von einem Menschen vorgeschlagen worden, hätte ich gesagt: Der kennt unseren Code richtig gut. Nur dass der Vorschlag komplett geraten war – und mit derselben Souveränität vorgetragen wurde wie die zwanzig korrekten Vorschläge davor.\n\n*Teil 7 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nWer ernsthaft mit Copilot, Claude Code oder Cursor arbeitet, kann so etwas erleben. Ich habe solche Fehler anfangs wie einen Bug betrachtet, der mit der nächsten Modellgeneration verschwinden müsste. Heute verlasse ich mich nicht darauf. Bessere Modelle können Halluzinationen reduzieren, beseitigen sie aber nicht zuverlässig – und seit mir das klar geworden ist, arbeite ich anders mit diesen Systemen.\n\n## Das Modell kennt seine Wissensgrenze nicht zuverlässig\n\nUm zu verstehen, warum die Erfindung so überzeugend klang, musste ich mir klarmachen, was ein Sprachmodell eigentlich tut: Es setzt Text fort. Aus Milliarden von Beispielen hat es gelernt, welche Fortsetzung nach einem gegebenen Anfang wahrscheinlich ist. Das ist keine abwertende Vereinfachung, sondern der Mechanismus – und er ist erstaunlich mächtig, wie ich [in Folge 2 dieser Serie](https://www.mikebild.dev/de/blog/gut-genug-modelle/) beschrieben habe. Aber er hat eine Eigenschaft, die man nicht wegdiskutieren kann: Wahre und falsche Aussagen entstehen beide als wahrscheinliche Fortsetzungen; eine Wahrheitsprüfung folgt aus diesem Mechanismus nicht automatisch.\n\nEin menschlicher Entwickler hat – bei aller Fehlbarkeit – ein Gefühl dafür, ob er etwas weiß oder vermutet. Wenn ich einen Kollegen nach einer Methode unserer internen Bibliothek frage, antwortet er entweder „die heißt so“ oder „ich müsste nachschauen“. Dieses Nachschauen-Müssen ist Metakognition: Wissen über das eigene Wissen, ein Gespür für die eigene Unsicherheit. Genau diese Instanz fehlt dem Modell. Es hat keinen inneren Zustand, der zwischen „das stand tausendfach im Trainingskorpus“ und „das klingt so, wie es klingen müsste“ unterscheidet.\n\nDeshalb ist die Souveränität, die uns so irritiert, keine Anmaßung, sondern ein Artefakt. Der Ton eines Textes ist Teil der Fortsetzung. Technische Dokumentation, Stack-Overflow-Antworten, Code-Kommentare – das Material, aus dem das Modell gelernt hat, ist überwiegend im Ton der Gewissheit geschrieben. Niemand dokumentiert eine API mit „ich glaube, diese Methode gibt es“. Also klingt auch die erfundene Methode nach Dokumentation. Der überzeugte Ton ist kein Signal für Korrektheit. Er war es nie.\n\nZwei Arbeiten stützen Teile dieser Erklärung. Ziwei Xu und Kollegen haben 2024 formal argumentiert, dass Halluzinationen für große Sprachmodelle nicht vollständig eliminierbar sind. Und OpenAI beschreibt in einer eigenen Veröffentlichung – Stand August 2026 online abrufbar – einen zweiten Mechanismus: Trainings- und Evaluationsanreize können Modelle zum Raten statt zum Eingestehen von Unsicherheit bewegen. Ein Modell, das bei Unsicherheit „weiß ich nicht“ sagt, kann in Benchmarks, die richtige Antworten belohnen, Enthaltungen aber nicht angemessen berücksichtigen, schlechter abschneiden als eines, das selbstbewusst rät – so wie ein Multiple-Choice-Test Studenten beibringt, bei Unwissen auf gut Glück anzukreuzen, statt das Feld leer zu lassen.\n\n## Symbole, die auf Symbole verweisen\n\nEs gibt noch eine tiefere Ebene, und sie ist älter als die aktuellen Modelle. 1990 – lange vor heutigen großen Sprachmodellen – hat der Kognitionswissenschaftler Stevan Harnad das *Symbol Grounding Problem* formuliert. Seine Frage: Wie kommt Bedeutung in ein System, das nur Symbole nach formalen Regeln manipuliert? Sein Bild: Man versuche, Chinesisch ausschließlich aus einem Chinesisch-Chinesisch-Wörterbuch zu lernen. Jedes Zeichen wird durch andere Zeichen erklärt, diese wiederum durch weitere Zeichen – man dreht sich im Kreis, ohne je bei der Sache selbst anzukommen. Symbole verweisen auf Symbole, nirgends berührt das System die Welt.\n\nIch zögere normalerweise, Paper aus der Kognitionswissenschaft in Alltagsdebatten zu ziehen, weil dabei oft mehr Nebel als Klarheit entsteht. Aber hier passt die Analogie unangenehm gut. Ein Sprachmodell kennt Text über die Welt, nicht die Welt. Es hat gelesen, was Menschen über HTTP-Clients, über Retries, über exponentielles Backoff geschrieben haben – und daraus statistische Zusammenhänge zwischen Token gelernt. Die Antwort in meiner Eingangsszene lieferte jedenfalls keinen Hinweis auf eine Prüfung an der Sache selbst: kein Compiler, der den Aufruf ablehnt, kein Test, der rot wird, keine Produktion, die um drei Uhr nachts alarmiert. Wo ich als Entwickler meine Begriffe an Erfahrung geeicht habe, hat das Modell seine Begriffe an anderen Begriffen geeicht. Das Wörterbuch erklärt sich selbst, und es erklärt sich flüssig.\n\nMan muss Harnads Problem nicht in voller philosophischer Schärfe übernehmen, um den praktischen Kern zu sehen: Ein System, dessen gesamtes „Wissen“ aus Textstatistik besteht, kann eine plausible Erfindung nicht von einer Tatsache unterscheiden, weil beide aus demselben Stoff sind. `withRetry` war für das Modell genauso real wie jede Methode, die es wirklich gibt – ein wahrscheinliches Symbol unter anderen Symbolen.\n\n## Warum größere Modelle das Problem mildern, aber nicht lösen\n\nDer Einwand liegt nahe: Die Modelle sind doch besser geworden. In meiner Arbeit erwische ich aktuelle Modelle im öffentlichen, gut dokumentierten Wissen jedenfalls nur noch selten bei freien Erfindungen.\n\nAber „seltener“ heißt nur „weniger oft“, nicht „grundsätzlich anders“. Der Mechanismus bleibt derselbe: Ein größeres Modell hat feinere statistische Zusammenhänge gelernt – es rät seltener, weil es mehr gesehen hat, nicht weil es aufgehört hätte zu raten. An der Stelle, wo sein Material endet, produziert es weiterhin die wahrscheinlichste Fortsetzung, im selben souveränen Ton. Die Grenzlinie zwischen Wissen und Vermutung verschiebt sich nach außen, aber sie verschwindet nicht, und das Modell zeigt sie mir nach wie vor nicht an. Genau das macht die restlichen Fälle so tückisch: Je seltener der Fehler, desto weniger rechne ich mit ihm – und desto ungeprüfter geht der Vorschlag durch.\n\n## Ohne interne Quellen bleiben organisationsspezifische Fakten Vermutung\n\nUnd damit zu dem Punkt, der mich in meiner täglichen Arbeit am meisten beschäftigt. Alles bisher Gesagte gilt für öffentliches Wissen – React, PostgreSQL, die AWS-APIs. Dort erlebe ich selten, dass das Modell rät – das öffentliche Material ist riesig. In dem Moment aber, in dem ich die Tür zu einer konkreten Organisation aufmache, kippt das Verhältnis. Denn was dort zählt, ist dem Modell ohne bereitgestellte interne Quellen nicht verlässlich zugänglich:\n\n- die internen Bibliotheken und Services mit ihren tatsächlichen Signaturen und Eigenheiten\n- die hauseigenen Konventionen – wie Fehler behandelt werden, wie Module geschnitten sind, was ein Deployment durchlaufen muss\n- die Begriffe der Fachdomäne, die im Unternehmen etwas Präzises bedeuten und außerhalb etwas anderes oder gar nichts\n\nWie weit das geht, hat mir der Fall aus der Eingangsszene gezeigt. Das Modell hat unseren HTTP-Client nie gesehen, also hat es ihn erfunden – und zwar so, wie ein solcher Client typischerweise aussieht. Deshalb war der Vorschlag so gut: Er war die Idealform eines internen HTTP-Clients, destilliert aus öffentlichen Mustern. Nur eben nicht unserer. Ohne interne Quelle waren die tatsächlichen Signaturen für das Modell nicht verlässlich ableitbar; die Erfindung lag nahe und sah dem echten Wissen zum Verwechseln ähnlich, weil das Modell so gut darin ist, den Stil einer Codebasis fortzusetzen.\n\nDas erklärt im Nachhinein auch, warum meine Versuche mit Instruktionsdateien so ernüchternd verliefen – ich habe das in der letzten Folge ausführlich erzählt. Damals dachte ich noch, das Problem sei die Verbindlichkeit: Die KI hält sich nicht an unsere Regeln, also müssen die Regeln klarer, strenger, prominenter formuliert werden. Aber selbst wenn eine AGENTS.md perfekt befolgt würde – sie beantwortet die falsche Frage. Eine Instruktion sagt dem System, wie es sich verhalten soll. Sie kann ihm nicht geben, was es tatsächlich nicht hat: die Fakten. „Erfinde keine Methoden“ ist eine hilflose Anweisung an ein System, das nicht merkt, wann es erfindet. Dem Modell fehlt nicht der Wille, es fehlt das Material. Ich habe an der Motivation eines Systems gearbeitet, das kein Motivationsproblem hat, sondern ein Wissensproblem.\n\n## Grounding: interne Fakten im Arbeitskontext bereitstellen\n\nFür diese Antwort auf das Wissensproblem verwende ich hier den Begriff Grounding – das Erden von Antworten in überprüfbaren Fakten. Die Idee ist im Kern einfach. Wenn das Modell meine Realität nicht aus dem Training kennen kann, dann muss ich sie ihm zum Zeitpunkt der Arbeit mitgeben: die echte Signatur statt der wahrscheinlichen, das tatsächliche Schema statt des typischen, unsere Konvention statt der branchenüblichen. Nicht als Verhaltensregel, sondern als Material. Das Modell soll nachschlagen können statt raten zu müssen – ungefähr so, wie mich eine gute IDE mit Typinformationen davon abhält, Methodennamen aus dem Gedächtnis zu tippen.\n\nHier verwende ich Grounding für die Bereitstellung konkreten Quellenmaterials im Arbeitskontext und unterscheide es damit von bloßen Instruktionen, die Verhaltensregeln formulieren. Grounding ist kein Produkt und kein Feature, das man einschaltet. Es ist zunächst eine Einsicht über die Arbeitsteilung: Das Modell liefert Sprachverständnis, Mustererkennung, Syntheseleistung – die Fakten über meine Welt muss meine Welt selbst liefern. Und es ist, ehrlich gesagt, auch keine vollständige Lösung. Ein geerdetes Modell kann die mitgegebenen Fakten immer noch falsch verknüpfen, und wer schon einmal versucht hat, „einfach alle Dokumente“ in den Kontext zu kippen, weiß, dass man sich damit neue Probleme einhandelt. Der Unterschied ist ein anderer: Bei einem geerdeten System streite ich über die Qualität meiner Quellen. Ohne Quellen prüfe ich freie Ergänzungen aus allgemeinen Mustern.\n\nDamit steht die Konsequenz dieser Folge fest, auch wenn sie niemandem Arbeit erspart: Bessere Modelle und strengere Anweisungen beseitigen überzeugende Falschantworten nicht zuverlässig. Grounding stellt dort konkretes Quellenmaterial bereit, wo das System sonst aus allgemeinen Mustern ergänzen müsste. Womit die eigentliche Arbeit beginnt – denn „interne Fakten mitgeben“ ist schnell gesagt. Welche Fakten eigentlich, in welcher Form, an welcher Stelle des Arbeitsflusses? Das ist keine rhetorische Frage, sondern die nächste Folge.\n\n## Weiterführende Quellen\n\n- [Stevan Harnad: The Symbol Grounding Problem (Physica D, 1990)](https://doi.org/10.1016/0167-2789(90)90087-6) – der Originalbeitrag mit dem Wörterbuch-Argument\n- [Ziwei Xu et al.: Hallucination is Inevitable – An Innate Limitation of Large Language Models (2024)](https://arxiv.org/abs/2401.11817) – die formale Argumentation, dass Halluzination für diese Modellklasse nicht eliminierbar ist\n- [OpenAI: Why Language Models Hallucinate](https://openai.com/index/why-language-models-hallucinate/) – warum Trainings- und Evaluationsanreize das Raten belohnen können (abgerufen im August 2026)\n- [Lilian Weng: Extrinsic Hallucinations in LLMs (2024)](https://lilianweng.github.io/posts/2024-07-07-hallucination/) – ausführlicher Überblick über Ursachen, Messung und Gegenmaßnahmen"},{"locale":"de","translation_key":"mein-erfolg-laesst-sich-nicht-kopieren","slug":"mein-erfolg-laesst-sich-nicht-kopieren","title":"Mein Erfolg lässt sich nicht kopieren","summary":"Ein Kollege übernimmt mein KI-Setup und bekommt andere Ergebnisse. Werkzeuge, Tests und Konventionen sind übertragbar; Aufgabenzuschnitt, Prüfblick und der einzelne Sessionverlauf sind es nur begrenzt.","tags":["Software","KI","Methodik","Delivery"],"published_at":"2026-03-04T11:00:00+00:00","updated_at":"2026-08-17T16:28:14.564928+00:00","url":"https://www.mikebild.dev/de/blog/mein-erfolg-laesst-sich-nicht-kopieren/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/9528d86b5e7adbc4b132902fcd66fab4f8661830a87775382f617f8432957cbe/mein-erfolg-laesst-sich-nicht-kopieren-vorlesen.mp3","audio_duration_secs":728,"text":"Im Februar fragte mich ein Kollege – erfahrener Entwickler, gutes Urteilsvermögen, kein Anfänger – ob er mein Setup haben kann. Er hatte über Wochen zugesehen, wie ich mit Claude Code arbeite, und wollte dasselbe: dieselben Werkzeuge, dieselbe Konfiguration, dieselben Ergebnisse. Ich habe ihm alles gegeben. Die komplette Werkzeugkette. Meine Instruktionsdateien, gewachsen über Monate. Meine Prompt-Sammlung für wiederkehrende Aufgaben, meine Checklisten für Reviews, sogar meine Notizen dazu, welche Aufgaben ich delegiere und welche nicht. Es gab keinen geheimen Rest. Er hatte wirklich alles, was ich habe.\n\n*Teil 5 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nZwei Wochen später saßen wir beim Kaffee, und er war ernüchtert. Nicht frustriert im Sinne von „das Werkzeug taugt nichts“ – er hatte durchaus brauchbare Momente erlebt. Aber das, was er bei mir gesehen hatte, diese Selbstverständlichkeit, mit der Aufgaben rausgehen und geprüfte Ergebnisse zurückkommen, stellte sich bei ihm nicht ein. Bei ihm lief die KI dreimal in die falsche Richtung, baute Dinge, die er nicht wollte, und er verbrachte mehr Zeit mit Aufräumen als vorher mit Selberschreiben. Sein Satz ist mir geblieben: „Ich habe dein Setup. Warum habe ich nicht deine Ergebnisse?“\n\nDie Frage hat mich länger beschäftigt als jedes Tool-Problem der letzten Monate. Denn die naheliegenden Antworten stimmen alle nicht. Es lag nicht am Modell – wir nutzten dasselbe. Nicht an der Konfiguration – sie war identisch, Datei für Datei. Nicht an mangelnder Erfahrung als Entwickler – er ist mindestens so gut wie ich. Was ihm fehlte, stand in keiner der Dateien, die ich ihm gegeben hatte. Und genau das ist der Punkt, an dem diese Serie den Sprung machen muss: vom Ich zum Team. Bisher habe ich beschrieben, warum der Harness mehr ausmacht als das Modell und [was mir an meiner eigenen Arbeitsweise Unbehagen bereitet](https://www.mikebild.dev/de/blog/was-ich-kritisch-sehe/). Beides war die Perspektive eines Einzelnen. Sobald ein zweiter Mensch ins Spiel kommt, taucht ein Problem auf, das ich vorher nur geahnt hatte: Varianz. Und zwar gleich dreifach.\n\n## Erste Ebene: dieselbe Aufgabe, zwei Sessions, zwei Ergebnisse\n\nDie erste Ebene hat noch gar nichts mit meinem Kollegen zu tun. Ich kann sie allein an meinem eigenen Rechner vorführen.\n\nIch gebe derselben KI dieselbe Aufgabe zweimal – unter weitgehend gleichen sichtbaren Bedingungen: gleicher Prompt, gleiches Repository, gleiche Instruktionsdateien. Session eins entscheidet sich, erst die Tests zu lesen, findet dort ein bestehendes Muster und erweitert es sauber. Session zwei springt direkt in den Produktionscode, hält eine Hilfsfunktion für unbenutzt, räumt sie „bei der Gelegenheit“ mit weg und liefert eine Lösung, die zwar läuft, aber anders geschnitten ist als alles Umliegende. Beide Sessions haben denselben Auftrag bekommen. Beide berichten selbstbewusst, sie seien fertig. Die Ergebnisse unterscheiden sich in Struktur, Stil und Nebenwirkungen.\n\nIn meinen Durchläufen unterschieden sich schon frühe Entscheidungen – etwa welche Datei zuerst gelesen wurde oder welches Muster als Vorbild diente. Danach liefen auch die weiteren Schritte auseinander.\n\nFür mich allein ist das handhabbar. Ich habe gelernt, Ergebnisse zu prüfen statt Wege vorzuschreiben, und in Folge 3 habe ich beschrieben, wie viel davon der Harness abfängt: Tools, Feedback-Schleifen, Prüfschritte. Aber schon hier zeigt sich der Fehler, „Best Practices“ mit reproduzierbaren Ergebnissen zu verwechseln: Derselbe Erfolgsfall lässt sich nicht exakt wiederholen. Wenn ich meinem Kollegen zeige, wie großartig eine Session gestern lief, zeige ich ihm einen einzelnen Durchlauf – auch bei mir würde der nächste anders aussehen.\n\n## Zweite Ebene: das Wissen, das in keiner Datei steht\n\nDie zweite Ebene ist die, an der mein Kollege tatsächlich gescheitert ist. Und sie ist unangenehmer, weil sie sich als Werkzeugfrage tarnt, aber eine Erfahrungsfrage ist.\n\nAls wir seine ernüchternden zwei Wochen durchgesprochen haben, fiel mir auf: Er hat dieselben Dinge getan wie ich – nur an anderen Stellen. Er hat delegiert, aber die falschen Aufgaben. Er hat geprüft, aber das Falsche angeschaut. Er hat abgebrochen, aber zu spät. Drei Beispiele aus unserem Gespräch:\n\n- Er gab der KI eine Aufgabe, die ich nie im Ganzen delegieren würde – eine Änderung quer durch drei Module mit unklarer Fachlogik – und wunderte sich über das Chaos. Ich hätte sie vorher in drei prüfbare Häppchen geschnitten. Dieser Zuschnitt steht in keinem meiner Prompts, ich mache ihn im Kopf, bevor ich überhaupt tippe.\n- Er las die Erklärungen der KI und fand sie überzeugend. Ich lese die Erklärungen kaum noch – ich schaue auf das Diff, die Tests und die Stellen, an denen erfahrungsgemäß unerwünschte Nebenwirkungen auftreten. Wo man hinschaut, ist Urteilskraft, keine Konfiguration.\n- Er ließ eine Session dreimal nachbessern, ehe er aufgab. Ich breche nach dem ersten gescheiterten Nachbesserungsversuch ab und formuliere die Aufgabe neu, denn ich habe gelernt: Wenn die Richtung einmal falsch ist, wird Nachsteuern teurer als Neustarten. Auch das steht nirgends – diese Abbruchregel stammt aus wiederholten Fehlversuchen.\n\nAufgabenzuschnitt, Prüfblick, Abbruchinstinkt – das ist implizites Wissen im klassischen Sinn. Man erwirbt es durch Reibung, nicht durch Lektüre. Meine Instruktionsdateien sind das Sediment dieses Wissens, aber sie sind nicht das Wissen selbst. Sie sagen der KI, was sie tun soll. Sie sagen meinem Kollegen nicht, was *er* tun soll, während die KI arbeitet.\n\nDie [METR-Studie vom Sommer 2025](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/) hat einen verwandten Effekt messbar gemacht: Bei erfahrenen Open-Source-Entwicklern dauerten Aufgaben mit frühen 2025er-KI-Werkzeugen im Mittel 19 Prozent *länger* – obwohl die Teilnehmenden einen Zeitgewinn erwarteten. Man kann über die Übertragbarkeit der Studie streiten, die Bedingungen waren speziell. Aber der belegte Befund passt zu dem, was ich bei meinem Kollegen gesehen habe: Erwarteter Zeitgewinn und gemessene Bearbeitungszeit können auseinanderliegen.\n\n## Dritte Ebene: es gibt keinen identischen Durchlauf\n\nDie dritte Ebene wird gern übersehen, weil sie so banal klingt: Mein Kollege arbeitet an anderen Aufgaben als ich.\n\nNicht grundsätzlich anders – gleiche Firma, verwandte Systeme, ähnlicher Stack. Aber seine konkrete Aufgabe an einem konkreten Dienstag ist nie meine konkrete Aufgabe. Sein Modul hat eine andere Geschichte, andere Altlasten, andere ungeschriebene Konventionen. Seine Bugs sitzen an anderen Stellen. Selbst wenn er meine Urteilskraft hätte und die Session-Lotterie zu seinen Gunsten ausginge: Er könnte meinen Erfolg trotzdem nicht reproduzieren, weil es den Versuchsaufbau „gleiche Aufgabe“ in echter Arbeit schlicht nicht gibt.\n\nDas unterscheidet KI-Werkzeuge fundamental von fast allem, was wir vorher im Team eingeführt haben. Formatter und CI-Pipelines zielen unter gleicher Version, Konfiguration und Umgebung auf reproduzierbare Ausführung; eine Framework-API stellt denselben Vertrag bereit. Bei diesen Werkzeugen gilt: Einer findet die gute Konfiguration, alle übernehmen sie, alle haben den Nutzen. Genau dieses Muster haben wir alle im Kopf, wenn wir „Setup teilen“ sagen – und genau dieses Muster greift hier nicht. Der Nutzen einer KI-Session entsteht aus dem Zusammenspiel von Aufgabe, Kontext, Person und Zufall. Drei dieser vier Faktoren sind bei jedem Teammitglied andere.\n\n## Was Organisationen daraus regelmäßig falsch schließen\n\nAuf Organisationsebene können diese Unterschiede zu falschen Produktivitätsannahmen führen. Denn aus der Einzelbeobachtung „bei Mike funktioniert das“ liegen drei Fehlschlüsse nahe.\n\nDer erste Fehlschluss: Lizenz gekauft heißt Team produktiv. Ein Konzern beschafft für alle Entwickler Zugänge, verbucht das als „KI-Adoption“ und erwartet den Produktivitätssprung, den die Power-User im Pilotprojekt gezeigt haben. Aber die Power-User waren ja gerade deshalb schnell, weil sie über Monate implizites Wissen aufgebaut haben. Die Lizenz kauft das Werkzeug, nicht die zweite Ebene. Der [DORA-Report 2025](https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report) bringt es auf eine Formel, die ich seither ständig zitiere: KI verstärkt, was da ist. Teams mit guten Feedback-Schleifen und sauberer Architektur werden besser, Teams mit schwachen Prozessen bekommen ihre Schwächen verstärkt zurück.\n\nDer zweite Fehlschluss: Prompt-Bibliothek teilen ist ein Rollout. Das war mein eigener Irrtum mit dem Kollegen, nur in klein. Prompts und Instruktionsdateien sind Sediment – nützlich, aber tot ohne die Praxis, aus der sie entstanden sind. Eine geteilte Prompt-Sammlung ohne geteilte Urteilskraft produziert Leute, die überzeugende Erklärungen lesen statt Diffs zu prüfen. Die [Stack-Overflow-Umfrage 2025](https://survey.stackoverflow.co/2025/ai/) zeigt die Folgen im Großen: KI-Werkzeuge werden breit genutzt, aber das Vertrauen bleibt begrenzt, und eine häufig genannte Frustration ist Code, der „fast richtig“ ist. Fast richtig zu erkennen ist exakt die Fähigkeit, die sich nicht allein per Datei verteilen lässt.\n\nDer dritte Fehlschluss: Was beim Piloten klappt, skaliert linear. Tut es nicht, wegen aller drei Varianz-Ebenen gleichzeitig. Ein Pilot kann motivierte Power-User enthalten (Personen-Varianz), ausgewählte, gut schneidbare Aufgaben (Aufgaben-Varianz) und selektiv berichtete Erfolgsgeschichten – missratene Sessions können in der Management-Präsentation fehlen (Session-Varianz). Wer daraus eine Hochrechnung für 200 Entwickler baut, kann mit einem nicht repräsentativen Durchschnitt rechnen.\n\nIch formuliere es zugespitzt, weil ich den Satz in [Folge 4](https://www.mikebild.dev/de/blog/was-ich-kritisch-sehe/) schon einmal gebraucht habe und er hier die organisatorische Konsequenz beschreibt: Die Erfolgsgeschichten der Einzelnen sind echt, und sie sind trotzdem kein Bauplan. Werkzeuge, Tests, Konventionen und Abnahmekriterien lassen sich kopieren. Mein konkretes Ergebnis entsteht zusätzlich aus Aufgabe, Kontext, Prüfblick und Sessionverlauf. Diesen Teil überträgt keine Setup-Datei.\n\n## Die Varianz ist auch eine Lernquelle\n\nDas klingt jetzt düsterer, als ich es meine. Denn dieselbe Varianz, die das Kopieren verhindert, ist eine brauchbare Diagnosequelle für ein Team.\n\nAls mein Kollege und ich seine zwei Wochen seziert haben, ist etwas Bemerkenswertes passiert: Ich musste zum ersten Mal aussprechen, *warum* ich Aufgaben so schneide, wie ich sie schneide. Warum ich Erklärungen ignoriere und Diffs lese. Warum ich nach einem gescheiterten Nachbesserungsversuch abbreche. Das war implizites Wissen, das ich selbst nicht als Wissen wahrgenommen hatte – für mich war es einfach „wie man das halt macht“. Erst der Unterschied zwischen seiner Arbeitsweise und meiner hat es sichtbar gemacht. Genau dort, wo zwei Leute dasselbe verschieden machen, liegt das implizite Wissen offen zutage. Man muss nur hinschauen, statt die Differenz als Versagen des Langsameren abzutun.\n\nMeine Schlussfolgerung nach diesem Februar: Wenn Einzelerfahrungen im Team zusammenfließen sollen, sind nicht die Prompts das Wertvolle. Es sind die Unterschiede. Zwei Entwickler, dieselbe Aufgabenklasse, verschiedene Ergebnisse – das ist kein Ärgernis, das ist ein Befund. Jede dieser Differenzen zeigt auf eine unausgesprochene Regel, eine Heuristik, ein Stück Urteilskraft, das bislang nur in einem Kopf existierte.\n\nMein Kollege arbeitet übrigens weiter mit dem Setup – inzwischen mit eigenen Instruktionsdateien, die sich von meinen zunehmend unterscheiden, und mit deutlich besseren Ergebnissen. Nicht weil er mich jetzt besser kopiert, sondern weil er aufgehört hat, es zu versuchen. Was er von mir übernommen hat, sind nicht die Dateien. Es sind die Fragen, die er sich vor jeder Delegation stellt.\n\nUnd damit stehe ich vor der Konsequenz, die sich jedes Team an dieser Stelle vornimmt, meines eingeschlossen: Wenn das entscheidende Wissen implizit ist, dann machen wir es eben explizit. Wir setzen uns hin, sprechen die Regeln aus, die bisher nur in Köpfen existierten, und schreiben sie auf – in genau die Dateien, die die KI bei jeder Session liest. Aufgabenzuschnitt, Prüfregeln, Abbruchkriterien, alles rein. Das muss doch reichen. Warum es das nicht tut – und warum die KI sich an unsere sorgfältig aufgeschriebenen Regeln erstaunlich selektiv hält – davon handelt die nächste Folge.\n\n## Weiterführende Quellen\n\n- [METR: Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/)\n- [Google Cloud: Announcing the 2025 DORA Report](https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report)\n- [Stack Overflow Developer Survey 2025: AI](https://survey.stackoverflow.co/2025/ai/)"},{"locale":"de","translation_key":"was-ich-kritisch-sehe","slug":"was-ich-kritisch-sehe","title":"Was ich kritisch sehe","summary":"Vier Beobachtungen und eine offene Hypothese nach intensiven Monaten mit KI – vom möglichen Kompetenzverlust bis zur Sorge vor gleichförmigeren Lösungen und meinen praktischen Gegenmaßnahmen.","tags":["Software","KI","Methodik"],"published_at":"2026-02-10T11:00:00+00:00","updated_at":"2026-08-17T16:28:14.564928+00:00","url":"https://www.mikebild.dev/de/blog/was-ich-kritisch-sehe/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/22c58d3306f742f4179d5bbf17356541eca1e4fa9f11ba3cb8e3f805b80d5626.mp3","audio_duration_secs":623,"text":"An einem Donnerstagabend im Januar habe ich einen Pull Request beinahe durchgewunken, den ich selbst in Auftrag gegeben hatte. Claude Code hatte eine Datenbank-Migration geschrieben, sauber formatiert, mit Kommentaren, mit Rollback-Pfad. Ich habe sie gelesen, genickt, den Mauszeiger schon über dem Merge-Button gehabt – und dann, eher aus Gewohnheit als aus Misstrauen, doch noch die betroffene Tabelle im Staging-System angeschaut. Die Migration hätte funktioniert. Sie hätte nur nebenbei eine Spalte umbenannt, auf die ein Report zugreift, von dem die Session nichts wissen konnte. Kein Drama, schnell gefunden. Aber der Moment davor beschäftigt mich bis heute: Ich hatte nicht geprüft. Ich hatte gelesen, wie man einen gut geschriebenen Text liest – wohlwollend, mit dem Strom.\n\n*Teil 4 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nIn der letzten Folge habe ich beschrieben, warum das Delegieren an KI für mich erst mit einem guten Harness funktioniert – mit Tools, Rückkopplung und Leitplanken um das Modell herum. Am Ende stand ein Unbehagen, das mit jeder delegierten Aufgabe lauter geworden ist. Dieses Unbehagen will ich heute ernst nehmen. Nicht als Alarmruf – ich arbeite weiter jeden Tag mit diesen Werkzeugen, gern und produktiv. Sondern als das, was Kritik eigentlich sein sollte: genau hinschauen, bevor man weitermacht. Ich trenne dabei vier Beobachtungen von einer offenen Hypothese.\n\n## Wer nur noch prüft, verlernt das Bauen\n\nWenn ich Code nur selten selbst schreibe, muss ich inzwischen genauer unterscheiden: Fehlt mir nur eine API-Signatur, oder fehlt mir Übung in der Routine? Wer eine selten genutzte Bibliotheksfunktion braucht, schlägt ihre Signatur nach – das war immer so und ist kein Problem. Das Problem wäre die Richtung der Bewegung: Wenn nicht mehr nur die Ausnahme nachgeschlagen wird, sondern die Routine ganz entfällt, fehlt die Wiederholung, aus der Geläufigkeit entsteht. Ob und wie schnell das bei mir passiert, kann ich nicht messen. Deshalb erledige ich bestimmte Routineaufgaben bewusst ohne KI und achte darauf, wo mir Übung fehlt.\n\nDie CHI-2025-Studie von Microsoft Research und Carnegie Mellon befragte dazu 319 Wissensarbeiter. Höheres Vertrauen in generative KI hing in den Selbstauskünften mit weniger eingesetztem kritischem Denken zusammen. Das ist ein Zusammenhang in einer Befragung, kein Nachweis dafür, dass Fähigkeiten bereits abgebaut wurden. Meine Sorge geht einen Schritt weiter als das Ergebnis der Studie: Wer Routinearbeit abgibt und nur noch die Ausnahmen behandelt, könnte genau die Übung verlieren, die er für die Ausnahmen braucht.\n\nFür mich ist das ein schleichendes Risiko, das ich aktiv managen kann. Mehr treibt mich um, wie die Rechnung für Berufsanfänger aussieht. Ich habe mein Handwerk gelernt, indem ich oft genug auf die Nase gefallen bin: Speicherlecks selbst gejagt, Race Conditions selbst gebaut und selbst verstanden. Wer in der Lernphase überwiegend generierten Code prüft, bekommt möglicherweise weniger Gelegenheit, diese Substanz aufzubauen – das ist eine Vermutung, keine Messung, und die zitierte Befragung sagt dazu nichts. Konkret würde dann die Erfahrung fehlen, die gutes Prüfen erst möglich macht: einschätzen zu können, ob ein Timeout, eine Sperre oder eine Error Handling zum eigenen System passt, weil man solche Entscheidungen selbst getroffen und ihre Folgen getragen hat.\n\n## Plausibel ist nicht richtig\n\nDie Szene vom Anfang hat einen Namen: Automation Bias. Eine systematische Übersicht von Goddard, Roudsari und Wyatt beschreibt ihn als Neigung, automatisierten Empfehlungen zu folgen und widersprechende Hinweise zu übersehen – die Forschung dazu ist älter als die aktuellen Sprachmodelle. Bei meiner Migration verstärkten die saubere Formatierung, die Kommentare und der mitgelieferte Rollback-Pfad genau diesen Vertrauenseindruck: Ich hätte beinahe freigegeben, was ich nicht geprüft hatte.\n\nOb Review und Vier-Augen-Prinzip gegen solche plausiblen Ausgaben systematisch schlechter greifen als gegen erkennbar schlampigen Code, kann ich nicht belegen.\n\nPassend dazu haben Perry und Kollegen in einer kontrollierten Studie gezeigt, dass Teilnehmende mit KI-Assistent häufiger unsicheren Code schrieben und zugleich überzeugter waren, sicheren geschrieben zu haben. Die Studie untersucht keine Code-Reviews. Für meine Review-Praxis ist die Kombination deshalb ein Warnsignal, kein Wirksamkeitsbeleg.\n\n## „Das hat die KI so gemacht“ ist keine Antwort\n\nIm Review reicht mir „Das hat mir die KI so vorgeschlagen“ nicht als Begründung. Der Satz erklärt die Herkunft, aber nicht die Entscheidung. Warum ist der Timeout hier auf dreißig Sekunden gesetzt? Warum ist das für unser System richtig? Wenn darauf keine Antwort folgt, ist die Entscheidung im Review nicht begründet – denn die Session, die den Wert gewählt hat, ist längst beendet und hat ihre Gründe, falls es welche gab, mitgenommen.\n\nIn einem Review gibt es keine dritte Partei. Es gibt den Menschen, der den Code einbringt, und den Menschen, der ihn freigibt – beide mit Namen, beide ansprechbar, beide morgen noch da. Was das Werkzeug vorgeschlagen hat, ist so relevant wie die Frage, in welchem Editor der Code getippt wurde. Wer einen Pull Request stellt, sagt damit: Ich stehe dafür ein. Wenn diese Zusage sich auflöst, weil „die KI“ als diffuser Mitautor im Raum steht, verliert das Review seinen Kern. Dann prüfen zwei Menschen etwas, für das sich keiner zuständig fühlt.\n\n## Schulden, die keiner aufgenommen hat\n\nTechnische Schulden können aus bewussten Abkürzungen entstehen: Wir bauen jetzt die schnelle Lösung und räumen später auf. Man kannte die bewusst eingegangenen Abkürzungen und ihre Folgen. Daneben sehe ich eine mögliche zweite Variante: Code, der funktioniert, alle Tests besteht – und den niemand im Team wirklich versteht. Nicht, weil er unverständlich wäre, sondern weil ihn nie jemand verstehen musste. Er wurde generiert, er lief, er wurde gemerged.\n\nWenn ein Team einen generierten Mechanismus beim Einbau nur im Groben nachvollzieht, kann es bei der nächsten Änderung nötig sein, Annahmen und Entscheidungsgründe zu rekonstruieren, bevor der Mechanismus sicher geändert werden kann. Dann kann technische Schuld entstanden sein, ohne dass sie jemand bewusst aufgenommen hätte – kein Vermerk, keine Entscheidung, kein „später räumen wir auf“. Solche Schulden können unbemerkt entstehen, weil keine bewusste Abkürzung dokumentiert wurde. Ein System, das zu größeren Teilen aus solchem Code besteht, ist nicht kaputt. Es ist etwas Schlimmeres: unverstanden bei voller Funktion.\n\n## Wenn alle dasselbe Modell fragen, können Entwürfe ähnlicher werden\n\nDie letzte Sorge ist eine offene Hypothese. Ein Gedankenexperiment macht sie greifbar: Vier Gruppen bekommen dieselbe offen gehaltene Entwurfsaufgabe, und alle vier stellen ihre erste Frage demselben Modell. Wie unterschiedlich fallen die Ergebnisse aus? Wenn alle mit einer sehr ähnlichen Erstantwort starten, kann diese Antwort den weiteren Entwurf prägen. Der Effekt ist nicht gemessen und hängt unter anderem von Prompt, Kontext, Sampling und Modell ab. Die erwähnte Microsoft-Studie untersucht ihn nicht.\n\nMan kann mit den Achseln zucken und sagen: Konvergenz auf bewährte Muster ist doch gut. Teilweise stimmt das – ich bin der Letzte, der eine ausgefallene Lösung schon deshalb gut findet, weil sie ausgefallen ist. Aber Architektur-Vielfalt ist kein Selbstzweck, sondern ein Suchverfahren. Unterschiedliche Entwürfe machen alternative Annahmen und Zielkonflikte sichtbar. Meine Sorge lautet deshalb: Wenn viele Entwurfsentscheidungen durch denselben Filter laufen, verengt sich der Raum der ernsthaft geprüften Alternativen. Messen kann ich das nicht.\n\n## Kritik heißt nicht Ablehnung\n\nAn dieser Stelle könnte der Text kippen – in Kulturpessimismus, in „früher haben wir noch richtig programmiert“. Das wäre bequem und falsch. Keiner dieser Punkte ist ein Argument gegen die Werkzeuge. Jeder einzelne ist ein Argument gegen einen bestimmten Umgang mit ihnen: den passiven. Kompetenz verfällt nicht, weil KI existiert, sondern weil ich aufhöre zu üben. Automation Bias schlägt zu, weil ich Plausibilität mit Korrektheit verwechsle. Verantwortung diffundiert, weil ich sie diffundieren lasse. Das ist der Haken an der Sache: Die Antwort liegt nicht im nächsten Modell-Release. Sie liegt bei mir.\n\nIch habe für mich ein paar Regeln aufgestellt. Keine Weisheiten, eher Hausregeln:\n\n- Regelmäßig bewusst ohne KI arbeiten. Kein Verzichtsritual, eher ein Lauf ohne Uhr: bestimmte Aufgaben – ein Algorithmus, ein Datenmodell, ein kniffliger Bugfix – von Hand, um zu spüren, wo es hakt. Wo es hakt, prüfe ich, ob mir Übung fehlt oder nur eine selten genutzte API nicht präsent ist.\n- Verstehens-Pflicht vor dem Merge. Nichts geht in den Hauptzweig, was ich nicht einem Kollegen an der Tafel erklären könnte – Zeile für Zeile bei kritischen Stellen. Kritische Stellen sind zum Beispiel möglicher Datenverlust, Rechteprüfungen, Concurrency und öffentliche APIs. „Im Groben nachvollzogen“ zählt nicht.\n- Erst das eigene Urteil, dann das Modell. Bei Entwurfsfragen schreibe ich meine Position in drei Sätzen auf, bevor ich frage. Sie muss nicht die bessere sein; sie ist ein Anker gegen die plausible Erstantwort – Abweichungen werden dann zu echter Information.\n- Herkunft benennen, Verantwortung behalten. Wenn Code generiert wurde, sage ich das im Review offen – und übernehme ihn trotzdem so, als hätte ich ihn getippt.\n\nNichts davon ist originell. Die zusätzliche Prüfung kostet mich Zeit, macht die Freigabe aber nachvollziehbarer. Und ich merke: Sie kostet Kraft. Im Alltag ist es einfacher, sie auszulassen.\n\nGenau da endet allerdings die Reichweite dieses Textes. Alles, was ich hier beschrieben habe, sind Maßnahmen eines Einzelnen – meine Regeln, meine Disziplin, meine Hausregeln. Das trägt genau so weit, wie meine Selbstkontrolle reicht, und an schlechten Tagen reicht sie erstaunlich wenig weit. Ein Team kann sich nicht auf die private Disziplin seiner Mitglieder verlassen; zehn Leute mit zehn verschiedenen Hausregeln ergeben noch keine gemeinsame Arbeitsweise. Was mit diesen Beobachtungen passiert, wenn nicht einer so arbeitet, sondern ein ganzes Team – mit unterschiedlicher Erfahrung, unterschiedlicher Sorgfalt und Termindruck obendrauf – das ist die Frage, die ich mir für die nächste Folge vorgenommen habe.\n\n## Weiterführende Quellen\n\n- [The Impact of Generative AI on Critical Thinking (Microsoft Research / Carnegie Mellon, CHI 2025)](https://www.microsoft.com/en-us/research/publication/the-impact-of-generative-ai-on-critical-thinking-self-reported-reductions-in-cognitive-effort-and-confidence-effects-from-a-survey-of-knowledge-workers/)\n- [Kate Goddard, Abdul Roudsari, Jeremy C. Wyatt: Automation bias – a systematic review of frequency, effect mediators, and mitigators (JAMIA, 2012)](https://academic.oup.com/jamia/article/19/1/121/732254)\n- [Neil Perry, Megha Srivastava, Deepak Kumar, Dan Boneh: Do Users Write More Insecure Code with AI Assistants? (arXiv, 2022)](https://arxiv.org/abs/2211.03622)"},{"locale":"de","translation_key":"gut-genug-modelle","slug":"gut-genug-modelle","title":"Gut genug: das Modell ist selten der Engpass","summary":"Bei den Alltagsaufgaben, die ich selbst mit KI bearbeite, ist die Modellwahl selten der erste Engpass. Aufgabenzuschnitt, Kontext und Prüfung wirken meist stärker.","tags":["Software","KI","Methodik"],"published_at":"2025-12-09T11:00:00+00:00","updated_at":"2026-07-14T20:56:33.58758+00:00","url":"https://www.mikebild.dev/de/blog/gut-genug-modelle/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/28d2f099078753ccde0ebc93fdf0571b346426172c2849fc5025b3f0ef956a30.mp3","audio_duration_secs":571,"text":"*Teil 2 der Serie „Von der Session zum System“ – hier geht es [zum Auftakt](https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/).*\n\nEnde November, ein Architektur-Review mit einem Team, das ich begleite, zweiter Tag, erste Kaffeepause. Ein Entwickler kommt mit der Tasse in der Hand zu mir und stellt die Frage, die seit zwei Jahren in jedem Teamgespräch und jedem Flurgespräch auf Konferenzen fällt: „Welches Modell nehmt ihr denn?“ Diesmal mit besonderem Nachdruck, denn der November 2025 war verrückt: GPT-5.1 am 12., Grok 4.1 am 17., Gemini 3 am 18., Claude Opus 4.5 am 24. Vier Flaggschiff-Ankündigungen in zwölf Tagen, dazu die üblichen Benchmark-Screenshots, die durch die Timelines wandern. Sein Team, erzählt er, diskutiert seit Wochen, ob man wechseln müsse.\n\nIch habe diese Frage früher ernsthaft beantwortet, mit Modellnamen und Begründung. Jede dieser Antworten war nach sechs Wochen veraltet. Inzwischen antworte ich anders: „Das ist die zweite Frage. Lass uns über die erste reden.“\n\n## Die Konvergenz, über die niemand gern spricht\n\nNüchtern und ohne Anbieter-Loyalität betrachtet: Bei dem großen Block an Alltagsaufgaben, für den ich KI einsetze, lagen die großen Modelle Ende 2025 in meinen eigenen Versuchen nah genug beieinander. Code lesen und erklären, ein Refactoring vorschlagen, Tests entwerfen, ein Konzeptpapier gegenlesen, eine API-Dokumentation zusammenfassen, einen Migrationspfad skizzieren – das bekam ich mit GPT-5, Claude Sonnet 4.5 und Gemini in brauchbarer Qualität hin. Nicht gleich gut in jedem einzelnen Lauf, aber gut genug, dass die Modellwahl selten meine erste Baustelle war.\n\nNatürlich sind sie nicht identisch. Jedes Modell hat einen eigenen Ton, eigene Vorlieben, eigene Schwächen, und bei einzelnen Aufgaben können die Unterschiede groß sein. Öffentliche Benchmarks helfen mir nur begrenzt, weil sie weder meinen Kontext noch meine Prüfkriterien abbilden und sich mit neuen Versionen schnell verschieben. Für eine Architekturentscheidung brauche ich deshalb Messungen an den eigenen Aufgaben statt eine allgemeine Rangliste.\n\nDas erzähle ich in solchen Runden ungern als Erster, weil es die Diskussion abkühlt, auf die sich alle gefreut haben. Der Modellvergleich ist unterhaltsam, er fühlt sich nach Ingenieursarbeit an, und er hat den Charme, dass man dabei nichts an der eigenen Arbeitsweise ändern muss. Aber er beantwortet die falsche Frage.\n\n## Das Rauschen im Alltag ist größer als der Unterschied zwischen Modellen\n\nWenn bei mir eine Session mit Claude oder ChatGPT schiefgeht, dann liegt das fast nie am Modell. Es liegt daran, dass ich die Aufgabe unklar gestellt habe. Dass das Modell den Kontext nicht kannte, der für die Lösung entscheidend war – die Architekturentscheidung von vor zwei Jahren, die ungeschriebene Konvention im Team, den Grund, warum dieser eine Service anders aufgebaut ist als alle anderen. Oder daran, dass ich das Ergebnis nicht geprüft habe und der Fehler erst im Review auffiel.\n\nEin Beispiel aus einem Teamgespräch in einem großen Konzern, anonymisiert wie immer: Zwei Kollegen, dasselbe Modell, dieselbe Aufgabe – ein Stück Legacy-Code verstehen und einen Umbau vorschlagen. Der eine bekam einen brauchbaren, konkreten Plan. Der andere bekam generischen Lehrbuch-Text. Der Unterschied war nicht das Modell, nicht einmal der Prompt im engeren Sinne. Der eine hatte dem Modell die relevanten Dateien, die Testfälle und die Randbedingungen mitgegeben. Der andere hatte eine Frage in ein leeres Fenster getippt.\n\nIn meinen eigenen Sessions schwankt das Ergebnis durch Aufgabenzuschnitt, Kontext und Prüfung oft stärker als durch den Wechsel zwischen den betrachteten Spitzenmodellen. Das ist keine allgemeine Messung des Marktes, sondern eine Beobachtung aus dieser Arbeit. Für mich folgt daraus: Bevor ich das Modell wechsle, prüfe ich zuerst, ob Aufgabe, Kontext und Abnahmekriterium sauber genug sind.\n\n## Wer auf das beste Modell wettet, wettet auf eine Commodity\n\nDamit zur These, die ich für die wichtigste dieses Beitrags halte: Wer seine Arbeitsweise oder gar sein Produkt auf „das beste Modell“ baut, wettet auf eine Commodity, die er nicht besitzt.\n\nDie Modelle gehören einer Handvoll Anbieter. Ich miete Zugriff über einen API-Schlüssel oder ein Abo, genau wie mein Wettbewerber, genau wie jedes andere Team. Ich kann nicht steuern, wann eine Version abgekündigt wird, wann sich das Verhalten nach einem Update leise verschiebt, wann der Preis fällt oder das nächste Modell die Rangliste umwirft. Der November hat das vorgeführt: Wer im Oktober seine Wahl auf einen Benchmark-Vorsprung gestützt hat, sah diesen Vorsprung innerhalb von zwei Wochen dreimal den Besitzer wechseln.\n\nWas ich dagegen besitzen kann, ist die Schicht um das Modell herum. Das ist keine Plattform und kein Produkt, sondern schlicht alles, was ich selbst in der Hand habe, bevor und nachdem das Modell rechnet:\n\n- der Zuschnitt der Aufgaben, also die Fähigkeit, Arbeit so zu zerlegen, dass ein Stück davon delegierbar wird\n- der Kontext, den eine Session am Anfang bekommt, statt dass das Modell meine Realität erraten muss\n- das Wissen des Teams in abrufbarer Form, von Konventionen bis zu den Gründen hinter alten Entscheidungen\n- der Prozess, der regelt, wann die KI arbeitet, wann ein Mensch prüft und was in den Main-Branch darf\n- die Prüfung selbst, also verlässliche Wege festzustellen, ob ein Ergebnis stimmt, bevor es etwas bewirkt\n\nDiese Schicht ist das Gegenteil einer Commodity. Sie ist spezifisch für mein Team, meine Codebasis, meine Domäne. Niemand kann sie mir durch ein Release wegnehmen, und der Wettbewerber kann sie nicht einfach mitmieten. Vor allem aber: Sie überlebt Modellwechsel. Eine Stunde, die ich in bessere Aufgabenbeschreibungen, in eine gepflegte CLAUDE.md oder AGENTS.md, in Review-Kriterien investiere, zahlt sich auch mit dem übernächsten Modell noch aus. Eine Stunde Benchmark-Studium ist beim nächsten Release entwertet.\n\nEs gibt einen angenehmen Side Effect, den ich aus der Architektur-Arbeit kenne: Wer die Schicht besitzt, für den sinken die Wechselkosten. Wenn Aufgabenzuschnitt, Kontext und Prüfung sauber stehen, ist das Modell dahinter austauschbar wie eine Abhängigkeit hinter einer klaren Schnittstelle. Dann kann ich sogar gelassen wechseln, wenn es einen echten Grund gibt – weil mein eigentliches Kapital nicht am Modellnamen hängt.\n\n## Wo die Modellwahl doch zählt\n\nEhrlichkeit gehört dazu, sonst wird aus der These ein Dogma. Es gibt Situationen, in denen die Modellwahl eine echte, messbare Rolle spielt. Drei begegnen mir regelmäßig.\n\nErstens die Spezialfälle. Wer mit exotischen Sprachen oder Nischen-Frameworks arbeitet, stark multimodale Aufgaben hat oder aus Datenschutzgründen on-premises bleiben muss, landet schnell bei kleineren offenen Modellen – und dort sind die Qualitätsunterschiede real und die Abwägungen andere. „Gut genug“ gilt für die großen Frontier-Modelle bei Alltagsaufgaben, nicht für jede Modellklasse bei jeder Aufgabe.\n\nZweitens Kosten und Latenz. Sobald Modelle nicht mehr interaktiv, sondern in Volumen laufen – Klassifikation in einer Pipeline, Autovervollständigung im Editor, Verarbeitung tausender Dokumente –, werden Preis pro Token und Antwortzeit zu harten Kriterien. Da liegen zwischen den Modellen Faktoren, nicht Prozentpunkte, und es lohnt sich zu messen.\n\nDrittens lange, agentische Aufgaben. Hier trennen sich die Modelle Ende 2025 tatsächlich noch spürbar: wie lange sie an einer mehrstufigen Aufgabe fokussiert bleiben, wie zuverlässig sie Tools bedienen, wie sie mit eigenen Fehlern umgehen. Nicht zufällig wurden Claude Sonnet 4.5 im September und Opus 4.5 im November genau über diese Fähigkeit beworben. Wer ganze Arbeitspakete delegiert statt einzelner Fragen, darf bei der Modellwahl wählerisch sein.\n\nAber – und das ist mir wichtiger als die drei Ausnahmen selbst – all das ist die zweite Frage. Sie lässt sich erst dann seriös beantworten, wenn die erste beantwortet ist. Ohne klaren Aufgabenzuschnitt und ohne verlässliche Prüfung kann ich Modelle nämlich gar nicht vergleichen; ich vergleiche dann nur Bauchgefühle an unterschiedlichen Tagen. Erst wenn die Schicht steht, wird die Modellwahl zu dem, was sie sein sollte: eine Optimierung mit Messwerten, ungefähr so aufregend wie die Wahl eines Datenbank-Index. Und wie dort gilt: gelegentlich neu bewerten, Versionen bewusst festhalten, Verhaltensänderungen nach Updates ernst nehmen. „Gut genug“ heißt weder „alle gleich“ noch „für immer“ – es heißt nur: nicht der Engpass.\n\n## Die erste Frage\n\nZurück in die Kaffeepause. Bleibt bei dem Modell, das ihr habt, habe ich ihm gesagt, und steckt die Diskussionsenergie eures Teams in die Fragen davor und danach. Woran erkennt ihr, dass ein Ergebnis stimmt? Was müsste eine Session über euer System wissen, um nicht zu raten? Welche eurer Aufgaben sind überhaupt so geschnitten, dass man sie abgeben kann? Wer diese drei Fragen gut beantwortet, holt aus jedem der aktuellen Modelle mehr heraus als der Nachbar mit dem Benchmark-Sieger und leerem Kontextfenster.\n\nEr war sichtlich unzufrieden – die Antwort ist weniger spektakulär als ein Modellvergleich, und sie macht Arbeit. Aber sie hat eine Konsequenz, die mich seither beschäftigt und die den Rest dieser Serie trägt: Wenn das Modell selten der Engpass ist, dann macht irgendetwas anderes den Unterschied zwischen der Session, die liefert, und der, die Zeit verbrennt. Bei mir läuft es jedes Mal auf die Umgebung hinaus, in der das Modell arbeitet – wie viel sie ihm zeigt, was sie ihm erlaubt und wogegen sie seine Ergebnisse hält. Genau dort geht es in der nächsten Folge weiter.\n\n## Weiterführende Quellen\n\n- [Anthropic: Introducing Claude Opus 4.5](https://www.anthropic.com/news/claude-opus-4-5)\n- [Google: Gemini 3 – das bislang leistungsfähigste Modell von Google](https://blog.google/products/gemini/gemini-3/)\n- [Simon Willison: Claude Sonnet 4.5 is probably the best coding model in the world (at least for now)](https://simonwillison.net/2025/Sep/29/claude-sonnet-4-5/)\n- [Anthropic Engineering: Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents)"},{"locale":"de","translation_key":"von-der-session-zum-system-auftakt","slug":"von-der-session-zum-system-auftakt","title":"Vom Werkzeug zur Arbeitsweise","summary":"Wie ein Gespräch in Berlin mich nach über dreißig Jahren Softwarehandwerk zum täglichen Arbeiten mit Claude, ChatGPT und Claude Code gebracht hat – und warum ich meiner Begeisterung trotzdem erst einmal misstraue.","tags":["Software","KI","Methodik"],"published_at":"2025-11-18T11:00:00+00:00","updated_at":"2026-07-14T20:54:48.643736+00:00","url":"https://www.mikebild.dev/de/blog/von-der-session-zum-system-auftakt/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/fd5beb8418445d1ea6ac4d2781f0b463829f64a864e1ab948f305ad7d91fe5e5.mp3","audio_duration_secs":697,"text":"*Auftakt der Serie „Von der Session zum System“.*\n\nVor einiger Zeit saß ich in Berlin mit [Sebastian Korfmann](https://skorfmann.com/) zusammen. Sebastian kenne ich als Software-Engineer aus dem Cloud- und Infrastruktur-Umfeld – jemand, der Werkzeuge nicht nach Marketing-Folien beurteilt, sondern danach, ob sie ihm im Alltag Arbeit abnehmen. Er erzählte von seinen Erfahrungen mit KI-Werkzeugen: was er damit baut, wie sich seine Arbeit verändert hat, wo es hakt. Ich habe interessiert zugehört – und dabei gemerkt, dass ich selbst erstaunlich wenig beisteuern konnte.\n\nDas muss ich erklären. Ich arbeite seit über dreißig Jahren an Software, einen großen Teil davon an verteilten Systemen – Node, TypeScript, GraphQL, Cloud-Architekturen – und habe über viele Jahre Training für Softwareentwickler und Architekten gegeben. Was mich an dieser Arbeit am meisten reizt: digitale Produkte zu bauen, und zwar ganzheitlich. Die Fachdomäne wirklich verstehen, Richtungsentscheidungen treffen, gestalten – es geht mir schon lange nicht mehr nur um Programmierung und Architektur. Mit den Jahren haben sich auch meine Schwerpunkte verschoben: weg davon, jedes feine Detail selbst in der Hand zu haben, hin zu Struktur, Konsistenz, Prozessen, Produktivität, Methoden und Konzepten. Mit KI hatte ich bis dahin trotzdem noch nie gearbeitet. Keine einzige Session, kein Copilot. Nicht aus Ablehnung – grundsätzliche Skepsis gegenüber neuer Technik ist nicht meine Art. Es hatte sich schlicht nie ergeben. Der Rummel seit dem ChatGPT-Start Ende 2022 war zwar nicht zu überhören – Schlagzeilen, Konferenz-Keynotes, Kollegen, die davon erzählten –, aber was ich hörte und las, klang für mich nach beeindruckenden Demos, und meine Tage waren voll. Wenn überhaupt, war ich ein bisschen zurückhaltend – so, wie man eben zurückhaltend ist bei Dingen, die man noch nicht selbst ausprobiert hat.\n\nDazu kam noch etwas anderes, und darüber rede ich nicht so gern, weil es nichts mit Technik zu tun hat, sondern mit mir. Ich war müde geworden. Nicht am Beruf, sondern an einer bestimmten Sorte Vorhaben: eigene, größere Projekte, digitale Produkte, die ich lange im Kopf hatte. Ich kenne die Komplexität solcher Vorhaben gut genug, um zu wissen: Viele dieser Themen kann ich allein nicht in der Qualität umsetzen, die ich selbst erwarte. Die Ideen waren da, teils detailliert ausgearbeitet, in Notizen und halb angefangenen Repositories. Was fehlte, war die Kraft für die schiere Menge an Umsetzungsarbeit – neben Anstellung und allem anderen. Wer einmal versucht hat, ein komplettes Produkt allein zu bauen, kennt das Verhältnis: Auf eine Stunde, in der man wirklich gestaltet – eine Richtungsentscheidung, ein Konzept, ein Stück Fachlichkeit –, kommen zwanzig Stunden Fleißarbeit. Boilerplate, Konfiguration, Formulare, Error Handling, Deployment, Dokumentation, dazu das ganze Organisatorische drumherum. Irgendwann habe ich aufgehört, neue Schubladen aufzumachen, weil die alten schon voll waren.\n\nIn dieser Verfassung traf ich also Sebastian. Was mich an dem Gespräch gepackt hat, war seine Art zu erzählen: keine Superlative, keine „das verändert alles“-Rhetorik, sondern die nüchterne Art, in der man einem Kollegen von einem Werkzeug berichtet, das sich im Alltag bewährt hat. Diese Tonlage kannte ich, und sie machte mich neugierig. Also habe ich mir vorgenommen, das Ganze endlich selbst auszuprobieren. Nicht zehn Minuten, sondern ein paar Tage, an echten Aufgaben.\n\n## Die ersten Tage\n\nIch habe mit Claude und ChatGPT angefangen, im Browser, an Aufgaben aus meinem tatsächlichen Alltag: ein Architekturkonzept gegenlesen, eine API-Migration skizzieren, einen Datenimport schreiben, den ich sonst vor mir hergeschoben hätte. Kurz darauf kamen Claude Code und Codex dazu – also die Werkzeuge, die nicht nur antworten, sondern im Terminal direkt am Repository arbeiten: Dateien lesen, ändern, Tests laufen lassen. Anthropic hatte Ende September Claude Sonnet 4.5 veröffentlicht, OpenAI etwa zeitgleich sein Codex-Update; ich bin, ohne es zu planen, in einem ziemlich guten Moment eingestiegen.\n\nUnd dann passierte etwas, womit ich nicht gerechnet hatte: Ich war binnen Tagen sehr angetan. Nicht milde interessiert – angetan. Drei Dinge haben mich erwischt:\n\n- Die Geschwindigkeit. Aufgaben, für die ich einen halben Tag angesetzt hätte, waren in einer Stunde in einem Zustand, den ich ernsthaft reviewen konnte.\n- Die Produktivität über den ganzen Tag. Nicht ein einzelner beeindruckender Moment, sondern die Summe: Es blieb abends messbar mehr fertig liegen als vorher.\n- Die Qualität. Das hatte ich am wenigsten erwartet. Der erzeugte Code war nicht fehlerfrei, aber deutlich besser, als ich es nach allem, was ich über generierten Code gehört und gelesen hatte, erwartet hätte – strukturiert, mit sinnvoller Error Handling, oft mit Tests.\n\nAus den paar Tagen Probe wurden Wochen täglicher Arbeit. Inzwischen arbeite ich jeden Tag mit diesen Werkzeugen und steige immer tiefer ein – gerade erst hat Anthropic mit den Skills eine Möglichkeit nachgelegt, Claude wiederverwendbare Arbeitsanweisungen mitzugeben, und ich merke, dass ich anfange, solche Ankündigungen zu lesen wie früher Release-Notes von Node.\n\nEin paar Wochen sind keine Erfahrung. Das ist mir bewusst, und genau deshalb schreibe ich das hier auf. Wer so schnell zum täglichen Nutzer wird, sollte der eigenen Begeisterung erst einmal misstrauen – frische Begeisterung ist ein schlechter Zeuge. Also versuche ich, genau hinzuschauen und zu notieren, was ich tatsächlich beobachte – mit dem einzigen Prüfstein, den ich habe: über dreißig Jahre Handwerk, an denen ich jedes Ergebnis messen kann.\n\n## Beobachtung eins: Erzeugen wird billig, Prüfen wird der Engpass\n\nDie erste Verschiebung habe ich schon nach wenigen Tagen bemerkt, und sie ist fundamentaler, als sie klingt. Der teure Teil meiner Arbeit war immer das Erzeugen: Code schreiben, Dokumente formulieren, Konzepte ausarbeiten. Das Prüfen – Reviews, Gegenlesen, Abnahme – war der kleinere Posten. Dieses Verhältnis kippt gerade. Erzeugen ist plötzlich billig; in einer Stunde entsteht mehr Text und Code, als ich früher an einem Tag geschafft hätte. Was nicht billiger geworden ist: beurteilen, ob das Erzeugte stimmt. Meine Arbeit verlagert sich sichtbar vom Schreiben zum Lesen, vom Produzieren zum Begutachten.\n\nIm Gespräch mit einem Kollegen habe ich dafür eine Formulierung gefunden, die hängen geblieben ist: Das Werkzeug ist weniger Assistent, mehr Sekretär. Ein Assistent, wie ihn die Produktnamen versprechen, ergänzt hier eine Zeile und schlägt dort ein Wort vor – die Arbeit bleibt meine. Ein Sekretär im alten Sinn nimmt ganze Vorgänge entgegen: Ich diktiere die Absicht, er fertigt das Schriftstück, und ich zeichne ab. Das klingt bequemer, ist aber eine andere Verantwortung. Beim Assistenten prüfe ich Vorschläge im Vorbeigehen; beim Sekretär muss ich das fertige Stück wirklich lesen, denn meine Unterschrift steht darunter. Wer abzeichnet, ohne zu lesen, hat nicht delegiert, sondern kapituliert. Ich ahne, dass in dieser Verschiebung der eigentliche Umbau meiner Arbeitsweise steckt – nicht im Werkzeug selbst.\n\n## Beobachtung zwei: Die Schubladen gehen wieder auf\n\nDie zweite Beobachtung ist persönlicher, und sie hat mich mehr überrascht als jede Benchmark. Die Müdigkeit, von der ich oben geschrieben habe, ist nicht weg – aber sie hat ihren Grund verloren. Die Produktideen, die liegen geblieben sind, weil die Umsetzung für einen Einzelnen zu groß war, sind plötzlich wieder in Reichweite. Nicht, weil die KI das Produkt baut. Sondern weil sie genau den Teil übernimmt, der mich zermürbt hat: die zwanzig Stunden Fleißarbeit rund um die eine Stunde, die wirklich Nachdenken verlangt. Das Formular-Grundgerüst, die Testabdeckung, der Import-Adapter, das Deployment-Skript – all das entsteht jetzt so schnell, dass ich – wie sagt man so schön – das Eisen schmieden kann, solange es heiß ist.\n\nVielleicht hat mich das Ganze auch deshalb so schnell für sich eingenommen: Meine Schwerpunkte hatten sich über die Jahre ohnehin genau dorthin verschoben, wo diese Werkzeuge nichts wegnehmen – Struktur, Konsistenz, Konzepte, die Fachdomäne, die Richtungsentscheidungen. Die Detailarbeit dagegen und die wiederkehrenden Aufgaben, auch die organisatorischen, gehen mir jetzt wieder leichter von der Hand. Nicht alle. Aber genug, dass es wieder Spaß macht.\n\nIch habe in den letzten Wochen abends wieder an eigenen Sachen gebaut, freiwillig und mit einer Freude, die ich eine Weile nicht hatte. Das ist die Stelle, an der ich vorsichtig formulieren muss, weil sie sich so leicht zur Heilsbotschaft aufblasen lässt. Also nüchtern: KI ist für mich gerade vor allem ein Hebel für den Einzelnen mit Erfahrung. Die Betonung liegt auf beidem. Der Hebel wirkt, weil ich nach dreißig Jahren weiß, was ich bauen will, wie es geschnitten sein muss und woran ich erkenne, dass ein Ergebnis taugt. Ob derselbe Hebel auch für jemanden wirkt, der diese Urteilsfähigkeit noch nicht hat, weiß ich schlicht nicht – ich habe da einen Verdacht, aber Verdacht ist kein Wissen, und für diese Serie will ich beides sauber auseinanderhalten.\n\n## Beobachtung drei: Der Ton stimmt immer\n\nDie dritte Beobachtung halte ich nur kurz fest, denn ich verstehe sie noch nicht gut genug, um mehr daraus zu machen. Mir fällt auf, *wie* diese Systeme antworten. Im Berufsleben gibt es dafür ein augenzwinkerndes Kürzel: SABTA – sicheres Auftreten bei totaler Ahnungslosigkeit. Die Psychologie kennt das Muster als Dunning-Kruger-Effekt: Am selbstbewusstesten tritt oft auf, wer am wenigsten weiß. Genau so wirken diese Systeme auf mich – die richtige Auskunft und die falsche kommen im selben ruhigen, kompetenten Ton. In einem Code-Review verrät sich ein unsicherer Kollege durch Formulierungen – „ich glaube“, „müsste eigentlich“. Hier gibt es dieses Signal nicht. Zweimal in den vergangenen Wochen hätte ich beinahe eine Behauptung übernommen, die sich bei der Prüfung als frei erfunden herausstellte – eine API-Signatur, die es nie gab, souverän vorgetragen. Beide Male hat mich nur die Gewohnheit gerettet, Dinge nachzuschlagen. Dieses sichere Auftreten verdient ein grundsätzliches Misstrauen, und ich will verstehen, woher es kommt – strukturell, nicht anekdotisch. Das hebe ich mir für später in dieser Serie auf, wenn die Beobachtungen dafür beisammen sind.\n\n## Was diese Serie werden soll\n\nIch beginne hier eine Serie, weil ich ahne, dass die Geschichte größer ist als mein Schreibtisch. Im Moment beobachte ich mich selbst: einen Einzelnen in der Session, mit direkter Kontrolle über jedes Ergebnis. Aber ich arbeite nicht allein – ich arbeite in und mit Teams, und ein Team ist etwas anderes als die Summe einzelner Sessions. Und über den Teams stehen Unternehmen mit ihren Prozessen, ihrem Wissen, ihrer Verantwortung. Diesen Bogen will ich in den kommenden Folgen Schritt für Schritt durchgehen: vom Ich über das Wir zum System. Nicht als Theorie, sondern entlang dessen, was ich tatsächlich erlebe und ausprobiere – inklusive der Sackgassen, von denen es absehbar einige geben wird.\n\nDie nächste Frage drängt sich dabei schon auf. Im Team, mittags unter Kollegen, zuletzt auf einem Konferenzflur: Das Gespräch landet nach wenigen Minuten an derselben Stelle. Welches Modell ist das beste? Claude oder GPT, welche Version, welche Benchmark. Ich habe diese Diskussion selbst geführt und dabei ein Unbehagen entwickelt, das ich erst allmählich einordnen kann: Nach diesen ersten Wochen täglicher Arbeit fällt mir auf, dass die Wahl des Modells meine Ergebnisse weniger verändert hat als so ziemlich alles andere an meiner Arbeitsweise. Alle reden über das beste Modell – aber ist das überhaupt die richtige Frage? Der gehe ich in der nächsten Folge nach.\n\n## Weiterführende Quellen\n\n- [Introducing Claude Sonnet 4.5](https://www.anthropic.com/news/claude-sonnet-4-5) – Anthropics Ankündigung des Modells, mit dem ich eingestiegen bin (September 2025)\n- [Claude Sonnet 4.5 is probably the „best coding model in the world“](https://simonwillison.net/2025/Sep/29/claude-sonnet-4-5/) – Simon Willisons nüchterne Ersteinschätzung\n- [Introducing upgrades to Codex](https://openai.com/index/introducing-upgrades-to-codex/) – OpenAIs Codex-Update mit GPT-5-Codex (September 2025)\n- [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills) – Anthropics Engineering-Beitrag zu Skills (Oktober 2025)"},{"locale":"de","translation_key":"react-ueberblick-von-jsx-zur-architektur","slug":"react-ueberblick-von-jsx-zur-architektur","title":"React-Überblick: Von JSX zur Komponentenarchitektur","summary":"Ein kompletter Durchgang durch React, wie ich es heute unterrichte – vom deklarativen Rendern über die Frage, wem ein State gehört, bis zur Architektur einer wachsenden Anwendung. Die Details zu einzelnen Stationen kommen später als eigene Beiträge.","tags":["Software","Frontend","React"],"published_at":"2024-12-30T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/react-ueberblick-von-jsx-zur-architektur/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/38edf579e81db16b717a5fea322df073216fd1ee50c4909af7cec8b15f79f10c/react-ueberblick-von-jsx-zur-architektur-vorlesen.mp3","audio_duration_secs":1174,"text":"# React-Überblick: Von JSX zur Komponentenarchitektur\n\nReact nimmt einem das Rendern ab, nicht die Architektur. Die Bibliothek berechnet aus einem State eine Oberfläche und schreibt die Unterschiede ins DOM – aber wo dieser State liegt, wie lange er lebt und wer ihn ändern darf, entscheidet sie an keiner Stelle. Genau dort, an dieser unscheinbaren Grenze, entstehen die Probleme, die sich später mit keinem Hook und keiner Bibliothek mehr wegräumen lassen.\n\nDieser Beitrag geht React deshalb einmal am Stück durch – vom ersten Stück JSX bis zu der Stelle, an der aus einzelnen Komponenten ein System wird. Es ist bewusst ein Überblick. Zu den meisten Stationen, die ich hier nur kurz betrete, folgen später eigene Beiträge, die tiefer graben. Heute geht es darum, den großen Bogen im Kopf zu haben, bevor man sich in ein Detail verliert.\n\nIch stütze mich dabei auf zwei Repositories, die ich gerade zusammenführe: `introduction-react` für die Grundlagen und `advanced-react` für die fortgeschrittenen Muster. Beide sind kein Foliensatz in Textform, sondern lauffähiger Code, an dem wir gemeinsam üben. Der Stand, den ich hier beschreibe, ist React 19 – die stabile Version von Ende 2024, mit allem, was seither zum Alltag geworden ist.\n\n## Das mentale Modell: die Oberfläche ist eine Funktion des States\n\nBevor eine einzige Zeile JSX Sinn ergibt, muss ein Gedanke sitzen. React dreht die Art um, wie man über eine Oberfläche nachdenkt. Statt Schritt für Schritt zu beschreiben, wie sich das DOM verändern soll – hier ein Element einfügen, dort ein Attribut ändern, da einen Knoten entfernen –, beschreibt man nur, wie die Oberfläche für einen gegebenen State aussehen soll. React kümmert sich um den Weg dorthin.\n\nMan kann das in eine einzige Zeile fassen, die den ganzen Rest trägt: Die Oberfläche ist eine Funktion des States. Ändert sich der State, ruft React die Funktion erneut auf, vergleicht das Ergebnis mit dem vorherigen und schreibt nur die tatsächlichen Unterschiede ins echte DOM. Dieser Abgleich läuft über eine interne, leichtgewichtige Repräsentation des Baums, oft Virtual DOM genannt. Der Name ist weniger wichtig als die Konsequenz: Man beschreibt das Ziel, nicht den Weg. Wie dieser Abgleich Schritt für Schritt abläuft, zeige ich ausführlich im Beitrag [Wie React den Baum rendert und aktualisiert](https://www.mikebild.dev/de/blog/wie-react-den-baum-rendert-und-aktualisiert/).\n\n```mermaid\nflowchart LR\n  State[\"Zustand (state)\"] --> Render[\"Komponente rendert\"]\n  Render --> View[\"beschriebene Oberfläche\"]\n  View --> DOM[\"React gleicht ab und schreibt ins DOM\"]\n  User[\"Nutzerinteraktion\"] --> Event[\"Event / setState\"]\n  Event --> State\n```\n\nDer zweite tragende Gedanke ist der unidirektionale Datenfluss. Daten fließen von oben nach unten, von der Elternkomponente zum Kind, über Props. Events fließen in die andere Richtung, als Callbacks nach oben. Es gibt keine geheimnisvolle Zweiwegbindung, bei der ein Eingabefeld und eine Variable magisch synchron bleiben. Das wirkt am Anfang umständlicher als in älteren Frameworks, aber es ist der Grund, warum sich React-Anwendungen auch nach zwei Jahren noch erklären lassen: Man kann für jede Stelle der Oberfläche sagen, woher ihre Daten kommen und wer sie ändern darf.\n\n## JSX und Komponenten: die kleinste Einheit ist eine Funktion\n\nJSX sieht aus wie HTML im JavaScript, ist aber nur eine bequeme Schreibweise für Funktionsaufrufe. Ein `<button>` wird zu einem Aufruf, der ein Objekt beschreibt, kein DOM-Element erzeugt. Deshalb kann man mitten im JSX rechnen, Listen abbilden und bedingt rendern – es ist ja alles nur JavaScript:\n\n```jsx\nfunction InvoiceList({ invoices }) {\n  if (invoices.length === 0) return <p>No invoices.</p>;\n\n  return (\n    <ul>\n      {invoices.map((i) => (\n        <li key={i.id}>\n          {i.number} - {i.paid ? \"paid\" : \"open\"}\n        </li>\n      ))}\n    </ul>\n  );\n}\n```\n\nDrei Details in diesem kleinen Beispiel sind in Wahrheit Architekturthemen. Das `key`-Attribut ist kein kosmetisches Detail, sondern die Information, an der React beim erneuten Rendern erkennt, welches Listenelement welchem entspricht. Das bedingte Rendern mit `?` oder mit einem frühen `return` ist die Stelle, an der Lade-, Fehler- und Leerzustände sichtbar werden – genau die States, die im Demo-Modus gern unterschlagen werden und im Betrieb dann fehlen. Und `props` ist eine schreibgeschützte Schnittstelle: Eine Komponente bekommt ihre Daten von außen und darf sie nicht verändern. Das macht Komponenten zu Bausteinen, deren Verhalten man von außen versteht. Die genauen Regeln von JSX – was Ausdruck ist, was beim Rendern verschwindet, wie Keys wirklich funktionieren – behandle ich im Detail im Beitrag [JSX genau: Die Regeln hinter dem Markup](https://www.mikebild.dev/de/blog/jsx-genau-die-regeln-hinter-dem-markup/).\n\nDer Standard ist heute die Functional Component. Sie ist eine Funktion, die Props entgegennimmt und JSX zurückgibt, und mit Hooks kann sie inzwischen alles, wofür man früher Klassen brauchte. Klassenkomponenten mit `render`-Methode und Lifecycle-Methoden wie `componentDidMount` existieren noch, und man trifft sie in älterem Code. Wer sie in einem gewachsenen Projekt vor sich hat, muss nicht erschrecken – sie sind eine historische Schicht, mehr nicht. Aber neuer Code entsteht mit Funktionen. Das ist keine Frage der Mode, sondern eine echte Vereinfachung: Ein Effect, der beim Einhängen und beim Aushängen etwas tun soll, war früher über zwei getrennte Lifecycle-Methoden verstreut. Heute steht er an einer Stelle.\n\nKomposition ersetzt Vererbung. Statt eine Basiskomponente zu erweitern, steckt man Komponenten ineinander und reicht Inhalt über `children` durch:\n\n```jsx\nfunction Card({ title, children }) {\n  return (\n    <section className=\"card\">\n      <h2>{title}</h2>\n      {children}\n    </section>\n  );\n}\n```\n\nEine solche `Card` weiß nichts über ihren Inhalt und ist gerade deshalb überall verwendbar. Wer diesen Reflex verinnerlicht – lieber zusammenstecken als vererben –, schreibt fast automatisch entkoppelte Oberflächen.\n\n## State ist kein Ort\n\nJetzt kommt die Frage vom Anfang, und sie ist die wichtigste im ganzen Beitrag. State ist kein Ort im Code, sondern eine Entscheidung über Besitz, Lebensdauer und Synchronisation. Bevor man `useState` schreibt, sollte man wissen, wem dieser State eigentlich gehört.\n\nDer lokale Fall ist der einfachste. Ein Zähler, ein aufgeklapptes Menü, der Text in einem Eingabefeld – solcher State gehört in die Komponente, die ihn anzeigt:\n\n```jsx\nimport { useState } from \"react\";\n\nfunction Counter({ start = 0 }) {\n  const [count, setCount] = useState(start);\n  return <button onClick={() => setCount((n) => n + 1)}>{count}</button>;\n}\n```\n\nDie Regel, die React an dieser Stelle einfordert, heißt: Komponenten rein halten. Für dieselben Eingaben soll dieselbe Ausgabe herauskommen. Der State wird nicht direkt verändert, sondern über die Setter-Function ersetzt, und React entscheidet, wann neu gerendert wird. Wer das ernst nimmt, bekommt Komponenten, die man ohne laufenden Browser im Kopf durchspielen kann.\n\nInteressant wird es, sobald ein State nicht mehr in eine einzelne Komponente passt. Dann muss man ehrlich beantworten, wo er hingehört, und die Antwort ist selten „in einen globalen Store“. Ich unterscheide vier Orte, und die Wahl zwischen ihnen ist die eigentliche Architekturarbeit im Frontend:\n\n```mermaid\nflowchart TB\n  Frage[\"Wem gehört dieser Zustand?\"]\n  Frage --> Lokal[\"Komponente<br/>(useState) – UI-Detail\"]\n  Frage --> URL[\"URL<br/>Filter, Seite, ausgewähltes Objekt\"]\n  Frage --> Server[\"Server-Cache<br/>geladene Daten, die dem Backend gehören\"]\n  Frage --> Global[\"globaler Store<br/>app-weite, geteilte Entscheidungen\"]\n```\n\nVieles, was Teams reflexhaft in einen globalen Store legen, gehört eigentlich in die URL – welcher Filter aktiv ist, welche Seite angezeigt wird, welches Objekt ausgewählt ist. In der URL ist dieser State teilbar, mit einem Lesezeichen speicherbar und überlebt einen Reload. Und ein großer Teil dessen, was wie Anwendungszustand aussieht, ist in Wahrheit gar keiner: Es sind Daten, die dem Server gehören und die man nur zwischengespeichert hat. Diese Unterscheidung zwischen echtem Client State und gecachten Serverdaten ist die folgenreichste im ganzen Frontend, und ich widme ihr einen eigenen Beitrag: [Client State vs. Server-Cache](https://www.mikebild.dev/de/blog/client-zustand-und-server-cache/).\n\n## Effects sind der Rand, nicht die Mitte\n\n`useEffect` ist der Hook, der in den Teams, mit denen ich gearbeitet habe, die meisten Missverständnisse produziert. Er synchronisiert eine Komponente mit etwas außerhalb von React – einem Netzwerkaufruf, einem Abonnement, dem Titel des Browsertabs, einem Timer. Der entscheidende Satz lautet: Ein Effect ist der Rand des Systems, nicht seine Mitte. Alles, was sich aus dem State berechnen lässt, gehört nicht in einen Effect, sondern direkt ins Rendern.\n\n```jsx\nimport { useState, useEffect } from \"react\";\n\nfunction useInvoice(id) {\n  const [data, setData] = useState(null);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    let active = true;\n    fetch(`/api/invoices/${id}`)\n      .then((r) => r.json())\n      .then((d) => active && setData(d))\n      .catch((e) => active && setError(e.message));\n    return () => {\n      active = false;\n    };\n  }, [id]);\n\n  return { data, error };\n}\n```\n\nZwei Dinge an diesem Beispiel sind die eigentliche Lektion. Das Abhängigkeits-Array `[id]` bestimmt, wann der Effect erneut läuft – vergisst man dort einen Wert, arbeitet die Komponente mit veralteten Daten weiter. Und die zurückgegebene Aufräumfunktion, die `active` auf `false` setzt, verhindert, dass eine spät eintreffende Antwort einen bereits ausgehängten oder inzwischen überholten State überschreibt. Genau dieser Wettlauf zwischen zwei Anfragen ist der Fehler, der im Test mit schnellen Antworten nie auftritt und erst im Betrieb mit langsamem Netz zuschlägt.\n\nIch habe die Logik hier bewusst in einen eigenen Custom Hook `useInvoice` gezogen. Damit sind wir schon beim heutigen Weg, Logik wiederzuverwenden – dazu gleich mehr. Wichtig ist an dieser Stelle nur die Haltung: Effects begrenzen, nicht häufen. Ein Frontend, in dem Datenladen, Ableitung, Synchronisation und Nutzerereignisse in einem einzigen Effektklumpen landen, ist fragil, weil niemand mehr sagen kann, warum welcher Effect wann läuft.\n\nDer häufigste Fehler, den ich in Code-Reviews sehe, ist genau der umgekehrte Reflex: einen Wert, der sich aus anderem State berechnen lässt, über einen Effect in einen zweiten State zu spiegeln. Wer den vollständigen Namen aus Vor- und Nachnamen per Effect in eine eigene Variable schreibt, hat sich zwei Quellen der Wahrheit gebaut, die auseinanderlaufen, sobald ein Rendern dazwischenkommt. Der berechnete Wert gehört nicht in einen Effect und auch nicht in einen zweiten `useState`, sondern schlicht ins Rendern, wo er bei jedem Durchlauf frisch entsteht. Was ableitbar ist, wird abgeleitet und nicht gespeichert – diese eine Regel erspart mehr Fehler als jede Bibliothek. Ein Effect ist erst dann berechtigt, wenn wirklich etwas außerhalb von React im Spiel ist.\n\nFür das Laden von Serverdaten muss man diesen Mechanismus in echten Projekten übrigens selten von Hand schreiben. In der Praxis übernimmt eine darauf spezialisierte Bibliothek das Caching, das erneute Laden und die Konsistenz. React 19 geht mit dem `use()`-Hook und Suspense noch einen Schritt weiter und erlaubt es, ein Promise direkt im Rendern abzuwarten, sodass Lade- und Fehlerzustände weiter nach außen an eine umschließende `<Suspense>`-Komponente wandern. Dieses eigene große Thema behandle ich im Beitrag [Suspense und der use-Hook](https://www.mikebild.dev/de/blog/react-suspense-und-use/).\n\n## Von HOCs und Render Props zu Custom Hooks\n\nDie fortgeschrittenen React-Pattern, die im `advanced-react`-Material einen eigenen Block bilden, sind fast alle Antworten auf dieselbe Frage: Wie teile ich Logik zwischen Komponenten, ohne sie zu kopieren? Die Antwort hat sich über die Jahre verschoben, und dieser Wandel ist selbst lehrreich.\n\nFrüher gab es dafür zwei etablierte Muster. Eine Higher-Order Component ist eine Funktion, die eine Komponente entgegennimmt und eine erweiterte zurückgibt – ein Wrapper, der Verhalten hinzufügt. Render Props lösen dasselbe Problem, indem eine Komponente ihre Logik über eine Funktion als Kind nach außen gibt. Beide funktionieren, aber beide haben denselben Preis: Sie verschachteln den Komponentenbaum und machen aus einer flachen Idee eine tiefe Struktur.\n\n[Custom Hooks](https://www.mikebild.dev/de/blog/von-hocs-und-render-props-zu-custom-hooks/) lösen genau dieses Problem, ohne den Baum zu verschachteln. Ein Custom Hook ist einfach eine Funktion, deren Name mit `use` beginnt und die andere Hooks benutzt. Das `useInvoice` von oben ist bereits einer. Die Logik steht in einer normalen Funktion, wird von mehreren Komponenten aufgerufen und taucht im Baum überhaupt nicht auf:\n\n```jsx\nfunction InvoiceView({ id }) {\n  const { data, error } = useInvoice(id);\n  if (error) return <ErrorMessage text={error} />;\n  if (!data) return <LoadingIndicator />;\n  return <InvoiceDetails invoice={data} />;\n}\n```\n\nDieselbe Bewegung findet man beim Kontext. Reichen Daten über viele Ebenen durch, ohne sie durch jede Zwischenkomponente als Prop zu fädeln, ist das die Aufgabe von Context: ein Provider oben im Baum, ein `useContext` unten. Der wichtige Hinweis dabei: Context ist zum Verteilen gedacht, nicht als Ersatz für einen durchdachten State-Besitz. Wer jeden veränderlichen Wert in einen Context legt, verlagert das Kopplungsproblem nur eine Ebene höher. Auch das – Context als Verteilweg gegen Context als heimlicher globaler State – behandle ich im Beitrag [Context richtig einsetzen](https://www.mikebild.dev/de/blog/context-richtig-einsetzen/).\n\n## Wenn geteilter State wirklich global ist: Redux und die Alternativen\n\nManchmal ist State tatsächlich app-weit und wird von vielen, weit auseinanderliegenden Stellen gelesen und geändert. Für diesen Fall gibt es etablierte Werkzeuge, und Redux ist das bekannteste. Sein Kern ist erstaunlich klein: Der gesamte State liegt in einem Store, geändert wird er nur durch das Verschicken einer Action – einem einfachen Objekt mit einem `type` –, und ein Reducer ist eine Pure Function, die aus altem State und Action den neuen State berechnet.\n\n```js\nfunction invoicesReducer(state = [], action) {\n  switch (action.type) {\n    case \"invoice/paid\":\n      return state.map((i) =>\n        i.id === action.id ? { ...i, paid: true } : i\n      );\n    default:\n      return state;\n  }\n}\n```\n\nDer Reiz dieses Musters ist, dass jede State-Änderung ein benanntes, protokollierbares Event wird. Man kann die Abfolge der Actions nachvollziehen, aufzeichnen und im Test durchspielen. Der Preis ist eine gewisse Menge an Struktur. Mir sind in Projekten drei Arten begegnet, diese Struktur zu organisieren, und die Wahl entscheidet darüber, ob ein UI-System fachlich oder technisch wächst: den Rails-Stil mit getrennten Ordnern für Actions, Reducer und Container; den Domain-Stil, der stattdessen pro Feature bündelt; und das Ducks-Pattern, das Actions und Reducer einer Sache in eine Datei legt. Der Domain-Schnitt ist fast immer der bessere, weil er die Datei-Grenzen entlang der Fachlichkeit zieht und nicht entlang technischer Rollen.\n\nHeute schreibt kaum jemand Redux mehr von Hand so aus. Das offizielle Redux Toolkit nimmt einem den größten Teil der Wiederholung ab, und für viele Anwendungen reicht eine leichtere Bibliothek oder schlicht Context mit einem Reducer. Reaktive Ansätze wie MobX verfolgen dasselbe Ziel mit einem anderen Modell, bei dem sich abgeleitete Werte automatisch aktualisieren. Welches dieser Werkzeuge passt, hängt weniger von der Mode ab als von der ehrlichen Antwort auf die Besitzfrage von vorhin – dem widme ich den eigenen Vergleich [State-Management in React: Redux Toolkit, leichte Stores, MobX](https://www.mikebild.dev/de/blog/state-management-vergleich/).\n\nIch mache in Architektur-Diskussionen gern die Gegenprobe: Für wie viel des vermeintlich globalen States braucht man den Store wirklich? Meistens schrumpft die Liste dramatisch, sobald man die URL für Auswahl und Filter nutzt und geladene Serverdaten als das behandelt, was sie sind – Cache, nicht State. Übrig bleibt oft nur ein kleiner Kern echter, app-weiter Entscheidungen: die angemeldete Person, das gewählte Sprach- oder Theme-Setting, vielleicht ein Warenkorb. Für diesen Kern lohnt sich ein Store, für den Rest ist er Ballast. Ein globaler Store ist also nicht die Standardantwort, sondern die Ausnahme, die man begründen können muss.\n\n## Router, Server und die Ränder der Anwendung\n\nZwei Ränder fehlen noch. Der erste ist die Navigation. In einer Single-Page-Anwendung wechselt man nicht die Seite, sondern bildet URLs auf Komponenten ab. Der Router hält Adresszeile und angezeigte Komponente synchron, sodass Vor- und Zurück-Knopf, Lesezeichen und geteilte Links weiter funktionieren:\n\n```jsx\nimport { BrowserRouter, Routes, Route } from \"react-router-dom\";\n\nfunction App() {\n  return (\n    <BrowserRouter>\n      <Routes>\n        <Route path=\"/\" element={<Start />} />\n        <Route path=\"/invoices/:id\" element={<InvoiceView />} />\n        <Route path=\"*\" element={<NotFound />} />\n      </Routes>\n    </BrowserRouter>\n  );\n}\n```\n\nDer Router ist damit auch der natürliche Ort für den State, der in die URL gehört. Der Parameter `:id`, den man in der Komponente über `useParams` ausliest, ist genau das ausgewählte Objekt, über das ich weiter oben gesprochen habe – kein Grund, es zusätzlich in einem Store zu halten. Für neue Projekte empfiehlt React Router inzwischen die Data-Router-Variante mit `createBrowserRouter`, bei der Routen zusätzlich Lade- und Schreibfunktionen bekommen; das ist der modernere Weg, dem ich den Beitrag [React Router Data Router](https://www.mikebild.dev/de/blog/react-router-data-router/) widme.\n\nDer zweite Rand ist das Rendern auf dem Server. Für Startzeit, Suchmaschinen und schwache Geräte ist es oft sinnvoll, die erste Fassung der Seite auf dem Server zu erzeugen und im Browser nur noch lebendig zu machen. Frameworks wie Next.js nehmen einem diese Mechanik ab. React 19 hat das Thema mit den Server Components noch einmal grundlegend erweitert: Komponenten können auf dem Server laufen, dort Daten laden und nur ihr Ergebnis an den Browser schicken, während die Server Actions das Gegenstück für schreibende Vorgänge bilden. Das verschiebt die alte Grenze zwischen Client und Server spürbar, und es ist ein so großes Thema, dass ich ihm den Beitrag [React Server Components und Server Actions](https://www.mikebild.dev/de/blog/react-server-components-und-server-actions/) widme; hier steht es nur als Wegweiser.\n\n## Betrieb: Tests, Werkzeugkette, Typen\n\nEin Überblick, der beim Rendern aufhört, wäre unvollständig, denn all die Grenzen, die ich beschrieben habe – State-Besitz, Effect-Disziplin, Datenfluss –, lassen sich unbemerkt kaputtmachen, wenn niemand eine Erwartung daran festhält. Tests sind im Frontend keine Pflichtübung, sondern der Ort, an dem diese Erwartungen sichtbar bleiben.\n\nIch teste Komponenten heute mit Vitest und der React Testing Library, und deren Leitidee passt genau zur Architektur dieses Beitrags: Man prüft, was Nutzer sehen und tun, nicht wie die Komponente innen gebaut ist. Ein Test, der an das sichtbare Ergebnis gebunden ist, überlebt ein Refactoring; ein Test, der an Implementierungsdetails klebt, bricht bei jeder Umbenennung.\n\n```jsx\nimport { describe, it, expect } from \"vitest\";\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Counter } from \"./Counter\";\n\ndescribe(\"Counter\", () => {\n  it(\"counts up on click\", async () => {\n    render(<Counter start={0} />);\n    const button = screen.getByRole(\"button\", { name: \"0\" });\n    await userEvent.click(button);\n    expect(screen.getByRole(\"button\", { name: \"1\" })).toBeInTheDocument();\n  });\n});\n```\n\nDahinter steht dieselbe Testpyramide wie überall: viele schnelle Komponententests an der Basis, weniger Integrationstests in der Mitte, eine Handvoll Ende-zu-Ende-Tests mit einem Werkzeug wie Playwright an der Spitze. Wer diese Verteilung auf den Kopf stellt, bezahlt es später mit einer trägen Build-Pipeline.\n\nAuch die Werkzeugkette ist eine Architekturentscheidung, keine Geschmacksfrage. Ob ein Projekt mit Vite, Next.js, Parcel oder einer handgeschriebenen Webpack-Konfiguration startet, legt fest, wie schnell die Rückmeldung beim Entwickeln ist, wie einfach das Server-Rendern wird und wie viel man selbst wartet. Und über all dem liegt [TypeScript](https://www.mikebild.dev/de/blog/typescript-in-react/), das aus Props und State überprüfbare Verträge macht. Ein falsch getippter Prop wird dann nicht zum Laufzeitfehler beim Nutzer, sondern zum roten Kringel im Editor. Der React Compiler, den das React-Team als eigenes Projekt neben der Bibliothek entwickelt, nimmt einem schließlich einen Teil der manuellen Optimierung ab: Er analysiert Komponenten beim Bauen und merkt sich automatisch, was sich zwischen zwei Renderdurchläufen nicht geändert hat, sodass viele Aufrufe von `useMemo`, `useCallback` und `memo` überflüssig werden.\n\n## Das Repository ist selbst schon Architektur\n\nEin Blick zum Schluss noch auf die Struktur der Repositories selbst. `introduction-react` und `advanced-react` sind nicht ein großer Klumpen, sondern viele kleine, eigenständige Beispiele – eine Basis-App, eine Redux-App, eine Router-App, eine mit Server-Rendern, dazu die fortgeschrittenen Ordner für asynchrone Muster, funktionale Komposition und Struktur. Jedes Beispiel steht für sich und lässt sich einzeln starten.\n\nDass ich die beiden Repositories gerade zusammenlege, ist deshalb selbst eine kleine Architekturübung. Die Frage ist dieselbe wie bei jedem wachsenden System: Was darf geteilt werden, und was muss getrennt bleiben, damit eine Änderung an einer Stelle nicht überraschend an einer anderen etwas kaputt macht? Ein sauber geschnittenes Monorepo aus Grundlagen- und Fortgeschrittenen-Beispielen löst genau dieselbe Aufgabe wie eine Anwendung, die aus vielen Komponenten und Modulen besteht. Die Grenzen, die man zieht, sind an beiden Stellen die eigentliche Arbeit.\n\n```mermaid\nflowchart TB\n  Repo[\"React-Monorepo\"]\n  Repo --> Grund[\"Grundlagen<br/>JSX, Komponenten, Hooks, Router\"]\n  Repo --> Fort[\"Fortgeschritten<br/>async, funktional, Struktur\"]\n  Repo --> Geteilt[\"geteilte Bausteine<br/>UI-Komponenten, Testhilfen\"]\n  Grund --> Geteilt\n  Fort --> Geteilt\n```\n\n## Was am Ende bleiben soll\n\nVon so einem Durchgang bleibt im besten Fall nicht der Satz „ich kenne jetzt die Hooks“ übrig, sondern ein Reflex: bei jedem State zuerst zu fragen, wem er gehört und wie lange er leben soll. Genau das ist der Kern. React gibt einem ein sehr gutes Werkzeug, um Oberflächen zu beschreiben, aber es trifft die Architekturentscheidungen nicht für einen. Wem ein State gehört, wo ein Effect seinen Rand hat, welcher State in der URL, im Server-Cache oder im Store liegt – das bleibt die Arbeit, die ein Mensch machen muss.\n\nDeshalb ist dieser Beitrag ein Überblick und kein Handbuch. Ich habe viele Stationen nur kurz betreten: den Unterschied zwischen Client State und Server-Cache, Context als Verteilweg, die Wahl zwischen Redux und seinen leichteren Alternativen, Suspense und Server Components, das Testen ohne Theater. Zu jeder dieser Stationen gibt es mehr zu sagen, als ein Überblick tragen kann, und genau das ist der Plan: Die Details folgen als eigene Beiträge, jeder mit einem konkreten Beispiel und mindestens einem Fehlerfall. Wer den großen Bogen im Kopf hat, weiß dann, an welcher Stelle er gerade steht.\n\n## Weiterführende Quellen\n\n- Repository introduction-react (Grundlagen): https://github.com/mikebild/introduction-react\n- Repository advanced-react (fortgeschrittene Muster): https://github.com/mikebild/advanced-react\n- Folienübersicht zu diesem Überblick: https://slides.mikebild.dev/introduction-react.html\n- React, offizielle Dokumentation (Thinking in React): https://react.dev/learn/thinking-in-react\n- React 19, Ankündigung der stabilen Version: https://react.dev/blog/2024/12/05/react-19\n- React, State verwalten und teilen: https://react.dev/learn/managing-state"},{"locale":"de","translation_key":"formulare-in-react-19-mit-actions","slug":"formulare-in-react-19-mit-actions","title":"Formulare in React 19: Actions, useActionState und useOptimistic","summary":"React 19 macht das Formular zur eigentlichen Schnittstelle: eine Funktion als form action, dazu drei Hooks für Ergebnis, Pending State und sofortiges UI-Feedback. Dieser Beitrag zeigt das Zusammenspiel – und wo optimistisches Rendern ohne sauberen Fehlerpfad kippt.","tags":["Software","Frontend","React"],"published_at":"2024-12-23T10:00:00+00:00","updated_at":"2026-07-13T08:57:08.736063+00:00","url":"https://www.mikebild.dev/de/blog/formulare-in-react-19-mit-actions/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/18563b58aba9422349aa8b42b47fdd6d084001eda56306ecba544a7621e8e458/formulare-in-react-19-mit-actions-vorlesen.mp3","audio_duration_secs":761,"text":"Ein optimistisch eingefügter Eintrag, der bei einem Fehler wieder verschwindet und keine Meldung hinterlässt, ist für den Nutzer eine Falschaussage: Er hat abgeschickt, er hat es kurz gesehen, dann war da nichts mehr. Das ist die eine Stelle, an der die Formular-APIs von React 19 Arbeit machen statt sie abzunehmen – und deshalb steht sie schon hier am Anfang.\n\nAlles andere daran ist Entlastung. Bis React 18 bestand ein Formular, das einen Namen speichert, aus `onSubmit`, `event.preventDefault()`, einem `useState` für den Ladezustand, einem zweiten für die Fehlermeldung und irgendwo einem `try/catch` – erstaunlich viel Handarbeit für eine erstaunlich alltägliche Aufgabe. React 19, stabil seit dem 5. Dezember 2024, übergibt dem `<form>`-Element stattdessen direkt eine Funktion und stellt drei Hooks daneben: `useActionState`, `useFormStatus` und `useOptimistic`. Sie kümmern sich um genau die Dinge, die man vorher von Hand zusammenbauen musste. Ich gehe der Reihe nach durch, was jeder dieser Bausteine übernimmt, wie sie zusammenspielen und wo der Fehlerpfad aus dem ersten Absatz hingehört.\n\n## Von onSubmit zu action\n\nDer Ausgangspunkt ist eine kleine, aber folgenreiche Änderung am `<form>`-Element. In React 19 akzeptiert das `action`-Attribut eine Funktion – nicht mehr nur einen URL-String wie im klassischen HTML. Diese Funktion bekommt beim Absenden ein `FormData`-Objekt und wird von React aufgerufen. React ruft dabei selbst `preventDefault` auf, verpackt den Aufruf in eine Transition und – ein Detail, das gerne übersehen wird – setzt ein unkontrolliertes Formular nach erfolgreicher Action automatisch zurück.\n\nSo sieht das im Vergleich aus. Vorher:\n\n```jsx\nfunction NameForm() {\n  const [isSaving, setIsSaving] = useState(false);\n  const [error, setError] = useState(null);\n\n  async function handleSubmit(event) {\n    event.preventDefault();\n    setIsSaving(true);\n    setError(null);\n    const formData = new FormData(event.currentTarget);\n    const result = await save(formData.get(\"name\"));\n    setIsSaving(false);\n    if (result.error) setError(result.error);\n  }\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <input name=\"name\" />\n      <button disabled={isSaving}>{isSaving ? \"Saving…\" : \"Save\"}</button>\n      {error && <p>{error}</p>}\n    </form>\n  );\n}\n```\n\nUnd nachher, mit einer Client Action:\n\n```jsx\nfunction NameForm() {\n  async function updateName(formData) {\n    await save(formData.get(\"name\"));\n  }\n\n  return (\n    <form action={updateName}>\n      <input name=\"name\" />\n      <button>Save</button>\n    </form>\n  );\n}\n```\n\nDie zweite Variante ist nicht nur kürzer, sie verlagert die Kontrolle. React weiß jetzt, dass hier eine Übergabe stattfindet, hält den Pending State konsistent und kümmert sich um das native Submit-Verhalten. Eine Funktion, die auf diese Weise Übergänge auslöst, nennt React in der Dokumentation schlicht eine „Action“. Was in der zweiten Variante noch fehlt, ist alles, was den ersten Codeblock eigentlich ausgemacht hat: der Ladezustand und die Error Handling. Genau die holen die drei Hooks zurück – aber ohne die Handarbeit.\n\n## Wer übernimmt was\n\nDie drei Hooks klingen auf den ersten Blick ähnlich, haben aber sehr unterschiedliche Aufgaben. Deshalb vor dem Code die Zuständigkeiten:\n\n- `useActionState` bündelt den kompletten Lifecycle einer Action an einer Stelle: Es umschließt deine Action-Function, hält das zurückgegebene Ergebnis als State, liefert ein `isPending`-Flag und reicht dir eine umschlossene `formAction` zurück, die du ans Formular hängst.\n- `useFormStatus` liest den Pending State des nächstgelegenen umgebenden `<form>` – gedacht für Kindkomponenten wie einen Submit-Button, die nichts über die Action selbst wissen müssen, aber wissen wollen, ob gerade gesendet wird.\n- `useOptimistic` zeigt sofort einen erwarteten Zwischenzustand an, während die Action noch läuft, und konvergiert danach automatisch auf den realen State zurück – bei Erfolg auf den Serverwert, bei Fehler auf den alten Wert.\n\nMan kann die drei einzeln oder zusammen einsetzen. In einem echten Formular greifen sie meistens ineinander, und das Zusammenspiel ist genau der Punkt, an dem es interessant wird.\n\n## useActionState: Ergebnis und Pending an einer Stelle\n\n`useActionState` importiert man aus `react` – nicht aus `react-dom`, was eine häufige erste Fehlerquelle ist. Die Signatur:\n\n```jsx\nconst [state, formAction, isPending] = useActionState(action, initialState, permalink);\n```\n\nDer entscheidende und für viele überraschende Punkt steckt in der Signatur der übergebenen Action-Function. Sie bekommt **nicht** nur die `FormData`, sondern als erstes Argument den vorherigen State und erst als Zweites die Formulardaten:\n\n```jsx\nimport { useActionState } from \"react\";\n\nasync function updateName(previousState, formData) {\n  const name = formData.get(\"name\");\n  const error = await save(name);\n  if (error) {\n    return { error };\n  }\n  return { ok: true };\n}\n\nfunction NameForm() {\n  const [state, formAction, isPending] = useActionState(updateName, {});\n\n  return (\n    <form action={formAction}>\n      <input name=\"name\" disabled={isPending} />\n      <SubmitButton />\n      {state.error && <p role=\"alert\">{state.error}</p>}\n      {state.ok && <p>Saved.</p>}\n    </form>\n  );\n}\n```\n\nWas hier passiert, ist der ganze erste Codeblock von oben – nur ohne die Handarbeit. Der Rückgabewert der Action wird zum neuen `state`, das `isPending`-Flag verwaltet React, und `formAction` ist die umschlossene Funktion, die ans `action`-Attribut gehängt wird. Die Fehlermeldung ist kein separates `useState` mehr, sondern fällt einfach aus dem zurückgegebenen State heraus.\n\nWenn ich in einem Code-Review sehe, dass der State plötzlich `undefined` ist oder der vorherige State verloren geht, ist die Ursache fast immer dieselbe: Die Action wurde als `(formData) => …` geschrieben statt als `(previousState, formData) => …`. Der erste Parameter ist eben nicht die FormData. Wer aus der alten `onSubmit`-Welt kommt, hat diesen Reflex im Finger, und er kostet regelmäßig ein paar Minuten Suchen.\n\nEin historischer Hinweis, damit ältere Tutorials nicht verwirren: Dieser Hook hieß in den Canary-Versionen `useFormState` und steckte in `react-dom`. Mit React 19 wurde er nach `react` verschoben und in `useActionState` umbenannt; das dritte Element `isPending` kam dabei hinzu. `useFormState` gilt seither als deprecated – wenn du es noch irgendwo siehst, ist der Code auf einem älteren Stand.\n\n## useFormStatus: Pending im Kind lesen\n\nJetzt zum Submit-Button, den ich oben schon als `<SubmitButton />` eingesetzt habe. Man könnte fragen, warum der ausgelagert ist – schließlich hätte ich `isPending` aus `useActionState` auch direkt an einen Button im Formular geben können. Beides ist möglich, aber `useFormStatus` löst ein spezielles Problem: eine wiederverwendbare Komponente, die den Pending State kennt, ohne dass man ihn ihr durchreichen muss.\n\n```jsx\nimport { useFormStatus } from \"react-dom\";\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus();\n  return (\n    <button disabled={pending}>\n      {pending ? \"Saving…\" : \"Save\"}\n    </button>\n  );\n}\n```\n\nDer Hook kommt aus `react-dom`, nimmt keine Parameter und liefert neben `pending` noch `data`, `method` und `action` des umgebenden Formulars. Die eine Regel, die man kennen muss und die für die meisten Fehlermeldungen an dieser Stelle verantwortlich ist: `useFormStatus` liest den Status des **nächstgelegenen Eltern-`<form>`** und muss deshalb in einer Kindkomponente stehen, nicht in derselben Komponente, die das `<form>` rendert.\n\nSteht der Hook versehentlich in der Formularkomponente selbst, ist `pending` schlicht immer `false` – es gibt aus dieser Perspektive kein umgebendes Formular, dessen Status man lesen könnte. Der Button muss ein Kind sein. Die eigene `SubmitButton`-Komponente ist deshalb keine Geschmacksfrage: Ohne diese Verschachtelung sieht der Hook überhaupt nichts.\n\n## useOptimistic: den erwarteten State sofort zeigen\n\nDer dritte Hook ist der beeindruckendste – und der gefährlichste, wenn man ihn halb versteht. `useOptimistic` zeigt den State, den man nach erfolgreicher Action erwartet, sofort an, ohne auf die Serverantwort zu warten. Das klassische Beispiel ist eine Nachrichtenliste, in der die eigene Nachricht sofort erscheint:\n\n```jsx\nimport { useOptimistic, useActionState } from \"react\";\n\nfunction Thread({ messages, sendMessage }) {\n  const [optimisticMessages, addOptimistic] = useOptimistic(\n    messages,\n    (currentMessages, newText) => [\n      ...currentMessages,\n      { text: newText, sending: true },\n    ]\n  );\n\n  const [state, formAction] = useActionState(\n    async (previousState, formData) => {\n      const text = formData.get(\"message\");\n      addOptimistic(text);\n      const error = await sendMessage(text);\n      if (error) {\n        return { error };\n      }\n      return { ok: true };\n    },\n    {}\n  );\n\n  return (\n    <div>\n      <ul>\n        {optimisticMessages.map((message, index) => (\n          <li key={index}>\n            {message.text}\n            {message.sending && <span> (sending…)</span>}\n          </li>\n        ))}\n      </ul>\n      <form action={formAction}>\n        <input name=\"message\" />\n        <SubmitButton />\n        {state.error && <p role=\"alert\">{state.error}</p>}\n      </form>\n    </div>\n  );\n}\n```\n\n`useOptimistic` bekommt den realen State und eine reine Reducer-Function, die aus aktuellem State und optimistischem Wert den nächsten Zwischenzustand berechnet. Der Aufruf von `addOptimistic` muss innerhalb einer Action beziehungsweise Transition passieren – hier also innerhalb der async-Action, die `useActionState` verwaltet. Ruft man ihn außerhalb auf, gibt es eine Warnung und kein optimistisches Rendering.\n\nDas eigentlich Elegante ist die automatische Konvergenz: Der optimistische Wert gilt nur, solange die Action läuft. Sobald sie abgeschlossen ist, fällt der angezeigte State auf den realen `messages`-State zurück. Bei Erfolg ist das der aktualisierte Serverwert, bei Fehler der alte Wert – die optimistisch eingefügte Nachricht verschwindet also von selbst wieder. Man muss nichts manuell zurücksetzen.\n\n## Der Fallstrick: optimistisch ohne Fehlerpfad\n\nDie automatische Konvergenz verführt dazu, den Fehlerfall für erledigt zu halten. Erledigt ist er nicht – hier entstehen die Bugs, die im Test niemand sieht und im Support jeder meldet.\n\nStell dir vor, `sendMessage` schlägt fehl. Der optimistische Wert wird automatisch zurückgenommen – die Nachricht verschwindet aus der Liste. Aus Sicht des Nutzers heißt das: Er hat etwas abgeschickt, es erschien kurz, und dann war es weg. Ohne weitere Rückmeldung. Kein Nutzer interpretiert das als „Fehler beim Senden“; die meisten denken, sie hätten sich verklickt, und probieren es einfach nochmal – im schlimmsten Fall entsteht so ein Duplikat, sobald der Server doch geantwortet hat.\n\nDer Denkfehler ist, `useOptimistic` als Error Handling misszuverstehen. Der Hook kümmert sich um den *sichtbaren Zwischenzustand*, nicht um die *Kommunikation des Ergebnisses*. Die beiden Aufgaben muss man trennen:\n\n- `useOptimistic` sorgt dafür, dass der optimistische Wert bei einem Fehler automatisch zurückgenommen wird – das ist der Rollback des UI States, und den bekommt man geschenkt.\n- Die sichtbare Fehlermeldung ist eine eigene Verantwortung. Sie muss aus dem `state` von `useActionState` kommen: Die Action fängt den Fehler, gibt ihn als `{ error }` zurück, und die UI leitet daraus eine Meldung ab.\n\nBei konkurrierenden Änderungen reicht dieser UI-Rollback nicht. Doppelte Übermittlungen, veraltete Serverstände und Konflikte brauchen weiterhin Idempotenzschlüssel, Versionsprüfung oder eine fachliche Konfliktregel auf dem Server.\n\nIm Code oben passiert genau das: Die Action gibt im Fehlerfall `{ error }` zurück, und `{state.error && <p role=\"alert\">…</p>}` macht ihn sichtbar. Der optimistische Wert verschwindet automatisch, aber der Nutzer sieht *warum*. Wer den Fehler dagegen im `catch` verschluckt oder gar nicht erst zurückgibt, hat ein UI, das bei Fehlern stumm den falschen Eindruck erweckt, es sei nichts passiert. Optimistisches Rendern ohne echten Fehlerpfad ist schlimmer als gar kein optimistisches Rendern.\n\n## Das Zusammenspiel im Bild\n\nWenn man die vier Beteiligten – das Formular, die Action, den Pending State und den optimistischen Wert – zeitlich anordnet, wird das Muster deutlich:\n\n```mermaid\nflowchart LR\n  A[\"form action(fn)<br/>Submit ausgelöst\"] --> B[\"isPending = true<br/>Button disabled<br/>via useFormStatus\"]\n  B --> C[\"addOptimistic()<br/>erwarteter Zustand<br/>sofort sichtbar\"]\n  C --> D[\"await save()\"]\n  D -->|Erfolg| E[\"realer State<br/>state.ok<br/>Formular-Reset\"]\n  D -->|Fehler| F[\"optimistisch revertiert<br/>state.error sichtbar\"]\n```\n\nDer obere Pfad ist der Normalfall, der untere der, den man aktiv gestalten muss. React nimmt einem den Weg von A bis D fast vollständig ab; die bewusste Design-Entscheidung liegt in der Verzweigung bei D – und darin, dass der Fehlerzweig nicht ins Leere läuft.\n\nDas zweite Diagramm ordnet noch einmal die Zuständigkeiten, weil die Verwechslungsgefahr zwischen den dreien real ist:\n\n```mermaid\nflowchart TB\n  subgraph Form[\"React 19 Formular\"]\n    UAS[\"useActionState<br/>Aufruf + Ergebnis + Pending\"]\n    UFS[\"useFormStatus<br/>liest Pending des Eltern-Forms<br/>im Kind\"]\n    UO[\"useOptimistic<br/>sofortiger Zwischenzustand<br/>mit Auto-Konvergenz\"]\n  end\n  UAS -->|reicht isPending<br/>und state| UI[\"Fehler- und Erfolgs-Anzeige\"]\n  UFS -->|pending| Button[\"SubmitButton\"]\n  UO -->|optimisticState| Liste[\"Live-Liste\"]\n```\n\n## Ein Wort zu Server Functions\n\nBisher habe ich von Client Actions gesprochen – Funktionen, die im Browser laufen. Der gleiche Mechanismus trägt aber auch über die Netzwerkgrenze. Mit der Direktive `\"use server\"` am Anfang einer Datei oder einer Funktion markiert man Server Functions, die vom Client aus aufrufbar sind, aber auf dem Server ausgeführt werden:\n\n```js\n\"use server\";\n\nexport async function updateName(previousState, formData) {\n  const name = formData.get(\"name\");\n  await db.users.update({ name });\n  return { ok: true };\n}\n```\n\nDiese Funktion lässt sich exakt wie eine Client Action an `useActionState` oder direkt an `<form action={…}>` übergeben – die Signatur ist dieselbe. Wichtig ist, `\"use server\"` nicht mit `\"use client\"` zu verwechseln; die beiden Direktiven markieren gegensätzliche Ausführungsorte. Und Server Functions setzen ein Framework beziehungsweise einen Bundler voraus, der React Server Components unterstützt; in einer reinen Client-App gibt es sie nicht.\n\nEin hübscher Side Effect in diesem Kontext ist Progressive Enhancement. Übergibt man `useActionState` als drittes Argument ein `permalink` – eine URL –, funktioniert das Formular auch dann, wenn JavaScript noch nicht hydriert oder gar nicht verfügbar ist: Der Browser navigiert klassisch zu dieser URL, der Server verarbeitet die FormData, und sobald React hydriert ist, übernimmt die clientseitige Action nahtlos. Das ist nur im RSC-Kontext relevant, aber es zeigt, dass das Actions-Modell bis in die Server-Kommunikation hinein durchdacht wurde und nicht bloß eine hübschere Schreibweise für `onSubmit` ist. Wer tiefer in dieses Zusammenspiel einsteigen will, findet in meinem Beitrag zu [React Server Components und Server Actions](https://www.mikebild.dev/de/blog/react-server-components-und-server-actions/) den größeren Rahmen.\n\n## Was bleibt hängen\n\nUnterm Strich läuft das auf einen Perspektivwechsel hinaus. Dem Formular gibt man in React 19 eine Funktion; das Hinterherräumen mit Event-Handlern entfällt. Die drei Hooks sind keine drei neuen Dinge zum Auswendiglernen, sondern die drei Verantwortungen, die man vorher selbst miteinander verknüpfen musste, sauber getrennt: `useActionState` für Aufruf, Ergebnis und Pending, `useFormStatus` für den Pending-Blick aus dem Kind, `useOptimistic` für das sofortige Feedback mit automatischem Rollback.\n\nDie zwei Stolperstellen, die erfahrungsgemäß am meisten Zeit kosten: Die Action von `useActionState` bekommt den vorherigen State als erstes Argument, nicht die FormData. Und optimistisches Rendern ist erst dann fertig, wenn der Fehlerfall eine sichtbare Meldung hat – der Hook nimmt dir den Rollback ab, aber nicht die Kommunikation. Mit diesen beiden Punkten im Hinterkopf werden Formulare in React 19 kürzer *und* robuster als alles, was man vorher von Hand gebaut hat.\n\n## Weiterführende Quellen\n\n- [React 19 Release-Blogpost (Actions-Überblick)](https://react.dev/blog/2024/12/05/react-19)\n- [`useActionState` – react.dev](https://react.dev/reference/react/useActionState)\n- [`useFormStatus` – react.dev](https://react.dev/reference/react-dom/hooks/useFormStatus)\n- [`useOptimistic` – react.dev](https://react.dev/reference/react/useOptimistic)\n- [`<form action>` – react.dev](https://react.dev/reference/react-dom/components/form)\n- [`\"use server\"` / Server Functions – react.dev](https://react.dev/reference/rsc/use-server)\n- [`useTransition` (Hintergrund zu Actions/Transitions) – react.dev](https://react.dev/reference/react/useTransition)"},{"locale":"de","translation_key":"react-server-components-und-server-actions","slug":"react-server-components-und-server-actions","title":"React Server Components und Server Actions: Die neue Grenze","summary":"Server Components laufen außerhalb des Client-Bundles und liefern ihr Ergebnis statt ihres Codes an den Browser. Server Functions holen Schreibvorgänge auf den Server – umgesetzt wird beides durch ein passendes Framework oder einen Bundler.","tags":["Software","Frontend","React"],"published_at":"2024-12-19T10:00:00+00:00","updated_at":"2026-07-13T08:04:22.356388+00:00","url":"https://www.mikebild.dev/de/blog/react-server-components-und-server-actions/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/46c0932f5f0f771e5e2c5a4765a548a6f0a9b14f9899f6d2bc19b0451972355d/react-server-components-und-server-actions-vorlesen.mp3","audio_duration_secs":928,"text":"# React Server Components und Server Actions: Die neue Grenze\n\n```text\nError: You're importing a component that needs `useState`.\nThis React Hook only works in a Client Component.\nTo fix, mark the file (or its parent) with the \"use client\" directive.\n```\n\nDiese Meldung ist für viele der erste Kontakt mit React Server Components, und der übliche Reflex darauf lautet: `\"use client\"` in die erste Zeile, Fehler weg, weiter im Text. Der Build ist damit wieder grün und die eigentliche Frage übersprungen. Die Meldung ist nämlich kein Konfigurationsfehler. Sie fragt, auf welche Seite einer Grenze dieses Stück Oberfläche gehört – und die Antwort reicht weit über die Datei hinaus, in der die Direktive am Ende steht.\n\nDenn wer eine Architekturgrenze verschiebt, verschiebt immer mehr als Code: auch, wo getestet wird, was deployt werden muss und welches Team für welchen Teil der Oberfläche zuständig ist. Genau das ist der Trade-off, um den es hier eigentlich geht. Die schnellere Auslieferung und das kleinere Bundle sind der sichtbare Gewinn. Die eigentliche Wirkung liegt darunter: kürzere Wege vom Datenzugriff zur Anzeige, weniger Reibung an der Naht zwischen den beiden Welten – erkauft mit einer Grenze, die man von nun an bewusst ziehen und verteidigen muss.\n\n**Redaktionelle Einordnung (Juli 2026):** React 19 hat Server Components als Komponentenmodell stabilisiert. Die Schnittstellen, mit denen Frameworks und Bundler sie umsetzen, folgen innerhalb React 19.x jedoch weiterhin nicht der üblichen Semver-Stabilität. React allein liefert daher noch keine vollständige Produktionsarchitektur dafür; die Beispiele dieses Beitrags verwenden den Next.js App Router. Server Components können außerdem beim Build oder pro Anfrage laufen. Nur die dynamische Variante braucht dafür einen Laufzeitserver.\n\nDaran bleiben viele zunächst hängen: Man sucht nach einem neuen Hook und stößt stattdessen auf eine Grenze, die sich verschoben hat – mit Folgen für Test, Betrieb und Teamzuschnitt. Welcher Teil der Oberfläche auf dem Server bleibt und welcher in den Browser geht, nimmt einem das Framework von jetzt an nicht mehr ab. Darum geht es in diesem Beitrag.\n\n## Was eine Server Component wirklich ist\n\nEine Server Component läuft in einer Umgebung außerhalb des Client-Bundles: beim Build oder auf einem Server pro Anfrage. Dort kann sie mit direktem Zugriff auf Datenbank, Dateisystem oder interne Services rendern und anschließend nur ihr Ergebnis an den Browser schicken. Nicht ihren Code. Das ist der entscheidende Satz. Für eine Komponente, die bloß etwas anzeigt, landet am Ende kein eigener Komponenten-Code im Client-Bundle. Der Browser bekommt eine Beschreibung dessen, was er darstellen soll, und nicht die Komponente, die diese Beschreibung erzeugt hat.\n\nDas ist ein anderer Umgang mit dem Wort „rendern“, als man ihn gewohnt ist. Deshalb lohnt sich der Rückgriff auf einen früheren Beitrag: In [Wie React den Baum rendert](https://www.mikebild.dev/de/blog/wie-react-den-baum-rendert-und-aktualisiert/) habe ich gezeigt, dass Rendern bei React ohnehin nur eine Berechnung ist – eine Funktion, die aus Eingaben eine Beschreibung des Baums macht, die React dann mit dem letzten Stand abgleicht. Wenn Rendern aber nur eine Berechnung ist, dann stellt sich sofort die Frage: Wo läuft diese Berechnung? Genau hier setzen Server Components an. Sie verlagern einen Teil dieser Berechnung dauerhaft auf den Server, statt ihn wie bisher im Browser zu erledigen.\n\n## Der Unterschied zu SSR, den fast alle verwechseln\n\nEin Punkt gehört hier geradegerückt, weil er zuverlässig für Verwirrung sorgt: Server Components sind nicht dasselbe wie Server-Side Rendering, und der Unterschied ist nicht kosmetisch.\n\nKlassisches SSR nimmt ganz normale Client-Komponenten und rendert sie einmal auf dem Server zu HTML, damit der Browser sofort etwas sieht. Danach schickt der Server aber trotzdem den Komponenten-Code hinterher, und im Browser läuft die Hydratisierung: React hängt sich an das gelieferte HTML, spielt dieselbe Komponente noch einmal durch und macht sie interaktiv. Der Code geht also mit – SSR ist ein früher erster Eindruck, kein Sparen von JavaScript. Die Komponente existiert am Ende doppelt: einmal als HTML vom Server, einmal als lauffähiger Code im Browser.\n\nEine Server Component existiert dagegen nie im Client-Bundle. Es gibt nichts zu hydratisieren, weil es im Browser keine zweite Ausführung gibt. Der Server hat gerechnet, das Ergebnis ist da, und damit endet die Geschichte für diesen Teil des Baums. SSR beantwortet die Frage „wann sieht der Nutzer zum ersten Mal etwas“. Server Components beantworten die andere Frage: „muss dieser Code überhaupt jemals in den Browser“. Für reine Anzeige ist die Antwort jetzt nein.\n\n```mermaid\nflowchart TB\n  subgraph Server\n    SC[\"Server Component<br/>liest Daten direkt\"]\n  end\n  subgraph Browser\n    UI[\"fertiges Ergebnis<br/>wird angezeigt\"]\n    Island[\"Client-Insel<br/>(Hooks, Events)\"]\n  end\n  DB[(\"Datenbank / Service\")]\n  SC -->|await| DB\n  SC -->|nur Ergebnis,<br/>kein Code| UI\n  SC -.->|bettet ein| Island\n```\n\n## Die Grenze heißt `\"use client\"`\n\nWenn Server Components der Normalfall sind, braucht man eine Markierung für die Ausnahme – für die Stelle, an der Interaktivität beginnt. Diese Markierung ist die Direktive `\"use client\"` am Anfang einer Datei. Alles oberhalb dieser Grenze läuft auf dem Server: Daten laden, anzeigen, Struktur bauen, kein State. Ab der Direktive ist man im Browser-Land mit allem, was dazugehört – `useState`, `useEffect`, Event-Handler, Zugriff auf `window`.\n\nWichtig ist die Richtung, in der diese beiden Welten zusammenpassen. Eine Server Component darf Client Components als Kinder enthalten – man streut Inseln der Interaktivität in eine ansonsten statische, serverseitig gerenderte Seite. Der umgekehrte Weg ist eingeschränkt: Eine Client Component kann eine Server Component nicht einfach importieren, weil der Server-Code dann ja doch im Browser landen müsste. Sie kann eine Server Component nur als übergebenen `children`-Slot einbetten – der Server rendert das Kind, die Client-Komponente bekommt das fertige Ergebnis gereicht und packt ihr interaktives Drumherum darum. Diese eine Regel erklärt die meisten Fehlermeldungen, über die Leute am Anfang stolpern.\n\n```mermaid\nflowchart TB\n  Page[\"Server Component (Seite)<br/>lädt Daten, zeigt an\"]\n  Page --> List[\"Server Component<br/>Rechnungsliste\"]\n  Page --> Button[\"Client-Insel<br/>&quot;use client&quot;: Button mit onClick\"]\n  Button -->|darf als children| Slot[\"Server-Inhalt<br/>als Slot\"]\n```\n\n## Server Components konkret\n\nWeil eine Server Component nur auf dem Server läuft, darf sie etwas, das im Browser nie ging: Sie darf `async` sein und im Body direkt `await` nutzen. Das Laden von Daten passiert dann ohne `useEffect`, ohne Lade-Flag, ohne den ganzen Apparat – man schreibt es hin, als wäre es eine normale Funktion, die eben auf eine Datenbank zugreifen kann.\n\n```jsx\n// invoices-page.jsx — a Server Component, no \"use client\" here\nimport { db } from \"@/lib/db\";\nimport { PayButton } from \"./pay-button\";\n\nexport default async function InvoicesPage() {\n  const invoices = await db.invoice.findMany({ where: { open: true } });\n\n  return (\n    <section>\n      <h1>Open invoices: {invoices.length}</h1>\n      <ul>\n        {invoices.map((invoice) => (\n          <li key={invoice.id}>\n            {invoice.title} — {invoice.amount} €\n            <PayButton invoiceId={invoice.id} />\n          </li>\n        ))}\n      </ul>\n    </section>\n  );\n}\n```\n\nZwei Dinge stehen hier bewusst nebeneinander. Der `await db.invoice.findMany(...)` greift direkt auf die Datenbank zu – dieser Code verlässt den Server nie, es gibt keine API-Route dazwischen und keinen Ladezustand im Browser. Und `PayButton` ist eine eingebettete Client-Insel: alles, was einen Klick braucht, wandert in eine eigene Datei mit `\"use client\"`.\n\n```jsx\n// pay-button.jsx\n\"use client\";\n\nimport { useState } from \"react\";\n\nexport function PayButton({ invoiceId }) {\n  const [busy, setBusy] = useState(false);\n  return (\n    <button disabled={busy} onClick={() => setBusy(true)}>\n      {busy ? \"Paying…\" : \"Pay\"}\n    </button>\n  );\n}\n```\n\nWas in einer Server Component nicht geht, ist ebenso lehrreich: kein `useState`, kein `useEffect`. In dieser Umgebung gibt es keinen lokalen Client State, den man über Klicks hinweg hält. Eine Server Component kann bei einem späteren Request oder einer erneuten Server-Ausführung wieder rendern; direkte Browser-Interaktion verarbeitet sie aber nicht. Alles, was auf einen Klick unmittelbar im Browser reagieren soll, gehört in eine Client-Insel jenseits der Grenze.\n\n## Server Actions: das Schreiben zurück auf den Server\n\nServer Components lösen das Lesen und Anzeigen. Für das Schreiben gibt es Server Functions, oft Server Actions genannt, markiert mit der Direktive `\"use server\"`. Das sind Funktionen, die auf dem Server laufen, aber über die Integration des Frameworks vom Client aus aufgerufen werden – am direktesten als `action` eines `<form>`. Man baut in der Anwendung keine eigene API-Route und kein eigenes Request-Format für diesen Aufruf. Den Transport, die Serialisierung und die Sicherheitsgrenze übernimmt aber nicht React als Laufzeit allein, sondern das eingesetzte Framework.\n\n```jsx\n// invoice-actions.js\n\"use server\";\n\nimport { db } from \"@/lib/db\";\nimport { revalidatePath } from \"next/cache\";\n\nexport async function payInvoice(formData) {\n  const id = formData.get(\"invoiceId\");\n  await db.invoice.update({ where: { id }, data: { open: false } });\n  revalidatePath(\"/invoices\");\n}\n```\n\nAufgerufen wird das direkt aus dem Formular. Damit der Nutzer während der laufenden Aktion Rückmeldung bekommt, gibt es zwei Hooks, die genau dafür da sind: `useActionState` bündelt den Aufruf mit seinem Ergebnis und einem Pending-Flag, `useFormStatus` liest den Pending State des umgebenden Formulars in einem Kind-Element aus.\n\n```jsx\n// pay-form.jsx\n\"use client\";\n\nimport { useActionState } from \"react\";\nimport { useFormStatus } from \"react-dom\";\nimport { payInvoice } from \"./invoice-actions\";\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus();\n  return (\n    <button type=\"submit\" disabled={pending}>\n      {pending ? \"Paying…\" : \"Pay invoice\"}\n    </button>\n  );\n}\n\nexport function PayForm({ invoiceId }) {\n  const [state, formAction] = useActionState(payInvoice, null);\n  return (\n    <form action={formAction}>\n      <input type=\"hidden\" name=\"invoiceId\" value={invoiceId} />\n      <SubmitButton />\n    </form>\n  );\n}\n```\n\nDer Reiz liegt darin, wie wenig hier steht. Kein `fetch`, kein manuelles `POST`, kein selbstgebauter Endpoint, keine Serialisierung. Man ruft eine Funktion auf, die zufällig auf dem Server läuft, und der Pending State für die Oberfläche fällt nebenbei ab.\n\n```mermaid\nflowchart LR\n  Form[\"Formular im Browser<br/>action = payInvoice\"]\n  Form -->|Absenden| Action[\"Server Action<br/>&quot;use server&quot;\"]\n  Action -->|schreibt| DB[(\"Datenbank\")]\n  Action -->|revalidatePath| Fresh[\"Server rendert<br/>betroffene Ansicht neu\"]\n  Fresh -->|neues Ergebnis| Form\n```\n\n## Was das für die Serie bedeutet\n\nDiese neue Grenze verschiebt eine andere, über die ich schon geschrieben habe. In [Client State vs. Server-Cache](https://www.mikebild.dev/de/blog/client-zustand-und-server-cache/) war der Kernpunkt: Das meiste, was wie State aussieht, ist in Wahrheit geliehener Server-Cache, den man im Browser nur zwischenspeichert. Server Components verschieben diese Grenze noch einmal. Ein großer Teil des Anzeige-Datenladens, für den man bisher eine Cache-Bibliothek im Browser gebraucht hat, wandert jetzt auf den Server – dort liest die Server Component direkt und schickt nur das Ergebnis. Der Bedarf, dieselben Daten im Client nachzuhalten, schrumpft entsprechend.\n\nDas heißt nicht, dass Server-State-Bibliotheken überflüssig werden. Sobald es interaktiv wird – Daten, die sich nach einem Klick ändern, ohne die ganze Seite neu zu laden – bleibt der Cache im Browser sinnvoll. Aber die Aufteilung verschiebt sich: weniger Anzeige im Client, mehr auf dem Server. Für das gestaffelte Ausliefern sorgt dabei [Suspense](https://www.mikebild.dev/de/blog/react-suspense-und-use/), das die serverseitig gerenderten Teile stückweise zum Browser streamt.\n\n## Was die verschobene Grenze mit Test, Betrieb und Team macht\n\nBis hierher klingt das nach einer sauberen technischen Umschichtung. Interessant wird es aber dort, wo diese Grenze auf die Art trifft, wie ein Team arbeitet, testet und ausliefert. Denn eine Architekturgrenze ist nie nur eine Zeile Code. Sie entscheidet, an welcher Stelle die Komplexität anfällt – und Komplexität hat immer eine Rechnung.\n\nFangen wir bei der Testbarkeit an, weil sich dort am deutlichsten zeigt, was die Verschiebung kostet und was sie einspart. Eine reine Anzeige-Komponente, die vorher im Browser Daten geladen hat, war überraschend aufwendig zu testen: `fetch` mocken, Ladezustand durchspielen, Fehlerpfad nachstellen, das erneute Rendern nach dem Eintreffen der Daten abwarten. Als Server Component fällt dieser ganze Apparat weg. Die Komponente ist eine `async`-Funktion, die Daten hereinbekommt und eine Beschreibung zurückgibt – testbar wie eine Funktion, ohne Browser-Umgebung, ohne Timing. Der Preis steht auf der anderen Seite der Grenze: Der direkte `await db.invoice.findMany(...)` im Komponenten-Body verwebt Datenzugriff und Darstellung, und die Komponente will für einen Test jetzt eine Datenbank sehen. Das Testen verlagert sich also, statt zu verschwinden: Server Components prüft man eher über Integrationstests gegen eine echte oder in-memory Datenquelle, die interaktiven Inseln weiterhin als isolierte Client-Tests. Wer diese Zweiteilung bewusst zieht, gewinnt; wer sie ignoriert, baut sich schwer testbare Zwitter.\n\nBeim Deployment verschiebt sich der Charakter der Anwendung, sobald Server Components pro Anfrage laufen oder Server Functions schreiben. Client-only React konnte am Ende ein Bündel statischer Dateien hinter einem CDN sein; reine, beim Build ausgeführte Server Components können ebenfalls statisch ausgeliefert werden. Die dynamische Variante braucht dagegen einen laufenden Prozess mit Zugriff auf Datenbank und interne Dienste. Das bringt Nähe – der Datenzugriff sitzt direkt neben der Komponente, ohne eigene API-Schicht dazwischen – und Betriebsverantwortung: Serverkapazität, Laufzeitfehler jenseits des Browsers und eine Grenze zwischen öffentlichem und internem Code, die zur Sicherheitsgrenze wird. Der Gewinn ist eine kürzere Kette vom Klick bis zur Persistenz. Die Kosten sind eine Betriebsfläche, die vorher nicht da war.\n\nUnd dann ist da der Teamzuschnitt, der Punkt, den man am leichtesten übersieht und am teuersten bezahlt. In der klassischen Aufteilung gab es eine harte Naht: Frontend baut die Oberfläche, Backend liefert die API, dazwischen ein Vertrag aus Endpoints und Formaten. Diese Naht war Reibung, aber auch eine klare Zuständigkeitsgrenze. Server Components und Server Actions lösen sie auf – der Datenzugriff wandert in die Komponente, das Schreiben in eine Funktion daneben, der Vertrag aus API-Routen verschwindet. Für ein Team, das über die ganze Tiefe arbeitet, ist das ein spürbarer Reibungsverlust: kürzere Wege, weniger Abstimmung über Endpoints, weniger Code, der nur Daten hin- und herträgt. Für zwei getrennte Teams mit sauberer Frontend-Backend-Trennung ist es das Gegenteil: Die Grenze, an der sie ihre Verantwortung übergeben haben, ist weg, und die neue verläuft mitten durch die Oberfläche. Ob Server Components ein Gewinn oder ein Konfliktherd sind, hängt damit weniger an der Technik als an der Organisation.\n\nDaraus ergeben sich die Entscheidungskriterien, die ich in Projekten anlege. Server Components zahlen sich aus, wenn das Team über die volle Tiefe arbeitet und die Frontend-Backend-Naht bisher eher Ballast als Schutz war, wenn ein laufender Server ohnehin zum Betrieb gehört, und wenn die Oberfläche datenlastig und wenig interaktiv ist. Sie kosten mehr, als sie bringen, wenn zwei Teams entlang einer bewusst gezogenen API-Grenze liefern, wenn der Betrieb rein statisch bleiben soll, oder wenn die Anwendung fast nur aus interaktiven Inseln besteht. Die Frage ist also nicht „ist die Technik gut“, sondern „passt die verschobene Grenze zu dem, wie wir bauen, testen und ausliefern“.\n\n## Ehrlich eingeordnet: neu und mit Reibung\n\nIch will das nicht schönreden. Server Components sind neu, und sie bringen Reibung mit sich. Man muss die Grenze zwischen Server und Client wirklich verstanden haben, sonst produziert man genau die Fehler, die ich oben beschrieben habe – einen Import über die Grenze, einen Hook auf der falschen Seite, einen Datenzugriff, der plötzlich im Browser landen soll. Das Ökosystem ist noch im Fluss: Die verbreitete Umsetzung ist heute der Next.js App Router, andere Frameworks ziehen nach, und manche Bibliothek muss erst lernen, wo sie in dieser Welt hingehört.\n\nUnd nicht jede Anwendung braucht das. Ein hochinteraktives Dashboard, das ohnehin fast vollständig im Browser läuft, gewinnt wenig, wenn man es durch die Server-Client-Grenze zwängt. Wo sich Server Components dagegen deutlich lohnen: bei datenlastigen, weitgehend statischen Oberflächen, wo viel angezeigt und wenig geklickt wird; wenn das Client-Bundle spürbar drückt und man Anzeige-Code loswerden will, der im Browser nichts zu suchen hat; und dort, wo serverseitig geliefertes HTML für Suchmaschinen und den ersten Eindruck zählt. Das ist eine ehrliche Abwägung, keine Pflicht.\n\n## Die eigentliche Entscheidung\n\nWenn ein Gedanke aus diesem Beitrag hängen bleiben soll, dann dieser: Server Components sind keine schnellere Art zu rendern. Sie sind eine Ortsentscheidung. Bei jedem Teil der Oberfläche fragt man jetzt zuerst: Bleibt das auf dem Server – weil es nur liest und anzeigt – oder gehört es in den Browser, weil ein Mensch damit interagiert? Die Direktiven `\"use client\"` und `\"use server\"` sind nichts anderes als die sichtbaren Markierungen dieser einen Entscheidung.\n\nWer die Grenze bewusst zieht, erntet die Wirkung, die unter der Technik liegt: kürzere Wege vom Datenzugriff zur Anzeige und damit schnellere Zyklen, weniger Reibung an der aufgelösten Frontend-Backend-Naht, und eine Testbarkeit, die sich sauber in serverseitige Integrationstests und Client-Inseln teilt. Wer die Grenze dagegen verwischt, bekommt das Gegenteil – schwer testbare Zwitter, unklare Zuständigkeiten, Betriebslast ohne Gegenwert. Der Unterschied liegt nicht im Framework. Er liegt darin, ob die verschobene Grenze zu dem passt, wie ein Team baut, testet und ausliefert – und ob man sie danach klar genug hält, um sie zu verteidigen. Diese Frage ist das Wesentliche – lange bevor man den ersten Hook nachschlägt.\n\n## Weiterführende Quellen\n\n- Repository introduction-react (Kapitel server-components, server-actions; App-Router-Beispiele): https://github.com/mikebild/introduction-react\n- React, „Server Components“: https://react.dev/reference/rsc/server-components\n- React, „Server Functions“: https://react.dev/reference/rsc/server-functions\n- Next.js, App Router: https://nextjs.org/docs/app"},{"locale":"de","translation_key":"react-router-data-router","slug":"react-router-data-router","title":"React Router Data Router: Die URL als State-Ort","summary":"Der Data Router von React Router macht die URL zum Koordinationspunkt – eine Route lädt ihre Daten per loader vor dem Rendern und schreibt über action, sodass Ladelogik aus dem Komponenten-Body verschwindet.","tags":["Software","Frontend","React"],"published_at":"2024-12-16T10:00:00+00:00","updated_at":"2026-07-13T13:23:13.585129+00:00","url":"https://www.mikebild.dev/de/blog/react-router-data-router/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/49c000730bd77e327e9e4bb8897ce659a67568eeadcbd65f5f729689a6e7137e/react-router-data-router-vorlesen.mp3","audio_duration_secs":702,"text":"# React Router Data Router: Die URL als State-Ort\n\nEine Route ist im Data Router von React Router keine Zuordnung von Pfad zu Komponente mehr. Sie ist eine vollständige Beschreibung dessen, was zu einer Adresse gehört: welcher Ausschnitt der Oberfläche erscheint, woher seine Daten kommen, was bei einem Schreibvorgang passiert, was im Fehlerfall zu sehen ist. Diese Beschreibungen sind Objekte, und weil sie schon vor dem ersten Rendern vorliegen, kann der Router aus ihnen ablesen, was für eine URL zu tun ist – ohne eine einzige Komponente laufen zu lassen.\n\nWie weit das trägt, zeigt der Vergleich mit dem Muster, das die klassische Variante nahelegt: Eine Route rendert eine Komponente, die Komponente hat einen `useEffect`, der Effect lädt die Daten, und daneben liegen drei `useState` für Ladezustand, Fehler und Ergebnis. Bei einer Seite geht das. Bei zwanzig verschachtelten Seiten entstehen Ladewasserfälle: Die äußere Komponente rendert, ihr Effect lädt, erst danach rendert die innere, ihr Effect lädt – nacheinander, obwohl beide von Anfang an bekannt waren. Im React-Überblick habe ich Routing noch mit `BrowserRouter` und `Routes` gezeigt und die moderne Variante bewusst liegengelassen; sie ist der Gegenstand dieses Beitrags. Der Data Router dreht die Reihenfolge um.\n\n**Redaktionelle Einordnung (Juli 2026):** React Router 8 unterscheidet drei Modi: Declarative, Data und Framework. Dieser Beitrag behandelt den Data Mode mit `createBrowserRouter`. Der Framework Mode baut darauf auf und ergänzt unter anderem typisierte Route-Module, Code-Splitting sowie mögliche SPA-, SSR- und statische Rendering-Strategien.\n\n## Die Kernidee: Die Route lädt, bevor sie rendert\n\nDer entscheidende Unterschied lässt sich in einem Satz sagen. Bei der alten Variante rendert die Komponente zuerst und lädt dann ihre Daten. Beim Data Router lädt die Route zuerst ihre Daten und rendert dann die Komponente – mit den Daten bereits in der Hand. Jede Route bekommt dafür eine Funktion, den `loader`. Er läuft beim Navigieren, noch bevor irgendetwas auf den Bildschirm kommt. Erst wenn er fertig ist, rendert React die Komponente, und die greift die Daten fertig geladen ab, statt sie selbst zu besorgen.\n\nDamit verschwindet die Ladelogik aus dem Komponenten-Body. Kein `useEffect` mehr, der beim ersten Rendern nachlädt, keine Handvoll `useState` für einen State, den es genau genommen nie geben sollte – denn wenn die Komponente rendert, sind die Daten längst da. Das schreibende Gegenstück heißt `action`. Es nimmt Formular-Übermittlungen entgegen, schreibt zum Server, und danach lädt React Router die betroffenen `loader` von selbst neu, damit die View wieder stimmt.\n\n## `createBrowserRouter` und die Route-Objekte\n\nMan beschreibt die Anwendung nicht mehr als verschachtelte JSX-Elemente, sondern als Objekte. `createBrowserRouter` nimmt ein Array von Route-Definitionen entgegen, und jede Definition trägt ihre Bausteine an einer Stelle: den Pfad, die Komponente, den `loader`, die `action`, das Fehler-Element.\n\n```jsx\nimport { createBrowserRouter } from \"react-router\";\nimport { RouterProvider } from \"react-router/dom\";\n\nconst router = createBrowserRouter([\n  {\n    path: \"/invoices\",\n    element: <InvoiceList />,\n    loader: invoiceListLoader,\n    errorElement: <RouteError />,\n    children: [\n      {\n        path: \":invoiceId\",\n        element: <InvoiceDetail />,\n        loader: invoiceDetailLoader,\n        action: invoiceDetailAction,\n      },\n    ],\n  },\n]);\n\nfunction App() {\n  return <RouterProvider router={router} />;\n}\n```\n\nStatt `path` und `element` über die halbe Anwendung verstreut zu suchen, steht alles, was eine Route ausmacht, beisammen: was sie anzeigt, woher ihre Daten kommen, wie sie auf Schreibvorgänge reagiert, was bei einem Fehler passiert. Diese Bündelung ist kein kosmetischer Vorteil. Sie ist die Voraussetzung dafür, dass React Router die Daten schon kennt, bevor gerendert wird – denn der Router kann aus dem Objektbaum ablesen, welche `loader` für eine URL zuständig sind, ohne die Komponenten erst zu rendern.\n\n## Der `loader`: Daten holen, bevor gerendert wird\n\nEin `loader` ist eine gewöhnliche Funktion. Sie bekommt unter anderem die Parameter aus dem Pfad, holt die Daten und gibt sie zurück. In der Komponente greift man sie mit `useLoaderData()` ab.\n\n```jsx\nimport { useLoaderData } from \"react-router\";\n\nasync function invoiceDetailLoader({ params }) {\n  const response = await fetch(`/api/invoices/${params.invoiceId}`);\n  if (!response.ok) {\n    throw new Response(\"Not found\", { status: 404 });\n  }\n  return response.json();\n}\n\nfunction InvoiceDetail() {\n  const invoice = useLoaderData();\n  return <h1>Invoice {invoice.number}</h1>;\n}\n```\n\nMan beachte, was hier nicht steht. Kein `useState` für die Rechnung, kein `useEffect` fürs Laden, keine Prüfung auf `null`, solange noch geladen wird. Wenn `InvoiceDetail` rendert, ist der `loader` abgeschlossen. Ob `invoice` fachlich existiert, muss der Loader selbst absichern – etwa indem er bei einem leeren Ergebnis eine 404-Response wirft. Das Warten des Routers ersetzt diese Validierung nicht.\n\nDer eigentliche Gewinn zeigt sich bei verschachtelten Routen. Öffnet jemand `/invoices/42`, sind zwei Routen betroffen: die Liste und das Detail. Bei der `useEffect`-Variante liefe das nacheinander – erst rendert die Liste und lädt, dann rendert das Detail und lädt. React Router kennt beide `loader` von vornherein und startet sie **parallel**. Damit fällt der Wasserfall weg: Alle betroffenen `loader` laufen gleichzeitig los, und die Seite ist fertig, sobald der langsamste durch ist.\n\n```mermaid\nflowchart TB\n  Nav[\"Navigation zu /invoices/42\"]\n  Nav --> Match[\"Router ermittelt betroffene Routen\"]\n  Match --> L1[\"loader Liste\"]\n  Match --> L2[\"loader Detail\"]\n  L1 --> Ready[\"alle loader fertig\"]\n  L2 --> Ready\n  Ready --> Render[\"Komponenten rendern<br/>mit useLoaderData\"]\n```\n\nHier lohnt der Bezug zum Server-Cache. Im Beitrag zu [Client State und Server-Cache](https://www.mikebild.dev/de/blog/client-zustand-und-server-cache/) habe ich gezeigt, dass Serverdaten kein State sind, den man besitzt, sondern eine Kopie, die man verwaltet – mit Schlüssel, Alter und Invalidierung, wofür sich eine Bibliothek wie TanStack Query anbietet. Der `loader` liegt eine Ebene darüber. Er sagt, *wann* geladen wird, nämlich beim Navigieren, gebunden an die Route statt an die Komponente. Ob dahinter ein nackter `fetch` steht oder ein Cache, ist davon unberührt. Beides ergänzt sich sauber: Der `loader` ruft den `queryClient` auf, und die Bibliothek entscheidet, ob sie eine frische Kopie hält oder wirklich neu lädt. Der Router bestimmt den Zeitpunkt, der Cache die Gültigkeit – sie schließen sich nicht aus, sie greifen ineinander.\n\n## Die `action`: Schreiben über `<Form>`\n\nFür schreibende Vorgänge hält React Router eine eigene Komponente bereit. `<Form method=\"post\">` sieht aus wie ein gewöhnliches HTML-Formular, wird aber vom Router abgefangen: Statt die Seite neu zu laden, ruft er die `action` der passenden Route auf und übergibt ihr die Formulardaten.\n\n```jsx\nimport { Form, redirect } from \"react-router\";\n\nasync function invoiceDetailAction({ request, params }) {\n  const formData = await request.formData();\n  await fetch(`/api/invoices/${params.invoiceId}/pay`, {\n    method: \"POST\",\n    body: formData,\n  });\n  return redirect(`/invoices/${params.invoiceId}`);\n}\n\nfunction InvoiceDetail() {\n  const invoice = useLoaderData();\n  return (\n    <Form method=\"post\">\n      <button type=\"submit\">Mark as paid</button>\n    </Form>\n  );\n}\n```\n\nDas Entscheidende passiert nach der `action`: React Router revalidiert standardmäßig die Loader der aktiven Routen. Die Rechnung wurde bezahlt, die `action` ist durch, und die View kann den frischen Stand zeigen, weil die betroffenen Loader noch einmal gelaufen sind. Mit `shouldRevalidate` lässt sich dieses Verhalten einschränken; externe Caches müssen weiterhin passend invalidiert werden. Der Ablauf ähnelt dem Browserprinzip „Formular abschicken, Seite neu holen“, nur ohne den vollen Dokument-Neuaufbau.\n\n```mermaid\nflowchart LR\n  F[\"Form method=post\"] --> A[\"action schreibt<br/>zum Server\"]\n  A --> R[\"loader werden<br/>revalidiert\"]\n  R --> U[\"Ansicht zeigt<br/>frischen Stand\"]\n```\n\nWer das mit dem `useEffect`-Dashboard aus dem Server-Cache-Beitrag vergleicht, erkennt dieselbe Krankheit und eine andere Medizin. Dort liefen die Zahl oben und die Liste daneben auseinander, weil niemand nach dem Bezahlen dafür sorgte, dass beide neu luden. Hier laufen sie nach der `action` gemeinsam neu, weil die Revalidierung alle `loader` der aktiven Route-Ebenen betrifft und nicht eine einzelne Komponente.\n\n## Verschachtelte Routen und `<Outlet />`\n\nDie Objekte aus dem ersten Beispiel hatten `children`, und das ist mehr als eine Verwaltungsfrage. Verschachtelte Routen bilden die UI-Hierarchie ab: Eine äußere Layout-Route rendert den Rahmen – Navigation, Kopfzeile, Randspalte –, und dort, wo die innere Route erscheinen soll, setzt sie einen `<Outlet />`.\n\n```jsx\nimport { Outlet, NavLink } from \"react-router\";\n\nfunction InvoiceList() {\n  const invoices = useLoaderData();\n  return (\n    <div className=\"layout\">\n      <nav>\n        {invoices.map((invoice) => (\n          <NavLink key={invoice.id} to={`/invoices/${invoice.id}`}>\n            {invoice.number}\n          </NavLink>\n        ))}\n      </nav>\n      <main>\n        <Outlet />\n      </main>\n    </div>\n  );\n}\n```\n\nNavigiert man im Data Mode von `/invoices/42` zu `/invoices/43`, bleibt die äußere Route ohne eigenen geänderten Parameter standardmäßig stehen; ihr Loader läuft in diesem Beispiel nicht erneut, und nur die innere Route wechselt ihre Daten und ihren Inhalt im `<Outlet />`. Geänderte Suchparameter oder eine eigene `shouldRevalidate`-Regel können eine breitere Revalidierung auslösen. Die URL liest sich damit wie ein Pfad durch den Baum der Oberfläche: Jedes Segment steht für eine Ebene, jede Ebene für eine Route, jede Route für ein Stück UI mit eigenen Daten. Eine Layout-Route ganz ohne `path` kann übrigens allein dem gemeinsamen Rahmen dienen, während ihre Kinder die eigentlichen Adressen tragen.\n\n## Die URL als State: Suchparameter\n\nBis hierher ging es um den Pfad. Der zweite Teil der URL ist mindestens so nützlich: die Suchparameter hinter dem `?`. Im React-Überblick habe ich dafür plädiert, dass Auswahl und Filter in die URL gehören – und `useSearchParams` ist das Werkzeug dazu. Es fühlt sich an wie `useState`, schreibt seinen Wert aber in die Adresszeile.\n\n```jsx\nimport { useSearchParams } from \"react-router\";\n\nfunction InvoiceFilter() {\n  const [searchParams, setSearchParams] = useSearchParams();\n  const status = searchParams.get(\"status\") ?? \"all\";\n\n  return (\n    <select\n      value={status}\n      onChange={(event) =>\n        setSearchParams({ status: event.target.value })\n      }\n    >\n      <option value=\"all\">All</option>\n      <option value=\"open\">Open</option>\n      <option value=\"paid\">Paid</option>\n    </select>\n  );\n}\n```\n\nDer gewählte Filter steht jetzt in der URL – `/invoices?status=open` –, und das ändert seinen Charakter grundlegend. Dieser State ist teilbar: Man schickt den Link, und der Empfänger sieht dieselbe gefilterte Liste. Er ist mit einem Lesezeichen speicherbar. Er überlebt einen Reload, weil er nicht im Komponentenspeicher liegt, sondern in der Adresse. Und er lässt sich mit dem `loader` verbinden: Da der `loader` Zugriff auf die `request`-URL hat, kann er den `status`-Parameter auslesen und gleich die passend gefilterte Liste vom Server holen. Der Filter steht in der URL, der `loader` liest ihn, der Server liefert – aus einem Stück UI State wird ein navigierbarer Ort.\n\n## Fehler und langsame Teildaten\n\nWeil der `loader` vor dem Rendern läuft, braucht das Fehlschlagen einen eigenen Platz. Wirft ein `loader` oder eine `action` – etwa die `throw new Response(..., { status: 404 })` von oben –, sucht React Router die nächste Route mit `errorElement` und rendert diese statt der Komponente. Innerhalb des Fehler-Elements kommt man mit `useRouteError()` an das, was geworfen wurde.\n\n```jsx\nimport { useRouteError } from \"react-router\";\n\nfunction RouteError() {\n  const error = useRouteError();\n  return <p role=\"alert\">Something went wrong: {error.status}</p>;\n}\n```\n\nDas ersetzt viele verstreute `if (error)`-Zweige durch eine Stelle auf Route-Ebene. Die Route Error Boundary behandelt nicht nur Fehler aus `loader` und `action`, sondern auch Renderfehler in ihrem Routenast. Erwartbare fachliche Fehler sollte die Anwendung trotzdem bewusst modellieren, statt jeden negativen State als Exception zu behandeln.\n\nEin Randthema sei nur angerissen: Manchmal soll die Seite nicht auf die langsamste Datenquelle warten. React Router 8 hat die frühere `defer`-Hilfsfunktion entfernt. Heute gibt ein Loader nicht kritische Daten als noch nicht aufgelöstes Promise zurück; in der Komponente wartet `<Await>` innerhalb einer `<Suspense>`-Grenze darauf. Kritische Daten werden im Loader weiterhin `await`et. So blockiert ein träger Teil nicht die ganze View, ohne dass eine spezielle `defer`-Response nötig ist.\n\n## Ein Wort zu den drei Modi\n\nWas ich hier gezeigt habe, heißt in der aktuellen Dokumentation Data Mode: `createBrowserRouter` in einer bestehenden Anwendung. Der Declarative Mode mit `BrowserRouter` bietet das klassische Routing ohne die Data APIs. Der Framework Mode setzt auf den Data Mode auf, organisiert Routen als Module und ergänzt Build- und Server-Functions. Das ist ein eigenes, größeres Thema, und ich lasse es hier bewusst stehen. Die Konzepte, die zählen – `loader`, `action`, Revalidierung, die URL als State-Ort –, bleiben im Data und Framework Mode dieselben.\n\n## Wohin die Daten gehören\n\nDer rote Faden dieses Beitrags ist eine einzige Verschiebung. Beim klassischen Ansatz hängen Laden und Schreiben an der Komponente: Sie rendert, ihr Effect holt, ihre Handler schreiben, und bei Verschachtelung reihen sich die Ladevorgänge zu einem Wasserfall. Der Data Router verankert beides an der Route. Der `loader` holt die Daten, bevor gerendert wird, und benachbarte Ebenen parallel; die `action` schreibt und lässt die `loader` danach von selbst revalidieren. Was in der Komponente bleibt, ist das Anzeigen – nicht das Besorgen.\n\nDamit wird aus der URL endgültig das, was sie im Überblick nur behauptet hat zu sein. Sie ist nicht mehr das Adressfeld, das anzeigt, wo man ist. Sie ist der Ort, an dem der navigierbare State wirklich liegt: Der Pfad bestimmt, welche Routen und damit welche Daten geladen werden, die Suchparameter tragen Filter und Auswahl, und beides zusammen ist teilbar, speicherbar und übersteht jeden Reload. Wer einmal so baut, gibt die Ladelogik nicht ungern aus dem Komponenten-Body her.\n\n## Weiterführende Quellen\n\n- Repository introduction-react (Routing-Kapitel, Ordner recipes zum Data Fetching): https://github.com/mikebild/introduction-react\n- React Router, offizielle Dokumentation: https://reactrouter.com/\n- React Router, „Picking a Mode“: https://reactrouter.com/start/modes\n- React Router, „Data Loading“: https://reactrouter.com/start/data/data-loading\n- React Router, „Actions“: https://reactrouter.com/start/data/actions"},{"locale":"de","translation_key":"react-transitions-mit-usetransition","slug":"react-transitions-mit-usetransition","title":"React Transitions: nicht dringende Updates mit useTransition","summary":"useTransition markiert Updates als nicht dringend und hält React während teurer oder suspendierender Renderings responsiv. Dazu useDeferredValue als Werkzeug für nachgelagerte Renderings.","tags":["Software","Frontend","React"],"published_at":"2024-12-13T10:00:00+00:00","updated_at":"2026-07-13T13:31:04.873406+00:00","url":"https://www.mikebild.dev/de/blog/react-transitions-mit-usetransition/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/b522d82a29a1a6d4b549ab64428a21667c7c89e5215a955db3ea1a09ed4898e1/react-transitions-mit-usetransition-vorlesen.mp3","audio_duration_secs":662,"text":"Zwei Prioritäten braucht eine React-Oberfläche: eine für das, was sofort passieren muss, und eine für das, was warten darf. Reacts Scheduler kennt unterschiedliche Prioritäten, doch ein gewöhnliches State-Update wird zunächst als direkte Aktualisierung behandelt. Erst mit einer Transition markiert die Anwendung die nachfolgende Renderarbeit ausdrücklich als nicht blockierend.\n\nAm deutlichsten wird das an einer Stelle, um die es im [Beitrag zu Suspense und dem use-Hook](https://www.mikebild.dev/de/blog/react-suspense-und-use/) schon ging: dem harten Zurückspringen in den Fallback. Der Bereich zeigt gerade noch echten Inhalt, der State ändert sich, die Daten sind weg – und der Spinner erscheint. Genau so kam in einem Projekt die Rückfrage eines Kollegen: „Der Content steckt doch in einer Suspense-Grenze. Wenn sich der State ändert, greift der Fallback. Was sollen wir dagegen machen?“ Man sagt React, dass dieses eine Update nicht dringend ist. Dafür gibt es `useTransition`.\n\n## Dringend oder nicht dringend – die einzige Unterscheidung, die zählt\n\nDie Trennlinie verläuft zwischen zwei Sorten von Updates. Auf der einen Seite die dringenden: Ich tippe einen Buchstaben, das Zeichen muss sofort im Eingabefeld stehen. Ich hake eine Checkbox an, sie muss sofort angehakt sein. Alles, was sich wie eine direkte physische Reaktion anfühlen soll, ist dringend. Verzögert React das auch nur um 100 Millisekunden, fühlt sich die App kaputt an.\n\nAuf der anderen Seite die nicht-dringenden Updates: Ich wechsle den Tab, ich ändere den Filter einer großen Liste, ich stelle die Suchanfrage um. Das Ergebnis dieser Aktion darf einen Moment brauchen. Niemand erwartet, dass 10.000 neu gefilterte Zeilen in null Millisekunden erscheinen. Was aber jeder erwartet: dass die Oberfläche in der Zwischenzeit nicht einfriert und nicht sinnlos flackert.\n\nWelche fachliche Reaktion warten darf, kann React nicht aus dem Namen eines State-Werts ableiten. Mit den Concurrent Features, die seit React 18 und dem Wechsel auf `createRoot` stabil verfügbar sind, bekommen wir die Werkzeuge, um diese Absicht mitzuteilen. `useTransition` ist das wichtigste davon.\n\n## Die Signatur ist bewusst schlicht\n\n```jsx\nimport { useTransition } from 'react';\n\nfunction TabContainer() {\n  const [isPending, startTransition] = useTransition();\n  const [tab, setTab] = useState('overview');\n\n  function selectTab(nextTab) {\n    startTransition(() => {\n      setTab(nextTab);\n    });\n  }\n\n  return (\n    <>\n      <TabButton active={tab === 'overview'} onClick={() => selectTab('overview')}>\n        Overview\n      </TabButton>\n      <TabButton active={tab === 'reports'} onClick={() => selectTab('reports')}>\n        Reports\n      </TabButton>\n      <section style={{ opacity: isPending ? 0.6 : 1 }}>\n        <TabPanel tab={tab} />\n      </section>\n    </>\n  );\n}\n```\n\nDer Hook nimmt keine Parameter und gibt ein Zwei-Tupel zurück: `isPending`, ein Boolean, und `startTransition`, eine Funktion. Aufrufen darf man ihn wie jeden Hook nur in einer Komponente oder einem Custom Hook.\n\nDer entscheidende Teil steckt in `selectTab`. Der `setTab`-Aufruf wandert in den Callback von `startTransition`. Damit sagt die Komponente React: „Dieses Update ist eine Transition.“ Wenn das neue Panel dabei innerhalb einer bereits sichtbaren Suspense-Grenze suspendiert, kann React den bisherigen Inhalt stehen lassen, statt ihn sofort durch den Fallback zu ersetzen. Neu hinzukommende Suspense-Grenzen dürfen ihren Fallback dagegen weiterhin zeigen. Solange der Übergang läuft, ist `isPending` auf `true`. Genau daran hängt in meinem Beispiel die dezente Ausgrauung über `opacity`.\n\nDas ist die konkrete Einlösung des Suspense-Versprechens: Ein Update innerhalb von `startTransition` verhindert, dass bereits sichtbarer Content in den Fallback zurückspringt.\n\n## Was im Hintergrund wirklich passiert\n\n„React macht das schon“ reicht als Erklärung nicht, deshalb der Ablauf explizit als Diagramm. Wichtig ist die Verzweigung am Ende: Eine Transition ist unterbrechbar.\n\n```mermaid\nflowchart TD\n    A[Nutzer klickt Tab] --> B[setTab läuft in<br/>startTransition]\n    B --> C[React rendert neuen Tab<br/>im Hintergrund]\n    C --> D[Alte UI bleibt sichtbar<br/>isPending = true]\n    D --> E{Neue Daten /<br/>Render fertig?}\n    E -->|ja| F[Wechsel zur neuen UI<br/>isPending = false]\n    E -->|dringendes Update<br/>kommt rein| G[Hintergrund-Render wird<br/>verworfen und neu gestartet]\n    G --> C\n```\n\nDer linke Pfad ist der Normalfall: React rendert im Hintergrund, hält die alte Oberfläche, zeigt `isPending` und wechselt am Ende. Der rechte Pfad ist der Grund, warum die App bei teuren Updates überhaupt responsiv bleibt. Kommt während des Hintergrund-Renderings ein dringenderes Update herein – etwa eine Tastatureingabe – dann verwirft React die halbfertige Arbeit und beginnt neu. Man muss nicht warten, bis das teure Rendering durch ist, um wieder tippen zu können. Diese Unterbrechbarkeit ist der eigentliche Trick hinter dem Wort „concurrent“.\n\n## startTransition ohne Komponente\n\nNicht jeder State-Wechsel entsteht in einer Komponente. In Routern und Stores sitzt die auslösende Logik oft außerhalb des Komponentenbaums. Für diesen Fall gibt es den Standalone-Import:\n\n```jsx\nimport { startTransition } from 'react';\n\nfunction navigate(url) {\n  startTransition(() => {\n    setCurrentUrl(url);\n  });\n}\n```\n\nDiese Variante funktioniert überall, hat aber einen Preis: Sie liefert kein `isPending`. Wer den Ladezustand anzeigen will, braucht den Hook. Wer nur ein Update als nicht-dringend markieren will und den Pending-State an anderer Stelle beschafft, ist mit dem Standalone-Import gut bedient. Ich verwende ihn bewusst in Router-Callbacks, wo die Navigationsanzeige ohnehin woanders sitzt.\n\nSeit React 19, stabil seit Dezember 2024, akzeptiert `startTransition` übrigens auch async-Functions; darauf bauen die neuen Actions und `<form action>` intern auf. Das ist ein eigenes Thema – hier zählt nur: Der Transition-Mechanismus selbst ist die Grundlage darunter.\n\n## Der Klassiker unter den Fehlern: das Eingabefeld einfrieren\n\nIn Code-Reviews taucht an dieser Stelle immer wieder derselbe naheliegende Fehler auf. Wenn eine Transition teure Renderings entschärft, warum wickelt man dann nicht einfach jedes Update ein – auch das des Suchfelds?\n\n```jsx\n// Do NOT do this\nfunction onChange(e) {\n  startTransition(() => {\n    setText(e.target.value);\n  });\n}\n```\n\nDas Ergebnis ist ein träges, schwammiges Eingabefeld. Der Grund: Text im Input ist ein dringendes Update. Es fühlt sich direkt physisch an, jeder Buchstabe muss sofort stehen. Packt man es in eine Transition, darf React es verzögern und unterbrechen – und tut das auch. Controlled Inputs bleiben also dringend, der Text-State wird ganz normal gesetzt. Was teuer ist, ist nicht das Tippen, sondern das, was aus dem Text folgt – die gefilterte Liste. Und für die gibt es ein eigenes Werkzeug.\n\n## useDeferredValue: wenn ein Teil der Anzeige nachlaufen darf\n\n`useTransition` markiert State-Updates an ihrer auslösenden Stelle. `useDeferredValue` setzt anders an: Der aktuelle Wert bleibt dringend und sichtbar, während ein teurer Verbraucher vorübergehend mit der vorherigen Version weiterarbeiten darf. Das ist bei Props nützlich, aber ebenso bei lokalem Input-State, dessen abgeleitete Liste langsamer nachlaufen soll.\n\n```jsx\nimport { useDeferredValue, useState } from 'react';\n\nfunction SearchPage() {\n  const [query, setQuery] = useState('');\n  const deferredQuery = useDeferredValue(query);\n  const isStale = query !== deferredQuery;\n\n  return (\n    <>\n      <input value={query} onChange={(e) => setQuery(e.target.value)} />\n      <div style={{ opacity: isStale ? 0.5 : 1 }}>\n        <SlowList query={deferredQuery} />\n      </div>\n    </>\n  );\n}\n```\n\nHier bleibt das Eingabefeld dringend: `setQuery` läuft ohne jede Transition, jeder Buchstabe erscheint sofort. Die teure `SlowList` bekommt aber nicht `query`, sondern `deferredQuery`. React rendert zuerst mit dem alten Wert weiter – die Liste bleibt kurz stehen – und rendert dann im Hintergrund mit dem neuen Wert nach. Über den Vergleich `query !== deferredQuery` weiß ich, ob die Liste gerade veraltet ist, und graue sie in der Zwischenzeit dezent aus.\n\nDie Signatur nimmt seit React 19 ein optionales zweites Argument: `useDeferredValue(value, initialValue)`. Ohne `initialValue` wird beim allerersten Render nicht deferred; gibt man es an, rendert der erste Durchlauf mit diesem Startwert und schiebt den echten Wert in den Hintergrund. Für den Alltag reicht die einargumentige Form fast immer.\n\nEin Punkt, der immer wieder zu Missverständnissen führt: `useDeferredValue` ist kein Debounce und kein Throttle. Es gibt keinen festen Delay, und es verhindert keine Netzwerk-Requests. Es ist reine Render-Priorisierung. Wer bei jedem Tastendruck einen Fetch auslöst, hat mit `useDeferredValue` denselben Fetch-Sturm wie vorher – nur das Rendering der Ergebnisse ist entzerrt. Debouncing des Requests bleibt eine getrennte Aufgabe.\n\n## Der zweite Klassiker: der verlorene Kontext nach await\n\nSobald async-Functions ins Spiel kommen, tappt fast jeder in dieselbe Falle:\n\n```jsx\n// The transition context is lost after the await\nstartTransition(async () => {\n  const data = await fetchPage(url);\n  setPage(data); // no longer part of the transition\n});\n```\n\nDas `setPage` nach dem `await` läuft nicht mehr innerhalb der Transition. React verfolgt den Transition-Kontext synchron; nach einem `await` ist der ursprüngliche Aufruf längst zurückgekehrt. Der Fix ist unspektakulär: das Update nach dem `await` erneut einwickeln.\n\n```jsx\nstartTransition(async () => {\n  const data = await fetchPage(url);\n  startTransition(() => {\n    setPage(data);\n  });\n});\n```\n\nVerwandt dazu ein weiterer Stolperstein: Ein `set`-Aufruf, der aus einem `setTimeout` heraus passiert, wird ebenfalls nicht als Transition markiert, selbst wenn der `setTimeout` innerhalb von `startTransition` steht. Der Callback läuft erst später, außerhalb des synchronen Fensters. `startTransition` erwartet ein synchrones Update; alles, was in einen späteren Tick verschoben wird, fällt aus dem Transition-Kontext heraus.\n\n## Wann welches Werkzeug – der Entscheidungsbaum\n\nOb `useTransition` oder `useDeferredValue` greift, hängt daran, was verzögert werden darf: der State-Übergang selbst oder nur ein nachgelagerter Teil der Anzeige.\n\n```mermaid\nflowchart TD\n    A[Teures Update soll<br/>Interaktion nicht blockieren] --> B{Darf der Übergang<br/>selbst warten?}\n    B -->|ja| C[useTransition /<br/>startTransition]\n    B -->|nein, nur Verbraucher| D[useDeferredValue]\n    C --> E[Update wird markiert<br/>isPending verfügbar]\n    D --> F[Aktueller Wert bleibt direkt<br/>Verbraucher läuft nach]\n    E --> G[Beide: alte UI bleibt stehen<br/>statt Fallback]\n    F --> G\n```\n\nDie Trennlinie ist also nicht „welches ist moderner“, sondern schlicht die Frage der Kontrolle. Zur Verdichtung die beiden Werkzeuge nebeneinander:\n\n- `useTransition` / `startTransition`: Ich steuere ein Update, dessen sichtbares Ergebnis warten darf. Ich will das harte Zurückspringen in den Fallback vermeiden und brauche mit dem Hook zusätzlich `isPending`. Typisch: Tab-Wechsel oder eine nicht dringende Navigation.\n- `useDeferredValue`: Der aktuelle Wert muss sofort gelten, aber ein teurer Verbraucher darf noch kurz die vorige Version sehen. Ein Pending-Flag gibt es nicht, wohl aber den Vergleich `value !== deferredValue`, um veraltete Anzeigen auszugrauen. Typisch: die große abgeleitete Liste unter einem schnellen Eingabefeld.\n\nGemeinsam ist beiden, dass weniger dringende Renderarbeit hinter einer direkten Interaktion zurückstehen darf. Bei einer bereits sichtbaren Suspense-Grenze kann dadurch der vorhandene Inhalt stehen bleiben. Der Unterschied liegt darin, ob das auslösende Update oder ein Wert für nachgelagerte Verbraucher verzögert wird; `isPending` liefert nur `useTransition`.\n\n## Was ich in der Praxis empfehle\n\nEin paar Leitplanken, die sich in Projekten bewährt haben:\n\n- State, der ein kontrolliertes Textfeld steuert, bleibt dringend und darf nicht in eine Transition. Bei anderen direkten Eingaben prüfe ich, welcher Teil sofort reagieren muss und welche Folgearbeit warten darf.\n- Navigations- und Tab-Wechsel können in `startTransition` gehören, wenn ihr Ziel suspendiert oder teuer rendert. Router können diese Koordination bereits selbst übernehmen.\n- Für teure abgeleitete Renderings unter einem schnellen Input greift `useDeferredValue`, weil der aktuelle Eingabewert sofort sichtbar bleiben soll und nur die Liste nachläuft.\n- `isPending` und `value !== deferredValue` zeigen an, dass etwas gerade veraltet ist. Ich nutze sie für dezente Ausgrauung statt für einen ganzseitigen Spinner. Der Sinn der Übung ist ja, dass der Inhalt eben nicht verschwindet.\n- Der Kontextverlust nach `await` und in `setTimeout` ist tückisch. Wenn ein Update partout dringend wirkt, obwohl es in einer Transition steht, ist das fast immer die Ursache.\n\nWer die Concurrent Features grundsätzlich einordnen möchte, findet den größeren Zusammenhang in meinem React-Überblick von JSX zur Architektur. Der springende Punkt für heute bleibt eng: React kann nicht wissen, welche fachliche Reaktion sofort sichtbar sein muss und welche Renderarbeit warten darf. `useTransition` und `useDeferredValue` drücken diese Absicht an unterschiedlichen Stellen aus. Bei teuren Renderings kann die Oberfläche dadurch responsiv bleiben; bei bereits sichtbarem Suspense-Inhalt lässt sich ein unnötiges Zurückspringen in den Fallback vermeiden.\n\n## Weiterführende Quellen\n\n- Repository: die Beispiele zu Tab-Wechsel mit `useTransition`, dem `useDeferredValue`-Suchfeld und dem Standalone-`startTransition` liegen als lauffähiges Repo bereit.\n- [react.dev – useTransition](https://react.dev/reference/react/useTransition)\n- [react.dev – startTransition](https://react.dev/reference/react/startTransition)\n- [react.dev – useDeferredValue](https://react.dev/reference/react/useDeferredValue)\n- [react.dev – Suspense](https://react.dev/reference/react/Suspense)\n- [React 19 Release (Actions und Transition-Kontext)](https://react.dev/blog/2024/12/05/react-19)"},{"locale":"de","translation_key":"react-testing-ohne-theater","slug":"react-testing-ohne-theater","title":"React Testing ohne Theater","summary":"Tests auf sichtbares Nutzerverhalten koppeln weniger an DOM-Struktur, Komponentengrenzen und internen State. Dadurch überstehen sie bestimmte Refactorings ohne Anpassung.","tags":["Software","Testing"],"published_at":"2024-12-12T10:00:00+00:00","updated_at":"2026-07-13T08:56:25.034215+00:00","url":"https://www.mikebild.dev/de/blog/react-testing-ohne-theater/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/1a3a617091034ccd5bb43d31cf0eecb3529bbe6e594fa5e67a939835a3980acf/react-testing-ohne-theater-vorlesen.mp3","audio_duration_secs":632,"text":"# React Testing ohne Theater\n\nEin grüner Test beweist nicht, dass die Anwendung funktioniert. Er beweist zunächst nur, dass der Code noch so aussieht wie an dem Tag, an dem der Test geschrieben wurde. Genau diesen Unterschied verwischen React-Suites gern: Jede Komponente ist von Mocks umstellt, jede Zusicherung kennt den Hook, den State, den Namen der internen Funktion. Solche Tests werden beim ersten Refactoring reihenweise rot, obwohl die Anwendung fachlich unverändert funktioniert – teuer im Unterhalt und ohne Aussage über das Produkt. Das ist das Theater im Titel: viel Bühne, wenig Inhalt.\n\nDer Anlass für diesen Beitrag ist banal: eine kleine Vite-React-App aus dem Repo `introduction-react`, ein einziger Test, eine sichtbare Zeile im UI. Interessant ist nicht die Zeile, sondern die Grenze, die sie zieht – zwischen dem, was ein Nutzer erlebt, und dem, wie ich es intern gebaut habe. Diese Grenze ist die eigentliche Architekturentscheidung beim Testen. Wer sie sauber zieht, bekommt Tests, die Umbauten überleben. Wer sie verfehlt, bekommt eine Suite, die bei jedem Sprint mitgepflegt werden muss und trotzdem keine Regression fängt.\n\n## Die These: Verhalten schlägt Implementierung\n\nEin Test hat genau zwei Aufgaben. Er soll ein reales Fehlverhalten fangen, bevor es beim Nutzer ankommt. Und er soll mich nicht daran hindern, den Code umzubauen. Diese beiden Ziele stehen in Spannung, und die Auflösung heißt: teste, was der Nutzer beobachtet, nicht, wie die Komponente es intern erreicht.\n\nDer Unterschied wird an zwei Varianten desselben Tests sichtbar. Zuerst die brüchige Variante, die an die Innerei koppelt:\n\n```tsx\n// Brittle: couples the test to internal state and structure\ntest(\"increments the count state\", () => {\n  const { result } = renderHook(() => useCounter());\n\n  act(() => result.current.increment());\n\n  expect(result.current.count).toBe(1);\n});\n```\n\nDieser Test kennt den Hook, seinen Rückgabewert und dass „increment“ so heißt. Sobald ich `useCounter` durch einen Reducer, einen Store oder eine ganz andere Mechanik ersetze, bricht er – obwohl der Zähler im Browser weiter tut, was er soll. Der Test misst meine Implementierung, nicht das Produkt.\n\nJetzt dieselbe Zusicherung über das beobachtbare Verhalten:\n\n```tsx\n// Robust: asserts what the user actually sees\ntest(\"shows the new count after a click\", async () => {\n  const user = userEvent.setup();\n  render(<Counter />);\n\n  await user.click(screen.getByRole(\"button\", { name: /increment/i }));\n\n  expect(screen.getByRole(\"status\")).toHaveTextContent(\"Count: 1\");\n});\n```\n\nDieser Test weiß nichts über Hooks, State oder Struktur. Er weiß, dass es einen Button gibt, den man klickt, und dass danach eine Zahl steht. Genau das ist der Vertrag mit dem Nutzer. Ich kann die gesamte Innerei austauschen, und solange dieser Vertrag hält, bleibt der Test grün. Das ist der Punkt, an dem ein Test von einer Umbau-Bremse zu einem Sicherheitsnetz wird.\n\n## Wo die Grenze physisch verläuft\n\nDiese Grenze ist keine Haltung, sie ist im Query-Design der Testing Library eingebaut. Die Reihenfolge der Queries ist eine Trade-off-Ansage: `getByRole` und `getByLabelText` zuerst, `getByText` danach, `getByTestId` als letzte Rettung. Das ist kein Stilgeschmack. Eine Rollen-Query prüft nebenbei die Accessibility – wenn der Test das Element über seine Rolle findet, findet ein Screenreader es auch. Eine `data-testid` prüft nur, dass ich mir selbst ein Etikett geklebt habe.\n\n```tsx\n// Prefer accessible queries – they double as an a11y assertion\nscreen.getByRole(\"searchbox\");\nscreen.getByRole(\"button\", { name: /search/i });\n\n// testid is an escape hatch, not the default\nscreen.getByTestId(\"product-list\");\n```\n\nDie praktische Konsequenz: Ich schreibe Komponenten so, dass sie über Rollen und Labels ansprechbar sind – semantische Elemente, `aria-label` wo nötig, echte `<button>` statt geklickter `<div>`. Der Test zwingt mich zu barrierefreiem Markup, weil unzugängliches Markup schlicht schwer testbar ist. Das ist die Art von Kopplung, die ich will: Testbarkeit und Produktqualität ziehen in dieselbe Richtung.\n\nDie `testid` ist damit nicht verboten, sie ist nur begründungspflichtig. Legitim ist sie, wenn ein Container keine sinnvolle Rolle trägt – ein Layout-Wrapper, ein Chart-Canvas, eine Liste ohne semantisches Pendant. Dann ist ein bewusst gesetztes `data-testid` ehrlicher als eine erzwungene Rolle, die es im Produkt gar nicht gibt. Der Unterschied ist die Reihenfolge: Ich greife zur `testid`, weil die zugängliche Query nicht passt, nicht weil sie mir zu umständlich war. Diese Reihenfolge ist der ganze methodische Gehalt der Query-Prioritäten – sie macht die Ausnahme sichtbar, statt sie zur Regel werden zu lassen.\n\n## Der Fehlerpfad ist die halbe Arbeit\n\nDer glückliche Pfad sieht im Demo-Modus sauber aus. Geld verdient man mit dem Rest: leerer Antwort, Timeout, 500er, doppeltem Klick, langsamer Verbindung. Bei React-Anwendungen liegt dieser Rest fast immer an der Netzgrenze, und genau dort setze ich den Mock an – nicht am Hook, nicht am `fetch`-Aufruf, sondern an der HTTP-Schicht. Mit Mock Service Worker läuft die Komponente durch ihre echte Datenlogik, nur die Antwort ist kontrolliert.\n\n```tsx\n// The happy path: results the API returned actually render\ntest(\"renders products returned by the API\", async () => {\n  const user = userEvent.setup();\n  render(<ProductSearch />);\n\n  await user.type(screen.getByRole(\"searchbox\"), \"react\");\n  await user.click(screen.getByRole(\"button\", { name: /search/i }));\n\n  expect(await screen.findByRole(\"listitem\"))\n    .toHaveTextContent(\"React Handbook\");\n});\n```\n\nUnd die Kehrseite, die im Betrieb den Unterschied macht:\n\n```tsx\n// The failure path: does the UI degrade gracefully?\ntest(\"shows an error message when the request fails\", async () => {\n  server.use(\n    http.get(\"/api/products\", () => HttpResponse.error()),\n  );\n\n  const user = userEvent.setup();\n  render(<ProductSearch />);\n\n  await user.click(screen.getByRole(\"button\", { name: /search/i }));\n\n  expect(await screen.findByRole(\"alert\"))\n    .toHaveTextContent(/something went wrong/i);\n});\n```\n\nDer zweite Test ist wichtiger als der erste. Er beschreibt, was passiert, wenn das Backend wegbricht – ob die App eine Fehlermeldung zeigt oder in einen leeren, verwirrenden Zustand fällt. Dass ich den Mock über `server.use` pro Test setze, ist Absicht: Der Default ist der glückliche Pfad, die Störung ist eine explizite, lesbare Abweichung. Wer den Fehlerpfad nicht testet, hat die Hälfte des Produkts nicht getestet. Der Nutzer erlebt beide.\n\nZum Fehlerpfad gehört auch die async-Disziplin. `findBy*` wartet auf das Erscheinen eines Elements, `waitFor` auf das Eintreten einer Bedingung – aber nur auf beobachtbare Zustände, nicht auf `setTimeout`-Raten. Wer stattdessen feste Wartezeiten einbaut, tauscht Flakiness gegen Langsamkeit und behält am Ende beides.\n\n## Specification by Example: Tests, die die Fachsprache sprechen\n\nDer stabilste Test benennt eine fachliche Absicht, keinen technischen Ablauf. Ein Testname wie „calls dispatch with INCREMENT“ beschreibt Mechanik und altert mit jeder Umbenennung. „shows the new count after a click“ beschreibt ein Versprechen an den Nutzer und altert nur, wenn sich das Versprechen ändert. Das ist der Kern von Specification by Example: Das Beispiel ist gleichzeitig Fachdokumentation, Erwartung und automatisierbare Prüfung – drei Dinge, die sonst auseinanderdriften.\n\nPraktisch heißt das, ich schreibe die `describe`- und `test`-Blöcke so, dass ein Product Owner sie lesen und bestätigen könnte, ohne den Code zu kennen:\n\n```tsx\ndescribe(\"Product search\", () => {\n  test(\"shows results matching the query\", async () => { /* ... */ });\n  test(\"shows an empty state when nothing matches\", async () => { /* ... */ });\n  test(\"shows an error when the service is unavailable\", async () => { /* ... */ });\n});\n```\n\nDiese Suite ist eine Spezifikation. Sie sagt, was das Feature kann und was es bei Störung tut. Ein Reviewer sieht sofort, ob ein Fall fehlt – der leere Zustand, der Fehlerfall – und kann fachlich widersprechen, ohne die Implementierung zu lesen. Genau darin liegt der methodische Hebel: Missverständnisse werden im Test sichtbar, nicht erst im Betrieb. Das verschiebt die teure Klärung vom Ende der Kette an den Anfang.\n\n## Die Architektur der Suite: Schichten statt Masse\n\nNicht jeder Test kostet gleich viel und bringt gleich viel. Eine tragfähige React-Suite ist geschichtet. Reine Logik – Formatierung, Validierung, Reducer – prüfe ich als schnelle Unit-Tests ohne DOM. Das Verhalten der Komponenten prüfe ich als Component-Tests mit gemockter Netzgrenze; das ist die Schicht, in die ich das meiste Vertrauen und die meiste Zeit investiere. Und ich halte eine kleine Zahl echter Integrationsläufe, die das reale Zusammenspiel der Teile einmal durchspielen, statt es zu simulieren.\n\n```mermaid\nflowchart TD\n  A[User intent<br/>Specification by Example] --> B[Component tests<br/>role and label queries]\n  B --> C[Network boundary<br/>mocked with MSW]\n  C --> D[Few integration runs<br/>real wiring]\n  D --> E[Refactor<br/>tests stay green]\n  E --> A\n```\n\nDie Verteilung ist eine bewusste Investitionsentscheidung, kein Dogma. Viele langsame End-to-End-Tests geben ein warmes Gefühl und eine kalte Pipeline: Sie sind langsam, flaky und teuer im Unterhalt, und wenn sie rot werden, weiß niemand sofort warum. Wenige, gezielte Integrationsläufe plus eine dichte, schnelle Component-Schicht fangen mehr echte Fehler pro investierter Minute. Der Testlauf gehört in die schnelle Feedbackschleife des Entwicklers, nicht nur in die nächtliche CI – deshalb Vitest und jsdom statt echtem Browser, wo immer die Aussage das hergibt.\n\n## Warum sich das rechnet\n\nTesten ist kein Selbstzweck und keine Gewissensberuhigung, es ist eine Investition mit messbarer Rendite. Der Ertrag ist Änderungsgeschwindigkeit. Eine Suite, die an Verhalten koppelt, erlaubt Refactoring ohne Angst: Ich baue `useCounter` zu einem Store um, die Tests bleiben grün, ich weiß, dass der Vertrag hält. Eine Suite, die an Implementierung koppelt, macht jedes Refactoring zu einem zweiten Projekt – erst Code umbauen, dann Dutzende Tests nachziehen. Die zweite Sorte bringt Teams dazu, Umbauten aufzuschieben. So entsteht technische Schuld nicht trotz, sondern wegen der Tests.\n\nDer konkrete Vorteil liegt in der geringeren Kopplung. Wenn ein Test über Rolle, Beschriftung und sichtbares Ergebnis zugreift, darf ich Komponenten aufteilen, internen State verschieben oder das Markup umordnen, solange das beobachtbare Verhalten gleich bleibt. Ob Reviews kürzer werden oder die Regressionsrate sinkt, hängt dagegen von Suite, Laufzeit und den tatsächlich geprüften Fehlerpfaden ab.\n\n## Typische Fehler\n\nDer erste Fehler ist, das Werkzeug mit der Lösung zu verwechseln. Testing Library erzeugt keine guten Tests, sie macht schlechte nur schwerer. Man kann auch mit ihr an `testid`s kleben, den State über Umwege inspizieren und die Netzgrenze am falschen Punkt kappen. Das Tool drückt eine Grenze aus, es zieht sie nicht.\n\nDer zweite Fehler ist, Coverage mit Sicherheit zu verwechseln. Neunzig Prozent Zeilenabdeckung sagen nichts darüber, ob der Fehlerpfad geprüft ist. Eine Suite, die jeden glücklichen Pfad abdeckt und keinen Störfall, hat hohe Zahlen und niedrigen Wert. Ich zähle lieber Fehlerfälle als Zeilen.\n\nDer dritte Fehler ist, alles zu mocken. Wer den Hook mockt, den Store mockt und die Kindkomponente mockt, testet am Ende nur noch die Mocks. Je tiefer der Mock sitzt, desto weniger echtes Verhalten läuft durch den Test. Die Netzgrenze ist fast immer der richtige Schnitt – dahinter beginnt fremder Code, davor liegt mein Produkt.\n\n## Woran ich einen Test prüfe\n\nBevor ein Test in die Suite darf, stelle ich ihm drei Fragen. Würde er rot, wenn das Feature fachlich kaputtginge? Wenn nein, prüft er nichts. Bleibt er grün, wenn ich die Implementierung umbaue, ohne das Verhalten zu ändern? Wenn nein, ist er eine Umbau-Bremse. Und beschreibt sein Name eine Nutzerabsicht, die ein Fachexperte bestätigen könnte? Wenn nein, altert er mit dem nächsten Rename.\n\nEin Test, der alle drei Fragen besteht, ist billig im Unterhalt und teuer nur einmal – beim Schreiben. Ein Test, der eine davon reißt, wird jeden Sprint erneut bezahlt. Über die Lebensdauer eines Projekts entscheidet diese Differenz darüber, ob die Suite Vertrauen schafft oder Wartungslast.\n\n## Weiterführende Quellen\n\n- Workshop-Repo introduction-react: https://github.com/MikeBild/introduction-react\n\nDas Repo zeigt die kleine Vite-React-App und die Testbeispiele im Kontext einer vollständigen Lernkurve vom Baustein bis zur Architektur. Die Docs von Testing Library und Vitest helfen beim Gegenprüfen von Query-Prioritäten und async-Verhalten – die eigentliche Aussage bleibt aber die Entscheidung, wo im konkreten Beispiel die Grenze zwischen Verhalten und Implementierung verläuft.\n\n## Schluss\n\nReact Testing wird wertvoll, wenn Tests eine Frage beantworten, die den Nutzer interessiert: Tut die Anwendung, was sie soll, auch wenn etwas schiefgeht? Ein Test, der einen Klick simuliert und ein sichtbares Ergebnis prüft, bleibt bei internen Umbauten stabil, solange der Fachfall gleich bleibt. Das ist der belastbare Vorteil; Geschwindigkeit oder Fehlerquote müssen sich im Projekt zeigen."},{"locale":"de","translation_key":"react-suspense-und-use","slug":"react-suspense-und-use","title":"Suspense und der use-Hook: rendern, als wären die Daten schon da","summary":"Statt in jeder Komponente einen Ladezustand zu verwalten, beschreibt man mit Suspense an einer einzigen Stelle im Baum, was während des Wartens erscheint – und der use-Hook lässt die Komponente darunter rendern, als wären die Daten längst da.","tags":["Software","Frontend","React"],"published_at":"2024-12-10T10:00:00+00:00","updated_at":"2026-07-13T08:03:33.68271+00:00","url":"https://www.mikebild.dev/de/blog/react-suspense-und-use/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/04bb5eababe12e74e92420b1d17a9d8682ca7689603d19fe74fb66d503c0f2b4/react-suspense-und-use-vorlesen.mp3","audio_duration_secs":684,"text":"# Suspense und der use-Hook: rendern, als wären die Daten schon da\n\nWer das Warten in jeder Komponente einzeln ausprogrammiert, bezahlt das an der Oberfläche: Drei datenladende Komponenten nebeneinander heißen drei Spinner, die unabhängig voneinander aufblitzen und zu drei verschiedenen Zeitpunkten wieder verschwinden. Die Seite zuckt beim Aufbau, und jede dieser Komponenten schleppt dieselben drei Fälle mit sich herum – lädt, Fehler, Daten. In jeder steht irgendwo `if (isLoading) return <Spinner />` und darunter `if (error) return <ErrorMessage />`.\n\nDaran ändert auch der Umzug auf TanStack Query oder SWR nichts. Im [Beitrag über Client State und Server-Cache](https://www.mikebild.dev/de/blog/client-zustand-und-server-cache/) habe ich gezeigt, wie Serverdaten aus dem Gebastel aus `useState` und `useEffect` herauswandern und einer Cache-Bibliothek zufallen – der Ladezustand wandert dabei nicht mit, er bleibt in jeder Komponente stehen, die Daten braucht. React 19 setzt an einer anderen Stelle an, nämlich bei der Frage, wo im Baum das Warten überhaupt stattfindet. Suspense dreht sie um: Das Warten gehört nicht mehr in jede einzelne Komponente, sondern an eine Stelle darüber. Und die Komponente darunter darf so tun, als seien die Daten schon da.\n\n**Redaktionelle Einordnung (Juli 2026):** Suspense reagiert nicht auf beliebiges Datenladen in einem Effect oder Event-Handler. Für Daten funktioniert der hier beschriebene Ablauf mit Suspense-fähigen Frameworks und Bibliotheken oder beim Lesen eines stabilen, gecachten Promise mit `use`. Eine frei nutzbare, stabile React-API zum Bau eigener Suspense-Datenquellen ist weiterhin nicht dokumentiert.\n\n## Der Ladezustand verlässt die Komponente\n\nSehen wir uns zuerst an, wie es ohne Suspense aussieht. Eine Komponente, die eine Liste von Rechnungen anzeigt, trägt die drei States selbst:\n\n```jsx\nfunction InvoiceList() {\n  const { data, isLoading, error } = useInvoices();\n\n  if (isLoading) return <Spinner />;\n  if (error) return <ErrorMessage error={error} />;\n\n  return (\n    <ul>\n      {data.map((invoice) => (\n        <li key={invoice.id}>{invoice.title}</li>\n      ))}\n    </ul>\n  );\n}\n```\n\nDas ist nicht schlimm, aber es wiederholt sich. Jede datenladende Komponente sieht so aus, jede hat ihren eigenen `Spinner`, ihre eigene Error Handling. Und wenn drei solche Komponenten nebeneinander stehen, blitzen drei Spinner unabhängig voneinander auf und verschwinden zu unterschiedlichen Zeitpunkten – ein unruhiges Bild.\n\nSuspense stellt dem eine andere Idee gegenüber. Man umschließt einen Teil des Baums einmal mit `<Suspense>` und sagt: Alles darin, das noch auf Daten wartet, soll so lange diesen Fallback zeigen.\n\n```jsx\n<Suspense fallback={<Spinner />}>\n  <InvoiceList />\n</Suspense>\n```\n\nDie `InvoiceList` selbst kennt jetzt keinen Ladezustand mehr. Sie fragt die Daten ab, und wenn die noch nicht da sind, hält React die Komponente an und zeigt stattdessen den Fallback der nächsten umschließenden `<Suspense>`-Komponente. Das Wort dafür ist *suspendieren*: Die Komponente pausiert mitten im Rendern, bis das Versprochene eintrifft. Der Fallback ist nicht mehr Sache der Komponente, sondern des `<Suspense>` darüber.\n\n## Der `use`-Hook liest ein Promise\n\nDamit eine Komponente überhaupt suspendieren kann, braucht sie eine Möglichkeit, ein noch offenes Versprechen zu „lesen“. Genau das macht der `use`-Hook, der mit React 19 stabil ist. Man übergibt ihm ein Promise, und er gibt den aufgelösten Wert zurück – oder unterbricht das Rendern, wenn der Wert noch nicht da ist.\n\n```jsx\nimport { use } from \"react\";\n\nfunction InvoiceList({ invoicesPromise }) {\n  const invoices = use(invoicesPromise);\n\n  return (\n    <ul>\n      {invoices.map((invoice) => (\n        <li key={invoice.id}>{invoice.title}</li>\n      ))}\n    </ul>\n  );\n}\n```\n\nMan liest diese Zeile fast wie synchronen Code: `const invoices = use(invoicesPromise)`, danach steht `invoices` einfach zur Verfügung. Von der Zwischenzeit, in der das Promise noch offen ist, sieht die Komponente nichts. Ist das Promise noch nicht erfüllt, suspendiert `use` die Komponente, React hält an und zeigt den Fallback der umschließenden `<Suspense>`-Komponente. Sobald das Promise erfüllt ist, rendert React die Komponente erneut, diesmal mit dem Wert in der Hand.\n\nNeben Promises nimmt `use` übrigens auch einen Context entgegen und ersetzt in dieser Rolle `useContext`. Der interessante Fall für diesen Beitrag ist aber das Promise, weil daran das Zusammenspiel mit Suspense hängt.\n\n## Warum `use` bedingt aufgerufen werden darf\n\nHier lohnt sich ein kurzer Blick auf eine Besonderheit, die auf den ersten Blick wie ein Regelbruch aussieht. Für alle anderen Hooks gilt eine eiserne Regel: Sie müssen auf oberster Ebene der Komponente stehen, in immer derselben Reihenfolge, nie in einer Bedingung oder Schleife. Der Grund ist, dass React die Hooks pro Render über ihre Aufrufreihenfolge zuordnet – gerät die Reihenfolge durcheinander, verwechselt React die States.\n\n`use` ist ausdrücklich von dieser Regel ausgenommen. Man darf ihn in einer `if`-Bedingung aufrufen, in einer Schleife, hinter einem frühen `return`:\n\n```jsx\nfunction Message({ show, messagePromise }) {\n  if (show) {\n    const message = use(messagePromise);\n    return <p>{message}</p>;\n  }\n  return null;\n}\n```\n\nDas ist mehr als eine Bequemlichkeit. `use` speichert selbst keinen State, der über eine feste Aufrufreihenfolge einer Komponente zugeordnet werden müsste – er liest nur einen Wert aus einem Objekt, das man ihm reicht. Deshalb kann er dort stehen, wo er inhaltlich hingehört, statt an den Anfang der Komponente gezwungen zu werden. Man ruft ein Promise genau dann ab, wenn man seinen Wert wirklich braucht.\n\n## Fehler übernimmt die Error Boundary\n\nBleibt der dritte State von oben: der Fehler. Wenn das Promise nicht erfüllt, sondern abgelehnt wird, wirft `use` diesen Fehler beim Rendern. Und ein geworfener Fehler landet bei der nächsten *Error Boundary* – demselben Mechanismus, mit dem React seit jeher Render-Fehler auffängt.\n\n```jsx\n<ErrorBoundary fallback={<ErrorMessage />}>\n  <Suspense fallback={<Spinner />}>\n    <InvoiceList invoicesPromise={invoicesPromise} />\n  </Suspense>\n</ErrorBoundary>\n```\n\nDamit ist die Rechnung aufgegangen. Aus den drei States, die vorher jede Komponente selbst verwaltet hat – lädt, Fehler, Daten –, sind zwei Auffangnetze im Baum geworden plus der reine Erfolgsfall in der Komponente. Das `<Suspense>` kümmert sich um das Warten, die `<ErrorBoundary>` um das Scheitern, und die Komponente selbst rendert nur noch den Fall, für den sie eigentlich da ist: die vorhandenen Daten. Das `if (isLoading)` und das `if (error)` sind ersatzlos verschwunden.\n\n```mermaid\nflowchart TB\n  R[\"Komponente rendert,<br/>ruft use(promise)\"] --> Q{\"Promise-Zustand?\"}\n  Q -->|offen| S[\"suspendiert →<br/>Suspense zeigt Fallback\"]\n  S -.->|Promise erfüllt| R\n  Q -->|erfüllt| OK[\"Inhalt erscheint<br/>mit den Daten\"]\n  Q -->|abgelehnt| ERR[\"Fehler wird geworfen →<br/>ErrorBoundary fängt ihn\"]\n```\n\nAn dieser Stelle ist eine Error Boundary noch eine Klassenkomponente oder man greift zu einem kleinen Paket wie `react-error-boundary` – eine eingebaute Funktions-Variante gibt es in React 19 noch nicht. Das ändert am Bild aber nichts: konzeptionell ist es das zweite Auffangnetz neben Suspense.\n\n## Ehrlich bleiben: `use` ist keine Cache-Bibliothek\n\nJetzt kommt der Teil, den man leicht überliest, weil die Beispiele oben so aufgeräumt wirken. Woher kommt eigentlich das `invoicesPromise`? In den Codeschnipseln habe ich es als Prop hereingereicht und die Frage damit verschoben. Sie ist aber die entscheidende.\n\nMan könnte auf die Idee kommen, das Promise einfach in der Komponente zu erzeugen:\n\n```jsx\nfunction InvoiceList() {\n  // Trap: creates a new promise on EVERY render\n  const invoices = use(fetch(\"/api/invoices\").then((r) => r.json()));\n  // ...\n}\n```\n\nDas sieht kompakt aus und ist trotzdem falsch. Jeder Render-Durchlauf ruft `fetch` erneut auf und erzeugt ein frisches Promise. React sieht ein noch offenes Promise, suspendiert, rendert nach dem Auflösen neu – und erzeugt dabei sofort das nächste neue Promise. Man baut sich eine Endlosschleife aus Ladevorgängen. `use` cacht nichts, es dedupliziert nichts, es *liest* nur, was man ihm gibt.\n\nDamit das funktioniert, muss das Promise von außerhalb des Renderns kommen: von jemandem, der es einmal erzeugt, unter einem Schlüssel ablegt und bei der nächsten Anfrage dasselbe Promise zurückgibt. Das ist genau die Buchhaltung – Schlüssel, Alter, Deduplizierung, Invalidierung –, die ich im [Beitrag über den Server-Cache](https://www.mikebild.dev/de/blog/client-zustand-und-server-cache/) beschrieben habe. `use` und Suspense lösen sie nicht, sie setzen sie voraus.\n\nIn der Praxis liefern deshalb dieselben Werkzeuge die Promises, die man ohnehin schon einsetzt. TanStack Query und SWR haben beide einen Suspense-Modus: Statt `isLoading` und `error` zurückzugeben, suspendieren sie und werfen im Fehlerfall, sodass Suspense und Error Boundary die States übernehmen. Oder ein Framework wie Next.js erzeugt die Promises auf dem Server und reicht sie hinein. Die Regel aus dem Cache-Beitrag gilt unverändert: Serverdaten brauchen einen Cache mit Schlüssel und Invalidierung. Suspense ändert nur, wie sich das Warten darauf im Baum anfühlt – nicht, dass jemand den Cache führen muss.\n\n## Wofür sich der Aufwand lohnt\n\nWenn `use` die Buchhaltung nicht abnimmt, warum dann der ganze Umbau? Der Gewinn liegt woanders, nämlich in der Koordination mehrerer Datenquellen unter einem gemeinsamen `<Suspense>`.\n\nStellen wir uns eine Profilseite vor, die Nutzerdaten, die letzten Beiträge und eine Statistik lädt – drei Quellen. Ohne Suspense blitzen drei Spinner unabhängig auf und lösen sich zu drei Zeitpunkten auf; die Seite zuckt beim Aufbau. Legt man die drei Komponenten unter ein gemeinsames `<Suspense>`, wartet React, bis alle drei so weit sind, und zeigt dann die fertige Seite in einem Stück. Ein Fallback statt drei, ein Moment des Erscheinens statt drei.\n\nGenauso oft will man das Gegenteil: nicht auf die langsamste Quelle warten, sondern das Schnelle sofort zeigen. Dann verschachtelt man mehrere `<Suspense>`-Komponenten. Das Nutzerprofil steht unter einem äußeren `<Suspense>` und erscheint früh; die langsame Statistik bekommt ihr eigenes inneres `<Suspense>` mit eigenem Fallback und schiebt sich nach, sobald sie da ist.\n\n```jsx\n<Suspense fallback={<PageSkeleton />}>\n  <UserProfile userPromise={userPromise} />\n  <Suspense fallback={<StatsSkeleton />}>\n    <Statistics statsPromise={statsPromise} />\n  </Suspense>\n</Suspense>\n```\n\nSo beschreibt man ein gestaffeltes Erscheinen als Struktur im Baum, nicht als Logik in den Komponenten. Wo etwas erscheint und in welcher Reihenfolge, liest man an der Verschachtelung der `<Suspense>`-Komponenten ab – an einer Stelle, statt über ein Dutzend `isLoading`-Abfragen verstreut. Das ist der eigentliche Zugewinn: Die Lade-UI liegt dort, wo man über Layout nachdenkt, und nicht in jeder Komponente noch einmal.\n\nDamit hängt ein zweiter, weniger sichtbarer Vorteil zusammen: Suspense wirkt Lade-Wasserfällen entgegen. Ein Wasserfall entsteht, wenn eine Komponente erst lädt, dann rendert, und ein Kind darin wiederum erst dann mit seinem eigenen Laden beginnt – die Anfragen reihen sich nacheinander auf, obwohl sie voneinander gar nicht abhängen. Genau dieses Muster produziert das klassische `useEffect`-Laden fast von selbst, weil jede Komponente erst dann fetcht, wenn sie gerendert wird, und Kinder erst rendern, wenn die Eltern fertig geladen haben. Reicht man die Promises dagegen von außen hinein und startet sie früh, laufen die Anfragen parallel, während `use` sie unter einem gemeinsamen `<Suspense>` wieder einsammelt. Die Struktur des Wartens und die Struktur des Ladens fallen nicht mehr zwangsläufig zusammen.\n\n## Ein Nachladen, das die alte UI stehen lässt\n\nEin Detail sei noch angerissen, weil es in der Praxis schnell wichtig wird. Suspense zeigt seinen Fallback nicht nur beim ersten Laden, sondern auch, wenn sich die Daten unter einem `<Suspense>` ändern – etwa wenn man von einer Rechnung zur nächsten wechselt und ein neues Promise entsteht. Ohne Vorkehrung springt die Seite dann zurück in den Spinner, obwohl gerade eben noch brauchbare Daten zu sehen waren.\n\nGenau dafür gibt es `useTransition` und `startTransition`. Markiert man den Datenwechsel als Übergang, hält React die alte Oberfläche stehen und lädt im Hintergrund nach, statt sofort in den Fallback zu fallen. Man kann währenddessen anzeigen, dass etwas im Gange ist – ausgegraut, mit einem dezenten Hinweis –, ohne den bereits gerenderten Inhalt wegzuwerfen. Das verdient einen eigenen Beitrag; hier soll nur klar sein, dass das harte Zurückspringen in den Fallback kein Zwang ist.\n\n## Was bleiben soll\n\nSuspense und `use` verschieben nicht, wer die Daten besorgt – das bleibt Sache eines Caches. Sie verschieben, wo das Warten beschrieben wird. Statt in jeder Komponente drei States auszuprogrammieren, zieht man Laden und Fehler an zwei Stellen im Baum zusammen – Suspense und Error Boundary – und lässt die Komponenten darunter den Erfolgsfall annehmen. Die einzelne Komponente wird dadurch kleiner und ehrlicher: Sie tut so, als seien die Daten da, weil ein `<Suspense>` über ihr dafür sorgt, dass sie es sind, wenn die Komponente an die Reihe kommt.\n\nBeim Entwurf einer Seite bleibt damit eine Frage übrig: An welchen Stellen im Baum darf gewartet werden, und was soll dort so lange zu sehen sein? Die Antwort sind ein paar `<Suspense>`-Komponenten an den richtigen Stellen – und Komponenten, die vom Warten nichts mehr wissen müssen.\n\n## Weiterführende Quellen\n\n- Repository introduction-react (Kapitel server-access, react-hooks; Ordner recipes zum Data Fetching): https://github.com/mikebild/introduction-react\n- React, „Suspense“: https://react.dev/reference/react/Suspense\n- React, „use“: https://react.dev/reference/react/use\n- React, Suspense-fähiges Data Fetching: https://react.dev/reference/react/Suspense#displaying-a-fallback-while-content-is-loading"},{"locale":"de","translation_key":"client-zustand-und-server-cache","slug":"client-zustand-und-server-cache","title":"Client State vs. Server-Cache: die folgenreichste Grenze im Frontend","summary":"Serverdaten sind State, aber nicht client-eigener State. Warum diese Unterscheidung wichtig ist, wann useEffect zum schlechten Cache wird und was eine Server-State-Bibliothek übernimmt.","tags":["Software","Frontend","React"],"published_at":"2024-12-06T10:00:00+00:00","updated_at":"2026-07-13T13:19:06.078134+00:00","url":"https://www.mikebild.dev/de/blog/client-zustand-und-server-cache/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/19c38bb5a94c192f8923863d9b56e0801b8caf9b67a9d6623099f73e63c47c45/client-zustand-und-server-cache-vorlesen.mp3","audio_duration_secs":739,"text":"# Client State vs. Server-Cache: die folgenreichste Grenze im Frontend\n\n```jsx\nconst [invoices, setInvoices] = useState([]);\n\nuseEffect(() => {\n  fetch(\"/api/invoices\")\n    .then((r) => r.json())\n    .then(setInvoices);\n}, []);\n```\n\n`invoices` ist kein client-eigener State. Es ist eine Cache-Kopie von Daten, deren Original in einer Datenbank hinter `/api/invoices` liegt. Und diesem Cache fehlt alles, was einen brauchbaren Cache ausmacht: ein Schlüssel, unter dem eine zweite Komponente dieselbe Kopie findet; ein Alter, ab dem sie als überholt gilt; eine Stelle, an der man sie nach einer Änderung für ungültig erklärt. Solange nur eine Komponente lädt und niemand etwas ändert, fällt das nicht auf.\n\nDer React-Überblick unterscheidet vier Orte für State: die Komponente, die URL, einen globalen Store und, fast beiläufig, den Server-Cache. Diese letzte Grenze verdient einen eigenen Beitrag, weil sie im Alltag die meisten Fehler verursacht und weil man sie so leicht übersieht.\n\nDiese Verwechslung ist kein Anfängerfehler, den man sich abgewöhnt. Ich sehe sie in Code-Reviews bei Leuten, die seit Jahren React schreiben, und ich habe sie selbst lange gemacht. Der Unterschied klingt akademisch, hat aber ganz praktische Folgen: Er entscheidet, welches Werkzeug man wählt, wie viele Bugs man später jagt und wie klein oder groß der Teil der Anwendung wird, den man von Hand verwalten muss.\n\n## Zwei Sorten State, die man ständig verwechselt\n\nFangen wir mit einer einfachen Frage an: Wo liegt die Wahrheit? Bei echtem Client State liegt sie im Browser. Der Text in einem Eingabefeld, ob ein Menü auf- oder zugeklappt ist, welcher Tab gerade aktiv ist – all das entsteht durch eine Nutzerinteraktion und existiert nur hier. Niemand außerhalb dieses Browsers kennt diesen Wert oder braucht ihn. Wenn die Komponente verschwindet, verschwindet er mit, und das ist völlig in Ordnung.\n\nBei Serverdaten ist es umgekehrt. Die Liste der Rechnungen, das Nutzerprofil, der Warenbestand – die Wahrheit dazu liegt im Backend, in einer Datenbank, hinter einer API. Was der Browser davon hat, ist nur eine Kopie. Und Kopien haben eine unangenehme Eigenschaft: Sie veralten. In der Sekunde, in der der Server die Antwort abschickt, kann jemand anderes den Datensatz schon geändert haben. Der Browser hält dann einen Abzug, der aussieht wie die Wahrheit, es aber nicht mehr ist.\n\n```mermaid\nflowchart TB\n  Frage[\"Wo lebt die Wahrheit?\"]\n  Frage --> Client[\"im Browser<br/>= Client-Zustand\"]\n  Frage --> Server[\"im Backend<br/>= Serverdaten\"]\n  Client --> C1[\"Eingaben, Auswahl,<br/>aufgeklappte Menüs\"]\n  Server --> S1[\"Der Browser hält nur<br/>eine Kopie – sie veraltet\"]\n```\n\nSobald man diese Frage einmal stellt, sortiert sich vieles neu. Der Zähler, das Formular, die Filterauswahl – Client State. Die geladene Liste, das Suchergebnis, der Kontostand – Serverdaten, also ein Cache. Und für einen Cache gelten andere Regeln als für State, den man selbst besitzt.\n\n## Warum `useEffect` allein keinen Server-Cache ersetzt\n\nDer übliche erste Reflex sieht so aus: Man nimmt `useState` für die Daten, `useEffect` für das Laden, und fertig. Hier noch einmal das Muster vom Anfang, diesmal mit Fehlerpfad und Aufräumfunktion, damit es überhaupt korrekt ist:\n\n```jsx\nfunction useInvoices() {\n  const [data, setData] = useState(null);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    let active = true;\n    fetch(\"/api/invoices\")\n      .then((r) => r.json())\n      .then((d) => active && setData(d))\n      .catch((e) => active && setError(e.message));\n    return () => {\n      active = false;\n    };\n  }, []);\n\n  return { data, error };\n}\n```\n\nDas funktioniert – für genau eine Komponente, die genau einmal lädt. Sobald die Anwendung wächst, fehlt hier fast alles, was Serverdaten wirklich brauchen. Zwei Komponenten, die dieselbe Liste anzeigen, laden sie zweimal, weil keine von der anderen weiß. Wechselt man weg und kommt zurück, wird von vorne geladen, obwohl die Daten von eben noch gut genug wären. Es gibt keinen Weg, die Kopie nach einer Änderung gezielt zu erneuern. Und der Wettlauf zwischen einer alten und einer neuen Anfrage, den die Aufräumfunktion oben entschärft, ist nur der offensichtlichste einer ganzen Familie von Problemen.\n\nEin Beispiel, das ich so ähnlich in einem echten Projekt erlebt habe: ein Dashboard, oben eine Zahl „offene Rechnungen: 12“, daneben eine Liste derselben Rechnungen. Beide Bausteine laden ihre Daten in einem eigenen Effect. Schon beim Start feuern zwei Anfragen, wo eine gereicht hätte. Ärgerlicher wird es, wenn jemand eine Rechnung bezahlt: Die Liste lädt neu und zeigt elf, die Zahl oben lädt nicht neu und zeigt weiter zwölf. Zwei Kopien derselben Wahrheit, die auseinanderlaufen – und niemand hat einen Fehler gemacht, der Code ist nur ehrlich zu Ende gedacht. Genau solche Widersprüche entstehen zwangsläufig, wenn jede Komponente ihren eigenen kleinen Cache hält, ohne dass es eine gemeinsame Stelle gibt, die weiß, welche Daten gerade gültig sind.\n\nDer eigentliche Punkt ist ein anderer. Ein Effect synchronisiert eine Komponente mit etwas außerhalb von React – das ist seine Aufgabe, und dafür ist er richtig. Aber das Verwalten eines Caches ist kein Randthema einer einzelnen Komponente. Es ist ein anwendungsweites Problem: Wer hält welche Daten, wie alt dürfen sie sein, wann werden sie erneuert, wer teilt sie sich? Dieses Problem in jedem `useEffect` einzeln und von Hand zu lösen, ist ungefähr so, als würde man in jeder Funktion eine eigene kleine Datenbank schreiben. Es geht, aber es skaliert nicht, und jede Kopie hat ihre eigenen Bugs.\n\n## Was eine Server-State-Bibliothek übernimmt\n\nAn dieser Stelle lohnt sich ein Werkzeug, das genau für diesen Fall gebaut ist. TanStack Query (früher React Query) und SWR sind die beiden verbreiteten Vertreter. Sie teilen dieselbe Grundidee, die man am Namen von SWR ablesen kann: *stale-while-revalidate*. Zeig die vorhandene, womöglich veraltete Kopie sofort an, und erneuere sie im Hintergrund. Der Nutzer sieht sofort Daten, und kurz darauf die frischen.\n\nDer Kern ist ein zentraler Cache, der Daten unter einem Schlüssel ablegt. Man beschreibt nur, was man will und woher es kommt:\n\n```jsx\nimport { useQuery } from \"@tanstack/react-query\";\n\nfunction useInvoices() {\n  return useQuery({\n    queryKey: [\"invoices\"],\n    queryFn: () => fetch(\"/api/invoices\").then((r) => r.json()),\n    staleTime: 30_000,\n  });\n}\n```\n\nDas sieht kaum kürzer aus als der `useEffect`, aber dahinter steckt eine ganze Maschinerie. Fragen zwei Komponenten `[\"invoices\"]` gleichzeitig ab, wird trotzdem nur eine Anfrage geschickt – das ist Deduplizierung. Kommt eine Komponente zurück, deren Daten jünger als die `staleTime` sind, wird gar nicht neu geladen. Sind sie älter, zeigt die Bibliothek die alte Kopie sofort und lädt im Hintergrund nach. Der `queryKey` ist dabei mehr als ein Name: Er ist die Identität der Daten im Cache und der Angelpunkt für alles Weitere.\n\nAm deutlichsten wird der Unterschied beim Schreiben. Nach einer Mutation muss der Cache erfahren, dass seine Kopie jetzt falsch ist:\n\n```jsx\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\n\nfunction usePayInvoice() {\n  const queryClient = useQueryClient();\n  return useMutation({\n    mutationFn: (id) => fetch(`/api/invoices/${id}/pay`, { method: \"POST\" }),\n    onSuccess: () => {\n      queryClient.invalidateQueries({ queryKey: [\"invoices\"] });\n    },\n  });\n}\n```\n\nDer Aufruf `invalidateQueries` markiert alle Abfragen unter `[\"invoices\"]` als veraltet und lädt die aktiven davon neu. Man sagt also nicht mehr „setze diesen State“, sondern „diese Serverdaten sind jetzt unzuverlässig, hol sie dir frisch“. Das ist genau die richtige Denkweise für einen Cache: Man besitzt die Daten nicht, man hält sie nur vorläufig, und nach einer Änderung erklärt man die Kopie für ungültig. Verwenden Zähler und Liste dieselbe Schlüsselfamilie, lassen sie sich mit dieser einen Invalidierung gemeinsam aktualisieren. Das beseitigt eine häufige Ursache für auseinanderlaufende Anzeigen; eine Garantie ersetzt es nicht, denn Schlüssel, Error Handling und Serverantworten müssen weiterhin zusammenpassen.\n\nWer will, geht einen Schritt weiter und aktualisiert die Oberfläche schon, bevor der Server geantwortet hat. Über den `onMutate`-Callback schreibt man den erwarteten neuen Stand direkt in den Cache, sodass die Rechnung sofort als bezahlt erscheint; kommt der Server dann mit einem Fehler zurück, rollt die Bibliothek den Cache auf den alten Stand zurück. Dieses optimistische Aktualisieren macht Oberflächen spürbar schneller, und es ist überhaupt nur möglich, weil die Daten an einer zentralen, benannten Stelle liegen und nicht in einem Dutzend einzelner `useState`-Werte verstreut sind.\n\n```mermaid\nflowchart LR\n  A[\"Komponente fragt<br/>queryKey\"] --> B{\"Kopie im Cache<br/>und noch frisch?\"}\n  B -->|ja| C[\"sofort anzeigen,<br/>nichts laden\"]\n  B -->|veraltet| D[\"alte Kopie zeigen +<br/>im Hintergrund neu laden\"]\n  D --> E[\"frische Daten<br/>ersetzen die Kopie\"]\n```\n\nDazu kommt eine ganze Reihe Kleinigkeiten, die man sonst von Hand bauen müsste: erneutes Laden, wenn das Fenster wieder den Fokus bekommt, Wiederholung bei Netzfehlern, `pending`- und `error`-States als sauberes Ergebnis statt als drei einzelne `useState`, und Werkzeuge, die den Cache im Browser sichtbar machen. Nichts davon ist Zauberei – es ist genau die Buchhaltung, die ein Cache braucht und die in einem `useEffect` immer fehlt.\n\n## SWR oder TanStack Query?\n\nBeide Bibliotheken lösen dasselbe Problem, setzen aber unterschiedliche Schwerpunkte. SWR ist bewusst schlank, hat eine schmale API und ist schnell verstanden. Man sagt ihr, wie lange Daten als frisch gelten, und ruft `mutate(key)` auf, um sie zu erneuern. Für lese-lastige Oberflächen mit einfachen Schreibvorgängen ist das oft genau richtig, gerade im Next.js-Umfeld.\n\nTanStack Query ist umfangreicher und gibt mehr Kontrolle: `staleTime` und `gcTime` trennen sauber, wie lange Daten frisch bleiben und wann sie aus dem Speicher fallen; `invalidateQueries` kann über einen Präfix ganze Familien von Abfragen auf einmal für veraltet erklären, was bei verschachtelten Daten viel wert ist; und `useMutation` ist eine vollständige State Machine mit Callbacks für optimistische Updates. Der Preis ist etwas mehr Gewicht und ein paar Stellschrauben mehr. Für kleine, überschaubare Fälle reicht SWR; sobald die Server-State-Komplexität zu wachsen droht, zahlt sich TanStack Query aus.\n\nDer wichtigere Punkt liegt aber quer zu dieser Wahl: Sobald man Serverdaten als das behandelt, was sie sind – einen Cache mit Schlüssel, Alter und Invalidierung –, verschwindet das ganze `useState`-und-`useEffect`-Gebastel, egal für welche der beiden man sich entscheidet.\n\n## Was dann noch echter Client State ist\n\nJetzt kommt die eigentliche Pointe, und sie überrascht auch erfahrene Kollegen regelmäßig. Wenn man die Serverdaten aus der State Management herauszieht, bleibt erschreckend wenig übrig. Die Gegenprobe ist schnell gemacht: alles auflisten, was bisher für „globalen State“ gehalten wurde, und dann Punkt für Punkt streichen. Die geladenen Listen? Cache. Die Detaildaten? Cache. Das Suchergebnis? Cache. Welcher Filter aktiv ist, welche Seite man sieht, welcher Datensatz ausgewählt ist? Das gehört in die URL – teilbar, mit Lesezeichen speicherbar, überlebt einen Reload.\n\nWas am Ende als client-eigener State übrig bleibt, ist in vielen Anwendungen ein kleiner Kern: der Text in einem Formular, während man noch tippt, UI-Details wie aufgeklappte Bereiche und einige app-weite Entscheidungen – etwa Theme oder Warenkorb. Dafür reichen häufig `useState`, Context oder ein leichter Store. Die Serverdaten bleiben ebenfalls State, haben aber eine andere Quelle, Lebensdauer und Invalidierungslogik. Genau deshalb gehören sie nicht ohne Weiteres in denselben globalen Store.\n\nDas ist der Grund, warum ich diese Grenze für die folgenreichste im ganzen Frontend halte. Sie entscheidet nicht nur über ein Werkzeug. Sie räumt die halbe State Management ab, bevor man sie überhaupt baut.\n\n## React 19: `use()` und Suspense\n\nEin Ausblick, weil sich hier gerade etwas verschiebt. React 19 bringt mit `use()` und Suspense einen weiteren Weg, Serverdaten ins Rendern zu holen: Man reicht einer Komponente ein stabiles Promise, `use()` suspendiert, bis es erfüllt ist, und eine umschließende `<Suspense>`-Komponente zeigt so lange einen Fallback. Das Promise sollte aus einem Framework oder Cache stammen und nicht bei jedem Rendern neu erzeugt werden. So rücken Lade- und Fehlerzustände an den Rand, statt in jeder Komponente einzeln behandelt zu werden.\n\nDas ersetzt eine Cache-Bibliothek nicht – irgendjemand muss die Promises weiterhin erzeugen, cachen und invalidieren, und genau das übernehmen TanStack Query und SWR inzwischen mit Suspense-Unterstützung. Aber es ändert, wie sich das Warten im Baum anfühlt. Diesem eigenen großen Thema widme ich den Beitrag Suspense und der use-Hook; hier steht es nur als Wegweiser, damit klar ist, wohin sich React hier entwickelt.\n\n## Was bleiben soll\n\nWenn von diesem Beitrag ein Satz hängen bleiben soll, dann dieser: Frag bei jedem Wert, der wie State aussieht, zuerst, wo seine Wahrheit liegt. Liegt sie im Browser, ist es echter Client State, und `useState` ist richtig. Liegt sie im Backend, ist es ein Cache, und dann braucht es Cache-Regeln – Schlüssel, Alter, Invalidierung – und ein Werkzeug, das diese Buchhaltung übernimmt, statt sie in jeden `useEffect` zu kopieren.\n\nDiese Unterscheidung zuerst zu treffen und erst danach das Werkzeug zu wählen, verhindert doppelte Caches und widersprüchliche Kopien. Serverdaten sind geliehener State: Der Client verwaltet ihre Darstellung, besitzt aber weder ihre Wahrheit noch ihren Lifecycle allein.\n\n## Weiterführende Quellen\n\n- Repository introduction-react (Kapitel server-access, react-hooks; Ordner recipes zum Data Fetching): https://github.com/mikebild/introduction-react\n- React, „Du brauchst vielleicht keinen Effect“: https://react.dev/learn/you-might-not-need-an-effect\n- React, mit Effects synchronisieren: https://react.dev/learn/synchronizing-with-effects\n- TanStack Query, Query Invalidation: https://tanstack.com/query/latest/docs/framework/react/guides/query-invalidation\n- SWR, offizielle Dokumentation: https://swr.vercel.app/"},{"locale":"de","translation_key":"scheduler-und-virtuelle-zeit-testen","slug":"scheduler-und-virtuelle-zeit-testen","title":"Scheduler und virtuelle Zeit testen","summary":"Injizierbare Zeit macht zeitabhängige Regeln schnell und deterministisch testbar. Daten, Isolation und externe Systeme bleiben davon unberührt.","tags":["Software","Reactive"],"published_at":"2024-11-12T10:00:00+00:00","updated_at":"2026-07-13T08:53:24.655184+00:00","url":"https://www.mikebild.dev/de/blog/scheduler-und-virtuelle-zeit-testen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/54183ee96e22b7fb3f5f42909db8046f0661617fdd6e8bb71425469f947738b4/scheduler-und-virtuelle-zeit-testen-vorlesen.mp3","audio_duration_secs":611,"text":"# Scheduler und virtuelle Zeit testen\n\nDie teuerste Stelle in einer asynchronen Codebasis ist selten der Algorithmus. Sie ist die Zeit. Debounce, Retry, Timeout, Polling, „warte 250 ms und feuere dann den letzten Wert“ – solche Regeln sind fachlich einfach, aber im Test brutal. Wer sie mit echter Zeit prüft, baut Suiten, die langsam laufen, gelegentlich rot werden und niemandem mehr etwas beweisen. Der Ausweg steckt in einer Stelle, die im Code kaum auffällt: dem Scheduler, über den ein Operator seine Uhr bezieht. Steht der als Argument in der Signatur statt als Framework-Default im Hintergrund, lässt sich die Uhr im Test vorspulen, statt auf sie zu warten.\n\nDie Reihenfolge, in der sich das erschließt, ist nicht die Reihenfolge der Dokumentation: MVVM, asynchrone Programmierung, Scheduler, Streams, Observable Pattern, Message Bus, Testing. Erst entsteht das Problem mit Zeit, dann kommt Rx als Modell dafür, und ganz am Ende steht der Scheduler als die Grenze, an der das Ganze überhaupt prüfbar wird. Dieser letzte Schritt trägt das meiste – er macht aus einer eleganten, aber schwer greifbaren Technik etwas, das man in Sekunden testen und im Team verteidigen kann.\n\n## Das eigentliche Problem ist nicht Async, sondern Warten\n\nReactive Programming – ob RxJS im Frontend oder ReactiveUI im Desktop-Client – modelliert asynchrone Daten als Observables mit Operatoren. Die Stärke liegt nicht in der Menge der Operatoren. Sie liegt darin, dass Zeit, Abbruch, Fehler und Transformation explizit werden. `debounce`, `switchMap`, `mergeMap` und `combineLatest` treffen jeweils eine andere Systemaussage: Wird ein alter Request abgebrochen? Dürfen Ergebnisse parallel eintreffen? Zählt nur der letzte Wert? Operatoren sind Antworten auf diese Fragen, keine Vokabelliste.\n\nSobald aber Zeit im Spiel ist, kippt die Testbarkeit. Ein Test für „debounce um 250 ms“ hat drei schlechte Optionen: real warten (langsam, und mit jeder solchen Regel summiert sich die Laufzeit), großzügige Sleeps setzen (nichtdeterministisch, weil sie auf langsamer CI anders takten) oder die Logik gar nicht testen (die Regel driftet unbemerkt). Alle drei kosten – und zwar dort, wo es am meisten weh tut: im täglichen Feedback-Zyklus des Teams. Eine Suite, die zehn Minuten läuft und alle paar Läufe grundlos rot ist, wird nicht mehr vertraut. Und einer Suite, der niemand vertraut, folgt niemand.\n\n## Die Idee: Zeit ist eine Abhängigkeit\n\nDer architektonische Hebel ist unspektakulär und genau deshalb tragfähig: Zeit wird nicht aus der Laufzeit genommen, sondern hereingereicht. Ein Scheduler ist die Abstraktion, über die Operatoren Zeit beziehen – „wann wird das nächste Event geplant, und relativ zu welcher Uhr“. In Produktion ist das eine echte Uhr. Im Test ist es eine virtuelle Uhr, die ich von Hand vorspule.\n\n```ts\nconst result$ = input$.pipe(\n  debounceTime(250, scheduler),\n  distinctUntilChanged(),\n  switchMap((query) => search(query))\n);\n```\n\nDer einzige Unterschied zur naiven Variante ist das zweite Argument von `debounceTime`. Es sieht nach einem Detail aus, verschiebt aber die Kontrolle über Zeit vom impliziten Framework-Default zu einer expliziten, austauschbaren Abhängigkeit. Das ist dasselbe Prinzip wie Dependency Injection für eine Datenbank oder einen HTTP-Client – nur angewandt auf die eine Ressource, die sich sonst nicht mocken lässt.\n\nIm Test wird dann nicht gewartet. Zeit wird bewegt.\n\n```ts\nscheduler.advanceBy(249);\nexpect(search).not.toHaveBeenCalled();\nscheduler.advanceBy(1);\nexpect(search).toHaveBeenCalledWith(\"abc\");\n```\n\nDer Test macht eine Aussage, die vorher gar nicht formulierbar war: „Bei 249 ms passiert nichts, bei genau 250 ms feuert der Aufruf.“ Er läuft in Mikrosekunden, unabhängig von der Maschine, und er dokumentiert die fachliche Regel exakt. Der Gewinn ist dabei nicht in erster Linie Tempo. Es ist die Präzision: Eine Zeitentscheidung, über die vorher nur geredet wurde, wird nachweisbar.\n\n```mermaid\nflowchart LR\n  Input[User input] --> Debounce\n  Debounce --> Distinct\n  Distinct --> SwitchMap\n  SwitchMap --> Result\n  SwitchMap -. cancel old request .-> Cancelled\n```\n\n## Warum das eine Architekturfrage ist, keine Testtechnik\n\nEs wäre bequem, virtuelle Zeit als Trick der Testschicht abzulegen. Das greift zu kurz. Die Entscheidung, Zeit injizierbar zu machen, zwingt den Produktivcode, seine zeitlichen Abhängigkeiten offenzulegen. Wo vorher ein `setTimeout` still im Inneren einer Klasse saß, steht jetzt ein Scheduler in der Signatur. Zeit wird von einem versteckten Side Effect zu einem sichtbaren Kontrakt.\n\nBeim Debounce lautet die fachliche Regel: Das Backend soll nicht jeden Tastendruck erhalten, die Oberfläche aber zeitnah reagieren. Der Scheduler macht die gewählten 250 Millisekunden zu einer austauschbaren Eingabe. Wenn der Wert zu knapp ist, ändere ich ihn zusammen mit einem Grenztest statt durch manuelles Klicken auf einer langsamen Umgebung.\n\nDer Trade-off ist real und gehört benannt. Ein Scheduler in der Signatur ist mehr Zeremonie als ein direkter Timer. Man muss ihn durchreichen, und Teams, die Rx neu einführen, empfinden das anfangs als Overhead. Spätestens mit der zweiten oder dritten zeitabhängigen Regel amortisiert sich der Aufwand. Vorher ist es Disziplin, danach ist es Selbstläufer. Wer den Scheduler von Beginn an mitführt, zahlt einen kleinen konstanten Preis; wer ihn nachrüsten muss, zahlt ihn als teures Refactoring quer durch die Aufrufkette.\n\n## Ein zweites Beispiel: Retry mit Backoff\n\nDebounce ist der freundliche Fall, weil die Zeit klein und einstellig ist. Der Fall, der ohne virtuelle Zeit praktisch untestbar bleibt, ist Retry mit exponentiellem Backoff. Die fachliche Absicht: Ein flüchtiger Netzwerkfehler soll nicht sofort durchschlagen, sondern nach 1 s, dann 2 s, dann 4 s erneut versucht werden – und nach drei Versuchen endgültig scheitern.\n\n```ts\nconst result$ = request$.pipe(\n  retryWhen((errors) =>\n    errors.pipe(\n      scan((count) => count + 1, 0),\n      delayWhen((count) => timer(2 ** count * 1000, scheduler)),\n      take(3)\n    )\n  )\n);\n```\n\nMit echter Zeit ist der Test dieser Regel eine Zumutung: Ein einziger Durchlauf wartet sieben Sekunden, und die Grenze „nach dem dritten Versuch kommt der Fehler durch“ prüft niemand gern in einer Suite, die hundertmal am Tag läuft. Mit injizierter Zeit wird daraus ein präziser, sofortiger Test:\n\n```ts\nscheduler.advanceBy(1000);\nexpect(request).toHaveBeenCalledTimes(2);\nscheduler.advanceBy(2000);\nexpect(request).toHaveBeenCalledTimes(3);\nscheduler.advanceBy(4000);\nexpect(onError).toHaveBeenCalled();\n```\n\nDas ist der Moment, in dem die Entscheidung ihren Wert zeigt. Eine Regel, die im Betrieb über Ausfallsicherheit entscheidet – zu aggressives Retry überlastet ein ohnehin schwaches Backend, zu zaghaftes lässt Nutzer im Regen stehen – wird zu einer Sache von drei Zeilen, die ich anpassen und beweisen kann. Ohne virtuelle Zeit ist genau diese Regel die, die in der Praxis ungetestet bleibt und im Zwischenfall zum Rätsel wird.\n\n## Die zweite Grenze: Besitz statt globaler Streams\n\nZeit testbar zu machen löst nur die eine Hälfte. Die andere ist die Subscription-Grenze. In UI- und Messaging-Systemen entscheidet vor allem, wer einen Stream besitzt und wann er endet. Ein Stream, der überall abonniert und nirgends beendet wird, ist nur globaler State mit einem anderen Namen – mit denselben Symptomen: Speicherlecks, doppelte Side Effects, schwer erklärbares Verhalten unter Last.\n\nGute Streams haben deshalb drei Eigenschaften, die ich im Review aktiv suche: einen klaren Besitzer, eine definierte Lebensdauer und benannte Side Effects. Das ist keine Stiltugend, sondern die Voraussetzung dafür, dass Tests überhaupt aussagekräftig bleiben. Ein Test mit virtueller Zeit ist wertlos, wenn die Subscription im echten System länger lebt als gedacht und in Produktion doppelt feuert. Zeit-Kontrolle und Lebensdauer-Kontrolle sind zwei Seiten derselben Disziplin.\n\n## Commands statt Button-Handler\n\nDenselben Gedanken – State und Lebensdauer explizit machen – trägt ReactiveUI in die Interaktion. ReactiveCommands modellieren eine UI-Aktion als ausführbare Operation mit State: kann ausgeführt werden, läuft gerade, liefert Ergebnis, liefert Fehler. Der Button trägt damit keine Business-Logik mehr; er zeigt nur noch den State eines Commands an.\n\n```mermaid\nflowchart LR\n  Button --> Command\n  Command --> CanExecute\n  Command --> IsExecuting\n  Command --> Result\n  Command --> Error\n  Result --> ViewModel\n  Error --> ErrorPolicy\n```\n\nDer Nutzer klickt nicht „eine Funktion“. Er startet eine Operation mit Lebensdauer – und die lässt sich, wieder über den Scheduler, deterministisch testen: Ist `CanExecute` während der Ausführung false? Wird der Fehlerpfad in die ErrorPolicy geleitet statt in einen verschluckten Exception-Handler? Das sind genau die Fragen, die im Demo-Modus nie auffallen und im Betrieb teuer werden. ReactiveCommands, Dynamic Data, `Bind`/`OneWayBind` und ein zentraler ExceptionHandler zeigen dieselbe Richtung: Reactive Programming heißt nicht, Operatorlisten zu lernen, sondern UI-Lebensdauer und Fehlerpfade zu modellieren.\n\n## Die methodische Konsequenz für Reviews\n\nWenn Zeit eine Abhängigkeit ist, ändert sich, worauf ich im Review schaue. Ich frage nicht mehr „gibt es einen Test“, sondern „welche Zeitentscheidung beweist dieser Test“. Feuert Debounce bei genau der Schwelle? Bricht `switchMap` den alten Request nachweislich ab? Läuft der Retry mit dem erwarteten Backoff, geprüft über eine vorgespulte Uhr statt über reales Warten?\n\nUnd ich prüfe den Fehlerpfad, nicht nur den glücklichen. Viele Systeme sehen im Demo sauber aus. Interessant wird es bei Wiederholung, Teilfehlern, Netzwerkproblemen und menschlicher Korrektur. Ein häufiger Denkfehler bleibt, das Werkzeug mit der Lösung zu verwechseln: Rx ist kein Fachmodell, ein Scheduler ist kein Test, und ein grüner glücklicher Pfad ist kein Beweis. Die Werkzeuge können gute Grenzen ausdrücken, aber sie erzeugen sie nicht von selbst.\n\n## Was der Aufwand einbringt\n\nDer Nutzen lässt sich an zwei Dingen prüfen: Zeitabhängige Fälle laufen mit virtueller Zeit in Millisekunden statt in realen Warteintervallen, und Grenzwerte wie „bei 249 nichts, bei 250 feuern“ werden exakt beschrieben. Das beseitigt zeitbasierte Flakiness. Ein roter Lauf kann trotzdem aus Daten, geteilter Isolation oder externen Systemen stammen; der Scheduler löst diese Ursachen nicht. Relevant sind deshalb die Laufzeit genau dieser Tests und ihr Anteil an den instabilen CI-Läufen.\n\n## Schluss\n\nReactive Code wird nicht besser, indem man mit Operatorlisten beginnt. Er wird verständlicher, wenn die zeitliche Semantik explizit wird. Zeit vom versteckten Default zur injizierten Abhängigkeit zu machen kostet etwas Zeremonie, erlaubt aber schnelle Tests für Debounce, Timeout und Backoff. Mehr verspricht der Scheduler nicht."},{"locale":"de","translation_key":"graphql-ueberblick-vom-schema-zur-foederierten-api","slug":"graphql-ueberblick-vom-schema-zur-foederierten-api","title":"GraphQL-Überblick: Vom Schema zur föderierten API","summary":"Ein Durchgang durch GraphQL – vom typisierten Schema über Queries und Resolver bis zu Echtzeit, Betrieb und föderierter Architektur, eingeordnet am Stand von Oktober 2024.","tags":["Software","API","GraphQL"],"published_at":"2024-10-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/graphql-ueberblick-vom-schema-zur-foederierten-api/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/d4a8040788908086c662f67179997b125ba8197a999dff984dd5996d35b21231/graphql-ueberblick-vom-schema-zur-foederierten-api-vorlesen.mp3","audio_duration_secs":807,"text":"# GraphQL-Überblick: Vom Schema zur föderierten API\n\nEin typisiertes Schema und mindestens ein `Query`-Einstieg reichen, um sehr unterschiedliche Fragen an eine GraphQL-API zu stellen. Häufig laufen diese Operationen über einen HTTP-Endpoint; die GraphQL-Spezifikation selbst schreibt den Transport aber nicht vor. Die entscheidende Frage dahinter lautet, wer die Form der Antwort bestimmt. Bei einer klassischen REST-Schnittstelle definiert der Server die Repräsentation einer Route. GraphQL lässt den Client daraus die benötigten Felder auswählen. Die Kontrolle bleibt beim Backend, weil jede erlaubte Auswahl vorher im Schema festgeschrieben ist.\n\nDieser Beitrag geht den Weg vom Schema bis zur verteilten Architektur einmal ganz durch, damit man die Stationen kennt, bevor man sich in einer davon verliert. Zu einzelnen Stationen – wie genau die Ausführung im Inneren abläuft – schreibe ich eigene, tiefere Beiträge, etwa [GraphQL-Konzepte: Schema, Resolver, Ausführung](https://www.mikebild.dev/de/blog/graphql-konzepte-schema-resolver-ausfuehrung/). Hier geht es um das Ganze, mit dem Werkzeugstand von Oktober 2024: Apollo Server 4 dient als Node.js-Beispiel, und der Federation-Abschnitt bezieht sich auf Apollo Federation 2. GraphQL-over-HTTP war damals und ist auch im Juli 2026 noch eine Stage-2-Draft-Spezifikation; sie beschreibt die HTTP-Semantik für Queries und Mutations, nicht den Transport von Subscriptions.\n\nGraphQL verbindet mehrere Verantwortungen, ohne sie zu einem einzigen Baustein zu machen.\n\n:::relationship{title=\"Vom Bedarf zur aufgelösten Antwort\" role=\"primary\" preferredPattern=\"architecture-map\"}\n- Client-Operation · beschreibt die benötigte Form der Antwort\n- Schema · begrenzt Typen, Felder und zulässige Operationen\n- Ausführung · prüft und plant die angeforderte Auswahl\n- Resolver · löst genau ein Feld innerhalb seines Kontexts auf\n- Datenquelle · besitzt Daten und fachliche Regeln hinter dem Resolver\n- Gateway · kann mehrere Subgraphen unter einem Vertrag koordinieren\n:::\n\nDas Schema bleibt dabei Vertrag und Orientierungspunkt. Es ersetzt weder Fachlogik noch Datenbesitz der angeschlossenen Systeme.\n\n## GraphQL ist eine Spezifikation, kein Framework\n\nDer häufigste Irrtum am Anfang: GraphQL sei eine Bibliothek, die man installiert. Ist es nicht. GraphQL ist eine Spezifikation – sie beschreibt eine Query Language und wie ein Server eine solche Query auszuwerten hat. Es gibt Referenzimplementierungen wie `graphql-js`, und darauf setzen Server wie Apollo Server oder GraphQL Yoga auf, aber das Herzstück ist ein Vertrag, keine Runtime.\n\nAus dieser einen Tatsache folgt fast alles Weitere. Weil der Vertrag typisiert ist, kann der Client vor dem ersten Aufruf wissen, welche Felder es gibt und welchen Typ sie haben. Und weil der Server die Auswahl auswertet statt nur eine festgelegte Repräsentation auszuliefern, kann ein gemeinsamer HTTP-Endpoint viele verschiedene Fragen beantworten. Ein einzelner Endpoint ist die verbreitete Bereitstellung, keine Forderung der transportagnostischen Spezifikation.\n\n```mermaid\nflowchart LR\n  Client[\"Client<br/>formuliert die Frage\"] -->|eine Query| Endpoint[\"ein GraphQL-Endpunkt\"]\n  Endpoint --> Engine[\"Ausführung<br/>gegen das Schema\"]\n  Engine --> DB[(\"Datenbank\")]\n  Engine --> REST[\"REST-API\"]\n  Engine --> Service[\"anderer Dienst\"]\n  Engine -->|genau die angefragten Felder| Client\n```\n\nWichtig dabei: Hinter dem einen Endpoint kann alles Mögliche liegen. GraphQL ist keine Datenbank und ersetzt keine – es ist eine Schicht, die verschiedene Quellen unter einem gemeinsamen, typisierten Modell zusammenführt.\n\n## Das Schema zuerst\n\nAlles beginnt beim Schema. Es wird in der Schema Definition Language geschrieben, kurz SDL, und beschreibt die Typen und ihre Beziehungen. Ein kleines Beispiel aus der Welt eines Blogs:\n\n```graphql\ntype Author {\n  id: ID!\n  name: String!\n  posts: [Post!]!\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  author: Author!\n}\n\ntype Query {\n  author(id: ID!): Author\n  posts: [Post!]!\n}\n```\n\nDrei Dinge lohnen den genauen Blick. Erstens die Modifizierer: Das Ausrufezeichen bedeutet „darf nicht null sein“, die eckigen Klammern bedeuten „Liste“. `[Post!]!` ist also eine nicht-nullbare Liste von nicht-nullbaren Posts – eine sehr präzise Aussage, die ein Client sich merken kann. Zweitens die Beziehungen: `Author` verweist auf `Post` und umgekehrt. Das Schema beschreibt keinen flachen Katalog, sondern einen Graphen aus Knoten und Kanten – daher der Name.\n\nDrittens, und das ist der Kern: `Query` ist ein besonderer Typ. Optional kommen `Mutation` fürs Schreiben und `Subscription` für laufende Ergebnisse hinzu. Diese Operationstypen sind die Entry Points in den Graphen. Was dort nicht als Feld steht, kann kein Client auswählen. Damit ist das Schema ein echter Vertrag: Es sagt verbindlich, welche Operationen und Antwortformen erlaubt sind.\n\nZwei Werkzeuge machen diesen Vertrag im Alltag deutlich leichter zu handhaben. Felder lassen sich mit `@deprecated(reason: \"…\")` als veraltet markieren, ohne sie sofort zu entfernen – Clients bekommen den Hinweis, brechen aber nicht. Und für Mutationen gibt es eigene Input-Typen, damit Eingaben nicht mit Ausgabetypen verwechselt werden. Beides sind kleine Zeichen dafür, dass GraphQL für langlebige APIs gedacht ist, nicht für den Wegwerf-Endpoint.\n\n## Die Abfrageseite: der Client fragt genau\n\nEine Query sieht dem Datenteil der Antwort ähnlich, den sie erzeugt. Man beschreibt die gewünschte Auswahl, und die erfolgreiche Antwort folgt dieser Form:\n\n```graphql\nquery AuthorWithPosts($id: ID!) {\n  author(id: $id) {\n    name\n    posts {\n      title\n    }\n  }\n}\n```\n\nDer Client fragt hier nach dem Namen eines Autors und den Titeln seiner Posts – und bekommt nur das. Kein überflüssiges Feld, keine zweite Runde für die Posts. Das `$id` ist eine Variable; Queries werden nicht durch String-Bastelei parametrisiert, sondern über typisierte Variablen, die der Server prüft.\n\nZwei weitere Bausteine tauchen schnell auf. Fragmente bündeln wiederkehrende Feldmengen, damit man sie nicht in jeder Query wiederholt. Und Introspection erlaubt es, das Schema selbst abzufragen – der Server beschreibt sich, weshalb Werkzeuge wie GraphiQL Autovervollständigung und Dokumentation ohne zusätzliche Konfiguration anbieten können. Der Vertrag ist also nicht nur verbindlich, er ist auch auslesbar.\n\n## Die Ausführung: Resolver für Resolver\n\nWie wird aus der Query eine Antwort? Der Server durchläuft die Query von oben nach unten und ruft für jedes Feld eine Funktion auf, den Resolver. Jeder Resolver bekommt vier Argumente in fester Reihenfolge: das Elternobjekt (`source`), die Argumente des Feldes (`args`), einen anfragebezogenen Kontext (`context`) und Informationen über den Ausführungszustand (`info`).\n\n```js\nconst resolvers = {\n  Query: {\n    author: (source, { id }, context) => context.db.loadAuthor(id),\n  },\n  Author: {\n    posts: (author, args, context) => context.db.loadPostsForAuthor(author.id),\n  },\n};\n```\n\nMan sieht das Prinzip: Der Resolver für `author` liefert einen Autor, und dessen Rückgabewert wird zum `source` für die Feld-Resolver darunter – der Resolver für `posts` bekommt den Autor als erstes Argument und lädt darüber seine Posts. So wandert die Ausführung als Kette durch den Graphen. Ein Resolver kann synchron, per Promise oder `async` arbeiten und dabei jede Datenquelle ansprechen – eine Datenbank, eine REST-API, einen anderen Dienst.\n\nGenau hier lauert die bekannteste Falle, das N+1-Problem. Fragt jemand zehn Autoren mit ihren Posts ab, läuft der `posts`-Resolver zehnmal und macht zehn einzelne Datenbankabfragen – plus die eine für die Autoren. Die Lösung heißt Batching: Man sammelt die zehn Anfragen innerhalb eines Ausführungstakts ein und beantwortet sie mit einer einzigen Query. Die dafür übliche Bibliothek ist DataLoader.\n\n```mermaid\nflowchart TB\n  subgraph Ohne[\"Ohne DataLoader (N+1)\"]\n    Q1[\"10 Autoren\"] --> R1[\"10× posts-Resolver\"]\n    R1 --> DB1[(\"10 einzelne Abfragen\")]\n  end\n  subgraph Mit[\"Mit DataLoader\"]\n    Q2[\"10 Autoren\"] --> R2[\"10× posts-Resolver\"]\n    R2 --> L[\"DataLoader sammelt IDs\"]\n    L --> DB2[(\"1 gebündelte Abfrage\")]\n  end\n```\n\nWie die Ausführung im Detail durch den Baum läuft, in welcher Reihenfolge Geschwisterfelder ausgewertet werden und warum Mutationen anders behandelt werden als Queries – das ist ein Thema für sich, dem ich im [Konzepte-Beitrag](https://www.mikebild.dev/de/blog/graphql-konzepte-schema-resolver-ausfuehrung/) einen eigenen, tieferen Abschnitt widme. Für diesen Überblick reicht: Eine Query ist ein Pfad durch den Graphen, und jeder Knoten auf dem Pfad wird von einem Resolver bedient.\n\n## Schreiben und Echtzeit\n\nLesen ist nur die halbe Geschichte. Mutationen sind der schreibende Teil und sehen aus wie Queries, tragen aber eine Absicht:\n\n```graphql\nmutation CreatePost($input: PostInput!) {\n  createPost(input: $input) {\n    id\n    title\n  }\n}\n```\n\nDer Unterschied ist mehr als kosmetisch: Auf oberster Ebene führt der Server Mutationen nacheinander aus, nicht parallel, damit sich zwei Schreibvorgänge nicht ins Gehege kommen. Und weil eine Mutation ein Ergebnis zurückgibt – hier den angelegten Post –, kann der Client seinen Zustand direkt aus der Antwort aktualisieren, ohne neu zu laden.\n\nFür laufende Aktualisierungen gibt es Subscriptions. Der Client abonniert ein Event, und der Server schickt neue Daten, sobald sie entstehen. Klassisch lief das über WebSockets; inzwischen ist auch der Transport über Server-Sent Events verbreitet, gerade wenn eine einfache, einseitige Verbindung genügt – dazu habe ich [an anderer Stelle](https://www.mikebild.dev/de/blog/graphql-subscriptions-ueber-sse/) mehr geschrieben. Der GraphQL-over-HTTP-Entwurf formuliert die HTTP-Semantik für Queries und Mutations aus, sodass Server und Clients verschiedener Hersteller verlässlicher zusammenspielen. Subscriptions liegen ausdrücklich außerhalb seines Geltungsbereichs.\n\n## Betrieb: Fehler, Paginierung, Auth, Caching\n\nZwischen dem ersten funktionierenden Schema und einer API, die in Produktion trägt, liegen ein paar Themen, die man nicht überspringen sollte.\n\nFehler behandelt GraphQL eigen: Eine Antwort kann gleichzeitig Daten und ein `errors`-Feld enthalten. Ein fehlgeschlagenes Teilfeld macht nicht die ganze Antwort kaputt – der Rest kommt trotzdem. Das ist mächtig, verlangt aber Disziplin, damit Clients erwartbare Fehler von echten Pannen unterscheiden können.\n\nPaginierung löst man selten über simple `offset`/`limit`-Argumente, sondern meist über [cursorbasierte Verbindungen](https://www.mikebild.dev/de/blog/graphql-paginierung-und-connections/) – das Connections-Pattern mit Kanten und Seiteninformationen, das aus der Relay-Welt stammt und sich als Konvention durchgesetzt hat. Es ist etwas umständlicher zu lesen, aber stabil, wenn sich die Liste unter den Fingern ändert.\n\n[Authentifizierung und Autorisierung](https://www.mikebild.dev/de/blog/graphql-auth-im-context/) sind nicht dasselbe. Die Identität wird häufig beim Aufbau des `context` ermittelt und von dort an die Ausführung weitergegeben. Die eigentlichen Zugriffsregeln können in Resolvern, Direktiven, der Domänenschicht oder der Datenzugriffsschicht liegen. Entscheidend ist, dass jede relevante Zugriffsstelle dieselbe Policy durchsetzt und nicht bloß darauf vertraut, dass ein Feld im Schema verborgen bleibt.\n\nCaching schließlich ist anders als bei vielen REST-APIs, bei denen URL und HTTP-Methode einen naheliegenden Cache-Schlüssel bilden. GraphQL über HTTP kann ebenfalls HTTP-Caching nutzen, doch unterschiedliche Operationen teilen häufig dieselbe Adresse und liegen oft im Request-Body. Clients wie [Apollo Client](https://www.mikebild.dev/de/blog/graphql-client-caching-mit-apollo/) ergänzen deshalb einen normalisierten Objekt-Cache: Objekte mit stabiler Identität lassen sich über mehrere Queries hinweg gemeinsam aktualisieren.\n\n## Architektur: eine Schicht, die aggregiert\n\nDamit sind wir bei der eigentlichen Stärke von GraphQL im Großen. Weil hinter dem Endpoint beliebige Quellen liegen können, eignet sich GraphQL hervorragend als Aggregationsschicht – ein Backend for Frontend, das mehrere Dienste, Datenbanken und fremde APIs unter einem Modell zusammenzieht, zugeschnitten auf das, was die Oberfläche wirklich braucht.\n\n```mermaid\nflowchart TB\n  App[\"Web- & Mobile-Client\"] --> GW[\"GraphQL-Gateway<br/>(föderiertes Schema)\"]\n  GW --> S1[\"Subgraph: Nutzer\"]\n  GW --> S2[\"Subgraph: Bestellungen\"]\n  GW --> S3[\"Subgraph: Katalog\"]\n  S1 --> DB1[(\"Nutzer-DB\")]\n  S2 --> DB2[(\"Bestell-DB\")]\n  S3 --> REST[\"Katalog-REST\"]\n```\n\nWird das Schema zu groß für ein einzelnes Team, kommt [Federation](https://www.mikebild.dev/de/blog/graphql-federation-und-subgraphs/) ins Spiel. Statt eines Monolithen betreibt jedes Team einen eigenen Teilgraphen (Subgraph), und ein Gateway setzt daraus für den Client ein einziges, zusammenhängendes Schema zusammen. Der Client merkt davon nichts – er sieht weiterhin einen Graphen. Federation ist heute der übliche Weg, wenn GraphQL organisatorisch skalieren muss; die ältere Schema-Stitching-Variante trifft man noch in Bestandssystemen.\n\nBei der Wahl des Servers hat sich das Feld sortiert. Apollo Server 4 ist die sichere Standardwahl für einen gewöhnlichen Node.js-Stack – das größte Ökosystem, gute Federation-Unterstützung, breite Verwendung in der Praxis. GraphQL Yoga ist die schlankere Alternative, besonders wenn man auf Edge-Runtimes deployt, wo Apollo Server zu schwergewichtig wäre. Beide setzen auf `graphql-js` in Version 16 als gemeinsamem Fundament.\n\n## Das Repository als roter Faden\n\nWer das alles anfassen will, findet in `introduction-graphql` die Stationen als einzelne Kapitel wieder – von `intro`, `architecture` und `principles` über `schema`, `types` und `resolver` bis zu `mutations`, `subscriptions`, `paging`, `auth` und `caching`. Dazu kommen ausführbare Beispiele: ein Apollo-Monorepo, ein Server in C# als Beleg dafür, dass GraphQL sprachunabhängig ist, und ein Ordner mit Rezepten für wiederkehrende Aufgaben – DataLoader, Paginierung, Auth, Optimistic UI, serverseitiges Rendern. Die Kapitel sind bewusst so geschnitten, dass jedes für sich lesbar ist, und genau so ist auch dieser Beitrag gedacht.\n\n## Was bleiben soll\n\nWenn von diesem Überblick ein Satz hängen bleiben soll, dann dieser: GraphQL ist zuerst eine Frage der API-Gestaltung und erst danach eine Frage des Werkzeugs. Das Schema ist der Vertrag, die Resolver sind die Umsetzung, und alles darüber – Federation, Caching, der konkrete Server – ist Ausführung dieser einen Idee, dass der Client seine Frage stellt und das Backend ein explizites Modell behält.\n\nDie Tools werden sich weiter ändern; Apollo Server 4 wird nicht die letzte Generation sein, und die nächste kommt bestimmt. Was bleibt, ist das typisierte Schema und die Ausführung entlang des Graphen. Zu einzelnen Stationen gibt es eigene Beiträge – wie die Ausführung im Inneren genau abläuft und wie man [ein Schema entwirft, das mitwächst](https://www.mikebild.dev/de/blog/graphql-schema-das-mitwaechst/).\n\n## Weiterführende Quellen\n\n- Repository introduction-graphql (Kapitel, Apollo-Beispiel, Rezepte): https://github.com/mikebild/introduction-graphql\n- Folienübersicht zu diesem Beitrag: https://slides.mikebild.dev/introduction-graphql.html\n- GraphQL, offizielle Einführung: https://graphql.org/learn/\n- GraphQL-Spezifikation: https://spec.graphql.org/\n- GraphQL over HTTP: https://graphql.github.io/graphql-over-http/\n- Apollo Server, Dokumentation: https://www.apollographql.com/docs/apollo-server\n- DataLoader (Batching gegen N+1): https://github.com/graphql/dataloader"},{"locale":"de","translation_key":"nodejs-http2-und-server-sent-events","slug":"nodejs-http2-und-server-sent-events","title":"HTTP/2 und Server-Sent Events in Node.js","summary":"Wie HTTP/2 viele Streams über eine Verbindung multiplext und warum Server-Sent Events oft die einfachere Antwort auf Live-Daten sind als WebSocket – mit einem lauffähigen SSE-Endpoint in Node und den üblichen Fallstricken.","tags":["Software","Node.js","Backend"],"published_at":"2024-10-22T10:00:00+00:00","updated_at":"2026-07-13T08:02:43.199724+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-http2-und-server-sent-events/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/b9da14985b6997092121acd341286840e049d4df27ec16303dc1ed2aeaeea001/nodejs-http2-und-server-sent-events-vorlesen.mp3","audio_duration_secs":956,"text":"WebSocket ist kein Protokoll für Live-Daten. Es ist ein bidirektionaler Kanal, der Live-Daten nebenbei mit erledigt – und wer ihn aufmacht, bezahlt den Rückkanal, ob er ihn nutzt oder nicht: Reconnect-Logik von Hand, Upgrade-Support an jeder Zwischenstation, eigene Timeouts für langlebige Verbindungen, im Cluster meist noch Sticky Sessions und eine Pub/Sub-Schicht. Bei einem Aktienticker, einem Build-Fortschritt oder einer Benachrichtigungsleiste ist von diesem Kanal genau eine Richtung überhaupt im Einsatz.\n\nDie Transportwahl ist damit eine Entwurfsentscheidung mit direkten Betriebs- und Testfolgen, keine Geschmackssache. Sie hängt an drei Achsen: der Richtung der Daten, der Betriebsumgebung und der Testbarkeit. Wer hier reflexhaft greift, zahlt später in mehr Code, mehr Infrastruktur und mehr selbstgebauter Error Handling – nicht beim ersten Endpoint, sondern bei jedem Feature, das danach an dem Kanal hängt. Bevor es um Server-Sent Events geht, lohnt ein kurzer Blick auf die Schicht darunter, denn HTTP hat sich in den letzten Jahren stärker verändert, als im Alltag ankommt.\n\n## Was HTTP/2 an der Grundlage ändert\n\nÜber Jahre war unser mentales Modell von HTTP denkbar einfach: eine Anfrage, eine Verbindung, eine Antwort. HTTP/1.1 hat das ein Stück weit aufgebohrt mit Keep-alive und Pipelining, aber im Kern blieb es dabei, dass eine TCP-Verbindung immer nur eine Anfrage gleichzeitig sinnvoll bedienen konnte. Der Browser hat das jahrelang mit roher Gewalt umgangen: Er öffnete pro Origin bis zu sechs parallele Verbindungen. Sechs. Wer schon einmal eine Seite mit hundert kleinen Assets gebaut hat, weiß, wie sich dieser Flaschenhals anfühlt.\n\nHTTP/2 dreht dieses Modell um. Statt vieler Verbindungen gibt es eine einzige, und über diese eine Verbindung laufen viele voneinander unabhängige Streams parallel – das nennt sich Multiplexing. Jeder Stream trägt genau eine Request/Response, und alle teilen sich denselben TCP-Tunnel. Damit verschwindet das Head-of-Line-Blocking auf Anwendungsebene, und die künstliche Sechser-Grenze pro Origin ist kein Thema mehr. Für gleichzeitig offene Streams sehen die meisten Implementierungen 100 vor (`SETTINGS_MAX_CONCURRENT_STREAMS`) – so empfiehlt es die HTTP/2-Spezifikation als Untergrenze –, und der Wert lässt sich konfigurieren.\n\n```mermaid\ngraph LR\n  subgraph HTTP1[\"HTTP/1.1 – sechs Verbindungen\"]\n    C1[Client] -->|Verbindung 1| S1[Server]\n    C1 -->|Verbindung 2| S1\n    C1 -->|Verbindung 3| S1\n    C1 -->|... bis 6| S1\n  end\n  subgraph HTTP2[\"HTTP/2 – eine Verbindung, viele Streams\"]\n    C2[Client] -->|Stream 1<br/>Stream 3<br/>Stream 5| S2[Server]\n  end\n```\n\nZwei weitere Dinge sind praktisch relevant. Zum einen komprimiert HTTP/2 Header per HPACK. Wer schon einmal mitgeschnitten hat, wie oft dieselben Cookie- und User-Agent-Header über die Leitung wandern, ahnt, wie viel Redundanz da steckt. HPACK hält dafür eine statische und eine dynamische Tabelle vor und referenziert wiederkehrende Header nur noch per Index statt sie erneut auszubuchstabieren.\n\nZum anderen gibt es Server Push – und hier bin ich inzwischen ausdrücklich zurückhaltend. Die Idee war charmant: Der Server schickt Ressourcen mit, von denen er weiß, dass der Client sie gleich braucht, bevor der überhaupt danach fragt. In der Praxis war das schwer richtig einzusetzen, oft hat es Bandbreite verschwendet, und Chrome hat HTTP/2 Server Push mit Version 106 im Jahr 2022 standardmäßig entfernt. Im Node-`http2`-Modul ist die Funktion weiterhin da, aber ich würde heute niemandem raten, eine Architektur darauf zu bauen. Wer Preloading möchte, ist mit `preload`-Hints und `103 Early Hints` besser bedient.\n\nEin wichtiger Punkt für den Browserkontext: HTTP/2 sprechen Browser praktisch ausschließlich über TLS mit ALPN-Aushandlung auf `h2`. Unverschlüsseltes h2c gibt es im Node-Modul zwar, aber für alles, was ein Browser anfassen soll, brauchst du Zertifikate.\n\n## Das http2-Modul in Node\n\nNode bringt HTTP/2 als eigenes Kernmodul mit, `node:http2`, stabil seit den frühen Node-10-Zeiten. Zum Veröffentlichungszeitpunkt dieses Beitrags waren 18, 20 und 22 die relevanten Release-Linien; im Juli 2026 sind 22 und 24 LTS, 26 ist Current. Das Modul steht ohne Flag bereit. Es gibt zwei Wege, damit zu arbeiten. Der erste ist die native Core-API rund um Streams:\n\n```js\nimport { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst server = createSecureServer({\n  key: readFileSync('localhost-key.pem'),\n  cert: readFileSync('localhost-cert.pem'),\n});\n\nserver.on('stream', (stream, headers) => {\n  const path = headers[':path'];\n  stream.respond({\n    ':status': 200,\n    'content-type': 'text/plain; charset=utf-8',\n  });\n  stream.end(`you requested ${path}`);\n});\n\nserver.listen(8443);\n```\n\nAuffällig sind die Pseudo-Header mit führendem Doppelpunkt und in Kleinbuchstaben: `:status`, `:method`, `:path`, `:scheme`, `:authority`. Sie sind der HTTP/2-Ersatz für die alte Statuszeile und die klassischen Request-Metadaten. Das `stream`-Event ist das Herzstück – für jeden eingehenden Stream bekommst du ein eigenes Duplex-Objekt.\n\nDer zweite Weg ist die Kompatibilitäts-API. Sie bildet `req`/`res` so nach, wie man sie aus dem alten `http`-Modul kennt, sodass bestehender HTTP/1-Code fast unverändert weiterläuft:\n\n```js\nimport { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst server = createSecureServer(\n  {\n    key: readFileSync('localhost-key.pem'),\n    cert: readFileSync('localhost-cert.pem'),\n  },\n  (req, res) => {\n    res.writeHead(200, { 'content-type': 'text/plain' });\n    res.end('ok');\n  },\n);\n\nserver.listen(8443);\n```\n\nAuf der Client-Seite verbindest du dich mit `http2.connect(authority)` und schickst Requests über `client.request({ ':path': '/' })`. Wer tiefer in die Node-Interna und das Zusammenspiel mit dem Event Loop einsteigen möchte, findet in meinem [Node.js-Training](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) die passende Grundlage.\n\n## Server-Sent Events: der einseitige Stream\n\nJetzt zum eigentlichen Kern. Bei sehr vielen Live-Anwendungen fließen die Daten fast nur in eine Richtung: Der Server hat etwas Neues, und der Client soll es erfahren. Ein Aktienticker, ein Build-Fortschritt, eine Benachrichtigungsleiste, ein Live-Log. Für all das braucht man keinen bidirektionalen Kanal, keinen Protokoll-Upgrade und keine eigene Reconnect-Logik. Man braucht Server-Sent Events.\n\nSSE ist kein spezielles Modul und kein neues Protokoll. Es ist gewöhnliches HTTP mit einem bestimmten Content-Type: `text/event-stream`. Der Server hält die Antwort offen und schreibt in einem simplen Zeilenformat immer neue Events hinein. Der Browser hat mit `EventSource` einen nativen Client dafür, und – das ist der eigentliche Charme – dieser Client reconnectet von allein, wenn die Verbindung abreißt.\n\nDas Wire-Format ist bewusst schlicht. Eine Message besteht aus Feldern, jedes auf einer eigenen Zeile, und endet mit einer Leerzeile:\n\n```\ndata: hello world\n\nevent: tick\ndata: {\"count\":42}\nid: 42\n\n: this is a keep-alive comment\n\n```\n\nDie wichtigsten Felder sind `data:` für den Nutzinhalt, `event:` für einen benannten Event-Typ, `id:` für eine fortlaufende Kennung und `retry:` für das Reconnect-Delay in Millisekunden. Zeilen, die mit einem Doppelpunkt beginnen, sind Kommentare und eignen sich gut als Keep-alive-Ping. Entscheidend ist die doppelte Leerzeile, das `\\n\\n`, am Ende jeder Message – vergisst man sie, wird das Event schlicht nie ausgeliefert.\n\n```mermaid\nsequenceDiagram\n  participant B as Browser (EventSource)\n  participant S as Node Server\n  B->>S: GET /events\n  S-->>B: 200 text/event-stream\n  loop alle 1s\n    S-->>B: data: { ... }<br/>(offen gehaltene Antwort)\n  end\n  Note over B,S: Verbindung bricht ab\n  B->>S: GET /events<br/>Last-Event-ID: 42\n  S-->>B: 200 text/event-stream<br/>(setzt ab id 42 fort)\n```\n\n## Ein SSE-Endpoint in Node\n\nDer Code dafür ist erfreulich kurz. Wichtig sind die Response-Header, das sofortige Flushen und – das übersehen die meisten beim ersten Mal – das Aufräumen, wenn der Client die Verbindung schließt.\n\n```js\nimport { createServer } from 'node:http';\n\nconst server = createServer((req, res) => {\n  if (req.url !== '/events') {\n    res.writeHead(404).end();\n    return;\n  }\n\n  res.writeHead(200, {\n    'Content-Type': 'text/event-stream',\n    'Cache-Control': 'no-cache',\n    'Connection': 'keep-alive',\n    'X-Accel-Buffering': 'no',\n  });\n  res.flushHeaders();\n\n  let count = 0;\n  const timer = setInterval(() => {\n    count += 1;\n    const payload = { count, time: Date.now() };\n    res.write(`id: ${count}\\n`);\n    res.write(`event: tick\\n`);\n    res.write(`data: ${JSON.stringify(payload)}\\n\\n`);\n  }, 1000);\n\n  req.on('close', () => {\n    clearInterval(timer);\n  });\n});\n\nserver.listen(3000);\n```\n\nDer `req.on('close', ...)`-Handler ist nicht optional. Ohne ihn läuft das `setInterval` munter weiter, auch wenn der Browser die Seite längst geschlossen hat. Der Handler schreibt dann in eine tote Verbindung, der Timer bleibt hängen, und bei vielen Clients hast du ein handfestes Speicherleck. In Projekten ist das der Fehler, der mir am zuverlässigsten begegnet – der Endpoint funktioniert im Happy Path prima, und erst unter Last fällt auf, dass niemand aufräumt.\n\nAuf der Browserseite ist der Client fast schon unspektakulär:\n\n```js\nconst es = new EventSource('/events');\n\nes.onmessage = (event) => {\n  // fires for messages without an explicit event: field\n  console.log('default message', event.data);\n};\n\nes.addEventListener('tick', (event) => {\n  const payload = JSON.parse(event.data);\n  render(payload);\n});\n\nes.onerror = (err) => {\n  // EventSource reconnects on its own; log and let it recover\n  console.warn('connection lost, reconnecting…', err);\n};\n\n// later, when you no longer need it\n// es.close();\n```\n\nDer Punkt, der mir dabei am wichtigsten ist: Du musst den Reconnect nicht selbst bauen. `EventSource` merkt sich die letzte gesehene `id:` und schickt sie beim Wiederverbinden im Header `Last-Event-ID` mit. Wenn dein Server diesen Header auswertet, kann er nahtlos ab der letzten Message fortsetzen. Das `retry:`-Feld steuert, wie lange der Browser vor einem neuen Versuch wartet.\n\n## Der Fallstrick, der dich garantiert erwischt\n\nEs gibt einen Klassiker, und ich habe ihn oft genug live miterlebt, um ihn hier ausdrücklich hinzuschreiben: Reverse-Proxy-Buffering. In der Entwicklung läuft alles gegen den nackten Node-Prozess und funktioniert tadellos. Sobald ein nginx davorsteht, kommen die Events plötzlich nicht mehr einzeln im Sekundentakt an, sondern gebündelt und verzögert – oder scheinbar gar nicht. Der Grund: nginx puffert Response-Bodies per Default, und ein `text/event-stream` ist für den Puffer erst einmal nur ein Body, der noch nicht fertig ist.\n\nDie Lösung ist der Response-Header `X-Accel-Buffering: no`, den nginx erkennt und daraufhin für diese eine Antwort das Buffering abschaltet. Alternativ setzt man `proxy_buffering off;` in der nginx-Konfiguration. Deshalb steht dieser Header oben schon im Beispiel – nicht, weil er in jeder Umgebung nötig ist, sondern weil er dich vor genau dem Debugging-Nachmittag bewahrt, der sonst unweigerlich kommt.\n\nZwei weitere Stolpersteine gehören dazu. Erstens das schon erwähnte Format: Zeilenumbrüche innerhalb der Nutzdaten musst du entweder auf mehrere `data:`-Zeilen aufteilen oder vermeiden – ein rohes `\\n` mitten im JSON zerreißt die Message. Zweitens eine Einschränkung von `EventSource` selbst: Der native Client kann nur GET und keine eigenen Header setzen. Authentifizierung läuft deshalb typischerweise über Cookies oder einen Token im Query-String, nicht über einen `Authorization`-Header.\n\n## Wann SSE und wann WebSocket\n\nAusschlaggebend ist die Richtung der Daten. Die Gegenüberstellung, an der sich das festmachen lässt:\n\n- Richtung: SSE ist einseitig, Server zu Client. WebSocket ist voll bidirektional.\n- Protokoll: SSE ist gewöhnliches HTTP mit einem speziellen Content-Type. WebSocket braucht einen Protokoll-Upgrade der Verbindung.\n- Reconnect: Bei SSE eingebaut inklusive `Last-Event-ID`. Bei WebSocket baust du ihn selbst.\n- Nutzdaten: SSE transportiert ausschließlich UTF-8-Text. WebSocket kann Text und Binärdaten.\n- Infrastruktur: SSE läuft durch normale Proxies, Auth und Kompression. WebSocket braucht überall Upgrade-Support.\n- Typischer Einsatz: SSE für Notifications, Live-Feeds und Fortschrittsanzeigen. WebSocket für Chat, Spiele und kollaborative Editoren.\n\nWenn der Client im Wesentlichen nur zuhört, reicht SSE. Erst wenn du einen echten Rückkanal mit niedriger Latenz brauchst – der Nutzer tippt, klickt, bewegt eine Spielfigur – ist WebSocket die richtige Investition. Für den Rest ist SSE weniger Code, weniger Infrastruktur-Gefummel und weniger selbstgebaute Error Handling.\n\n## Transportwahl als Entwurfsentscheidung\n\nDie Gegenüberstellung oben beantwortet die Frage nach der Datenrichtung. In der Praxis entscheidet aber selten die Richtung allein, sondern was die Wahl im Betrieb und im Test kostet. Drei Achsen tragen die Entscheidung, und sie lassen sich in dieser Reihenfolge durchgehen.\n\nZuerst die Datenrichtung, weil sie am härtesten ist. Fließt der Verkehr im Wesentlichen vom Server zum Client, ist der Rückkanal von WebSocket totes Gewicht, das trotzdem betreut werden will. Fließt er in beide Richtungen mit niedriger Latenz, ist SSE das falsche Werkzeug, und jeder Versuch, den Rückkanal über einen zweiten HTTP-Request nachzubauen, wird schnell unangenehmer als ein sauberer WebSocket. Diese Achse ist keine Geschmacksfrage, sondern legt fest, welche Fähigkeit du überhaupt brauchst.\n\nDann die Betriebsumgebung, weil sie über die laufenden Kosten entscheidet. SSE ist gewöhnliches HTTP. Es läuft durch dieselben Reverse-Proxies, Load-Balancer, Auth-Layer und Kompressions-Stufen wie jeder andere Request, und das bestehende Monitoring sieht es ohne Sonderbehandlung. WebSocket verlangt an jeder Zwischenstation Upgrade-Support, eigene Timeouts für langlebige Verbindungen und oft Sticky Sessions, damit ein Client bei seinem Backend bleibt. Das ist alles beherrschbar, aber es ist zusätzliche Betriebsfläche, die jemand pflegen muss. Wer horizontal skaliert, merkt den Unterschied zuerst: Eine SSE-Verbindung ist ein Stream, den jeder Knoten beenden und der Client neu aufbauen kann, während ein WebSocket-Cluster in der Regel eine eigene Pub/Sub-Schicht braucht, damit ein Event auch den Knoten erreicht, auf dem der Empfänger hängt.\n\nZuletzt die Testbarkeit, weil sie die Entwicklungszyklen bestimmt. Einen SSE-Endpoint teste ich mit Werkzeugen, die ohnehin da sind. Ein `curl -N http://localhost:3000/events` zeigt den Stream roh im Terminal, und im Browser-Test reicht der native `EventSource`, um Events und Reconnect zu prüfen. Ein WebSocket-Kanal braucht dafür meist eine eigene Client-Bibliothek im Testaufbau und mehr Choreografie, um Handshake, bidirektionalen Fluss und den selbstgebauten Reconnect abzudecken. Das schlägt nicht bei der ersten Zeile durch, sondern bei jedem Feature danach, das an dem Kanal hängt.\n\nWirtschaftlich ist die Rechnung unspektakulär und genau deshalb wichtig. Die günstigere Transportwahl ist die, die weniger fremde Systeme berührt und sich mit Bordmitteln testen lässt. Für einen Live-Feed, einen Fortschrittsbalken oder eine Benachrichtigungsleiste heißt das fast immer SSE: kürzere Zyklen, weil weniger Infrastruktur im Spiel ist, und weniger Reibung im Betrieb, weil nichts Neues überwacht werden muss. Die Grenze ist ebenso klar. Sobald echte Interaktion mit Rückkanal ins Spiel kommt, kauft der WebSocket seine höheren Betriebskosten mit einer Fähigkeit zurück, die SSE schlicht nicht hat. Die Wahl bewusst zu treffen kostet einmal ein paar Minuten Nachdenken. Sie reflexhaft zu treffen kostet über die Lebensdauer des Systems deutlich mehr.\n\n## SSE und HTTP/2 zusammen\n\nUnd hier schließt sich der Kreis zum Anfang. SSE braucht kein HTTP/2 – es läuft völlig zufrieden über HTTP/1.1. Aber es profitiert davon. Über HTTP/1.1 zählt jede offene SSE-Verbindung gegen das Sechser-Limit des Browsers pro Origin. Wer in mehreren Tabs oder mit mehreren parallelen Streams arbeitet, rennt schnell dagegen. Über HTTP/2 sind offene SSE-Verbindungen dagegen Streams innerhalb einer Verbindung. Wie viele davon gleichzeitig offen sein dürfen, handelt die Gegenstelle über `SETTINGS_MAX_CONCURRENT_STREAMS` aus; RFC 9113 empfiehlt mindestens 100, garantiert diesen Wert aber nicht. Das starre HTTP/1.1-Limit wird dadurch meist deutlich weniger relevant.\n\nWeil SSE ein langlebiger Stream ist, der Daten in Häppchen ausliefert, lohnt sich außerdem ein Blick darauf, wie Node Streams intern behandelt und was passiert, wenn ein Client langsamer liest, als der Server schreibt. Wer viele Clients bedient, sollte Backpressure verstanden haben – dazu passt mein Beitrag zu [Node.js-Streams und Backpressure](https://www.mikebild.dev/de/blog/nodejs-streams-und-backpressure/).\n\nHTTP/2 hat die Transportschicht so weit entspannt, dass viele alte Optimierungstricks überflüssig geworden sind, und Server-Sent Events bringen genau so viel Komplexität mit, wie ein einseitiger Stream nun einmal braucht – keinen Deut mehr. Die Grenze bleibt dabei scharf: Sobald die Daten wirklich in beide Richtungen fließen, ist WebSocket die richtige Investition. Nur fließen sie seltener in beide Richtungen, als der erste Reflex glauben macht. Wer die drei Achsen einmal durchgeht, bevor er sich festlegt, spart sich im günstigen Fall eine komplette Pub/Sub-Schicht.\n\n## Weiterführende Quellen\n\n- [Node.js-Training](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) und [Node.js-Streams und Backpressure](https://www.mikebild.dev/de/blog/nodejs-streams-und-backpressure/) – die passenden Grundlagen aus meinem Blog.\n- [Node.js HTTP/2-Modul](https://nodejs.org/api/http2.html) – Core-API, Kompatibilitäts-API, `createSecureServer`, `pushStream`.\n- [MDN: Using server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) – SSE in der Praxis.\n- [MDN: EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) – das EventSource-Interface im Detail.\n- [WHATWG: Server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html) – die Spezifikation des `text/event-stream`-Formats.\n- [RFC 9113 (HTTP/2)](https://www.rfc-editor.org/rfc/rfc9113) und [RFC 7541 (HPACK)](https://www.rfc-editor.org/rfc/rfc7541) – die zugrunde liegenden Standards."},{"locale":"de","translation_key":"markdown-reports-statt-dashboard","slug":"markdown-reports-statt-dashboard","title":"Markdown Reports statt Dashboard-Zwang","summary":"Warum ein diffbarer Markdown Report für Nachvollziehbarkeit, Review und Betrieb oft mehr leistet als ein Dashboard – und wie ich das architektonisch aufziehe.","tags":["Software","Content","Publishing"],"published_at":"2024-10-12T10:00:00+00:00","updated_at":"2026-07-20T13:27:22.94021+00:00","url":"https://www.mikebild.dev/de/blog/markdown-reports-statt-dashboard/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/0bb356437d075e25eba82605b63c31743094ae4d5bff2ed6e55ee4f11720f891.mp3","audio_duration_secs":722,"text":"# Markdown Reports statt Dashboard-Zwang\n\nWer eine Auswertung nur als Dashboard baut, kann ein halbes Jahr später nicht mehr belegen, was zum Zeitpunkt der Freigabe darin stand. Die Ansicht existiert noch, die Zahlen sind aktuell – nur eben nicht mehr dieselben. Der übliche Notbehelf ist ein Screenshot, und der leistet genau das, was ein Screenshot eben leistet: nicht prüfbar, nicht durchsuchbar, nicht vergleichbar.\n\nEin Markdown Report kostet an derselben Stelle fast nichts. Er friert einen Stand ein, er besteht aus Text und ist damit diffbar, und er überlebt das System, das ihn erzeugt hat. Dieser Beitrag ist kein Loblied auf Textdateien. Er beschreibt eine architektonische Entscheidung – Report als versioniertes Artefakt statt als Live-View – und was diese Entscheidung für Review-Zyklen, Betrieb und Qualität konkret verändert.\n\nDie Formatfrage wird klarer, sobald der Leserzweck vor der Oberfläche steht.\n\n::::comparison{title=\"Live beobachten oder einen Stand belegen\" role=\"primary\" preferredPattern=\"split-comparison\"}\n:::side{label=\"Dashboard\"}\n- Frage · Was geschieht gerade?\n- Zustand · wird bei jedem Aufruf neu berechnet\n- Stärke · schnelle Reaktion auf laufende Veränderungen\n- Grenze · der frühere Stand ist ohne zusätzliches Archiv nicht belegt\n:::\n:::side{label=\"Veröffentlichter Report\"}\n- Frage · Was galt für den abgeschlossenen Zeitraum?\n- Zustand · immutable, versioniertes Artefakt\n- Stärke · prüfbar, diffbar und langfristig lesbar\n- Grenze · keine interaktive Echtzeitanalyse\n:::\n::::\n\nDie beiden Formen konkurrieren damit nicht um dieselbe Aufgabe. Sie werden erst dann verwechselt, wenn ein historischer Nachweis wie eine Live-Ansicht behandelt wird.\n\n## Die eigentliche Frage: flüchtiger Zustand oder Artefakt\n\nEin Dashboard beantwortet die Frage „Wie sieht es gerade aus?“. Das ist wertvoll, wenn ich einen laufenden Prozess überwache und in Sekunden reagieren muss – Latenzen, Fehlerraten, Auslastung. Für Operations ist ein Dashboard oft konkurrenzlos.\n\nDer Denkfehler beginnt, wenn dasselbe Muster auf Auswertungen angewendet wird, deren eigentlicher Wert in der Nachvollziehbarkeit liegt: eine Inventur, ein Abgleich, ein Publishing-Lauf, ein Datenmigrations-Report. Hier ist die interessante Frage nicht „Wie sieht es jetzt aus?“, sondern „Wie sah es zum Zeitpunkt X aus, warum, und was hat sich seitdem geändert?“. Ein Dashboard kann das strukturell nicht beantworten, weil es keinen festen Stand hat. Es rendert bei jedem Aufruf neu. Der Zustand von letzter Woche ist weg, sobald sich die Datenbasis dreht.\n\nEin Markdown Report zieht die Grenze anders. Er friert einen Stand ein, ist textuell, damit diffbar, und lässt sich als Datei ablegen, versionieren und weiterreichen. Drei Eigenschaften fallen dabei praktisch ins Gewicht:\n\nNachvollziehbarkeit heißt, dass der Report seinen eigenen Kontext trägt – Eingabestand, Regeln, Ergebnis, Ausnahmen. Wer ihn in sechs Monaten öffnet, muss nicht das erzeugende System rekonstruieren.\n\nDiffbarkeit heißt, dass zwei Läufe sich vergleichen lassen, ohne dass jemand zwei Screenshots nebeneinanderlegt. Ein `git diff` zeigt in Sekunden, welche Position neu ist, welcher Match gekippt ist, welche Zeile verschwunden ist. Review wird damit vom Interpretationsakt zum mechanischen Vorgang.\n\nArchivierbarkeit heißt, dass der Report ohne die erzeugende Infrastruktur überlebt. Kein laufender Dienst, keine Datenbankverbindung, kein Auth-Token. Eine Textdatei in einem Repository ist in zehn Jahren noch lesbar.\n\n## Der Report als Architekturartefakt\n\nAm deutlichsten wird das an einem Werkzeug, das ich für einen Inventur- und Kontenabgleich gebaut habe. Aufgabe: Inventarpositionen gegen Rechnungen und Buchungen matchen, Belege den richtigen Vorgängen zuordnen, Lücken sichtbar machen. Die naheliegende Lösung wäre ein Dashboard mit ein paar grünen und roten Kacheln gewesen. Ich habe stattdessen den Report zum zentralen Artefakt gemacht – und die gesamte Architektur darauf ausgerichtet.\n\nTragend ist eine Dreistufigkeit, die unabhängig vom Dateiformat gilt: Kontoblatt über Rechnungsnummern an PDFs koppeln, Inventarpositionen gegen Rechnungspositionen matchen, Nicht-PDF-Vendors separat über Buchungstext-Regeln behandeln. Diese Stufen sind die eigentliche Fachlogik. Das Ausgabeformat ist die Konsequenz, nicht die Entscheidung.\n\nInnerhalb der Matching-Stufe trenne ich harten Match und Fuzzy-Fallback strikt. Erst müssen definierte Tokens im Produkttitel stehen; erst wenn der harte Weg nichts findet, greift Fuzzy Matching. An dieser Reihenfolge hängt, ob die Automatisierung erklärbar bleibt. Jede Zeile im Report kann sagen, warum sie so zugeordnet wurde – `exact` oder `fuzzy` – und ein Mensch kann genau die zweite Kategorie gezielt prüfen.\n\n```ts\ntype MatchKind = \"exact\" | \"fuzzy\" | \"orphan\";\n\ntype ReconciliationRow = {\n  inventoryItem: string;\n  invoiceNumber: string | null;\n  purchaseDate: string | null;\n  matchKind: MatchKind;\n  confidence: number; // 0..1, only meaningful for fuzzy\n  note: string;\n};\n```\n\nDie OCR-Schicht behandle ich bewusst nicht als Wahrheit, sondern als Sensor. Apple Vision liefert die Basis, Tesseract korrigiert gezielt Beträge in der Soll/Haben-Region, und ein JSON-Cache macht spätere Läufe reproduzierbar. Das ist die architektonische Pointe: Ein Sensor hat einen Messfehler, und sobald der im Modell steht, wird der Umgang mit Unsicherheit ein expliziter Teil des Systems statt einer versteckten Annahme. Der Cache dient dabei nicht der Geschwindigkeit; er garantiert Determinismus – derselbe Beleg ergibt denselben Report.\n\nDas Ergebnis ist ein Report, der Inventarpositionen, Rechnungsnummern, Kaufdatum, Match-Art, verwaiste Kontoeinträge und ungenutzte Rechnungspositionen sichtbar macht:\n\n```md\n## Reconciliation 2024-10-12\n\n| item              | invoice | date       | match  | note                  |\n|-------------------|---------|------------|--------|-----------------------|\n| ThinkPad X1       | R-1042  | 2024-03-11 | exact  | token \"X1\" matched    |\n| USB-C Hub         | R-1043  | 2024-03-11 | fuzzy  | 0.82, title reworded  |\n| Monitor Stand     | —       | —          | orphan | no invoice position   |\n\nOrphans: 1 · Fuzzy: 1 · Unused invoice lines: 3\n```\n\nGenau dadurch wird aus einem Skript ein prüfbares Datensystem. Die verwaisten Einträge – der eigentlich interessante Teil – stehen nicht in einem Log, das niemand liest, sondern im selben Artefakt wie die erfolgreichen Matches. Ein Buchhalter kann diesen Report abzeichnen, ablegen und im nächsten Jahr gegen den neuen halten. Ein Dashboard hätte dieselbe Information gezeigt und beim nächsten Reload vergessen.\n\nDer konkrete Fall, der mich von diesem Zuschnitt überzeugt hat, war unspektakulär und genau deshalb lehrreich. Ein Vendor hatte auf einer Rechnung denselben Artikel zweimal gelistet, einmal als Sammelposten und einmal einzeln. Der harte Match griff beide Male, und in einer Kachelansicht wäre das als „alles grün“ durchgelaufen. Im diffbaren Report fiel es auf, weil dieselbe Rechnungsnummer plötzlich in zwei Zeilen mit unterschiedlichem Kaufdatum stand – eine Anomalie, die man beim Lesen sieht und beim Rendern übersieht. Der Fehler lag in den Daten, nicht im Code; der Report machte ihn zu einer sichtbaren Zeile statt zu einer stillen Doppelbuchung. Das ist für mich der Kern: Ein Artefakt, das man liest, deckt eine andere Klasse von Fehlern auf als eine Ansicht, die man nur überfliegt.\n\n## Publishing als dieselbe Bewegung\n\nDasselbe Prinzip trägt in einem ganz anderen Kontext, dem Publishing. Hier ist Markdown die Eingabe, aber der Weg vom Text zur veröffentlichten Seite ist kein magischer CMS-Klick. Ich zerlege ihn in getrennte, benennbare Zustände: Markdown als Eingabe, Revision als unveränderbarer Stand, Preview als Vertrauensschritt, Release als aktivierter Pointer, Rollback als kontrollierte Rückkehr.\n\n```mermaid\nflowchart LR\n  Markdown[Markdown input] --> Revision[Immutable revision]\n  Revision --> Preview[Preview build]\n  Preview --> Release[Release pointer]\n  Release --> Live[Live site]\n  Release -.rollback.-> Revision\n```\n\nDer entscheidende Trade-off steckt in der Trennung von Build und Aktivierung. Eine Revision wird gebaut und geprüft, bevor sie sichtbar wird. Aktivierung ist dann nur ein Pointer-Wechsel – und Rollback ebenfalls. Das nimmt dem Release den Nervenkitzel: Wer exakt sieht, was veröffentlicht wird, und weiß, dass ein Fehler ein Pointer-Wechsel zurück ist, braucht weniger Mut und produziert weniger Hotfixes um Mitternacht. Immutable Releases zahlen sich genau hier aus: Die Kosten eines Fehlers verschieben sich von „Rekonstruktion unter Druck“ auf „ein Kommando“.\n\nDass die Eingabe Markdown ist, hält die ganze Kette portabel. Inhalt bleibt getrennt von Darstellung und Betrieb. Aus demselben Text kann ich später eine Präsentation erzeugen oder ihn in ein anderes Zielsystem exportieren, ohne ihn neu zu schreiben. Für persönliche Seiten und technische Portfolios ist dieser Zuschnitt fast immer wertvoller als ein großes CMS – entscheidend sind Vorschau, atomare Veröffentlichung, stabile URLs und ein klarer Exportpfad, nicht der Funktionsumfang eines Editors.\n\n## Die Entscheidung vor dem Format\n\nBeim Abgleich sollen Lücken sichtbar und korrigierbar bleiben; beim Publishing soll ein Entwurf kontrolliert veröffentlicht und zurückgenommen werden können. Daraus folgen die Grenzen: OCR ist ein Sensor, Matching bleibt Fachlogik, Revision und Release sind getrennte Zustände. Erst dann entscheide ich über das Format. Für einen prüfbaren Stand passt ein versioniertes Artefakt, für laufende Beobachtung ein Dashboard.\n\n## Was das messbar verändert\n\nDie Wirkung dieser Entscheidung ist nicht nur ästhetisch, sie ist im Arbeitsalltag messbar.\n\nReview-Zyklen werden kürzer, weil Diff die Interpretation ersetzt. Statt zwei Stände visuell zu vergleichen, sieht ein Reviewer die drei geänderten Zeilen. Was vorher eine halbstündige Sichtung war, wird ein Blick auf einen Pull Request.\n\nReibung sinkt, weil Freigaben an einem konkreten Artefakt hängen statt an einer flüchtigen Ansicht. Ein abgezeichneter Report ist ein Dokument mit Zeitstempel. Eine abgenickte Dashboard-Ansicht ist eine Erinnerung.\n\nQualität steigt, weil der Fehlerpfad Teil der Ausgabe ist. Verwaiste Einträge, Fuzzy-Matches und ungenutzte Positionen stehen im selben Artefakt wie die Erfolge. Man muss nicht danach suchen; man sieht sie beim Lesen. Und beim Publishing verschiebt Rollback-als-Pointer die mittlere Fehlerbehebungszeit von Minuten unter Druck auf ein einzelnes Kommando.\n\nDiese Effekte sind der eigentliche Business-Outcome: schneller prüfen, weniger streiten, Fehler früher finden. „Wir haben ein schönes Dashboard“ steht auf dieser Liste nicht.\n\n## Wo ich beim Dashboard bleibe\n\nIch will die Entscheidung nicht dogmatisch machen. Für echtes Monitoring – Live-Metrics, Alerts, Zeitreihen mit Sekundenauflösung – ist ein Dashboard das richtige Werkzeug, und ein Markdown Report wäre absurd. Die Trennlinie ergibt sich aus der Natur der Frage, nicht aus einer Glaubensfrage Report gegen Dashboard: kontinuierliche Beobachtung eines laufenden Systems gegen prüfbaren Stand einer abgeschlossenen Auswertung. Viele Teams greifen zum Dashboard, weil es der Default ist, obwohl ihre Frage eindeutig zur zweiten Kategorie gehört. Genau diesen reflexartigen Default will ich aufbrechen.\n\n## Der Fehlerpfad als Prüfstein\n\nEine Idee ist erst belastbar, wenn auch ihr Fehlerpfad beschrieben ist. Beim Abgleich frage ich: Was passiert bei Wiederholung? Ist der Lauf idempotent? Der JSON-Cache sorgt dafür – zweimal derselbe Beleg, zweimal dasselbe Ergebnis. Beim Publishing: Kann ich das Schema erweitern, ohne bestehende Seiten zu brechen? Kann ich einen fehlerhaften Release erklären und zurücknehmen? Wenn die Antwort nein wäre, fehlte noch ein Teil der Architektur, egal wie sauber der glückliche Pfad aussieht.\n\nDer häufigste Fehler dabei ist, das Werkzeug mit der Lösung zu verwechseln. Markdown ist keine Architektur, ein CMS ist kein Publishing-Prozess, und OCR ist kein Wahrheitsbeweis. Diese Werkzeuge können gute Grenzen ausdrücken, aber sie erzeugen sie nicht von selbst. Die Grenze zieht man vorher, im Modell – und der Report macht sie nur sichtbar.\n\n## Schluss\n\nDer Reflex „bauen wir ein Dashboard“ ist so eingeübt, dass die Alternative kaum noch bewusst geprüft wird. Dabei ist ein Markdown Report in erstaunlich vielen Fällen die stärkere Wahl: diffbar, archivierbar, selbsterklärend, und damit ein echtes Artefakt statt eines flüchtigen Fensters. Der eigentliche Gewinn steckt nicht im Format. Er steckt in der Grenze, die es zieht – zwischen dem, was gerade passiert, und dem, was nachvollziehbar bleiben muss. Wer diese Grenze bewusst setzt, prüft schneller, veröffentlicht ruhiger und findet Fehler dort, wo sie noch billig sind.\n\n## Weiterführende Quellen\n\n- [CommonMark-Spezifikation 0.31.2](https://spec.commonmark.org/0.31.2/)\n- [Git: `git diff`](https://git-scm.com/docs/git-diff/2.45.0)"},{"locale":"de","translation_key":"graphql-federation-und-subgraphs","slug":"graphql-federation-und-subgraphs","title":"GraphQL Federation: ein Schema aus vielen Subgraphs","summary":"Wenn ein Team ein Monolith-Schema nicht mehr allein tragen kann, teilt Federation den Graphen in Subgraphs auf, die ein Router zu einem Supergraph komponiert. Dieser Artikel zeigt an einem User- und Orders-Beispiel, wie @key und __resolveReference Entities über Subgraph-Grenzen hinweg zusammenhalten.","tags":["Software","GraphQL","API"],"published_at":"2024-09-24T10:00:00+00:00","updated_at":"2026-07-13T08:52:54.757214+00:00","url":"https://www.mikebild.dev/de/blog/graphql-federation-und-subgraphs/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/fbc01d1fa1a191f4cb238d7fcd765a483bd7e4c330c40f68533960b8151090db/graphql-federation-und-subgraphs-vorlesen.mp3","audio_duration_secs":696,"text":"```bash\n$ rover supergraph compose --config ./supergraph.yaml\n\nerror[E029]: Encountered 1 build error while trying to build a supergraph.\n\nCaused by:\n    INVALID_GRAPHQL: [orders] Unknown directive \"@key\".\n```\n\nDiese Meldung kommt nicht aus einem laufenden Server, sondern aus einem Build-Schritt, den ein einzelner GraphQL-Service gar nicht kennt: der Komposition. Der Orders-Service benutzt `@key`, ohne die Direktive vorher importiert zu haben – und dieser eine fehlende Eintrag reicht, damit aus mehreren Schemas kein gemeinsamer Graph wird.\n\n`@key` ist die Direktive, mit der Apollo Federation einen Typ über Service-Grenzen hinweg referenzierbar macht. Daran hängt alles Weitere: wer welchen Typ besitzt, wer welche Felder beisteuert, wer die Teile zur Antwort zusammensetzt – und die Frage, wie man ein Schema auseinanderschneidet, an dem drei Teams arbeiten, ohne dass die Clients davon etwas merken. Zu früh gezogen kostet dieser Schnitt allerdings mehr, als er einbringt; darauf komme ich am Schluss zurück.\n\n## Das Problem: ein Schema, das niemandem mehr gehört\n\nAm Anfang ist ein GraphQL-Schema wunderbar. Ein Team, ein Repository, ein `type Query`, alles liegt beieinander. Der Reiz von GraphQL ist ja gerade, dass Clients sich aus einem einzigen Endpoint genau die Felder holen, die sie brauchen. Verwandte Fragen habe ich in früheren Beiträgen schon behandelt – etwa wie man Listen mit [GraphQL-Paginierung](https://www.mikebild.dev/de/blog/graphql-paginierung-und-connections/) sauber ausliefert oder wie Berechtigungen über [GraphQL-Auth im Context](https://www.mikebild.dev/de/blog/graphql-auth-im-context/) durchgereicht werden.\n\nDas Problem beginnt mit dem Wachstum. Sobald mehrere Teams an einem Schema arbeiten, wird die Datei zum Nadelöhr. Das User-Team will ein Feld an `type Order` hängen, muss dafür aber in den Code des Order-Teams greifen. Deployments koppeln sich aneinander. Ein `type` gehört plötzlich vielen, und „vielen gehören“ heißt in der Praxis: niemandem. Was im Alltag als Merge-Konflikt auftaucht, ist ein Zuständigkeitskonflikt.\n\nFederation dreht die Frage um. Statt „Wie teilen sich Teams ein Schema?“ fragt sie: „Wie betreibt jedes Team sein eigenes Schema – und der Client sieht trotzdem nur einen Graphen?“\n\n## Die Grundidee: Subgraphs, Supergraph, ein Endpoint\n\nIn Apollo Federation 2 – das ist die Generation, die seit 2022 relevant ist und die ich hier durchgehend meine – betreibt jedes Team einen **Subgraph**. Ein Subgraph ist ein ganz normaler GraphQL-Service mit eigenem Schema, eigener Datenbank, eigenem Deployment. Die einzelnen Subgraph-Schemas werden zu einem **Supergraph-Schema** komponiert. Zur Laufzeit sitzt davor ein Router (oder ein Gateway), der die eingehende Query entgegennimmt, einen Plan erstellt und die Teilfragen an die zuständigen Subgraphs verteilt.\n\nDer entscheidende Punkt: Der Client merkt von all dem nichts. Er spricht mit einem Endpoint, sieht ein Schema, stellt eine Query. Die Aufteilung ist reine Betriebs- und Team-Topologie – für den Konsumenten unsichtbar.\n\n```mermaid\nflowchart TB\n  Client[\"Client<br/>eine Query, ein Endpoint\"]\n  Router[\"Router / Gateway<br/>führt den Query-Plan aus\"]\n  Users[\"Users-Subgraph<br/>Team A\"]\n  Orders[\"Orders-Subgraph<br/>Team B\"]\n  UDB[(\"Users-DB\")]\n  ODB[(\"Orders-DB\")]\n\n  Client --> Router\n  Router --> Users\n  Router --> Orders\n  Users --> UDB\n  Orders --> ODB\n```\n\nWer die Laufzeit betreibt, hat 2024 zwei etablierte Optionen: den **`@apollo/gateway`** in Node oder den in Rust geschriebenen **Apollo Router**. Beide sind gültig. Der Router ist der performantere Weg und die übliche Empfehlung für neue Setups, aber das Gateway ist keineswegs abgelöst – wer schon ein Node-Gateway betreibt, muss nicht umziehen.\n\n## Rollen im System\n\nBevor Code entsteht, hilft es, die drei Bausteine sauber auseinanderzuhalten:\n\n- Der **Subgraph** trägt genau seine eigenen Felder bei. Er kennt seine Datenbank, sein Schema, sein Deployment – und sonst nichts. Team-Autonomie steckt hier.\n- Die Direktive **`@key`** markiert einen Typ als Entity, also als subgraph-übergreifend referenzierbar. Ohne `@key` kann ein anderer Subgraph den Typ weder erweitern noch per Referenz auf ihn zeigen.\n- Der **Router** plant die Query. Er zerlegt eine eingehende Anfrage in Teilfragen, holt sich bei jedem Subgraph dessen Beitrag und fügt die Antwort wieder zusammen. Cross-Subgraph-Joins sind seine Aufgabe, nicht die der Teams.\n\nDiese Trennung ist der ganze Trick: Teams denken lokal, der Router denkt global.\n\n## Fed 2 ist explizit: das @link-Opt-in\n\nEin Subgraph in Federation 2 sagt ausdrücklich, welche Federation-Direktiven er nutzen will. Das geschieht über `@link` am Schema. Das ist ein bewusster Bruch mit Federation 1, wo `extend type ... @key` implizit ein bestimmtes Verhalten mitbrachte. In Fed 2 importiert man, was man braucht:\n\n```graphql\nextend schema\n  @link(\n    url: \"https://specs.apollo.dev/federation/v2.0\"\n    import: [\"@key\", \"@shareable\", \"@external\"]\n  )\n```\n\nWer das `@link` vergisst oder eine Direktive nutzt, die nicht importiert wurde, bekommt keinen Laufzeitfehler, sondern einen Kompositionsfehler – und zwar früh, beim Komponieren oder Publizieren. Das überrascht Fed-1-Umsteiger regelmäßig, ist aber der bessere Zeitpunkt für einen Fehler.\n\n## Der Users-Subgraph\n\nFangen wir mit dem einfachen Teil an. Der Users-Subgraph besitzt die `User`-Entity. Er definiert sie, markiert sie mit `@key` und liefert einen Reference-Resolver, der eine `User`-Repräsentation auflöst.\n\n```graphql\nextend schema\n  @link(url: \"https://specs.apollo.dev/federation/v2.0\", import: [\"@key\"])\n\ntype User @key(fields: \"id\") {\n  id: ID!\n  name: String!\n  email: String!\n}\n\ntype Query {\n  user(id: ID!): User\n}\n```\n\nDer Code dazu nutzt `buildSubgraphSchema` aus dem Paket `@apollo/subgraph`. Das ist der Baustein, der aus `typeDefs` und `resolvers` ein federiertes `GraphQLSchema` macht, das die Federation-Direktiven und die von der Spec verlangten Felder wie `_entities` kennt.\n\n```ts\nimport { ApolloServer } from '@apollo/server';\nimport { startStandaloneServer } from '@apollo/server/standalone';\nimport { buildSubgraphSchema } from '@apollo/subgraph';\nimport gql from 'graphql-tag';\n\nconst typeDefs = gql`\n  extend schema\n    @link(url: \"https://specs.apollo.dev/federation/v2.0\", import: [\"@key\"])\n\n  type User @key(fields: \"id\") {\n    id: ID!\n    name: String!\n    email: String!\n  }\n\n  type Query {\n    user(id: ID!): User\n  }\n`;\n\nconst resolvers = {\n  Query: {\n    user: (_parent, { id }) => fetchUserById(id),\n  },\n  User: {\n    // The router hands us a representation: { __typename: \"User\", id }\n    __resolveReference: (reference) => fetchUserById(reference.id),\n  },\n};\n\nconst server = new ApolloServer({\n  schema: buildSubgraphSchema({ typeDefs, resolvers }),\n});\n\nconst { url } = await startStandaloneServer(server, { listen: { port: 4001 } });\nconsole.log(`Users subgraph ready at ${url}`);\n```\n\nDas Herzstück ist `__resolveReference`. Diese Funktion bekommt eine **Representation** – ein Objekt mit `__typename` und den `@key`-Feldern – und liefert die vollständige Entity zurück (oder `null`, wenn es sie nicht gibt). Wichtig zu verstehen: Ein normaler Feld-Resolver reicht hier nicht, weil der Router den Auflösungsprozess nur mit den Key-Feldern startet. Ohne Reference-Resolver kann er die Lücke nicht füllen.\n\n## Der Orders-Subgraph mit Cross-Reference\n\nJetzt wird es interessant. Der Orders-Subgraph besitzt `Order`. Eine Order gehört einem User – aber der Orders-Subgraph kennt von `User` nur die ID. Er will trotzdem ein Feld `order.user` anbieten. Dafür nimmt er `User` als Stub auf: mit `@key`, aber nur mit dem Key-Feld, ohne eigene Auflösung der übrigen Felder.\n\n```graphql\nextend schema\n  @link(url: \"https://specs.apollo.dev/federation/v2.0\", import: [\"@key\"])\n\ntype Order @key(fields: \"id\") {\n  id: ID!\n  total: Int!\n  user: User\n}\n\n# User lives in the users subgraph; here it is only referenced.\ntype User @key(fields: \"id\") {\n  id: ID!\n}\n\ntype Query {\n  order(id: ID!): Order\n}\n```\n\nDer Resolver für `Order.user` macht etwas, das anfangs fast zu simpel wirkt: Er gibt nur eine Referenz zurück – `__typename` plus Key-Feld. Die eigentliche Auflösung von `name` oder `email` passiert später im Users-Subgraph.\n\n```ts\nconst resolvers = {\n  Query: {\n    order: (_parent, { id }) => fetchOrderById(id),\n  },\n  Order: {\n    __resolveReference: (reference) => fetchOrderById(reference.id),\n    // Return just a reference; the users subgraph fills in the rest.\n    user: (order) => ({ __typename: 'User', id: order.userId }),\n  },\n};\n```\n\nSo bleibt jede Verantwortung dort, wo sie hingehört. Das Orders-Team weiß, welcher User zu einer Order gehört (die `userId` liegt in seiner DB), aber es muss die User-Daten nicht selbst kennen. Der Router übernimmt den Rest.\n\n## Was der Router im Hintergrund tut\n\nNehmen wir eine Client-Query, die beides überspannt:\n\n```graphql\nquery {\n  order(id: \"42\") {\n    total\n    user {\n      name\n    }\n  }\n}\n```\n\nDer Client sieht eine Query. Der Router sieht einen Plan. Er holt zuerst `total` und die `user.id` aus dem Orders-Subgraph, schickt dann eine `_entities`-Anfrage mit der Representation `{ __typename: \"User\", id }` an den Users-Subgraph, dessen `__resolveReference` daraus den `name` besorgt, und merged am Ende alles zu einer Antwort.\n\n```mermaid\nsequenceDiagram\n  participant C as Client\n  participant R as Router\n  participant O as Orders-Subgraph\n  participant U as Users-Subgraph\n\n  C->>R: order(id: 42) { total, user { name } }\n  R->>O: order { total, user { id } }\n  O-->>R: { total: 90, user: { id: 7 } }\n  R->>U: _entities([{ __typename: User, id: 7 }])\n  U-->>R: { name: \"Ada\" }\n  R-->>C: { total: 90, user: { name: \"Ada\" } }\n```\n\nWenn dieser Ablauf einmal sitzt, macht es „klick“: `@key` sagt, woran eine Entity erkennbar ist, `__resolveReference` sagt, wie man sie aus dieser Erkennung vollständig macht, und der Router orchestriert dazwischen.\n\n## Komponieren und starten\n\nDie Subgraph-Schemas müssen zu einem Supergraph zusammengeführt werden. Das ist ein Build- oder Publikationsschritt, keine Aufgabe des Routers während einer Anfrage. Lokal geht die Komposition mit `rover supergraph compose` und einer Konfiguration, die auf die Subgraphs zeigt:\n\n```bash\n# supergraph.yaml lists each subgraph and its endpoint\nrover supergraph compose --config ./supergraph.yaml > supergraph.graphql\n\n# Start the Apollo Router with the composed supergraph\n./router --supergraph supergraph.graphql\n```\n\nIn größeren Setups übernimmt Managed Federation über Apollo Studio / GraphOS diesen Schritt: Jeder Subgraph publiziert sein Schema, die Komposition passiert zentral, der Router zieht die aktuelle Supergraph-Version. Der wichtige Punkt bleibt derselbe – die Komposition ist der Moment, in dem Fehler auffallen, nicht die Laufzeit.\n\n## Geteilte Felder: der Unterschied zu Federation 1\n\nEin Detail, an dem Fed-1-Umsteiger regelmäßig stolpern: In Federation 2 sind Nicht-Key-Felder standardmäßig **nicht** teilbar. Wenn dasselbe Feld eines Typs in mehreren Subgraphs aufgelöst wird, muss es explizit mit `@shareable` markiert sein – sonst schlägt die Komposition fehl. Das betrifft vor allem Value-Types, die in mehreren Subgraphs identisch vorkommen.\n\n```graphql\ntype Money @shareable {\n  amount: Int!\n  currency: String!\n}\n```\n\nVerwandt ist `@external`: Ein Feld, das in diesem Subgraph nur referenziert wird und einem anderen gehört, wird als `@external` markiert – häufig zusammen mit `@requires` oder `@provides`, wenn ein Subgraph für seine Logik ein fremdes Feld braucht. Fed 2 ist an dieser Stelle strenger als Fed 1, und das ist Absicht: Mehrdeutigkeiten werden zum Fehler, statt sich still in der Laufzeit zu verstecken.\n\n## Drei Fallstricke\n\nFederation löst ein Organisationsproblem, handelt sich dafür aber technische Eigenheiten ein. Drei davon fallen besonders ins Gewicht.\n\nIm Reference-Resolver lauert N+1. Der Router löst Entities einzeln oder in Batches auf, und wenn `__resolveReference` naiv pro Aufruf einen DB-Roundtrip macht, entstehen viele kleine Anfragen. Ein DataLoader pro Subgraph-Request bündelt sie – dasselbe Muster, das man auch außerhalb von Federation gegen N+1 einsetzt.\n\nDas Key-Feld muss außerdem verlässlich in der Payload landen. Ein Feld mit Argumenten oder ein Union- bzw. Interface-Rückgabetyp taugt nicht als `@key`; ein nullbares Feld ist erlaubt, aber nicht empfehlenswert. Unterschiedliche Key-Felder für dieselbe Entity über verschiedene Subgraphs sind zwar zulässig, aber fehleranfällig – im Zweifel überall denselben Key nutzen.\n\nUnd der dritte Punkt trifft jeden, der aus einer Welt kommt, in der solche Dinge erst im Betrieb knallen: Ein vergessenes `@shareable`, ein Typ-Mismatch, ein fehlender `@link`-Import – all das wird schon beim Komponieren oder Publizieren abgelehnt, nicht zur Laufzeit. Der richtige Zeitpunkt, aber ein ungewohnter.\n\n## Federation 2 oder Schema-Stitching?\n\nWer länger mit GraphQL arbeitet, kennt noch **Schema-Stitching** – den älteren Weg, mehrere Schemas zusammenzuführen, heute etwa mit `@graphql-tools/stitch`. Beim Stitching kombiniert man Remote-Schemas manuell und schreibt Delegations- und Merge-Logik selbst. Das funktioniert, aber die Kopplung liegt im Gateway-Code, nicht in einer Spec. Federation deklariert die Beziehungen stattdessen im Schema (`@key`, `@shareable`) und überlässt dem Router die Ausführung. Stitching ist nicht tot – für manche Sonderfälle mit fremden, nicht anpassbaren Schemas ist es weiterhin brauchbar. Für eine neue, teamgetriebene Architektur greife ich 2024 aber zu Federation 2.\n\n## Wann ich NICHT federiere\n\nDer wichtigste Satz zum Schluss, weil er in Architektur-Diskussionen am meisten Widerspruch auslöst: Federation ist Overhead. Router, Komposition, Reference-Resolver, ein zusätzlicher Netzwerk-Hop pro Cross-Subgraph-Join – das alles will betrieben und verstanden sein. Wenn ein einzelnes Team ein Schema betreibt, das gut in einen Service passt, dann löst Federation ein Problem, das dieses Team nicht hat. Man handelt sich verteilte Systeme ein, um eine Organisationsgrenze abzubilden, die noch gar nicht existiert.\n\nFederation folgt der Team-Struktur, nicht der Technik. Erst wenn mehrere Teams sich an einem Schema in die Quere kommen, wenn Deployments sich koppeln, wenn ein `type` niemandem mehr gehört – dann zahlt sich der Schnitt aus. Vorher ist ein guter Monolith mit klaren Modulen fast immer die bessere Wahl. Und wer clientseitig ohnehin schon sauber mit [Apollo-Client-Caching](https://www.mikebild.dev/de/blog/graphql-client-caching-mit-apollo/) arbeitet, merkt: An der Client-Seite ändert Federation nichts – dort bleibt es genau der eine Graph, der es immer war.\n\n## Weiterführende Quellen\n\n- Introduction to Apollo Federation: https://www.apollographql.com/docs/federation/\n- Entities (`@key`, `__resolveReference`): https://www.apollographql.com/docs/federation/entities\n- Implementing a Subgraph with Apollo Server: https://www.apollographql.com/docs/federation/subgraphs/\n- API `@apollo/subgraph` (`buildSubgraphSchema`): https://www.apollographql.com/docs/apollo-server/using-federation/api/apollo-subgraph\n- Moving to Federation 2 (inkl. `@shareable`): https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/reference/moving-to-federation-2\n- Subgraph-Spec (`_entities`, `_Entity`, `@link`): https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/reference/subgraph-spec"},{"locale":"de","translation_key":"fuzzy-matching-mit-grenzen","slug":"fuzzy-matching-mit-grenzen","title":"Fuzzy Matching mit expliziten Grenzen","summary":"Ein Fuzzy-Match ist eine Behauptung mit Konfidenz, kein Fakt – nützlich wird er erst durch versionierte Schwellwerte, drei Entscheidungszonen und einen diffbaren Report der Grauzone.","tags":["Software","Daten","Tools"],"published_at":"2024-09-12T10:00:00+00:00","updated_at":"2026-07-14T17:24:17.741369+00:00","url":"https://www.mikebild.dev/de/blog/fuzzy-matching-mit-grenzen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/82854627b7945e364ad507cfad564d78763575af06edf5d42d99f476128c0099/fuzzy-matching-mit-grenzen-vorlesen.mp3","audio_duration_secs":693,"text":"# Fuzzy Matching mit expliziten Grenzen\n\n```sql\nSELECT similarity('Schmidt Bau GmbH', 'Schmitt Bau GmbH');\n-- 0.72\n\nSELECT similarity('Bäckerei Hoffmann GmbH & Co. KG',\n                  'BAECKEREI HOFFMANN DANKE RG 4711');\n-- 0.34\n```\n\nDer erste Wert sieht aus wie ein Treffer und ist keiner: zwei verschiedene Firmen, ein Buchstabe Unterschied, beide existieren. Der zweite Wert sieht aus wie Rauschen und ist der richtige Kunde – nur eben so, wie er in einem Überweisungs-Verwendungszweck ankommt: großgeschrieben, ohne Umlaute, mit Rechnungsnummer und Grußformel im selben Feld. Wer diese beiden Zahlen nebeneinander gesehen hat, glaubt keiner Ähnlichkeitsfunktion mehr blind. Genau das ist der richtige Zustand, um mit Fuzzy Matching zu arbeiten.\n\n## Ausgangslage: Verwendungszwecke gegen offene Posten\n\nDer Kontext ist dasselbe private Datenprojekt wie im Vormonat: Rechnungs- und Zahlungsdaten abgleichen. Auf der einen Seite stehen offene Posten mit sauberen Debitorennamen aus der Stammdatenpflege. Auf der anderen Seite stehen Kontoumsätze, deren Verwendungszweck ein Freitextfeld ist. Dort schreiben Menschen und Buchhaltungssysteme, was sie wollen: mal die Rechnungsnummer, mal der Firmenname in einer von fünf Schreibweisen, mal beides, mal keins von beidem.\n\nSolange eine Rechnungsnummer im Text steht, ist der Abgleich trivial – ein regulärer Ausdruck, ein exakter Schlüssel, fertig. Interessant wird es bei den restlichen Zahlungen, bei denen nur ein Firmenname als Anker bleibt. „Müller & Söhne GmbH\" kommt als „MUELLER SOEHNE\", „Mueller u. Soehne Bau\" oder „M&S GmbH\" an. Exaktes Matching findet hier nichts, und genau dafür gibt es Fuzzy Matching. Die Frage ist nicht, ob man es einsetzt, sondern wie man verhindert, dass aus „ähnlich\" stillschweigend „gleich\" wird.\n\nMir hat dabei ein Satz geholfen, den ich mir früh an den Report geschrieben habe: Ein Match ist eine Behauptung mit einer Konfidenz, kein Fakt. Alles Weitere in diesem Beitrag ist die technische Konsequenz aus diesem Satz.\n\n## Normalisierung zuerst\n\nBevor irgendeine Distanzfunktion läuft, lohnt sich der langweiligste Schritt am meisten: Normalisierung. Ein großer Teil der scheinbaren Unschärfe ist gar keine – es sind systematische Unterschiede, die man deterministisch wegräumen kann. Rechtsformen wie GmbH, AG oder KG tragen fast keine Unterscheidungskraft, blähen aber jede Ähnlichkeitsrechnung auf. Umlaute erscheinen im Zahlungsverkehr traditionell als ae/oe/ue. Groß- und Kleinschreibung, doppelte Leerzeichen, Satzzeichen: alles Störgeräusch.\n\n```python\nimport re\n\nLEGAL_FORMS = re.compile(\n    r\"\\b(gmbh|ag|kg|ug|ohg|gbr|mbh|co)\\b\\.?\",\n    re.IGNORECASE,\n)\n\nUMLAUT_MAP = str.maketrans(\n    {\"ä\": \"ae\", \"ö\": \"oe\", \"ü\": \"ue\", \"ß\": \"ss\"}\n)\n\ndef normalize_name(raw: str) -> str:\n    text = raw.strip().lower().translate(UMLAUT_MAP)\n    text = LEGAL_FORMS.sub(\" \", text)\n    text = re.sub(r\"[^a-z0-9 ]+\", \" \", text)\n    return re.sub(r\"\\s+\", \" \", text).strip()\n```\n\nNach diesem Schritt sind „Müller & Söhne GmbH\" und „MUELLER SOEHNE\" beide `mueller soehne` – ein exakter Treffer, ganz ohne Fuzzy-Verfahren. In meinem Datensatz hat allein die Normalisierung rund die Hälfte der vorher „unscharfen\" Fälle in exakte Matches verwandelt. Das ist der Grund, warum ich Normalisierung nicht als Vorstufe des Fuzzy Matching sehe, sondern als eigenständige Stufe mit eigenem Erfolgsmaß. Jeder Fall, der hier exakt wird, muss später nicht mit einer Konfidenz verteidigt werden.\n\nWichtig ist, dass `normalize_name` auf beiden Seiten identisch läuft – auf den Debitorennamen genauso wie auf den Verwendungszwecken. Sobald zwei leicht unterschiedliche Normalisierungen im Spiel sind, jagt man Geistern hinterher.\n\n## Distanzen, Trigramme, Phonetik\n\nFür den Rest bleiben die klassischen Verfahren, und sie haben unterschiedliche Stärken. Levenshtein zählt Editieroperationen und ist gut für Tippfehler. Jaro-Winkler gewichtet Übereinstimmungen am Wortanfang stärker – passend für Firmennamen, bei denen der Anfang meist stabil ist und hinten Zusätze variieren. Trigramm-Ähnlichkeit zerlegt Strings in Dreiergruppen von Zeichen und vergleicht die Mengen; sie ist unempfindlich gegen Wortreihenfolge und in Postgres über die Erweiterung pg_trgm direkt in SQL verfügbar.\n\nDazu kommt ein Verfahren, das im deutschsprachigen Raum zu selten erwähnt wird: die Kölner Phonetik. Sie ist das deutsche Gegenstück zu Soundex und bildet Wörter auf einen Lautcode ab, der für die deutsche Aussprache entworfen wurde. „Meyer\", „Maier\" und „Mayr\" landen auf demselben Code – für Distanzfunktionen sind das drei verschiedene Strings, fürs Ohr ist es derselbe Name. Als alleiniges Kriterium ist Phonetik zu grob, als zusätzliches Signal neben einer Distanz ist sie wertvoll.\n\nIn Python bündelt rapidfuzz die Distanzverfahren in einer schnellen Bibliothek. Ich kombiniere zwei Maße zu einem Score, weil kein einzelnes Verfahren alle Fehlerarten abdeckt:\n\n```python\nfrom rapidfuzz import fuzz, distance\n\ndef score_pair(payment_name: str, debtor_name: str) -> float:\n    jaro_winkler = distance.JaroWinkler.similarity(\n        payment_name, debtor_name\n    )\n    token_sort = fuzz.token_sort_ratio(\n        payment_name, debtor_name\n    ) / 100\n    return 0.6 * jaro_winkler + 0.4 * token_sort\n```\n\n`token_sort_ratio` sortiert die Wörter vor dem Vergleich und fängt damit vertauschte Reihenfolgen ab („bau schmidt\" gegen „schmidt bau\"). Die Gewichte 0,6 und 0,4 sind kein Naturgesetz – sie sind ein Parameter, den ich an einem von Hand gelabelten Ausschnitt der Daten kalibriert habe. Auch das gehört zur Ehrlichkeit des Verfahrens: Der Score ist eine konstruierte Größe, keine Wahrheit.\n\n## Blocking gegen die quadratische Falle\n\nWer jeden Verwendungszweck gegen jeden offenen Posten vergleicht, bezahlt O(n²). Bei ein paar hundert Datensätzen ist das egal, bei zehntausenden Zahlungen gegen tausende Debitoren nicht mehr. Die Standardantwort heißt Blocking: eine billige, grobe Vorauswahl, die die Kandidatenmenge klein macht, bevor die teuren Vergleiche laufen.\n\nHier spielt pg_trgm seine zweite Stärke aus. Die Trigramm-Ähnlichkeit ist nicht nur eine Funktion, sondern auch ein indexierbarer Operator. Mit einem GIN-Index über den normalisierten Namen liefert Postgres die ähnlichsten Kandidaten, ohne die ganze Tabelle anzufassen:\n\n```sql\nCREATE EXTENSION IF NOT EXISTS pg_trgm;\n\nCREATE INDEX idx_open_invoice_debtor_trgm\n    ON open_invoice\n    USING gin (debtor_name_normalized gin_trgm_ops);\n\nSET pg_trgm.similarity_threshold = 0.45;\n\nSELECT i.invoice_no,\n       i.debtor_name_normalized,\n       similarity(i.debtor_name_normalized, :payment_name)\n           AS trigram_score\nFROM open_invoice AS i\nWHERE i.debtor_name_normalized % :payment_name\nORDER BY trigram_score DESC\nLIMIT 10;\n```\n\nDer Operator `%` prüft gegen den eingestellten Schwellwert und nutzt dabei den Index. Die 0,45 sind bewusst niedrig angesetzt: In dieser Stufe ist ein übersehener Kandidat schlimmer als zwanzig überflüssige, denn was das Blocking verwirft, sieht die Feinbewertung nie wieder. Die eigentliche Entscheidung fällt später – mit `score_pair` über die zehn Kandidaten, nicht in SQL.\n\nDiese Zweiteilung hat sich bewährt: Postgres macht die Vorauswahl grob und schnell, Python macht die Bewertung genau und nachvollziehbar. Beide Stufen haben ihren eigenen Schwellwert mit eigener Begründung.\n\n## Drei Zonen statt einer Schwelle\n\nDamit zur eigentlichen Pointe. Die meisten Fuzzy-Matching-Beispiele, die man findet, enden mit einer einzigen Schwelle: Score über X gleich Match, darunter kein Match. Das ist die Stelle, an der aus einem nützlichen Werkzeug ein gefährliches wird, denn eine einzelne Schwelle behauptet eine Trennschärfe, die die Daten nicht hergeben. Es gibt immer einen Bereich, in dem das Verfahren schlicht nicht weiß, ob zwei Namen zusammengehören – und dieses Nichtwissen gehört in die Architektur, nicht unter den Teppich.\n\nDeshalb hat der Abgleich bei mir drei Zonen statt einer Schwelle:\n\n- Oberhalb der Akzeptanzschwelle wird automatisch zugeordnet, und die Zuordnung trägt den Score als Metadatum.\n- Zwischen den Schwellen landet das Paar in einer Durchsichtsliste – ein Mensch entscheidet.\n- Unterhalb der Ablehnungsschwelle passiert nichts, die Zahlung bleibt offen.\n\n```python\nTHRESHOLDS = {\n    \"version\": \"2024-09-03\",\n    \"accept\": 0.93,\n    \"reject\": 0.72,\n}\n\ndef classify(score: float) -> str:\n    if score >= THRESHOLDS[\"accept\"]:\n        return \"accept\"\n    if score < THRESHOLDS[\"reject\"]:\n        return \"reject\"\n    return \"review\"\n```\n\nDie Schwellwerte stehen versioniert im Repository, nicht als Konstante irgendwo im Code verstreut. Jede Änderung an ihnen ist ein Commit mit Begründung. Das klingt bürokratisch, hat mir aber schon nach zwei Wochen geholfen: Als ich die Akzeptanzschwelle von 0,90 auf 0,93 angehoben habe, weil das Schmidt/Schmitt-Paar aus dem Einstieg durchgerutscht war, konnte ich im Verlauf genau sehen, welche Zuordnungen unter welchem Regelstand entstanden sind.\n\n```mermaid\nflowchart LR\n    P[Verwendungszweck] --> N[normalize_name]\n    D[Debitorenname] --> N\n    N --> B[Blocking<br/>pg_trgm, Schwelle 0.45]\n    B --> S[Feinbewertung<br/>score_pair]\n    S --> Z{Score}\n    Z -->|ab 0.93| A[automatisch<br/>zuordnen]\n    Z -->|0.72 bis 0.93| R[Durchsicht<br/>durch Menschen]\n    Z -->|unter 0.72| X[offen lassen]\n    R --> AL[Alias-Regel<br/>versioniert]\n    AL --> N\n```\n\nDie Rückkopplung unten rechts im Diagramm ist kein Detail. Jede manuelle Entscheidung aus der Durchsicht wird als Alias-Regel festgehalten – „M&S\" ist „Müller & Söhne\" – und fließt als Datum zurück in die Normalisierung. Beim nächsten Lauf ist derselbe Fall ein exakter Treffer. Die Grauzone schrumpft dadurch mit der Zeit, und zwar durch dokumentierte Entscheidungen statt durch mutigere Schwellwerte.\n\n## Der Report der Grauzone\n\nDie Durchsichtsliste ist bei mir kein Dashboard, sondern eine Markdown-Datei, die jeder Lauf deterministisch erzeugt: gleiche Eingabe, gleiche Schwellwerte, gleicher Report. Sortiert nach Score, mit beiden Namen im Original und normalisiert, dem Trigramm-Wert aus dem Blocking und dem kombinierten Score daneben.\n\nDer Grund für Markdown ist Diffbarkeit. Zwei Läufe lassen sich mit `diff` vergleichen, und die Differenz erzählt eine Geschichte: Welche Fälle sind durch neue Alias-Regeln aus der Grauzone verschwunden? Welche neuen Zweifelsfälle sind mit dem letzten Kontoauszug dazugekommen? Hat die Schwellwert-Änderung die Zone vergrößert oder verkleinert? Ein Dashboard zeigt den letzten Zustand; ein diffbarer Report zeigt die Bewegung. Für ein Abgleichsystem, dessen Kern die Frage „was hat sich geändert und warum\" ist, wiegt das schwerer als jede Oberfläche.\n\nSide Effect: Der Report ist gleichzeitig das Prüfartefakt. Wenn ich in drei Monaten wissen will, warum eine Zahlung so zugeordnet wurde, steht der Score, der Regelstand und gegebenenfalls die manuelle Entscheidung in der Historie.\n\n## Asymmetrische Kosten\n\nBleibt die Frage, wo die Schwellen liegen sollen – und die beantwortet man nicht mit Statistik allein, sondern mit den Kosten der beiden Fehlerarten. Die sind hier deutlich asymmetrisch. Eine unzugeordnete Zahlung ist ein bekanntes Problem: Sie taucht in der Liste der offenen Fälle auf, jemand schaut drauf, ordnet zu, fertig. Eine falsch zugeordnete Zahlung ist ein unbekanntes Problem: Der offene Posten des einen Kunden gilt als beglichen, der andere bekommt womöglich eine Mahnung für eine bezahlte Rechnung. Der Fehler fällt erst auf, wenn sich jemand beschwert – und dann ist die Fehlersuche teuer, weil niemand mehr weiß, welcher Lauf mit welchem Regelstand die Zuordnung erzeugt hat.\n\nDeshalb liegt die Akzeptanzschwelle bewusst hoch und die Grauzone ist breiter, als es die reine Trefferquote nahelegen würde. Ich nehme lieber zwanzig manuelle Durchsichten pro Monat in Kauf als eine stille Falschzuordnung pro Quartal. Das ist keine technische Entscheidung, sondern eine fachliche – aber sie wird erst möglich, weil die Architektur die Stellschraube explizit macht. Eine einzelne, hart codierte Schwelle bietet diese Abwägung gar nicht erst an.\n\n## Was ich daraus mitnehme\n\nFuzzy Matching hat einen schlechten Ruf bei Leuten, die einmal von einer Falschzuordnung gebissen wurden, und einen zu guten Ruf bei Leuten, die nur die Demo gesehen haben. Beides geht am Punkt vorbei. Die Verfahren – Levenshtein, Jaro-Winkler, Trigramme, Kölner Phonetik – sind seit Jahrzehnten verstanden und tun zuverlässig, was sie versprechen: Sie messen Ähnlichkeit. Was sie nicht können, ist Identität feststellen. Der Fehler liegt fast nie im Verfahren, sondern in der Systemgrenze, die aus einem Ähnlichkeitswert stillschweigend eine Tatsache macht.\n\nNützlich wird das Ganze genau in dem Moment, in dem die Grenzen explizit werden: Normalisierung als eigene Stufe, damit Deterministisches deterministisch bleibt. Blocking mit bewusst niedriger Schwelle, damit die teure Bewertung bezahlbar bleibt. Drei Zonen mit versionierten Schwellwerten, damit das Nichtwissen des Verfahrens einen definierten Ort hat. Ein diffbarer Report, damit die Grauzone beobachtbar schrumpft statt unbemerkt zu wachsen. Und Schwellen, die sich an den asymmetrischen Fehlerkosten orientieren statt an der Trefferquote.\n\nNichts davon ist neu, und genau das gefällt mir daran. Es ist dieselbe Haltung, die sich schon beim Modellieren der Rechnungsdaten im Vormonat ausgezahlt hat: Unsicherheit nicht wegabstrahieren, sondern ihr einen Namen, einen Wert und einen Platz im Datenmodell geben. Ein Match ist eine Behauptung mit Konfidenz. Systeme, die das ernst nehmen, darf man automatisieren lassen.\n\n## Weiterführende Quellen\n\n- RapidFuzz auf GitHub: https://github.com/rapidfuzz/RapidFuzz\n- Postgres 16, Erweiterung pg_trgm: https://www.postgresql.org/docs/16/pgtrgm.html\n- Kölner Phonetik (Wikipedia): https://de.wikipedia.org/wiki/K%C3%B6lner_Phonetik"},{"locale":"de","translation_key":"event-sourcing-auf-aws-dynamodb-streams","slug":"event-sourcing-auf-aws-dynamodb-streams","title":"Event Sourcing auf AWS: DynamoDB Streams und Lambda","summary":"Event Sourcing serverless umgesetzt: DynamoDB als append-only Event-Store, DynamoDB Streams als Change-Feed und Lambda als idempotenter Projector in CQRS-Read-Models.","tags":["Software","AWS","Cloud"],"published_at":"2024-09-10T10:00:00+00:00","updated_at":"2026-07-13T07:29:27.668417+00:00","url":"https://www.mikebild.dev/de/blog/event-sourcing-auf-aws-dynamodb-streams/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/77816269684f59e894593ce2dd8c25f52d5ad31b9e7bd74753cb5795412bd2d5/event-sourcing-auf-aws-dynamodb-streams-vorlesen.mp3","audio_duration_secs":749,"text":"Ein Event-Store ist keine Tabelle, deren Zeilen man aktualisiert. Es wird nur angehängt: Jede Zustandsänderung ist ein neues, immutable Item, und der Zustand eines Aggregats entsteht erst, wenn man dessen Events in Versionsreihenfolge faltet. In der [Konzept-Betrachtung zum Event Sourcing](https://www.mikebild.dev/de/blog/event-sourcing-der-event-store-als-logbuch/) habe ich das als Logbuch beschrieben – die Event-Folge trägt die Wahrheit, der Zustand ist nur ihr Ergebnis.\n\nAuf dem Whiteboard ist das schnell erklärt. Tragfähig wird es erst mit den Antworten auf die nächsten Fragen: Wo läuft der Store? Wer garantiert die Reihenfolge? Was passiert, wenn ein Consumer denselben Event zweimal sieht? Auf AWS lässt sich das aus verwalteten Diensten zusammensetzen, und die scharfen Kanten liegen dann bei Concurrency beim Anhängen, bei der Reihenfolge im Change-Feed und bei doppelter Zustellung an die Projection. Genau darum geht es hier – samt dem Code, den ich dafür schreibe.\n\n## Die drei Bausteine\n\nBevor ich in den Code gehe, das mentale Modell. Wer die Rollen sauber trennt, macht später deutlich weniger Fehler:\n\n- Der Event-Store ist eine DynamoDB-Tabelle, append-only: ein Item pro Event, immutable. Das ist die Source of Truth, die einzige Wahrheit im System.\n- Die Streams bilden den Change-Feed dieser Tabelle. Jede neue Zeile erzeugt einen Stream-Record. Kein zweiter Store, nur ein Fenster auf die Änderungen.\n- Die Projection ist eine Lambda, die die Stream-Records liest und daraus denormalisierte Read-Models schreibt. Das ist exakt die [Projektions-Idee der Read Models](https://www.mikebild.dev/de/blog/read-models-sind-projektionen/), nur eben in AWS-Diensten gegossen.\n\nWichtig für die spätere Fehlersuche: Der Stream ist kein Archiv. Records werden nach 24 Stunden getrimmt. Wer den kompletten Verlauf braucht, liest ihn aus der Tabelle, nicht aus dem Stream. Der Stream transportiert nur den Delta-Fluss von der Write-Side zur Read-Side.\n\nIm Zusammenhang sieht der Weg eines Commands so aus:\n\n```mermaid\ngraph LR\n  A[Command] --> B[CommandHandler]\n  B -->|Conditional Write| C[(DynamoDB<br/>Event-Store)]\n  C --> D[DynamoDB Streams]\n  D --> E[Lambda<br/>Projektor]\n  E --> F[(Read-Model-Tabelle)]\n  F --> G[Query]\n```\n\nLinks steht die Schreibseite, rechts die Leseseite. Der Stream verbindet beide Seiten asynchron. DynamoDB Streams hält jeden Änderungsdatensatz einmal vor; die Verarbeitung durch Lambda ist dagegen at-least-once. Genau deshalb muss die Projection Wiederholungen vertragen.\n\n## Der Event-Store als Tabelle\n\nDas Datenmodell ist bewusst schlicht. Der Partition-Key ist die `aggregateId`, der Sort-Key ist die `version` – zero-padded, damit die numerische Sortierung als String stimmt. Ein Aggregat ist damit eine Partition, und seine Events liegen dort aufsteigend nach Version. Das passt direkt auf die Prinzipien aus dem [Single-Table-Design](https://www.mikebild.dev/de/blog/dynamodb-datenmodellierung-single-table/): Der Zugriffspfad steht im Schlüssel.\n\nStreams aktiviere ich beim Anlegen der Tabelle über die `StreamSpecification`. Der `StreamViewType` hat genau vier zulässige Werte – `KEYS_ONLY`, `NEW_IMAGE`, `OLD_IMAGE` und `NEW_AND_OLD_IMAGES`. Für Event Sourcing brauche ich das neue Bild, denn das Event steckt in der frisch geschriebenen Zeile:\n\n```yaml\nResources:\n  EventStore:\n    Type: AWS::DynamoDB::Table\n    Properties:\n      TableName: event-store\n      BillingMode: PAY_PER_REQUEST\n      AttributeDefinitions:\n        - AttributeName: pk\n          AttributeType: S\n        - AttributeName: sk\n          AttributeType: S\n      KeySchema:\n        - AttributeName: pk\n          KeyType: HASH\n        - AttributeName: sk\n          KeyType: RANGE\n      StreamSpecification:\n        StreamViewType: NEW_IMAGE\n```\n\nEin Detail, das mich früher einmal Stunden gekostet hat: Der `StreamViewType` ist nach dem Anlegen nicht mehr änderbar. Wer ihn wechseln will, muss den Stream deaktivieren und neu anlegen – mit einer neuen Stream-ARN und damit einem neuen Event Source Mapping. Das im ersten Anlauf richtig zu setzen spart später einen unangenehmen Migrationsschritt.\n\n## Events anhängen mit Optimistic Concurrency\n\nDer interessante Teil beim Schreiben ist nicht das Schreiben selbst, sondern die Frage: Was, wenn zwei Commands gleichzeitig dasselbe Aggregat auf Version N+1 fortschreiben wollen? Genau einer darf gewinnen. Das löse ich mit Optimistic Concurrency über einen Conditional Write.\n\nDie Idee: Ich schreibe das Event für `version = expectedVersion + 1` und knüpfe die Bedingung daran, dass unter diesem Schlüssel noch kein Item existiert. Existiert es schon, hat jemand anderes die Version belegt, und DynamoDB wirft eine `ConditionalCheckFailedException`. Der Caller liest dann die aktuelle Version neu und versucht den Command erneut.\n\n```ts\nimport { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\nimport {\n  DynamoDBDocumentClient,\n  PutCommand,\n} from \"@aws-sdk/lib-dynamodb\";\nimport { ConditionalCheckFailedException } from \"@aws-sdk/client-dynamodb\";\n\nconst client = DynamoDBDocumentClient.from(new DynamoDBClient({}));\n\nexport class ConcurrencyError extends Error {}\n\ninterface DomainEvent {\n  type: string;\n  payload: Record<string, unknown>;\n}\n\nexport async function appendEvent(\n  aggregateId: string,\n  expectedVersion: number,\n  event: DomainEvent,\n): Promise<void> {\n  const nextVersion = expectedVersion + 1;\n\n  try {\n    await client.send(\n      new PutCommand({\n        TableName: \"event-store\",\n        Item: {\n          pk: aggregateId,\n          sk: String(nextVersion).padStart(12, \"0\"),\n          version: nextVersion,\n          type: event.type,\n          payload: event.payload,\n          createdAt: new Date().toISOString(),\n        },\n        ConditionExpression: \"attribute_not_exists(pk)\",\n      }),\n    );\n  } catch (err) {\n    if (err instanceof ConditionalCheckFailedException) {\n      throw new ConcurrencyError(\n        `version ${nextVersion} already exists for ${aggregateId}`,\n      );\n    }\n    throw err;\n  }\n}\n```\n\n`attribute_not_exists(pk)` prüft, ob der komplette Item-Key frei ist – DynamoDB wertet die Bedingung gegen genau das Item aus, dessen Schlüssel im `PutCommand` steht. Damit ist die Kombination aus `aggregateId` und `version` der Uniqueness-Anker. Kein zusätzlicher Lock, keine separate Sequenz-Tabelle, keine Transaktion über mehrere Systeme.\n\nWenn ich mehrere Events atomar schreiben muss – etwa bei einem Command, der zwei Domain Events auslöst – nutze ich `TransactWriteItems` statt einzelner Puts. Das bündelt bis zu 100 Items in einer atomaren Transaktion, und ich kann die gleiche Bedingung auf jedes Event legen. Für die Regel „ein Event = ein Item“ reicht der einfache Conditional Write.\n\n## Die Projection als Stream-Handler\n\nJetzt kommt die Leseseite. Sobald ein Event geschrieben ist, erscheint es im Stream, und das Event Source Mapping zieht es in eine Lambda. Deren Aufgabe: die Events auf ein Read-Model falten.\n\nDer Handler bekommt ein `DynamoDBStreamEvent` mit einem Batch von Records. Jeder Record trägt einen `eventName` – für unseren append-only Store ist das immer `INSERT`. Das neue Bild lese ich aus `dynamodb.NewImage` und unmarshalle es in ein normales Objekt.\n\n```ts\nimport type { DynamoDBStreamEvent, DynamoDBBatchResponse } from \"aws-lambda\";\nimport { unmarshall } from \"@aws-sdk/util-dynamodb\";\nimport {\n  DynamoDBDocumentClient,\n  GetCommand,\n  UpdateCommand,\n} from \"@aws-sdk/lib-dynamodb\";\nimport { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\n\nconst client = DynamoDBDocumentClient.from(new DynamoDBClient({}));\n\nclass ProjectionGapError extends Error {}\n\nexport async function handler(\n  event: DynamoDBStreamEvent,\n): Promise<DynamoDBBatchResponse> {\n  const batchItemFailures: { itemIdentifier: string }[] = [];\n\n  for (const record of event.Records) {\n    if (record.eventName !== \"INSERT\") continue;\n    if (!record.dynamodb?.NewImage) continue;\n\n    try {\n      const item = unmarshall(record.dynamodb.NewImage as never);\n      await project(item);\n    } catch (err) {\n      batchItemFailures.push({\n        itemIdentifier: record.dynamodb!.SequenceNumber!,\n      });\n    }\n  }\n\n  return { batchItemFailures };\n}\n```\n\nZwei Dinge sind hier wichtig. Erstens gebe ich am Ende `batchItemFailures` zurück. Wenn `ReportBatchItemFailures` am Event Source Mapping aktiviert ist, verwendet Lambda die kleinste gemeldete `SequenceNumber` als Checkpoint und wiederholt ab dort. Das reduziert Wiederholungen, schließt sie für bereits erfolgreiche Folgerecords aber nicht aus. Ohne partielle Rückmeldung gilt dagegen der ganze Batch als fehlgeschlagen.\n\nZweitens die eigentliche Projection. Hier lauert der teuerste Fehler des ganzen Setups, und deshalb bekommt er einen eigenen Abschnitt.\n\n## Idempotenz ist keine Option\n\nDas Event Source Mapping liefert at-least-once. Der Stream selbst enthält jeden Record genau einmal – aber die Verarbeitung durch Lambda kann bei Retries, bei `BisectBatchOnFunctionError` oder bei einem Timeout denselben Batch mehrfach zustellen. Diese beiden Aussagen werden in Sekundärquellen oft vermischt: Der Stream ist exactly-once und pro Item geordnet; die Lambda-Verarbeitung ist at-least-once. Für den Code, den ich schreibe, zählt die zweite Aussage.\n\nKonkret heißt das: Meine Projection muss denselben Event zweimal verkraften, ohne das Read-Model zu verfälschen. Bei einer Zählung wäre eine doppelte Verarbeitung sonst eine Doppelzählung. Der Guard dagegen ist ein Conditional Write auf eine lückenlos steigende Version im Read-Model. Ich schreibe die neue Projection nur, wenn ihre Version genau auf die zuletzt gespeicherte folgt:\n\n```ts\nasync function project(item: Record<string, unknown>): Promise<void> {\n  const aggregateId = item.pk as string;\n  const version = item.version as number;\n\n  const current = await client.send(\n    new GetCommand({\n      TableName: \"read-model-orders\",\n      Key: { pk: aggregateId },\n      ConsistentRead: true,\n    }),\n  );\n\n  const lastProcessedVersion =\n    (current.Item?.lastProcessedVersion as number | undefined) ?? 0;\n\n  // A repeated delivery has no effect.\n  if (version <= lastProcessedVersion) return;\n\n  // A later event must wait until the missing versions were applied.\n  if (version !== lastProcessedVersion + 1) {\n    throw new ProjectionGapError(\n      `expected version ${lastProcessedVersion + 1}, received ${version}`,\n    );\n  }\n\n  await client.send(\n    new UpdateCommand({\n      TableName: \"read-model-orders\",\n      Key: { pk: aggregateId },\n      UpdateExpression: [\n        \"SET lastProcessedVersion = :v\",\n        \"#status = :status\",\n        \"updatedAt = :now\",\n      ].join(\", \"),\n      ConditionExpression:\n        \"attribute_not_exists(pk) OR lastProcessedVersion = :previous\",\n      ExpressionAttributeNames: {\n        \"#status\": \"status\",\n      },\n      ExpressionAttributeValues: {\n        \":v\": version,\n        \":previous\": lastProcessedVersion,\n        \":status\": deriveStatus(current.Item?.status, item),\n        \":now\": new Date().toISOString(),\n      },\n    }),\n  );\n}\n```\n\nKommt ein Event doppelt an, beendet die Funktion die Arbeit vor dem Update. Kommt dagegen Version 5, während im Read Model erst Version 3 steht, wird die Lücke als Fehler gemeldet. Lambda stellt diesen Record erneut zu; Version 4 kann vorher verarbeitet werden. Die Bedingung im `UpdateCommand` schützt zusätzlich gegen zwei gleichzeitig arbeitende Projektoren. Schlägt sie nach dem Lesen fehl, wird ebenfalls wiederholt – sie darf nicht pauschal als erfolgreicher Duplikatfall verschwinden.\n\nEin Randfall, der leicht übersehen wird: Ein `PutItem` oder `UpdateItem`, das die Daten gar nicht verändert, erzeugt keinen Stream-Record. Wer seine Projektions-Erwartungen an „für jeden Write kommt ein Event“ knüpft, wundert sich sonst über fehlende Records. Im append-only Event-Store tritt das nicht auf, weil jedes Event ein neues Item ist – aber sobald man am Store herummodelliert, sollte man es im Kopf behalten.\n\n## Ordering muss die Projection selbst prüfen\n\nDer zweite Fallstrick betrifft die Reihenfolge. AWS garantiert für DynamoDB Streams: Für jedes einzelne Item erscheinen die Stream-Records in derselben Reihenfolge wie die tatsächlichen Änderungen an diesem Item. In diesem Datenmodell ist aber jede Event-Version ein eigenes Item – gleicher Partition-Key, anderer Sort-Key. Aus der Garantie pro Item folgt daher keine garantierte Reihenfolge über die Events eines Aggregats.\n\nIm Normalbetrieb kommen aufeinanderfolgende Writes häufig in der erwarteten Reihenfolge an. Darauf darf sich der Projector trotzdem nicht verlassen, erst recht nicht bei Retries, partiellen Batch-Fehlern oder einem erhöhten `ParallelizationFactor`. Deshalb prüft der Code oben auf eine lückenlose Version. Eine Lücke wird wiederholt oder gezielt aus dem Event-Store aufgefüllt, statt ein späteres Event vorzuziehen und das fehlende anschließend als veraltet zu verwerfen.\n\nGlobales Ordering über Aggregate hinweg gibt es ebenfalls nicht. Die Records verteilen sich auf Shards, und Shards werden parallel verarbeitet. Wer eine global chronologische Sicht braucht – etwa einen Feed über alle Bestellungen sortiert nach Zeit –, muss eine dafür geeignete Ordnung modellieren. Ein Zeitstempel kann zur Darstellung dienen, ist aber allein noch keine konfliktfreie globale Sequenz.\n\n## Rebuild und Snapshots\n\nEin Read-Model ist ableitbar. Das ist einer der schönsten Vorteile des Ansatzes: Wenn ich die Projektionslogik ändere oder ein Read-Model korrupt ist, werfe ich es weg und baue es neu. Der Rebuild ist ein Replay – ich lese alle Events eines Aggregats aufsteigend und falte sie:\n\n```ts\nimport {\n  DynamoDBDocumentClient,\n  QueryCommand,\n} from \"@aws-sdk/lib-dynamodb\";\n\nexport async function rebuildProjection(\n  aggregateId: string,\n  fromVersion = 0,\n): Promise<ReadModelState> {\n  const result = await client.send(\n    new QueryCommand({\n      TableName: \"event-store\",\n      KeyConditionExpression: \"pk = :id AND sk > :from\",\n      ExpressionAttributeValues: {\n        \":id\": aggregateId,\n        \":from\": String(fromVersion).padStart(12, \"0\"),\n      },\n    }),\n  );\n\n  const events = result.Items ?? [];\n  return events.reduce(applyEvent, initialState());\n}\n```\n\nBei Aggregaten mit sehr vielen Events wird das teuer – jedes Replay liest den ganzen Stream. Dagegen empfiehlt die AWS Prescriptive Guidance Snapshots: den materialisierten Zustand eines Aggregats zu Version N, periodisch abgelegt. Der Rebuild lädt dann den Snapshot und faltet nur die Delta-Events seit dieser Version. Der `fromVersion`-Parameter oben ist genau die Naht dafür – ich starte den Query bei `snapshot.version` statt bei null. Der komplette Rebuild ohne Snapshot bleibt als Reißleine für den Fall, dass sich die Fold-Logik selbst geändert hat.\n\n## Hot Partitions und der blockierte Shard\n\nDer dritte Fallstrick ist der Preis der klaren Partitionierung. Die `aggregateId` als Partition-Key bedeutet: Ein sehr aktives Aggregat konzentriert alle Writes und den gesamten Stream-Verkehr auf eine Partition und einen Shard. Das führt zu Throttling und Latenz – eine klassische Hot Partition.\n\nDazu kommt ein Reader-Limit: Pro Shard sind maximal zwei Prozesse zulässig, die gleichzeitig lesen. Ein Batch, den die Lambda nicht verarbeiten kann, blockiert außerdem den Fortschritt des Shards, bis er entweder gelingt oder ausläuft. Genau dagegen gibt es die Stellschrauben am Event Source Mapping:\n\n- `BisectBatchOnFunctionError` teilt einen fehlgeschlagenen Batch rekursiv, um den einen giftigen Record zu isolieren.\n- `MaximumRetryAttempts` und `MaximumRecordAgeInSeconds` begrenzen, wie lange ein Record blockieren darf.\n- Ein On-failure-`DestinationConfig` schiebt endgültig gescheiterte Batches nach SQS oder SNS, statt sie im Stream festzuhalten.\n\nZusammen mit `ReportBatchItemFailures` aus dem Handler ergibt das eine Error Handling, die einen einzelnen kaputten Event nicht die ganze Projection anhalten lässt. Wer das von Anfang an setzt, spart sich den Incident, bei dem eine Read-Model-Tabelle stundenlang stehenbleibt, weil ein einziger Record nicht geparst werden konnte.\n\n## Fazit\n\nEvent Sourcing auf AWS braucht erstaunlich wenig: eine DynamoDB-Tabelle mit `aggregateId` als Partition-Key und `version` als Sort-Key, einen Conditional Write für Optimistic Concurrency, DynamoDB Streams als Change-Feed und eine Lambda, die daraus idempotente Read-Models faltet. Das ist Event Sourcing plus CQRS, serverless zusammengesetzt aus verwalteten Diensten.\n\nDie Konzepte tragen genauso wie auf dem Whiteboard – aber die Betriebsdetails entscheiden, ob das System nachts durchhält. Drei Dinge nehme ich in jedes Projekt mit: Projections müssen idempotent sein, weil die Verarbeitung at-least-once ist. Die Reihenfolge der getrennten Event-Items muss über ihre Version geprüft werden. Und die Error Handling am Event Source Mapping entscheidet darüber, ob sich der Stream selbst wieder freiräumt oder stehen bleibt.\n\nWer diesen Stack einmal aufgesetzt hat, merkt schnell, wie gut er sich weiterspinnen lässt – etwa in Richtung einer GraphQL-Leseseite mit [AppSync und DynamoDB](https://www.mikebild.dev/de/blog/appsync-dynamodb-graphql-api/), die direkt auf den projizierten Read-Models sitzt. Der Event-Store bleibt die Wahrheit, die Projections bleiben ableitbar, und die API liest nur noch fertig geformte Sichten.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html\n- [DynamoDB Streams – Retention, StreamViewType, Ordering, Shards](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)\n- [DynamoDB Streams und Lambda-Trigger](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.html)\n- [Using AWS Lambda with DynamoDB – ESM, Batch, ParallelizationFactor, Error Handling](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html)\n- [Condition Expressions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html)\n- [Optimistic Locking mit Versionierung](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html)\n- [AWS Prescriptive Guidance – Event Sourcing Pattern](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/event-sourcing.html)\n- [AWS Database Blog – Build a CQRS event store with Amazon DynamoDB](https://aws.amazon.com/blogs/database/build-a-cqrs-event-store-with-amazon-dynamodb/)"},{"locale":"de","translation_key":"rxjs-testen-mit-marble-diagrammen","slug":"rxjs-testen-mit-marble-diagrammen","title":"RxJS testen mit Marble-Diagrammen","summary":"Marble-Diagramme machen den zeitlichen Ablauf asynchroner Streams sichtbar. Mit TestScheduler.run und virtueller Zeit testest du RxJS-Operatoren deterministisch: kein echtes Warten, keine Flakiness.","tags":["Software","Reactive"],"published_at":"2024-08-13T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/rxjs-testen-mit-marble-diagrammen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/a6690b13769a71066712305e0d05fde3c5ce610dd9388f45f34721612e0d6c47/rxjs-testen-mit-marble-diagrammen-vorlesen.mp3","audio_duration_secs":776,"text":"Ein Test für `debounceTime(2000)` gegen die echte Uhr dauert zwei Sekunden. Zwanzig solcher Tests dauern vierzig Sekunden – und trotz dieser Wartezeit schlagen sie sporadisch fehl, sobald die Maschine unter Last steht. An dieser Rechnung scheitern reaktive Testsuiten: `setTimeout`, `done`-Callbacks, ein Framework, das pro Testfall wartet. Die Suite wird langsam, sie wird flaky, und irgendwann traut sich niemand mehr, sie ernst zu nehmen.\n\nDer `TestScheduler` rechnet stattdessen. Innerhalb von `run()` läuft eine virtuelle Uhr, in der ein Frame genau einer Millisekunde entspricht, und der komplette zeitliche Ablauf eines Streams steht als kurzer String da: `'-a-b-c|'`. Aus zwei Sekunden Wartezeit werden Mikrosekunden Rechenzeit. Wie diese Marble-Syntax funktioniert, wie man mit `TestScheduler.run` echte Operatoren testet und wo die typischen Stolperfallen liegen – darum geht es hier, durchgehend auf dem Stand von RxJS 7.\n\n## Warum Zeit das eigentliche Problem ist\n\nEin Observable ist ein Wert im zeitlichen Verlauf – oder genauer: eine Folge von Emissionen, verteilt über eine Zeitachse, abgeschlossen durch ein `complete` oder abgebrochen durch einen Fehler. Bei synchronen Werten ist das Testen trivial: subscribe, sammle die Werte in ein Array, vergleiche. Aber das Interessante an RxJS ist ja gerade der zeitliche Teil. Wann feuert ein `debounceTime`? Verschluckt ein `throttleTime` die richtigen Werte? Kommt das `complete` vor oder nach der letzten Emission?\n\nSobald du das mit echter Zeit testest, hast du drei Probleme auf einmal. Der Test dauert real so lange wie das Timing es vorgibt. Er ist nichtdeterministisch, weil die reale Uhr nun einmal nicht auf die Millisekunde genau tickt. Und er zwingt dich zu asynchronem Test-Code mit `done`-Callbacks, bei denen ein vergessener Aufruf den Test stumm hängen lässt, bis der Timeout zuschlägt.\n\nMarble-Testing dreht diese Logik um. Statt echter Zeit läuft eine virtuelle Uhr, die der `TestScheduler` kontrolliert. Zeit wird nicht abgewartet, sie wird berechnet. Und der Ablauf wird nicht in imperativem Code beschrieben, sondern als Diagramm.\n\n## Die Marble-Syntax\n\nEin Marble-Diagramm ist ein String, in dem jedes Zeichen eine Bedeutung auf der Zeitachse hat. Die Zeit läuft von links nach rechts, und jedes Symbol steht entweder für einen Zeitfortschritt oder für ein Event im Stream. Das ist die gesamte Referenz:\n\n- `-` – ein Zeit-Frame, also ein Tick der virtuellen Uhr. Innerhalb von `run()` entspricht ein Frame genau 1 ms.\n- `a`–`z` (oder jedes andere Zeichen) – eine `next`-Emission. Der konkrete Wert wird über ein `values`-Objekt gemappt, etwa `{ a: 1, b: 2 }`.\n- `|` – das `complete`-Signal, der Stream endet normal.\n- `#` – ein `error`, der Stream endet mit einem Fehler.\n- `()` – synchrone Gruppierung: mehrere Notifications im selben Frame, zum Beispiel `(ab|)`.\n- `^` – der Subscription-Punkt bei `hot`, der sogenannte Zero-Frame. Frames davor zählen negativ.\n- `!` – der Unsubscription-Punkt, relevant in Subscription-Diagrammen.\n- `<n>ms` / `<n>s` / `<n>m` – Kurzschreibweise für viele Frames, etwa `10ms` statt zehn Bindestrichen.\n\nEin Detail, das gerne übersehen wird: Leerzeichen erzeugen keinen Frame. Sie dienen nur der optischen Ausrichtung und werden ignoriert. Du kannst also Input und erwarteten Output untereinander schreiben und mit Leerzeichen sauber ausrichten, ohne das Timing zu verändern – nur `-` und die eigentlichen Symbole zählen.\n\nDer String `'-a-b-c|'` liest sich damit so: ein Frame Stille, dann Wert `a`, ein Frame, Wert `b`, ein Frame, Wert `c`, direkt gefolgt vom `complete`. Insgesamt sechs Frames, drei Werte, ein sauberer Abschluss. Genau diese Lesbarkeit ist der Punkt – du siehst das Timing, ohne es aus imperativem Code rekonstruieren zu müssen.\n\n## cold und hot\n\nBevor wir Tests schreiben, brauchst du die Unterscheidung zwischen `cold` und `hot`, denn sie bestimmt, wann die Zeit zu laufen beginnt.\n\nEin `cold`-Observable startet erst, wenn jemand subscribed. Die Zeitachse beginnt am Subscription-Zeitpunkt. Das ist das typische Verhalten für HTTP-Requests oder andere Datenquellen, die pro Abonnent neu loslaufen. Ein `hot`-Observable dagegen läuft bereits, unabhängig von Subscriptions – wie ein DOM-Event oder ein Subject, das schon feuert, während du noch gar nicht zuhörst. Hier markiert das `^` den Moment, in dem die getestete Subscription einsteigt; alles davor ist bereits passiert und liegt im negativen Frame-Bereich.\n\nWenn du die vier Subject-Typen und ihr Multicast-Verhalten noch einmal nachlesen willst, habe ich das in [Die vier Subject-Typen in RxJS](https://www.mikebild.dev/de/blog/rxjs-die-vier-subject-typen/) ausführlich behandelt – `hot`-Marbles bilden genau dieses „läuft schon“-Verhalten ab.\n\n## Der erste Test: map mit virtueller Zeit\n\nFangen wir mit dem einfachsten sinnvollen Fall an: einem `map`-Operator. Wir wollen zeigen, dass jeder eingehende Wert mit zehn multipliziert wird und Timing sowie Completion unverändert durchgereicht werden.\n\nZuerst der Aufbau des `TestScheduler`. Der Konstruktor bekommt eine Assertion-Funktion, die die Deep-Equality deines Testframeworks kapselt – hier am Beispiel von Jest, aber Jasmine oder Vitest funktionieren identisch:\n\n```ts\nimport { TestScheduler } from 'rxjs/testing';\nimport { map, debounceTime } from 'rxjs/operators';\n\nlet testScheduler: TestScheduler;\n\nbeforeEach(() => {\n  testScheduler = new TestScheduler((actual, expected) => {\n    expect(actual).toEqual(expected);\n  });\n});\n```\n\nDer eigentliche Test läuft dann komplett innerhalb von `testScheduler.run`. Der Callback bekommt ein `helpers`-Objekt, aus dem wir `cold` und `expectObservable` herausziehen:\n\n```ts\ntest('map multiplies each value by ten', () => {\n  testScheduler.run(({ cold, expectObservable }) => {\n    const source$ = cold('-a-b-c|', { a: 1, b: 2, c: 3 });\n\n    const result$ = source$.pipe(map((x) => x * 10));\n\n    expectObservable(result$).toBe('-a-b-c|', { a: 10, b: 20, c: 30 });\n  });\n});\n```\n\nDas Muster, das du hier siehst, wiederholt sich in jedem Marble-Test: Ist-Stream gegen Soll-Diagramm. Der Input ist ein `cold`-Observable mit einem Diagramm und einem `values`-Objekt. Die Operator-Pipeline hängt daran. Und `expectObservable(...).toBe(...)` beschreibt, was herauskommen soll. Das Timing des Outputs ist identisch mit dem des Inputs, weil `map` nichts an der Zeit ändert – nur die Werte-Zuordnung im zweiten Objekt ist eine andere.\n\nWarum funktioniert das ohne echtes Warten? Weil `run()` beim Zurückkehren automatisch die virtuelle Zeit durchlaufen lässt – intern über einen `flush`, den du in aller Regel nicht selbst aufrufen musst. Der ganze Ablauf ist synchron abgearbeitet, sobald der Callback endet.\n\n## Der eigentliche Gewinn: debounceTime\n\nBei `map` merkst du den Vorteil noch nicht wirklich. Er wird schlagartig deutlich, sobald ein zeitbasierter Operator ins Spiel kommt. `debounceTime(n)` gibt einen Wert erst weiter, wenn danach `n` Frames lang Stille herrscht – kommt vorher ein neuer Wert, wird der alte verworfen. Das ist genau die Art von Verhalten, die mit echter Zeit zur Qual wird und mit virtueller Zeit zur Fingerübung.\n\nDer entscheidende Punkt: Innerhalb des `run()`-Callbacks wird jeder zeitbasierte Operator automatisch auf den `TestScheduler` umgeleitet. Du musst den Scheduler nicht manuell an `debounceTime` durchreichen. `delay`, `debounceTime`, `throttleTime`, `interval`, `timer` – sie alle greifen auf die virtuelle Uhr zu, sobald sie innerhalb von `run()` laufen.\n\n```ts\ntest('debounceTime keeps only the last value after a quiet window', () => {\n  testScheduler.run(({ hot, expectObservable }) => {\n    // frame:      0    5    10\n    const source$ = hot('-a--b--c---|');\n\n    const result$ = source$.pipe(debounceTime(3));\n\n    // a is displaced by b, b by c; only c survives the 3-frame quiet window\n    expectObservable(result$).toBe('----------c|');\n  });\n});\n```\n\nRechnen wir das durch, denn genau hier passieren die meisten Fehler. `a` kommt bei Frame 1 an, sein Debounce-Fenster liefe also bei Frame 4 aus. Genau dann trifft aber `b` ein und verdrängt `a`, bevor dessen Emission ausgelöst wird. Für `b` beginnt das Fenster neu und endete bei Frame 7 – dort kommt `c`, dasselbe Spiel, `b` fällt ebenfalls weg. Nach `c` bei Frame 7 herrscht endlich lang genug Ruhe: Das Fenster läuft bei Frame 10 aus, das `complete` folgt bei Frame 11. Übrig bleibt also nur `c`, um drei Frames nach hinten verschoben. Das erwartete Diagramm bildet exakt diese Verschiebung ab.\n\nDiese Rechnerei ist kein Nebenschauplatz, sie ist der Kern. Wenn dein erwartetes Marble auch nur um einen Frame danebenliegt, schlägt der Deep-Equal fehl. Das ist anfangs nervig und wird schnell zur Stärke: Der Test zwingt dich, das Timing wirklich zu verstehen, statt es zu erahnen.\n\n## Was in einem Frame passiert\n\nDas folgende Diagramm zeigt den Ablauf für den `map`-Fall als drei parallele Zeitachsen – Input oben, Operator in der Mitte, Output unten. So sieht man am schnellsten, dass `map` die Werte transformiert, das Timing aber unangetastet lässt.\n\n```mermaid\nflowchart TB\n  subgraph IN[\"input$ – cold('-a-b-c|')\"]\n    direction LR\n    i0[\"-\"] --> i1[\"a=1\"] --> i2[\"-\"] --> i3[\"b=2\"] --> i4[\"-\"] --> i5[\"c=3\"] --> i6[\"|\"]\n  end\n  subgraph OP[\"operator\"]\n    direction LR\n    op[\"map(x =&gt; x * 10)<br/>gleiche Frames,<br/>neue Werte\"]\n  end\n  subgraph OUT[\"output$ – '-a-b-c|'\"]\n    direction LR\n    o0[\"-\"] --> o1[\"a=10\"] --> o2[\"-\"] --> o3[\"b=20\"] --> o4[\"-\"] --> o5[\"c=30\"] --> o6[\"|\"]\n  end\n  IN --> OP --> OUT\n```\n\nJedes Kästchen ist ein Frame. Die Werte wandern von oben nach unten durch den Operator, das Timing bleibt Frame für Frame erhalten. Bei einem zeitbasierten Operator wie `debounceTime` würde sich die untere Achse gegenüber der oberen verschieben und Werte fallen lassen – genau das, was wir eben durchgerechnet haben.\n\n## Subscription-Timing prüfen\n\nManchmal reicht es nicht zu wissen, welche Werte herauskommen – du willst wissen, wann und wie lange überhaupt subscribed wurde. Dafür liefern `cold` und `hot` eine `.subscriptions`-Property, die du gegen ein eigenes Diagramm prüfen kannst. `expectSubscriptions` verwendet dabei `^` für den Subscribe- und `!` für den Unsubscribe-Zeitpunkt:\n\n```ts\ntest('records subscription and unsubscription frames', () => {\n  testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => {\n    const source$ = cold('-a-b-c|');\n    const subscription = '^-----!';\n\n    expectObservable(source$).toBe('-a-b-c|');\n    expectSubscriptions(source$.subscriptions).toBe(subscription);\n  });\n});\n```\n\nDas ist besonders wertvoll, wenn du Operatoren wie `switchMap` oder `takeUntil` testest, bei denen der eigentliche Effect darin besteht, dass eine innere Subscription zum richtigen Zeitpunkt abgebrochen wird. Der Werte-Stream sieht dann oft unspektakulär aus – die Wahrheit steckt im Subscription-Diagramm.\n\n## Die drei Stolperfallen\n\nIn Code-Reviews tauchen immer dieselben drei Fehlerquellen auf. Sie stecken hinter den meisten „Warum ist mein Test rot?“-Momenten.\n\nErstens: echte statt virtueller Zeit. Die automatische Umleitung der zeitbasierten Operatoren gilt ausschließlich innerhalb des `run()`-Callbacks. Baust du dein Observable außerhalb auf oder greifst du auf den alten Stil zurück, bei dem du den Scheduler manuell durchreichst, läuft plötzlich wieder die reale Uhr. Der Test wird langsam und flaky, und der ganze Gewinn ist dahin. Alles, was Timing hat, gehört in den `run()`-Callback.\n\nZweitens: die Frame-Zählung. `debounceTime(20)` innerhalb von `run()` bedeutet 20 Frames, also 20 ms. Dein erwartetes Diagramm muss diese Verzögerung exakt abbilden – ob mit 20 Bindestrichen oder mit `20ms`. Ein Off-by-one bei der Frame-Zählung ist mit Abstand der häufigste Grund für einen fehlschlagenden Marble-Test. Nimm dir die Zeit, das Timing wirklich durchzurechnen, statt es zu schätzen.\n\nDrittens: Whitespace täuscht. Leerzeichen erzeugen keinen Frame, sie richten nur optisch aus. Wenn du Input und erwarteten Output ausrichtest, achte darauf, dass beide frame-synchron sind – und dass Werte, die synchron im selben Frame feuern, mit `()` gruppiert werden. Ein `(ab|)` ist etwas völlig anderes als `ab|`, auch wenn es fast gleich aussieht.\n\n## Der alte Stil als Kontrast\n\nZur Einordnung noch ein Wort zur Geschichte, denn du wirst online auf älteren Code stoßen. Früher hat man den `TestScheduler` ohne `run()` verwendet, den Scheduler explizit an die Operatoren durchgereicht und am Ende manuell `testScheduler.flush()` aufgerufen. In diesem Legacy-Stil entsprach ein Frame außerdem 10 ms statt 1 ms. Das funktioniert prinzipiell noch, ist aber fehleranfälliger und umständlicher.\n\nDer empfohlene Weg ist eindeutig `testScheduler.run(helpers => …)` mit der klaren Regel: ein Frame gleich 1 ms, automatische Umleitung aller zeitbasierten Operatoren, automatischer Flush am Ende. Wenn du also irgendwo `testScheduler.flush()` oder ein manuell durchgereichtes Scheduler-Argument siehst, ist das ein Hinweis auf alten Code – kein Muster, dem du folgen solltest.\n\n## Fazit\n\nMarble-Testing löst das eine Problem, das reaktive Programmierung schwer testbar macht: die Zeit. Statt sie abzuwarten, machst du sie sichtbar und berechenbar. Ein kurzer String beschreibt den kompletten zeitlichen Ablauf eines Streams, der `TestScheduler` verifiziert ihn in virtueller Zeit, und deine Suite bleibt schnell und deterministisch – keine `done`-Callbacks, keine Timeouts, keine sporadischen Fehlschläge.\n\nDer Einstieg kostet etwas Übung, vor allem beim Frame-Zählen. Aber sobald das sitzt, willst du nicht mehr zurück. Ein `debounceTime`-Test, der früher zwei Sekunden lief und gelegentlich rot war, läuft jetzt in Mikrosekunden und ist verlässlich. Und das erwartete Diagramm dokumentiert nebenbei das Verhalten so klar, dass es die halbe Doku ersetzt. Fang klein an – ein `map`, ein `debounceTime` – und rechne jedes Timing bewusst durch. Wenn du danach reaktive Ströme auch serverseitig einsetzt, findest du in [RxJS in Node.js](https://www.mikebild.dev/de/blog/rxjs-in-node-ereignisstroeme/) die passende Fortsetzung.\n\n## Weiterführende Quellen\n\n- [Testing RxJS Code with Marble Diagrams](https://rxjs.dev/guide/testing/marble-testing) – die offizielle Anleitung zu Marble-Syntax und `TestScheduler.run`.\n- [TestScheduler API](https://rxjs.dev/api/testing/TestScheduler) – die vollständige API-Referenz mit allen Helper-Signaturen."},{"locale":"de","translation_key":"rechnungsdaten-als-domaene","slug":"rechnungsdaten-als-domaene","title":"Rechnungsdaten als Domäne","summary":"Warum ein Rechnungsimport kein CSV-Job ist, sondern eine Fachdomäne mit eigenen Begriffen, Invarianten und Zeitregeln – und wie explizite Typen und ein Ablehnungs-Report aus stillen Datenfehlern erklärbare Daten machen.","tags":["Software","Daten","Tools"],"published_at":"2024-08-12T10:00:00+00:00","updated_at":"2026-07-14T17:22:26.666484+00:00","url":"https://www.mikebild.dev/de/blog/rechnungsdaten-als-domaene/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/f9df0cf504d2e5084fef41e48c29f1adb07583f8f3ae29c58527e44826e33f13/rechnungsdaten-als-domaene-vorlesen.mp3","audio_duration_secs":733,"text":"# Rechnungsdaten als Domäne\n\nRechnungsdaten sind, fachlich betrachtet, keine Zahlenkolonnen. Eine Rechnung ist ein Beleg: ein Dokument mit Aussteller, Empfänger, Belegnummer, Positionen und Steuersätzen – und mit rechtlicher Bedeutung, die im Umsatzsteuergesetz ziemlich genau beschrieben ist. Ein Beleg hat Verwandte: die Gutschrift, die einen Betrag zurückgibt, und den Storno, der einen Beleg aufhebt und dabei zwingend auf das Original verweist. Und ein Beleg trägt Regeln in sich, die in keiner Exportdatei stehen: Die Summe der Positionen muss zur Belegsumme passen, Netto plus Steuer muss Brutto ergeben, und ein Zahlungsziel rechnet ab dem Rechnungsdatum – nicht ab dem Leistungsdatum, und erst recht nicht ab dem Tag, an dem das Geld tatsächlich fließt.\n\nWer eine Rechnung nur als Zeile mit Betrag liest, liest sie falsch. Genau das passiert aber, wenn man die Aufgabe „Rechnungsdaten zusammenführen\" als das behandelt, wonach sie auf den ersten Blick aussieht: als Import-Job.\n\n## Ein privates Datenprojekt als Auslöser\n\nDer Anlass war unspektakulär. Über mehrere Jahre hatten sich bei mir Rechnungs- und Belegdaten in drei Formen angesammelt: PDFs von Lieferanten, CSV-Exporte aus einem Buchhaltungswerkzeug und ein Konto-Export der Bank. Ich wollte sie in einer lokalen Datenbank zusammenführen, um endlich Fragen beantworten zu können, die keines der Einzelsysteme beantwortet: Welche Beträge wurden in Rechnung gestellt, aber nie bezahlt? Wie verteilen sich Ausgaben über Steuersätze? Welche Gutschriften gehören zu welchen Originalen? Alles anonymisiert und rein privat – es geht hier um die Struktur des Problems, nicht um konkrete Geschäftszahlen.\n\nDie erste Version war ein Abend Arbeit: PDFs in Text wandeln, CSVs mit Papa Parse einlesen, Spalten umbenennen, ab in SQLite. Der Import lief durch, ohne eine einzige Fehlermeldung. Und genau das war das Problem.\n\nDenn die Daten waren still kaputt. Ein Lieferant exportiert Bruttobeträge, der andere Netto – beide nennen die Spalte `amount`. Ein Export schreibt deutsche Dezimalkommas, der nächste Punkte. In einer Datei stand in der Datumsspalte das Leistungsdatum, in der anderen das Rechnungsdatum. Zwei Stornos tauchten als ganz normale Rechnungen mit negativem Betrag auf, ohne Bezug zum Original. Nichts davon ist ein Parser-Fehler. Jede einzelne Zeile war syntaktisch einwandfrei. Falsch war die Bedeutung – und Bedeutung prüft kein CSV-Parser.\n\nMir ist an diesem Punkt aufgefallen, dass ich die Aufgabe falsch einsortiert hatte. Das hier war kein Datentransport. Das war Domänenmodellierung, nur eben für Daten, die schon existieren.\n\n## Die Begriffe ernst nehmen\n\nDer erste Schritt raus aus dem stillen Kaputtgehen war kein Code, sondern eine Begriffsliste. Welche fachlichen Dinge kommen in diesen Dateien überhaupt vor? Am Ende standen erstaunlich wenige Begriffe auf dem Zettel, aber jeder davon mit scharfer Bedeutung:\n\n- Beleg – das Dokument als Ganzes, mit eindeutiger Belegnummer und einer Belegart\n- Position – eine Zeile auf dem Beleg, mit Menge, Einzelpreis und eigenem Steuersatz\n- Steuersatz – in meinem Bestand 0, 7 oder 19 Prozent, nichts anderes\n- Gutschrift – ein eigenständiger Beleg mit umgekehrtem Vorzeichen\n- Storno – hebt einen Beleg auf und referenziert dessen Belegnummer\n- Zahlungsziel – ein Datum, abgeleitet aus Rechnungsdatum plus Frist\n\nDiese Liste sieht banal aus. Sie hat aber sofort Entscheidungen erzwungen, die vorher unsichtbar im Spaltenmapping versteckt waren. Ist ein negativer Betrag eine Gutschrift oder ein Storno? Fachlich ein riesiger Unterschied: Die Gutschrift ist ein neuer Vorgang, der Storno macht einen alten ungültig. In meinen Rohdaten waren beide dieselbe Zeile mit Minuszeichen. Ohne Begriffsliste hätte ich das nie als Problem erkannt – die Zahl stimmt ja.\n\nDie Beziehungen zwischen den Belegarten lassen sich klein aufzeichnen:\n\n```mermaid\nflowchart LR\n  I[\"Rechnung<br/>INV-2023-0117\"] --> P1[\"Position 1<br/>19 %\"]\n  I --> P2[\"Position 2<br/>7 %\"]\n  C[\"Storno<br/>CAN-2023-0119\"] -- \"referenziert\" --> I\n  G[\"Gutschrift<br/>CRN-2023-0121\"] -- \"bezieht sich auf\" --> I\n```\n\nDer Storno ohne Referenz ist in diesem Bild schlicht nicht darstellbar. Genau so soll es sein: Was sich nicht zeichnen lässt, sollte sich auch nicht speichern lassen.\n\n## Invarianten: was immer gelten muss\n\nBegriffe allein reichen nicht. Die eigentliche Substanz einer Domäne steckt in ihren Invarianten – den Aussagen, die für jeden gültigen Datensatz gelten müssen, egal woher er kommt. Für Rechnungsdaten sind das vor allem drei:\n\nErstens: Summen müssen aufgehen. Die Positionssummen je Steuersatz, darauf die Steuer, das Ganze addiert – das muss den Bruttobetrag des Belegs ergeben, auf den Cent. Rundung passiert je Steuersatzgruppe, nicht je Position, sonst driftet es.\n\nZweitens: Ein Storno referenziert ein Original. Ein Storno ohne Referenz ist kein Storno, sondern ein Datenfehler mit Minuszeichen.\n\nDrittens – der Klassiker: Brutto und Netto dürfen nie verwechselbar sein. Ein Feld, das mal das eine und mal das andere enthält, ist schlimmer als gar kein Feld. Bei 19 Prozent Differenz fällt der Fehler in Summenauswertungen nicht einmal sofort auf; er verteilt sich als gleichmäßiger Nebel über alle Zahlen.\n\nMit TypeScript und Zod lässt sich das alles explizit machen. Beträge führe ich grundsätzlich als ganzzahlige Cent-Werte – Gleitkomma und Geld vertragen sich nicht:\n\n```typescript\nimport { z } from \"zod\";\n\nconst TaxRate = z.union([z.literal(0), z.literal(7), z.literal(19)]);\n\nconst InvoiceLine = z.object({\n  description: z.string().min(1),\n  quantity: z.number().positive(),\n  unitPriceNetCents: z.number().int(), // money as integer cents, never floats\n  taxRate: TaxRate,\n});\n\nconst Invoice = z.object({\n  invoiceNumber: z.string().regex(/^(INV|CRN|CAN)-\\d{4}-\\d{4}$/),\n  kind: z.enum([\"invoice\", \"credit_note\", \"cancellation\"]),\n  referencesInvoice: z.string().optional(),\n  issueDate: z.string().date(),   // invoice date\n  serviceDate: z.string().date(), // date of supply\n  dueDate: z.string().date(),     // payment target\n  lines: z.array(InvoiceLine).min(1),\n  totalGrossCents: z.number().int(),\n});\n```\n\nDas ist erst die Struktur. Die Invarianten kommen als Verfeinerung obendrauf, damit ein Verstoß denselben Weg nimmt wie ein Strukturfehler:\n\n```typescript\nconst ValidInvoice = Invoice.superRefine((inv, ctx) => {\n  // sum per tax rate group, round per group, then add up\n  const grossByRate = new Map<number, number>();\n  for (const line of inv.lines) {\n    const net = line.quantity * line.unitPriceNetCents;\n    const gross = Math.round(net * (1 + line.taxRate / 100));\n    grossByRate.set(line.taxRate, (grossByRate.get(line.taxRate) ?? 0) + gross);\n  }\n  const computedGross = [...grossByRate.values()].reduce((a, b) => a + b, 0);\n\n  if (computedGross !== inv.totalGrossCents) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message: `gross mismatch: lines say ${computedGross}, document says ${inv.totalGrossCents}`,\n    });\n  }\n  if (inv.kind === \"cancellation\" && !inv.referencesInvoice) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message: \"cancellation must reference an original invoice\",\n    });\n  }\n});\n```\n\nDer Unterschied zur ersten Version des Projekts ist grundsätzlich. Vorher hat der Import akzeptiert, was sich parsen ließ. Jetzt akzeptiert er, was fachlich stimmt. Das ist dieselbe Verschiebung, die man aus dem Domain-Driven Design kennt, nur auf der unscheinbarsten Ebene überhaupt: beim Einlesen von Dateien.\n\n## Drei Daten, drei Bedeutungen\n\nDie Zeitregeln verdienen einen eigenen Abschnitt, weil sie der Ort sind, an dem Auswertungen am leisesten falsch werden. Auf einem Beleg stehen bis zu drei Daten, und keines davon ist „das Datum\":\n\nDas Leistungsdatum sagt, wann etwas geliefert oder geleistet wurde. Das Rechnungsdatum sagt, wann der Beleg ausgestellt wurde. Das Zahldatum – das gar nicht auf dem Beleg steht, sondern aus dem Konto-Export kommt – sagt, wann Geld geflossen ist. Zwischen Leistung und Rechnung können Wochen liegen, zwischen Rechnung und Zahlung noch einmal. Eine Auswertung „Ausgaben pro Monat\" liefert je nach gewähltem Datum drei verschiedene Wahrheiten, und alle drei sind für irgendeine Frage die richtige: Das Leistungsdatum gehört zur Frage „Wann ist der Aufwand entstanden?\", das Rechnungsdatum zur Umsatzsteuer, das Zahldatum zur Liquidität.\n\nIn meinen Rohdaten hatte jede Quelle genau eine Datumsspalte, und keine zwei Quellen meinten dasselbe damit. Seit die drei Daten getrennte, verpflichtende Felder sind, muss jede Auswertung sagen, welches sie meint – die Frage lässt sich nicht mehr versehentlich überspringen. Das Zahlungsziel ist dann nur noch abgeleitete Information: Rechnungsdatum plus Frist ergibt `dueDate`, und ein Abgleich mit dem Zahldatum zeigt, was überfällig war.\n\n## Die Grenze: ablehnen statt durchwinken\n\nBleibt die Frage, was mit Zeilen passiert, die die Prüfung nicht bestehen. Die übliche Antwort ist eine Log-Zeile, und die übliche Folge ist, dass niemand sie liest. Bei einem Import, der einmal im Monat läuft, ist das gleichbedeutend mit stillem Datenverlust – nur dass diesmal die schlechten Daten draußen bleiben statt drin, was besser ist, aber immer noch unsichtbar.\n\nDie für mich brauchbare Antwort: Abgelehnte Zeilen sind ein Ergebnis des Laufs, gleichrangig mit den akzeptierten. Der Import erzeugt zwei Artefakte – die Datenbank und einen Ablehnungs-Report als Markdown-Datei, mit Quelle, Zeilennummer und dem fachlichen Grund:\n\n```typescript\ntype RejectedRow = {\n  source: string;   // e.g. \"supplier-a-2023.csv\"\n  rowNumber: number;\n  reason: string;   // human-readable, domain language\n};\n\nconst rejectedRows: RejectedRow[] = [];\n\nfor (const [rowNumber, candidate] of candidates.entries()) {\n  const result = ValidInvoice.safeParse(candidate);\n  if (!result.success) {\n    rejectedRows.push({\n      source: candidate.source,\n      rowNumber,\n      reason: result.error.issues.map((i) => i.message).join(\"; \"),\n    });\n    continue;\n  }\n  accepted.push(result.data);\n}\n// afterwards: write rejected-rows report next to the database, fail if quota exceeded\n```\n\nDer Report ist bewusst eine Datei und kein Log-Strom. Dateien kann man diffen, ablegen, im nächsten Monat mit dem Vormonat vergleichen. Läuft der Import zweimal über dieselben Eingaben, muss exakt derselbe Report entstehen – warum ich auf diese Eigenschaft so viel Wert lege, habe ich in [Deterministische CLIs](https://www.mikebild.dev/de/blog/deterministische-clis/) ausführlicher beschrieben. Und für die Werte, die aus PDFs stammen, gilt ohnehin gesteigertes Misstrauen: Was eine Texterkennung liefert, ist ein Messwert mit Unsicherheit, kein Fakt – dazu mehr in [OCR mit Cache und Misstrauen](https://www.mikebild.dev/de/blog/ocr-mit-cache-und-misstrauen/).\n\nDer komplette Fluss sieht dann so aus:\n\n```mermaid\nflowchart LR\n  A[\"PDF-Belege\"] --> N[\"Normalisieren<br/>Kommas, Encoding, Spalten\"]\n  B[\"CSV-Exporte<br/>Buchhaltung\"] --> N\n  K[\"Konto-Export<br/>Bank\"] --> N\n  N --> V{\"Domänen-Validierung<br/>Typen + Invarianten\"}\n  V -- \"gültig\" --> DB[(\"SQLite<br/>Belege + Positionen\")]\n  V -- \"abgelehnt\" --> R[\"Ablehnungs-Report<br/>Markdown, diffbar\"]\n```\n\nWichtig an dem Bild ist die eine Raute. Es gibt genau eine Stelle, an der Rohdaten zu Domänendaten werden. Hinter dieser Grenze darf jeder Code den Feldern trauen: `totalGrossCents` ist brutto, in Cent, und die Summen gehen auf. Vor der Grenze ist alles verdächtig. Diese Asymmetrie macht den Rest des Projekts so angenehm – die Auswertungen enthalten keine einzige Abwehrzeile mehr, kein „falls das Feld doch leer ist\", kein zweites Nachrechnen.\n\n## Auswerten, wenn die Daten sauber sind\n\nFür die Analysen habe ich DuckDB direkt auf die Datenbank gesetzt. Sobald die Domäne stimmt, sind die interessanten Fragen erstaunlich kurze SQL-Statements. Offene Posten zum Beispiel – Belege, deren Zahlungsziel verstrichen ist, ohne dass ein Zahldatum existiert:\n\n```sql\nSELECT i.invoice_number,\n       i.due_date,\n       i.total_gross_cents / 100.0 AS gross_eur\nFROM invoices i\nLEFT JOIN payments p ON p.invoice_number = i.invoice_number\nWHERE i.kind = 'invoice'\n  AND p.paid_date IS NULL\n  AND i.due_date < current_date\nORDER BY i.due_date;\n```\n\nDass diese Query stimmt, verdankt sie vollständig der Grenze davor. Mit den Rohdaten der ersten Version hätte dieselbe Query plausible und falsche Zahlen geliefert – Stornos als offene Posten gezählt, Brutto und Netto gemischt, das Leistungsdatum als Fälligkeit interpretiert. Nichts davon wäre aufgefallen, weil das Ergebnis nach Geld aussieht und Geldbeträge immer irgendwie glaubwürdig wirken.\n\nEin Side Effect, mit dem ich nicht gerechnet hatte: Der Ablehnungs-Report wurde zum besten Werkzeug, um die Quellen selbst zu verstehen. Häufen sich Ablehnungen aus einer Datei mit demselben Grund, ist das kein Rauschen, sondern eine Erkenntnis über den Exporteur – etwa dass ein Werkzeug bei Gutschriften das Vorzeichen anders setzt als bei Rechnungen. Solche Muster standen früher in keinem Log; jetzt stehen sie gesammelt in einer Datei, die ich tatsächlich lese.\n\n## Und die E-Rechnung?\n\nMan könnte einwenden, dass sich das Problem von selbst erledigt: Mit dem Wachstumschancengesetz ist im März 2024 beschlossen worden, dass die elektronische Rechnung im deutschen B2B-Geschäft ab 2025 schrittweise verpflichtend wird – strukturierte Formate nach EN 16931 statt PDF-Prosa. Das ist eine gute Nachricht, denn genau die Felder, um die es hier ging, sind dort formal definiert: Belegart, Steuersätze je Position, Leistungs- und Rechnungsdatum.\n\nNur verschiebt ein strukturiertes Format die Arbeit, es beseitigt sie nicht. Ob ein XML-Feld oder eine CSV-Spalte behauptet, ein Bruttobetrag zu sein – prüfen, dass die Summen aufgehen und der Storno sein Original findet, muss weiterhin die empfangende Seite. Und die Bestandsdaten der vergangenen Jahre bleiben ohnehin, was sie sind: PDFs und Exporte mit Eigenheiten. Die Domänengrenze wird also nicht überflüssig; sie bekommt künftig nur besseres Eingangsmaterial.\n\n## Was ich daraus mitnehme\n\nDer Reflex, Rechnungsdaten als Transportproblem zu behandeln, ist verständlich – die Dateien sind klein, die Formate bekannt, die Werkzeuge fertig. Aber die Schwierigkeit liegt nicht im Transport. Sie liegt darin, dass diese Daten eine Fachsprache haben, Invarianten, die kein Parser kennt, und drei Zeitachsen, die sich nicht in einer Datumsspalte unterbringen lassen. Wer das ignoriert, bekommt einen Import, der grün durchläuft und trotzdem falsche Zahlen produziert. Wer es modelliert, bekommt etwas Selteneres als korrekte Daten: erklärbare Daten. Jede Zahl in der Datenbank hat eine Herkunft, jede fehlende Zeile einen dokumentierten Grund.\n\nUnterm Strich hat das kleine private Projekt damit mehr über Softwarearchitektur gesagt als mancher Servicezuschnitt: Eine Domäne erkennt man nicht an ihrer Größe, sondern daran, dass sie eigene Begriffe, eigene Regeln und eigene Zeit hat. Rechnungsdaten haben alle drei.\n\n## Weiterführende Quellen\n\n- [Zod auf GitHub](https://github.com/colinhacks/zod) – Schema-Validierung für TypeScript\n- [Zod-Dokumentation](https://zod.dev) – Referenz zu Refinements und Error Handling\n- [DuckDB-Dokumentation](https://duckdb.org/docs/) – lokale Analysen direkt auf Dateien und Datenbanken\n- [§ 14 UStG](https://www.gesetze-im-internet.de/ustg_1980/__14.html) – Pflichtangaben einer Rechnung im deutschen Umsatzsteuerrecht\n- [Papa Parse](https://www.papaparse.com/) – CSV-Parsing im Browser und in Node.js"},{"locale":"de","translation_key":"nodejs-testing-mit-mocha","slug":"nodejs-testing-mit-mocha","title":"Node.js testen: die Testpyramide mit Mocha","summary":"Wie sich eine Node.js-Testsuite sinnvoll auf verschiedene Testebenen verteilt und wie Mocha, node:assert, sinon und supertest dabei zusammenspielen.","tags":["Software","Node.js","Backend"],"published_at":"2024-07-16T10:00:00+00:00","updated_at":"2026-07-13T08:02:04.028363+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-testing-mit-mocha/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/c279591952357f6641325189341292127b3e1bb161a52759cf3751512042aa21/nodejs-testing-mit-mocha-vorlesen.mp3","audio_duration_secs":777,"text":"Ein Test beweist nicht, dass Code funktioniert. Er hält fest, welches Verhalten jemand einmal von diesem Code erwartet hat – und schlägt Alarm, wenn diese Erwartung bricht. Eine Testsuite ist damit weniger ein Beweis als ein Gedächtnis, und derjenige, der die Erwartung bricht, ist erstaunlich oft man selbst, ein halbes Jahr später. Im Backend, wo eine falsche Berechnung still durch eine API rutscht und erst in der Buchhaltung auffällt, ist dieses Gedächtnis Gold wert.\n\nDie entscheidende Frage ist deshalb nie \"Testen wir?\", sondern \"Wie verteilen wir unseren Testaufwand?\" Genau dafür gibt es ein Bild, das seit Jahren trägt: die Testpyramide. Sie ist eine Heuristik, kein Mengenverhältnis, das für jedes System gleich aussieht. Ich schaue mir in diesem Artikel an, wie sie funktioniert, warum Suiten mit der Zeit kippen, und welche Werkzeuge im Node.js-Alltag dazu passen – Mocha als Runner, `node:assert` für Assertions, sinon für die Isolation externer Abhängigkeiten und supertest für HTTP-Endpoints. Node.js bringt inzwischen mit `node:test` selbst einen stabilen Test-Runner mit; Mocha bleibt hier die bewusst gewählte, nicht die einzig zeitgemäße Variante.\n\n## Die Pyramide: breite Basis, schmale Spitze\n\nDie Idee ist einfach. Nicht alle Tests sind gleich teuer, und nicht alle geben gleich schnell Auskunft. Ein Unit-Test läuft in Millisekunden, isoliert eine einzelne Funktion und sagt mir bei einem Fehlschlag ziemlich genau, wo das Problem sitzt. Ein End-to-End-Test fährt die ganze Anwendung hoch, klickt sich durch mehrere Systeme und braucht Sekunden bis Minuten – und wenn er rot wird, weiß ich erst mal nur, dass irgendwo auf dem langen Weg etwas kaputt ist.\n\nDaraus folgt häufig eine Verteilung mit vielen schnellen Tests an der Basis, gezielten Integrationstests in der Mitte und wenigen durchgängigen Szenarien an der Spitze. Wie breit die Schichten ausfallen, hängt von den Risiken und den Systemgrenzen ab.\n\n```mermaid\ngraph TD\n    E2E[\"E2E<br/>wenige, langsam, brüchig\"]\n    INT[\"Integration<br/>weniger, mittelschnell\"]\n    UNIT[\"Unit<br/>viele, schnell, isoliert\"]\n    E2E --> INT\n    INT --> UNIT\n    style UNIT fill:#2d6a4f,color:#fff\n    style INT fill:#40916c,color:#fff\n    style E2E fill:#74c69d,color:#000\n```\n\nDie Basis ist breit, weil Unit-Tests billig sind – schnell geschrieben, schnell ausgeführt, stabil. Die Spitze ist schmal, weil E2E-Tests teuer im Unterhalt sind. Sie brechen bei jeder Umgebungsänderung, sie werden flaky, sobald Timing ins Spiel kommt, und sie kosten in jeder CI-Runde Zeit. Ein paar davon braucht man – sie sind die einzigen, die belegen, dass die Teile auch zusammen funktionieren. Aber sie sind das Salz, nicht die Suppe.\n\n## Welches Werkzeug wofür\n\nBevor ich zu Code komme, eine kurze Einordnung, denn in Node.js verteilt sich die Arbeit auf ein kleines Ökosystem statt auf ein einzelnes Framework:\n\n- Mocha ist der Runner. Er gibt die Struktur (`describe`/`it`), führt die Tests aus, verwaltet Hooks und meldet Ergebnisse. Mocha selbst bringt bewusst keine Assertions mit.\n- `node:assert` liefert genau diese Assertions – eingebaut, ohne zusätzliche Abhängigkeit. Wer eine ausdrucksstärkere BDD-Syntax will, greift alternativ zu Chai (in der CommonJS-Welt 2024 die v4-Linie).\n- sinon stellt Test-Doubles bereit: Spies beobachten Aufrufe, Stubs ersetzen Verhalten. Damit isoliere ich externe Abhängigkeiten wie Datenbank, HTTP oder Zeit.\n- supertest testet HTTP-Endpoints auf App-Ebene, ohne einen echten Netzwerk-Port oder Browser zu brauchen.\n\nDiese Trennung irritiert Umsteiger aus anderen Sprachen anfangs. Sie ist aber eine Stärke: Man kombiniert austauschbare Bausteine, statt sich an ein Monolith-Framework zu binden.\n\n## Unit-Tests: das Fundament\n\nFangen wir unten an. Ein Unit-Test nimmt eine Funktion, gibt ihr Eingaben und prüft die Ausgabe. Nichts sonst – keine Datenbank, kein Netzwerk, kein Dateisystem.\n\nMocha strukturiert das über `describe` (ein Block, der zusammengehörige Tests gruppiert) und `it` (ein einzelner Testfall). Für die Assertion nehme ich `node:assert` im Strict-Modus. Der `node:`-Präfix macht klar, dass es ein Built-in ist, und `/strict` sorgt dafür, dass keine stillschweigende Typ-Umwandlung passiert.\n\n```js\nconst assert = require('node:assert/strict');\nconst { sum } = require('../src/math');\n\ndescribe('sum()', () => {\n  it('adds two positive numbers', () => {\n    assert.strictEqual(sum(2, 3), 5);\n  });\n\n  it('handles negative operands', () => {\n    assert.strictEqual(sum(-4, 1), -3);\n  });\n});\n```\n\nZwei Details lohnen einen zweiten Blick. Erstens die Argument-Reihenfolge: `assert.strictEqual(actual, expected)` – immer erst der tatsächliche Wert, dann der erwartete. Wer das vertauscht, bekommt bei einem Fehlschlag eine Diff-Ausgabe, die genau falsch herum liest. Zweitens `strictEqual` statt `equal`: Der Strict-Modus vergleicht mit `Object.is`/`===` und wandelt nichts stillschweigend um. `1` ist nicht `'1'`. Das klingt pedantisch, verhindert aber genau die Klasse von Bugs, die man mit Tests eigentlich fangen will.\n\nFür Objekte und Arrays nehme ich `deepStrictEqual`, das tief und typgenau vergleicht:\n\n```js\nconst assert = require('node:assert/strict');\n\nit('builds the expected payload', () => {\n  const result = buildUser({ id: 1, name: 'Ada' });\n  assert.deepStrictEqual(result, {\n    id: 1,\n    name: 'Ada',\n    role: 'guest',\n  });\n});\n```\n\n## Verhalten testen, nicht Implementierung\n\nHier kommt der Punkt, an dem in Code-Reviews die meisten Diskussionen entstehen. Ein Kollege fragte einmal, ob er nicht prüfen solle, dass seine Funktion intern `Array.map` aufruft. Besser nicht: Interessieren sollte den Test das Ergebnis – die transformierte Liste –, nicht der Weg dorthin.\n\nDer Unterschied ist praktisch und nicht akademisch. Ein Test, der auf beobachtbares Verhalten zielt, überlebt ein Refactoring: Solange die Funktion bei gleicher Eingabe die gleiche Ausgabe liefert, bleibt er grün, egal ob innen `map`, `reduce` oder eine `for`-Schleife steht. Ein Test, der Implementierungsdetails festnagelt, bricht dagegen bei jeder Umbauaktion – obwohl fachlich nichts kaputt ist. Solche Tests erziehen ein Team dazu, Refactorings zu scheuen. Und ein Team, das sich nicht mehr traut umzubauen, sammelt technische Schulden schneller an, als jeder Test sie je einfangen könnte.\n\n## Externe Abhängigkeiten isolieren mit sinon\n\nSobald eine Funktion die reine Berechnung verlässt und mit einer Datenbank, einem HTTP-Client oder der Uhr redet, wird es interessant. Diese Abhängigkeiten will ich im Unit-Test nicht echt ansprechen – sie sind langsam, unzuverlässig und schwer in einen definierten Zustand zu bringen. Stattdessen ersetze ich sie durch Test-Doubles.\n\nsinon unterscheidet dabei vor allem zwischen Spy und Stub. Ein Spy lässt die echte Funktion laufen und beobachtet nur, wie oft und womit sie aufgerufen wurde. Ein Stub ersetzt das Verhalten komplett – ich sage ihm, was er zurückgeben oder werfen soll.\n\nNehmen wir einen Service, der einen Nutzer über ein Repository lädt. Ich will testen, dass er sich bei einem DB-Fehler korrekt verhält, ohne je eine echte Datenbank anzufassen:\n\n```js\nconst assert = require('node:assert/strict');\nconst sinon = require('sinon');\nconst userRepo = require('../src/user-repo');\nconst service = require('../src/user-service');\n\ndescribe('userService.getUser()', () => {\n  afterEach(() => {\n    sinon.restore();\n  });\n\n  it('propagates a repository failure', async () => {\n    const stub = sinon\n      .stub(userRepo, 'findById')\n      .rejects(new Error('db down'));\n\n    await assert.rejects(() => service.getUser(1), /db down/);\n    assert.ok(stub.calledOnceWith(1));\n  });\n\n  it('returns the user on success', async () => {\n    sinon.stub(userRepo, 'findById').resolves({ id: 1, name: 'Ada' });\n\n    const user = await service.getUser(1);\n    assert.strictEqual(user.name, 'Ada');\n  });\n});\n```\n\nDer wichtigste Baustein hier ist nicht der Stub selbst, sondern das `afterEach(() => sinon.restore())`. Seit sinon v5 ist das Default-Objekt `sinon` selbst eine Sandbox; `restore()` setzt alle ersetzten Methoden zurück. Vergisst man das, leben die Stubs über den Testfall hinaus weiter. Der nächste Test bekommt dann unbemerkt einen manipulierten `userRepo` untergeschoben – und je nach Ausführungsreihenfolge geht er mal durch, mal nicht. Genau das meint man mit \"flaky\": ein Test, dessen Ergebnis von der Reihenfolge oder der Parallelität abhängt, nicht vom Code. Wer eine eigene Sandbox bevorzugt, nutzt `const sandbox = sinon.createSandbox()` und ruft `sandbox.restore()` auf – das Prinzip bleibt.\n\nAber Vorsicht: Test-Doubles sind ein scharfes Messer. Wer alles wegmockt, testet am Ende nur noch, dass die Mocks so reagieren, wie er sie konfiguriert hat. Solche Tests spiegeln die eigene Erwartung zurück und brechen beim ersten echten Refactoring. Ersetzen sollte man die Grenze zum externen System – nicht die eigene Logik gleich mit.\n\n## Integrationstests: HTTP-Endpoints mit supertest\n\nEine Ebene höher liegen Integrationstests. Hier will ich nicht mehr eine einzelne Funktion prüfen, sondern das Zusammenspiel – etwa dass eine Express-Route den richtigen Statuscode und Body liefert. Dafür gibt es supertest.\n\nsupertest nimmt eine Express-App oder einen `http.Server`, bindet sie an einen ephemeren Port und schickt echte HTTP-Requests dagegen. Kein Browser, kein manuell gestarteter Server, keine feste Portnummer. Die API ist fluent und liest sich fast wie eine Beschreibung:\n\n```js\nconst assert = require('node:assert/strict');\nconst request = require('supertest');\nconst app = require('../src/app');\n\ndescribe('GET /users', () => {\n  it('returns 200 and a JSON list', async () => {\n    const res = await request(app)\n      .get('/users')\n      .expect(200)\n      .expect('Content-Type', /json/);\n\n    assert.ok(Array.isArray(res.body));\n    assert.strictEqual(res.body.length, 2);\n  });\n\n  it('returns 404 for an unknown user', async () => {\n    await request(app).get('/users/999').expect(404);\n  });\n});\n```\n\nDas `await` vorne ist entscheidend. supertest gibt ein Promise zurück; ohne `await` (oder ein `return` des Promises) endet der Test, bevor die Assertions gelaufen sind – und Mocha meldet ihn fälschlich als grün. Diese Art von False Positive ist besonders tückisch, weil die Suite wochenlang beruhigend grün bleibt, obwohl sie nichts prüft.\n\nDamit ist auch klar, warum ich Async konsequent auf einem Weg abwickle. Mocha erlaubt zwei Stile: entweder `async`/Promise-returning oder den klassischen `done`-Callback. Mischen darf man sie nicht. Entweder\n\n```js\nit('waits for the promise', async () => {\n  const value = await loadValue();\n  assert.strictEqual(value, 42);\n});\n```\n\noder, wenn man mit einer Callback-basierten API arbeitet:\n\n```js\nit('waits for the callback', function (done) {\n  loadValue((err, value) => {\n    if (err) return done(err);\n    assert.strictEqual(value, 42);\n    done();\n  });\n});\n```\n\nBeides gleichzeitig – ein `done`-Parameter und `async` – lehnt Mocha mit einem klaren Fehler ab (\"Resolution method is overspecified\"). Ein Detail am Rande: Mochas Default-Timeout pro Test liegt bei 2000 ms. Wenn ein asynchroner Test nie sein `done` aufruft oder ein Promise nie auflöst, läuft er in diesen Timeout und wird rot – oft der erste Hinweis auf ein vergessenes `await` oder `done`.\n\n## Der häufigste Fehler: die Pyramide auf dem Kopf\n\nJetzt zum häufigsten Fallstrick. Ein Team startet mit den besten Absichten, schreibt aber vor allem E2E-Tests, weil die sich so schön \"echt\" anfühlen. Nach einem Jahr sieht die Verteilung so aus:\n\n```mermaid\ngraph TD\n    UNIT[\"Unit<br/>kaum vorhanden\"]\n    INT[\"Integration<br/>ein paar\"]\n    E2E[\"E2E<br/>viele, langsam, flaky\"]\n    UNIT --> INT\n    INT --> E2E\n    style E2E fill:#9d0208,color:#fff\n    style INT fill:#dc2f02,color:#fff\n    style UNIT fill:#f48c06,color:#000\n```\n\nMan nennt das die \"Ice-Cream-Cone\" – die umgedrehte Pyramide mit der breiten, teuren Spitze oben. Die Symptome sind immer gleich: Die Suite läuft zehn Minuten statt zehn Sekunden. Ein einzelner roter Test sagt nicht, wo der Bug sitzt, weil er ein Dutzend Komponenten gleichzeitig durchläuft. Und weil E2E-Tests von Timing und Umgebung abhängen, werden sie flaky – irgendwann lässt das Team die Pipeline einfach so lange neu laufen, bis sie grün ist. Das ist der Moment, in dem Tests aufhören, ein Gedächtnis zu sein, und zu einem Ritual werden, das niemand mehr ernst nimmt.\n\nDer Weg heraus ist unspektakulär: Für jeden Bug, der durch einen langsamen E2E-Test auffällt, schreibt man den eigentlichen Regressionstest eine Ebene tiefer – als Unit- oder Integrationstest, der dieselbe Ursache in Millisekunden fängt. Die Pyramide richtet sich nicht durch einen großen Umbau wieder auf, sondern durch die Gewohnheit, Fehler auf der billigsten Ebene festzuhalten, auf der sie reproduzierbar sind.\n\nDiese Haltung passt zu einem Gedanken, den ich schon beim Thema [Fehler als Architektur](https://www.mikebild.dev/de/blog/nodejs-fehler-als-architektur/) beschrieben habe: Ein Fehler ist kein Ärgernis, das man wegdrückt, sondern eine Information über das System. Ein Test ist die Konserve dieser Information. Und wer verstehen will, warum asynchrone Tests im Backend überhaupt so eine große Rolle spielen, findet die Grundlagen dazu im [Node.js-Training](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) rund um Event Loop und Architektur.\n\n## Ein Wort zu Hooks\n\nDamit Tests unabhängig bleiben, braucht jeder einen sauberen Ausgangszustand. Mocha bietet dafür vier Hooks: `before` und `after` laufen einmal pro `describe`-Block, `beforeEach` und `afterEach` vor beziehungsweise nach jedem einzelnen Test. Die Reihenfolge ist verlässlich: erst alle `before`, dann pro Test `beforeEach` → Test → `afterEach`, am Ende `after`.\n\n```js\ndescribe('orderService', () => {\n  let db;\n\n  before(async () => {\n    db = await connectTestDb();\n  });\n\n  beforeEach(async () => {\n    await db.reset();\n  });\n\n  afterEach(() => {\n    sinon.restore();\n  });\n\n  after(async () => {\n    await db.close();\n  });\n\n  it('creates an order', async () => {\n    // ...\n  });\n});\n```\n\nTeure Einmal-Arbeit wie der Verbindungsaufbau gehört in `before`/`after`, das Zurücksetzen von Zustand in `beforeEach`/`afterEach`. Ein `beforeEach` innerhalb eines verschachtelten `describe` gilt nur für dessen Tests – so hält man Setup lokal und vermeidet, dass ein globaler Hook die halbe Suite unnötig verlangsamt.\n\n## Fazit\n\nTesten im Backend ist keine Fleißarbeit, die man am Ende noch draufsattelt, sondern die Art, wie ein Team seine Architektur-Erwartungen festhält und über Refactorings hinweg absichert. Die Testpyramide gibt dabei eine Richtung vor, aber keine feste Stückzahl: schnelle Tests tragen die Basis, Integrationstests sichern wichtige Grenzen ab, wenige durchgängige Szenarien prüfen das Zusammenspiel. In diesem Beispiel ist der Werkzeugkasten klein und austauschbar – Mocha strukturiert, `node:assert` prüft, sinon isoliert externe Abhängigkeiten, supertest testet HTTP-Endpoints.\n\nWas sich für mich über die Jahre als Kern herausgestellt hat: beobachtbares Verhalten testen, nicht die Implementierung, und Fehler auf der billigsten Ebene festhalten, auf der sie reproduzierbar sind. Dann bleibt die Suite schnell, aussagekräftig und – das Wichtigste – vertrauenswürdig. Eine Testsuite, der niemand mehr glaubt, ist teurer als gar keine.\n\n## Weiterführende Quellen\n\n- Mocha – Dokumentation und Hooks: [mochajs.org](https://mochajs.org/) und [mochajs.org/features/hooks](https://mochajs.org/features/hooks/)\n- node:assert – Strict Mode: [nodejs.org/api/assert.html](https://nodejs.org/api/assert.html)\n- node:test – eingebauter Test-Runner: [nodejs.org/api/test.html](https://nodejs.org/api/test.html)\n- sinon – Test-Doubles und Stubs: [sinonjs.org](https://sinonjs.org/) und [sinonjs.org/concepts/stubs](https://sinonjs.org/concepts/stubs/)\n- supertest: [npmjs.com/package/supertest](https://www.npmjs.com/package/supertest)\n- Chai (Alternative zu assert): [chaijs.com](https://www.chaijs.com/)\n- Begleitendes Repository mit Testing-Kapitel: [github.com/mikebild/introduction-nodejs](https://github.com/mikebild/introduction-nodejs)"},{"locale":"de","translation_key":"deterministische-clis","slug":"deterministische-clis","title":"Deterministische CLIs","summary":"Determinismus ist eine Architekturentscheidung: gleiche Eingaben, gleicher Report, reviewbar per Diff. Er lohnt sich dort, wo ein Artefakt wiederholt geprüft wird.","tags":["Software","Daten","Tools"],"published_at":"2024-07-12T10:00:00+00:00","updated_at":"2026-07-20T13:27:22.94021+00:00","url":"https://www.mikebild.dev/de/blog/deterministische-clis/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/4cf2d80358bbfdd332b59ab886bde6046f5efff5cd805904aa941dc98bc69531/deterministische-clis-vorlesen.mp3","audio_duration_secs":654,"text":"# Deterministische CLIs\n\nZwei Läufe, dieselben Eingabedateien, zwei verschiedene Reports. Der Unterschied besteht aus einem Zeitstempel im Kopf und einer Tabelle, deren Zeilen diesmal in anderer Reihenfolge stehen. Fachlich hat sich nichts geändert, aber der Diff zeigt hundert Zeilen an, und keine davon bedeutet etwas. Also liest der Reviewer den ganzen Report noch einmal. Beim nächsten Mal liest er ihn gar nicht mehr.\n\nEin deterministisches CLI dreht diese Lage um: Was im Diff auftaucht, hat sich auch fachlich geändert. Byte für Byte. Das klingt nach einem Implementierungsdetail, ist in Wirklichkeit aber eine Entscheidung über Systemgrenzen.\n\nDeterminismus wird meist als Side Effect behandelt, den man „auch noch“ mitnimmt. In Wahrheit ist er die Voraussetzung dafür, dass ein Ergebnis reviewbar wird. Und Reviewbarkeit ist die Währung, in der digitale Produktentwicklung tatsächlich bezahlt: Was ich nicht vergleichen kann, kann ich nicht freigeben, nicht widerlegen und nicht mit gutem Gewissen automatisieren.\n\n## Warum Determinismus ein Architektur-Hebel ist\n\nDer Reflex ist, Determinismus als Eigenschaft der Ausgabe zu sehen. Ich sehe ihn als Eigenschaft der Systemgrenze. Ein CLI, das reproduzierbar arbeitet, zwingt mich, jede Quelle von Nichtdeterminismus explizit zu machen: Zeitstempel, Zufallszahlen, unsortierte Maps, Netzwerkantworten, OCR-Ergebnisse, Modell-Outputs. Jede dieser Quellen muss ich entweder einfrieren, sortieren, cachen oder aus dem Ergebnis heraushalten.\n\nGenau diese Übung ist wertvoll, unabhängig vom Werkzeug. Wer Nichtdeterminismus benennt, hat die Zustands- und Abhängigkeitsgrenzen eines Systems schon halb dokumentiert. Die Frage „warum ist dieser Lauf nicht reproduzierbar?“ ist fast immer dieselbe wie „welcher Teil meines Systems ist verstecktes, ungezähmtes Ich-weiß-nicht?“.\n\nDer Business-Outcome ist konkret. Ein deterministischer Report lässt sich per `diff` reviewen. Ein Reviewer sieht in Sekunden, was sich zwischen zwei Läufen geändert hat, statt eine ganze Ausgabe erneut zu lesen. Das verkürzt den Feedback-Zyklus von „ich lese das komplett neu“ auf „ich schaue mir die drei geänderten Zeilen an“. In Teams, die täglich solche Reports produzieren, ist das der Unterschied zwischen Reibung und Fluss.\n\n## Das Kostenmodell – Determinismus ist nicht gratis\n\nDeterminismus hat einen Preis. Wer ihn verschweigt, liefert eine Werbebotschaft statt einer Abwägung.\n\nMan zahlt in expliziter Zustandskontrolle. Zeit muss injiziert statt gelesen werden. Zufall braucht einen Seed. Externe Sensoren – OCR, HTTP, ein Modell – brauchen einen Cache, damit ein zweiter Lauf dasselbe sieht wie der erste. Sortierung wird zur Pflicht, nicht zur Kür, weil sonst die Reihenfolge einer Hash-Map den Report verändert. Das ist zusätzliche Arbeit, und bei kleinen Wegwerf-Skripten lohnt sie sich oft nicht.\n\nDer Gegenwert ist Reviewbarkeit, Auditierbarkeit und Testbarkeit in einem. Ein deterministischer Report ist automatisch ein Golden-Master-Test: Ich checke einen erwarteten Report ein und lasse die CI gegen ihn diffen. Ich brauche keine gesonderte Assertion-Wüste, das Artefakt selbst ist der Test. Die Kosten fallen einmalig an, die Wirkung wiederholt sich bei jedem Lauf. Genau deshalb setze ich Determinismus dort ein, wo etwas oft läuft und oft geprüft wird – und lasse ihn dort weg, wo ein Skript einmal etwas kippt und dann verschwindet.\n\nDiese Abwägung ist die eigentliche Ingenieursleistung, nicht die Implementierung. Ich habe schon Teams gesehen, die jedes Skript deterministisch zwingen wollten und über Seed-Injektion in Wegwerf-Tools stolperten. Und ich habe das Gegenteil gesehen: einen täglichen Report, den niemand mehr las, weil er bei jedem Lauf anders aussah und ein Review Stunden gekostet hätte. Die Grenze verläuft nicht zwischen „immer“ und „nie“. Sie verläuft an der Frage, ob das Artefakt wiederholt geprüft wird. Wird es das, zahlt sich der Preis um Größenordnungen aus. Wird es das nicht, ist Determinismus Gold-Plating.\n\n## Die Grenze vor dem Werkzeug\n\nVor der Toolwahl kläre ich, welche Daten führend sind, was später nachvollziehbar sein muss und welche Teile unabhängig geändert werden sollen. So kann ich den PDF-Parser tauschen, ohne Matching-Regeln oder Reportformat anzufassen. Determinismus hilft beim letzten Punkt, ersetzt aber keine klare Fachgrenze: Ein reproduzierbarer Report kann auch Unklarheit zuverlässig wiederholen.\n\n## Ein konkretes Beispiel – Belege gegen Buchungen matchen\n\nIch zeige das an einem Inventur-Werkzeug, das ich als Muster immer wieder verwende. Die Aufgabe: ein Kontoblatt über Rechnungsnummern an PDF-Belege koppeln, Inventarpositionen gegen Rechnungspositionen matchen und die Lücken sichtbar machen. Klingt nach Buchhaltung, ist in Wahrheit eine Architekturübung über unsichere Daten.\n\nDrei Design-Entscheidungen tragen das Ganze, und keine davon ist ein Werkzeug.\n\nDie erste ist die Dreistufigkeit: Kontoblatt an Belege koppeln, Positionen matchen, Nicht-PDF-Vendors separat über Buchungstext-Regeln behandeln. Diese Stufen sind wichtiger als jedes Dateiformat. Sie sind die Fachgrenze, an der ich später unabhängig etwas ändern kann.\n\nDie zweite ist die saubere Trennung von hartem Match und Fuzzy-Fallback. Zuerst müssen definierte Tokens im Produkttitel stehen; Fuzzy Matching kommt nur zum Zug, wenn der harte Weg nichts findet. Damit bleibt Automatisierung erklärbar. Ich kann für jede Zeile sagen, warum sie zugeordnet wurde – hart über eine Regel oder weich über eine Ähnlichkeit oberhalb einer Schwelle. Ein Fuzzy-Match, den niemand mehr begründen kann, ist kein Feature – er ist die Fehlersuche von übermorgen.\n\nDie dritte ist die Behandlung von OCR als unsicherer Sensor. Vision liefert die Basis, Tesseract korrigiert gezielt Beträge in der Soll/Haben-Region, ein JSON-Cache macht spätere Läufe reproduzierbar. Der entscheidende Satz: Der erkannte Text ist ein Messwert, keine Wahrheit. Beträge, Namen und Nummern können falsch gelesen werden. Deshalb bekommt diese Schicht Cache, Schwellenwerte, manuelle Alias-Regeln und – das ist der Kern – Diffbarkeit.\n\nDer Report selbst ist dann ein Architekturartefakt, kein Nebenprodukt. Inventarpositionen, Rechnungsnummern, Kaufdatum, Match-Art, verwaiste Kontoeinträge und ungenutzte Rechnungspositionen stehen sichtbar nebeneinander. Genau dadurch wird aus einem Skript ein prüfbares Datensystem: Man sieht nicht nur, was gematcht wurde, sondern auch, was nicht passt – und das ist meist die interessantere Information.\n\n## Wie das aufgerufen wird\n\n```bash\ninventory-correlate \\\n  --account account.pdf \\\n  --inventory inventory.pdf \\\n  --out report.md\n\n# review is just a diff against the last known-good run\ndiff last-report.md report.md\n```\n\nDas Beispiel ist bewusst klein. Es soll keine vollständige Anwendung simulieren, sondern die Grenze zeigen. Ein gutes Beispiel hat nicht die meisten Features. Es hat die eine Entscheidung, über die man nach fünf Minuten streiten kann. Hier steckt sie im zweiten Aufruf: Weil der Report deterministisch ist, ist der Review ein `diff`. Kein Dashboard, kein State, kein „lies das nochmal ganz“.\n\n```mermaid\nflowchart LR\n  PDFs --> Parser\n  Parser --> Normalize\n  Normalize --> Match[\"Hard match<br/>then fuzzy fallback\"]\n  Match --> Report[\"Deterministic<br/>Markdown report\"]\n  Report --> Diff[\"Review via diff\"]\n```\n\n## Markdown als Audit-Artefakt\n\nWarum Markdown und nicht sofort eine Oberfläche? Weil ein Markdown-Report reviewbar, diffbar und archivierbar ist, ohne dass ich ein Dashboard bauen muss. Bei Datenwerkzeugen ist Diffbarkeit ein starkes Qualitätsmerkmal. Liegt ein Report als Markdown vor, kann eine Änderung im Review gesehen werden – Zeile für Zeile, mit voller Historie im Git. Das ist oft wertvoller als eine Oberfläche, die nur den letzten Zustand zeigt und die Frage „was hat sich geändert?“ gar nicht beantworten kann.\n\nDasselbe Prinzip trägt weit über Buchhaltung hinaus. Publishing-Werkzeuge können nach demselben Muster arbeiten: Eingabe rein, deterministisches Artefakt raus, Änderungen als Diff sichtbar. Ob ich Belege zuordne oder Präsentationen erzeuge – die Architektur ist identisch, weil das Qualitätsproblem identisch ist: Ich will Änderungen sehen, nicht Zustände raten.\n\n## Woran ich den Nutzen prüfe\n\nEin Diff begrenzt den Review auf die tatsächlich geänderten Zeilen. Ob das Zeit spart, lässt sich an der Review-Dauer eines wiederkehrenden Reports ablesen. Ein erwarteter Report kann außerdem als Golden Master dienen; ein unerwarteter Diff ist dann ein konkretes Prüfsignal. Dafür investiere ich in Caches, Seeds und explizite Sortierung – nicht, weil Determinismus für jedes Skript ein Selbstzweck wäre.\n\n## Worauf ich prüfe, bevor ich das produktiv nenne\n\nEine Idee ist erst belastbar, wenn auch der Fehlerpfad beschrieben ist. Was passiert bei Wiederholung? Was ist idempotent? Wo liegt die Transaktionsgrenze? Welche Logs oder Reports helfen später bei der Analyse? Diese Fragen wirken trocken, sind aber oft der Unterschied zwischen Demo und Betrieb.\n\nBeim deterministischen CLI kommt eine spezifische Frage dazu: Ist der Nichtdeterminismus wirklich eingefangen, oder nur zufällig gerade still? Ein Report, der heute stabil ist, weil die Map zufällig sortiert ausliefert, kippt morgen bei einer anderen Laufzeit. Deshalb erzwinge ich Sortierung explizit, versioniere Caches und behandle manuelle Korrekturen als Daten, nicht als Handgriffe. Fuzzy Matching braucht explizite Schwellen und einen Weg, harte Regeln vorzuziehen – sonst ist das Ergebnis nicht mehr erklärbar. Ein Tool darf unsicher sein, aber es muss seine Unsicherheit zeigen.\n\nVor einem produktiven Einsatz prüfe ich drei Dinge:\n\n- Gleiche Eingaben erzeugen byteweise dasselbe Ergebnis.\n- Uhrzeit, Zufall, Reihenfolge und externe Antworten sind explizit begrenzt.\n- Fehler und unsichere Zuordnungen erscheinen im prüfbaren Artefakt.\n\n## Typische Fehler\n\nDer erste Fehler ist, das Werkzeug mit der Lösung zu verwechseln. Docker ist keine Architektur. GraphQL ist kein Fachmodell. React ist kein State-Konzept. Ein LLM ist kein Prozess. Diese Werkzeuge können gute Grenzen ausdrücken, aber sie erzeugen sie nicht automatisch. Determinismus ist genauso: Er ist eine Entscheidung über Systemgrenzen, kein Flag, das man setzt.\n\nDer zweite Fehler ist, den glücklichen Pfad zu überbewerten. Viele Systeme sehen im Demo-Modus sauber aus. Interessant wird es bei Wiederholung, Teilfehlern, alten Daten, Netzwerkproblemen, falschen Berechtigungen oder menschlicher Korrektur. Genau dort zeigt sich, ob das Modell trägt – und ob der Report morgen noch denselben Diff liefert wie heute.\n\n## Schluss\n\nIch investiere in Determinismus, wenn ein Ergebnis wiederholt geprüft wird. Dann zeigt der Diff die Änderung, und Caches, Seeds oder explizite Sortierung haben einen konkreten Zweck. Für ein einmaliges Wegwerfskript wäre derselbe Aufwand Gold-Plating.\n\n## Weiterführende Quellen\n\n- [Git: `git diff`](https://git-scm.com/docs/git-diff/2.45.0)\n- [Reproducible Builds: Definition](https://reproducible-builds.org/docs/definition/)"},{"locale":"de","translation_key":"observability-mit-opentelemetry","slug":"observability-mit-opentelemetry","title":"Observability mit OpenTelemetry: Logs, Traces und Metrics","summary":"Logs, Traces und Metrics mit OpenTelemetry einheitlich instrumentieren, über Trace-IDs verbinden und per OTLP an geeignete Backends ausgeben.","tags":["Software","Platform"],"published_at":"2024-07-09T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/observability-mit-opentelemetry/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/a6e5d7c260075d0b6d39a00bfe90ca04d4210f81ad976003e634fe340296cb9e/observability-mit-opentelemetry-vorlesen.mp3","audio_duration_secs":805,"text":"```json\n{\"ts\":\"2024-07-09T12:14:03.221Z\",\"level\":\"error\",\"msg\":\"stock reservation failed\",\"order_id\":\"4711\"}\n```\n\nDiese Zeile ist strukturiert, hat einen Zeitstempel, ein sauberes Feld für die Bestell-ID – und beantwortet trotzdem keine der Fragen, die nach einem Ausfall zählen. Welcher Request hat sie ausgelöst? Welcher Aufruf lief davor, welcher danach? Ist das der Einzelfall oder der hundertste seit Mittag? Die Zeile weiß nichts von dem Vorgang, aus dem sie stammt, und deshalb bleibt die Suche im Log-Volumen genau das: Suche.\n\nWas fehlt, ist die Verbindung – zwischen dem einzelnen Event, dem Pfad des Requests durch die Services und der aggregierten Sicht über die Zeit. Dafür stehen Logs, Traces und Metrics, und richtig nützlich werden sie erst, wenn sie sich gegenseitig referenzieren. OpenTelemetry ist der Standard, mit dem ich sie in Node einheitlich erhebe.\n\nDie drei Telemetriesignale sind keine austauschbaren Darstellungen derselben Information. Jedes beantwortet eine andere Frage.\n\n::::comparison{title=\"Drei Signale, drei Untersuchungsfragen\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Metrics\"}\n- Frage · Wie verändert sich ein aggregierter Wert über Zeit?\n- Stärke · Trends, Schwellen und Alarmierung\n- Grenze · erklärt keinen einzelnen langsamen Request\n:::\n:::side{label=\"Traces\"}\n- Frage · Welchen Pfad nahm eine konkrete Ausführung?\n- Stärke · Latenz und Abhängigkeiten über Servicegrenzen hinweg\n- Grenze · ersetzt keine langfristige Aggregation\n:::\n:::side{label=\"Logs\"}\n- Frage · Welches diskrete Event wurde mit welchem Kontext festgehalten?\n- Stärke · Details, Fehlermeldungen und fachliche Hinweise\n- Grenze · bleibt ohne Korrelation und Begrenzung schwer auswertbar\n:::\n::::\n\nDer praktische Gewinn entsteht beim Wechsel zwischen diesen Perspektiven: vom Trend zum betroffenen Trace und von dort zu den korrelierten Events.\n\n## Drei Signale, drei Blickwinkel\n\nBevor ich über Werkzeuge rede, lohnt sich die begriffliche Sauberkeit. Logs, Traces und Metrics sind keine drei Wege, dasselbe zu tun – sie beantworten unterschiedliche Fragen und haben unterschiedliche Kosten.\n\n- Logs sind diskrete Events mit Zeitstempel: \"Bestellung 4711 abgelehnt, weil Lagerbestand null.\" Sie liefern das Detail, den konkreten Fall, den Debug-Kontext. Dafür sind sie teuer in der Retention und werden bei hoher Kardinalität schnell unübersichtlich.\n- Traces zeigen den Pfad eines einzelnen Requests durch das System: welcher Service ruft welchen, wie lange dauert jeder Hop, wo entsteht die Latenz. Ein Trace ist ein Baum von Spans, und er endet nicht an der Servicegrenze.\n- Metrics sind aggregierte Zahlenreihen über die Zeit: Requests pro Sekunde, Fehlerrate, Latenzverteilung. Sie sind billig zu speichern, eignen sich für Alarme und Trends – aber sie sagen mir nie, *welcher* Request langsam war, nur *dass* es welche gab.\n\nDer Denkfehler, den ich immer wieder sehe, ist die Annahme, eines dieser Signale reiche aus. Metrics allein sagen mir, dass die Latenz gestiegen ist, aber nicht warum. Logs allein ertrinken im Volumen. Traces allein zeigen den Pfad, aber nicht den Trend über eine Woche. Erst zusammen ergeben sie ein Bild – und der eigentliche Gewinn entsteht dort, wo ich zwischen ihnen springen kann: von einer Latenzspitze in der Metric zum konkreten Trace, von dort in die korrelierten Logs.\n\n## OpenTelemetry trennt Instrumentierung und Backend\n\nOpenTelemetry (kurz OTel) ist ein herstellerneutrales CNCF-Projekt, und genau diese Neutralität ist der Grund, warum ich es empfehle. Früher hieß Observability oft, sich an ein Backend zu binden: Das Agent-SDK des Anbieters wurde in den Code gewoben, und ein Wechsel bedeutete, die Instrumentierung neu zu schreiben. OTel trennt die Erzeugung und den Transport der Telemetrie vom Backend. Ich instrumentiere meinen Code gegen eine standardisierte API und gebe die Daten über OTLP oder einen passenden Exporter aus. Das senkt die Wechselkosten deutlich, macht Backends aber nicht austauschbar: Abfragesprachen, Aggregationen, Aufbewahrung, unterstützte Signale und Dashboards bleiben produktspezifisch. Ein Wechsel kann deshalb bei der Collector-Konfiguration beginnen und trotzdem Anpassungen an Semantik und Auswertung verlangen.\n\nEin Wort zum Reifegrad, denn der ist Mitte 2024 nicht überall gleich. Tracing ist in JavaScript stabil, Metrics ebenfalls. Das Logs-Signal ist in JS dagegen noch experimentell – `@opentelemetry/api-logs` und `sdk-logs` tragen den Alpha-Stempel und sind als Bridge für bestehende Logger gedacht, nicht als direkte Log-API für Anwendungscode. Praktisch heißt das: Ich schreibe meine Logs weiterhin mit dem Logger meiner Wahl und sorge selbst dafür, dass die Trace-Korrelation drinsteht. Dazu später mehr.\n\n## Das SDK aufsetzen – und zwar früh genug\n\nDie Instrumentierung beginnt mit dem Node-SDK. Der entscheidende Punkt, den ich in Reviews am häufigsten anmahne: Das SDK muss starten, *bevor* irgendein anderes Modul geladen wird. OTel funktioniert über Monkey-Patching der Bibliotheken – wenn `http` oder `graphql` schon geladen sind, bevor das SDK sie patchen konnte, bekomme ich einen No-op-Tracer und wundere mich über leere Traces. Deshalb lade ich die Instrumentierung über `--require`, nicht als regulären Import in `app.ts`.\n\n```ts\n// instrumentation.ts\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { Resource } from '@opentelemetry/resources';\nimport { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';\n\nconst sdk = new NodeSDK({\n  resource: new Resource({\n    [SemanticResourceAttributes.SERVICE_NAME]: 'checkout-service',\n    [SemanticResourceAttributes.SERVICE_VERSION]: '1.4.0',\n  }),\n  traceExporter: new OTLPTraceExporter({\n    url: 'http://collector:4318/v1/traces',\n  }),\n  metricReader: new PeriodicExportingMetricReader({\n    exporter: new OTLPMetricExporter({\n      url: 'http://collector:4318/v1/metrics',\n    }),\n  }),\n  instrumentations: [\n    getNodeAutoInstrumentations({\n      // File-system spans are noisy; turn them off.\n      '@opentelemetry/instrumentation-fs': { enabled: false },\n    }),\n  ],\n});\n\nsdk.start();\n\nprocess.on('SIGTERM', () => {\n  sdk.shutdown().finally(() => process.exit(0));\n});\n```\n\nGestartet wird das Ganze so, dass die Instrumentierung garantiert zuerst läuft:\n\n```bash\nnode --require ./instrumentation.js ./app.js\n```\n\n`getNodeAutoInstrumentations()` deckt eine überraschende Menge ab, ohne dass ich eine Zeile Business-Code anfassen muss: HTTP und HTTPS, Express oder Fastify, GraphQL, gRPC, gängige Datenbank-Clients. Für den Anfang bekomme ich damit einen vollständigen Request-Baum durch die Standard-Schichten praktisch geschenkt. Wer sich generell fragt, wie man einem laufenden Node-Prozess auf die Finger schaut, findet in [Node.js debuggen und beobachten](https://www.mikebild.dev/de/blog/nodejs-debuggen-und-beobachten/) die Grundlagen, auf denen das hier aufbaut.\n\n## Manuelle Spans für die Business-Logik\n\nAuto-Instrumentation kennt HTTP und GraphQL, aber sie kennt nicht meine Domäne. Ob ein Checkout durch die Bonitätsprüfung fällt oder am Lagerbestand scheitert, sieht kein generischer Instrumentation-Plugin. Genau dafür setze ich manuelle Spans – dort, wo die fachlich interessanten Entscheidungen fallen.\n\n```ts\nimport { trace, SpanStatusCode } from '@opentelemetry/api';\n\nconst tracer = trace.getTracer('checkout', '1.4.0');\n\nexport async function processCheckout(order: Order): Promise<Receipt> {\n  return tracer.startActiveSpan('checkout.process', async (span) => {\n    span.setAttribute('order.id', order.id);\n    span.setAttribute('order.item_count', order.items.length);\n\n    try {\n      await reserveStock(order);\n      const receipt = await charge(order);\n      span.setAttribute('payment.provider', receipt.provider);\n      return receipt;\n    } catch (err) {\n      span.recordException(err as Error);\n      span.setStatus({ code: SpanStatusCode.ERROR });\n      throw err;\n    } finally {\n      span.end();\n    }\n  });\n}\n```\n\nDrei Dinge sind hier wichtig. `startActiveSpan` macht den Span zum aktiven Kontext, sodass alles, was innerhalb des Callbacks passiert – auch die Spans der Auto-Instrumentation für `reserveStock` und `charge` – korrekt als Kinder eingehängt wird. `recordException` plus `setStatus` markiert den Span als fehlerhaft, was ihn im Backend auffindbar macht. Und `span.end()` im `finally` sorgt dafür, dass der Span auch im Fehlerfall geschlossen wird – ein vergessenes `end()` ist ein Leck, das im Backend als hängender Span sichtbar wird.\n\nBei den Attributen halte ich mich zurück. Die Bestell-ID gehört dazu, die item-Anzahl auch. Was nicht dazugehört, ist alles, was die Kardinalität sprengt oder sensibel ist – vollständige Warenkörbe, personenbezogene Daten, freie Texte.\n\n## Der Trace hört nicht an der Servicegrenze auf\n\nDer eigentliche Wert eines Traces zeigt sich, sobald mehrere Services beteiligt sind. Ein Request trifft das Gateway, das ruft den Checkout-Service, der spricht mit der Datenbank und nebenbei mit einem Payment-Provider. Damit das ein zusammenhängender Trace bleibt und nicht in vier unverbundene Fragmente zerfällt, muss der Trace-Context über die Grenzen wandern.\n\nOpenTelemetry nutzt dafür standardmäßig den W3C-Trace-Context: einen `traceparent`-Header, der Trace-ID, Span-ID und Sampling-Entscheidung trägt. Die Auto-Instrumentation injiziert und extrahiert ihn bei HTTP-Aufrufen automatisch – der Empfänger hängt seine Spans an den Parent aus dem Header, und der Baum wächst über Prozessgrenzen hinweg weiter.\n\n```mermaid\ngraph TD\n    A[Client Request] -->|traceparent| B[API Gateway<br/>Span: http.request]\n    B -->|traceparent| C[Checkout Service<br/>Span: checkout.process]\n    C --> D[Span: db.query]\n    C -->|traceparent| E[Payment Provider<br/>Span: payment.charge]\n    B -.->|eine trace_id| F[(Ein Trace =<br/>Baum aus Spans)]\n    C -.-> F\n    D -.-> F\n    E -.-> F\n```\n\nInteressant wird es dort, wo kein HTTP-Header existiert. In einer Lambda-Function oder bei einer Message-Queue gibt es keinen automatischen Transport für den Context. Dann muss ich ihn selbst durch die Event-Payload reichen – beim Absenden mit `propagation.inject` in die Nachricht schreiben, beim Empfang mit `propagation.extract` herausziehen und den Context aktiv setzen. Bei Serverless kommen zwei weitere Punkte dazu: Der Cold Start verlängert die Init-Phase, und vor dem Freeze der Funktion muss ich einen Force-Flush auslösen, sonst gehen die letzten Spans verloren, weil der Export sie nicht mehr rausschicken konnte.\n\n## Logs an Traces koppeln – über die trace_id\n\nJetzt zum Punkt, an dem Observability aus meiner Sicht steht und fällt: der Korrelation. Ein Log ohne Trace-Bezug ist eine Zeile im Nirgendwo. Ein Log mit `trace_id` und `span_id` ist ein Sprungbrett – von der Fehlermeldung direkt in den vollständigen Request-Pfad, der sie erzeugt hat.\n\nDer aktive Span liegt im Context, und der Context wird in Node über `AsyncLocalStorage` getragen – das ist auch der Default-Context-Manager, den OTel intern verwendet. Ich muss also nur den aktiven SpanContext auslesen und seine IDs in jedes strukturierte Log hängen. Wie `AsyncLocalStorage` diesen impliziten Kontext durch asynchrone Aufrufketten trägt, habe ich in [Async-Kontext mit AsyncLocalStorage](https://www.mikebild.dev/de/blog/nodejs-async-context-mit-asynclocalstorage/) im Detail beschrieben; hier ist es der Träger, der die Trace-Korrelation überhaupt erst möglich macht.\n\n```ts\nimport { trace } from '@opentelemetry/api';\n\ntype Fields = Record<string, unknown>;\n\nexport function log(level: 'info' | 'warn' | 'error', msg: string, fields: Fields = {}): void {\n  const span = trace.getActiveSpan();\n  const ctx = span?.spanContext();\n\n  const entry = {\n    ts: new Date().toISOString(),\n    level,\n    msg,\n    ...(ctx && { trace_id: ctx.traceId, span_id: ctx.spanId }),\n    ...fields,\n  };\n\n  process.stdout.write(JSON.stringify(entry) + '\\n');\n}\n```\n\nEin Aufruf wie `log('error', 'stock reservation failed', { order_id: order.id })` mitten in der Business-Logik erzeugt jetzt eine JSON-Zeile, die dieselbe `trace_id` trägt wie der Span, in dem sie entstanden ist. Im Backend filtere ich später auf diese ID und habe Log und Trace nebeneinander. In der Praxis kapsle ich das nicht selbst, sondern lasse es einen etablierten Logger wie Pino über einen Mixin erledigen – das Prinzip bleibt dasselbe: den aktiven SpanContext auslesen und anhängen.\n\n## RED: Rate, Errors, Duration\n\nMetrics sind die aggregierte Gesundheit des Systems, und ich fange nicht mit hundert Custom-Metrics an, sondern mit dreien. Die RED-Methode – Rate, Errors, Duration – deckt für jeden Service das Wesentliche ab: Wie viele Requests kommen rein, wie viele davon scheitern, wie lange dauern sie.\n\n```ts\nimport { metrics } from '@opentelemetry/api';\n\nconst meter = metrics.getMeter('http-server');\n\nconst requestCounter = meter.createCounter('http.server.requests', {\n  description: 'Total number of HTTP requests',\n});\nconst errorCounter = meter.createCounter('http.server.errors', {\n  description: 'Total number of failed HTTP requests',\n});\nconst latencyHistogram = meter.createHistogram('http.server.duration', {\n  description: 'HTTP request duration in milliseconds',\n  unit: 'ms',\n});\n\nexport function recordRequest(route: string, statusCode: number, durationMs: number): void {\n  const attributes = { route, status_class: `${Math.floor(statusCode / 100)}xx` };\n  requestCounter.add(1, attributes);\n  if (statusCode >= 500) {\n    errorCounter.add(1, attributes);\n  }\n  latencyHistogram.record(durationMs, attributes);\n}\n```\n\nDiese drei Aufrufe stecken in einer Middleware und laufen für jeden Request. Der Counter für die Rate, der Counter für die Errors, das Histogram für die Duration – letzteres, weil mich bei Latenz nicht der Durchschnitt interessiert, sondern die Verteilung, das p95 und p99. Ein Durchschnitt von 80 Millisekunden versteckt, dass jeder zwanzigste Nutzer zwei Sekunden wartet.\n\nWichtig ist bei den Attributen die Zurückhaltung. Ich labele mit `route` und einer Statusklasse – Werte mit begrenztem, überschaubarem Wertebereich. Was ich nicht tue: die volle URL mit eingebetteter Bestell-ID als Label verwenden, oder die User-ID. Jede eindeutige Label-Kombination erzeugt eine eigene Zeitreihe, und unbegrenzte Werte lassen die Kardinalität explodieren, bis das Metric-Backend in die Knie geht. Kardinalität gehört in Traces, nicht in Metrics.\n\n## Die Fallstricke, die mich Zeit gekostet haben\n\nEin paar Fehler sehe ich so regelmäßig, dass ich sie hier ausdrücklich nenne. Der teuerste ist das erwähnte Logging ohne Korrelation – Logs, die zwar strukturiert sind, aber keine `trace_id` tragen. Sie sehen ordentlich aus und nützen im Ernstfall trotzdem wenig, weil ich sie keinem Request zuordnen kann. Der zweite ist die zu späte SDK-Initialisierung, die das Monkey-Patching ins Leere laufen lässt.\n\nDer dritte betrifft das Sampling. In Produktion jeden Trace zu erfassen ist selten sinnvoll – das Volumen und die Kosten explodieren. Also samplen. Aber naives Head-Sampling, das blind jeden hundertsten Trace behält, verwirft mit hoher Wahrscheinlichkeit gerade die Fehler-Traces, die ich sehen will. Ich setze deshalb auf `ParentBased(TraceIdRatio)`: Die Sampling-Entscheidung fällt am Anfang, wird über den `traceparent`-Header propagiert und bleibt für den gesamten Trace konsistent – kein Service entscheidet für sich allein, sodass ich keine halben Traces bekomme. Der vierte Fallstrick ist die schon erwähnte Kardinalitätsfalle bei Custom-Metrics.\n\n## Fazit\n\nObservability ist keine Frage des richtigen Dashboards, sondern der Fähigkeit, jede Frage an ein laufendes System beantworten zu können – auch die, die ich mir vorher nicht gestellt habe. Die drei Signale liefern dafür die Rohdaten: Logs für das konkrete Event, Traces für den Request-Pfad, Metrics für die aggregierte Gesundheit. Ihre eigentliche Kraft entfalten sie erst in der Korrelation, wenn ich von der Metric-Spitze zum Trace und von dort zum Log springen kann, ohne die Werkzeuge zu wechseln.\n\nOpenTelemetry hält die Instrumentierung herstellerneutraler und lässt die Exportziele getrennt davon konfigurieren. Auto-Instrumentation bringt mich schnell in die Nähe, manuelle Spans decken die Domäne ab, die Trace-Context-Propagation hält alles über Servicegrenzen zusammen, und die Kopplung von Logs an die `trace_id` über `AsyncLocalStorage` schließt den Kreis. Der Anfang darf klein sein: drei RED-Metrics, Auto-Instrumentation, korrelierte Logs. Beim Wechsel des Backends bleiben trotzdem dessen Abfragemodell, Dashboards und Eigenheiten zu prüfen. Spätestens beim nächsten Incident zahlt sich die Vorarbeit aus – dann ist das System sichtbar, bevor jemand anfängt, es zu reparieren.\n\n## Weiterführende Quellen\n\n- [OpenTelemetry JS – Getting Started (Node.js)](https://opentelemetry.io/docs/languages/js/getting-started/nodejs/)\n- [OpenTelemetry JS – Instrumentation](https://opentelemetry.io/docs/languages/js/instrumentation/)\n- [OpenTelemetry – Traces](https://opentelemetry.io/docs/concepts/signals/traces/), [Metrics](https://opentelemetry.io/docs/concepts/signals/metrics/) und [Logs](https://opentelemetry.io/docs/concepts/signals/logs/)\n- [OpenTelemetry – Context Propagation](https://opentelemetry.io/docs/concepts/context-propagation/)\n- [OpenTelemetry – Signal-Reifegrad (Status)](https://opentelemetry.io/docs/specs/status/)\n- [W3C Trace Context](https://www.w3.org/TR/trace-context/)\n- [The RED Method – Grafana Blog](https://grafana.com/blog/2018/08/02/the-red-method-how-to-instrument-your-services/)"},{"locale":"de","translation_key":"graphql-client-apollo-link-und-fragments","slug":"graphql-client-apollo-link-und-fragments","title":"Der GraphQL-Client: Apollo Link und Fragments","summary":"Apollo Link lässt jede GraphQL-Operation durch eine Kette von Middleware laufen: authLink setzt Header, errorLink behandelt Fehler zentral, split routet Subscriptions. Dazu Fragments als wiederverwendbare Feldmengen und warum Interfaces possibleTypes brauchen.","tags":["Software","GraphQL","API"],"published_at":"2024-06-25T10:00:00+00:00","updated_at":"2026-07-13T10:04:59.062506+00:00","url":"https://www.mikebild.dev/de/blog/graphql-client-apollo-link-und-fragments/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/13bf667a1bbcd7a8e40602bb177e0bb321b47daf4b53bcb94da4e8c3e1a9f0bb/graphql-client-apollo-link-und-fragments-vorlesen.mp3","audio_duration_secs":984,"text":"Im Beitrag über das [Apollo-Client-Caching](https://www.mikebild.dev/de/blog/graphql-client-caching-mit-apollo/) ging es darum, was mit einer Antwort passiert, sobald sie beim Client angekommen ist: wie der normalisierte Cache die Daten zerlegt, ablegt und wiederfindet. Diesmal drehe ich die Blickrichtung um. Bevor eine Antwort im Cache landen kann, muss die Anfrage erst hinaus zum Server, und auf diesem Weg fallen Entscheidungen an, die mit der einzelnen Query nichts zu tun haben: einen Token mitschicken, einen 401 zentral behandeln, Subscriptions auf einen anderen Transport leiten. Das sind Cross-Cutting-Concerns, und die eigentliche Frage lautet nicht, welche API man dafür aufruft, sondern wo diese Belange hingehören. Verteilt über jeden einzelnen `useQuery`-Aufruf oder gebündelt an einer Stelle.\n\nGenau das ist die Entscheidung, um die es hier geht, und ich halte die gebündelte Variante für die tragfähigere. Apollo Client beantwortet sie mit einer Kette aus Middleware. Der Trade-off ist überschaubar: Man akzeptiert eine Indirektion, die man einmal verstehen muss, und bekommt eine Architektur, in der Auth, Error Handling und Routing jeweils an einer benannten Stelle stehen statt verstreut in Dutzenden. Verändert sich die Auth-Strategie, ändert man einen Link, nicht vierzig Komponenten. Genau daran misst sich der Wert einer Transport-Schicht, nicht an der Zahl ihrer Optionen.\n\nSolche Anforderungen kommen gestaffelt. Zuerst steht ein `ApolloClient`, alles funktioniert. Dann heißt es: „Wir müssen einen Auth-Token mitschicken.“ Kurz darauf: „Und wenn der Server einen 401 zurückgibt, sollen alle betroffenen Operationen zentral behandelt werden.“ Und schließlich: „Ach ja, Subscriptions brauchen wir auch noch.“ Spätestens hier zeigt sich, dass der eine Netzwerk-Link aus dem Setup nur die Spitze war. Darunter steht ein komponierbares System, das genau für solche Fälle gebaut wurde: Apollo Link.\n\nDer zweite Teil dieses Beitrags widmet sich den Fragments. Sie wirken auf den ersten Blick wie eine reine Schreiberleichterung, sind aber der Baustein, mit dem sich Queries sauber zusammensetzen und Komponenten wartbar halten lassen. Ich verwende Apollo Client 3.10, die Import-Pfade und Signaturen beziehen sich auf diese Version. In Apollo Client 4 kommen React-Hooks wie `useFragment` aus `@apollo/client/react`; das gezeigte Cache-Modell bleibt gleich.\n\n## Apollo Link ist eine Kette\n\nDie Grundidee ist schnell erzählt. Jede Operation, ob Query, Mutation oder Subscription, durchläuft eine Kette von Links, bevor sie den Server erreicht, und die Antwort läuft dieselbe Kette rückwärts wieder zurück. Ein Link ist ein Stück Middleware: Er darf die Operation ansehen, sie verändern und an den nächsten Link weiterreichen. Der letzte Link in der Kette ist besonders. Er ist **terminierend**, das heißt, er reicht nicht weiter, sondern schickt die Anfrage tatsächlich ab. In den allermeisten Fällen ist das der `HttpLink`.\n\nWer schon einmal Express-Middleware oder eine Redux-Middleware-Kette gesehen hat, erkennt das Muster sofort. Jeder Link bekommt die Operation und eine `forward`-Funktion, mit der er an den nächsten Link übergibt. Und wie bei jeder Middleware-Kette gilt: Die Reihenfolge entscheidet über das Verhalten.\n\nZusammengesetzt wird die Kette mit `ApolloLink.from`, das ein Array von Links in genau der Reihenfolge verkettet, in der sie dort stehen. Für zwei Links reicht auch `linkA.concat(linkB)`. Schauen wir uns eine typische Kette an.\n\n```typescript\nimport { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\nimport { onError } from '@apollo/client/link/error';\n\nconst httpLink = new HttpLink({ uri: '/graphql' });\n\nconst authLink = setContext((_, { headers }) => {\n  const token = getToken();\n  return {\n    headers: {\n      ...headers,\n      authorization: token ? `Bearer ${token}` : '',\n    },\n  };\n});\n\nconst errorLink = onError(({ graphQLErrors, networkError, operation }) => {\n  if (graphQLErrors) {\n    for (const err of graphQLErrors) {\n      console.error(`[GraphQL error] ${operation.operationName}: ${err.message}`);\n    }\n  }\n  if (networkError) {\n    console.error(`[Network error] ${networkError.message}`);\n  }\n});\n\nconst link = ApolloLink.from([errorLink, authLink, httpLink]);\n\nconst client = new ApolloClient({\n  link,\n  cache: new InMemoryCache(),\n});\n```\n\nDrei Links, eine klare Aufgabenteilung. Der `errorLink` steht außen, weil er sowohl die hinausgehende Operation als auch die zurückkommende Antwort sehen soll. Fehler, die tief in der Kette entstehen, laufen auf dem Rückweg durch ihn hindurch. Der `authLink` steht kurz vor dem Netzwerk-Link, weil er den Token möglichst spät setzt, wenn er am aktuellsten ist. Und der `httpLink` steht ganz am Ende, weil er terminierend ist.\n\n## Warum die Reihenfolge zählt\n\nGenau hier liegt der Fallstrick, der mir in Code-Reviews am häufigsten begegnet. Der terminierende Link muss das letzte Element sein. Steht der `authLink` versehentlich hinter dem `httpLink`, wird er nie erreicht, denn die Anfrage ist längst abgeschickt, wenn dieser Link an der Reihe wäre. Das Ergebnis: Der Token fehlt, der Server antwortet mit 401, und die Fehlersuche beginnt an der völlig falschen Stelle, nämlich beim Auth-Server statt bei der Link-Reihenfolge.\n\nDer `authLink` verdient noch einen zweiten Blick, weil sein Name in die Irre führen kann. `setContext` verändert die HTTP-Header nicht direkt. Es liefert ein Objekt, das in den Context der Operation gemischt wird, üblicherweise unter dem Schlüssel `headers`. Erst der `HttpLink` liest diesen Context aus und übersetzt ihn in echte HTTP-Header. Der `authLink` bereitet also nur vor, gesendet wird woanders. Wer das verinnerlicht hat, versteht auch, warum die Reihenfolge so wichtig ist: Der Vorbereiter muss vor dem Absender stehen.\n\nEin Detail, das in der Praxis oft gebraucht wird: Die Funktion in `setContext` darf asynchron sein. Gibt sie ein Promise zurück, wartet Apollo Link, bevor die Operation weiterläuft. Damit lässt sich ein Token bei Bedarf erst nachladen oder erneuern, ohne die aufrufende Komponente damit zu belasten. Im Blick behalten sollte man dabei nur, dass jede Operation auf diese Auflösung wartet: Ein langsamer Token-Endpoint bremst dann sämtliche Anfragen aus. In der Regel legt man den Token deshalb in einem Speicher ab, den `setContext` synchron lesen kann, und stößt die Erneuerung getrennt davon an.\n\nDer `errorLink` unterscheidet zwei Fehlerklassen, die man nicht verwechseln sollte. `graphQLErrors` ist ein Array von Fehlern, die der Server bewusst zurückgegeben hat, etwa eine fehlgeschlagene Validierung oder ein nicht gefundener Datensatz. Der Transport hat funktioniert, die Antwort enthält nur eben Fehler im `errors`-Feld. `networkError` dagegen bedeutet, dass der Transport selbst gescheitert ist: keine Verbindung, ein 500er, ein Timeout. Diese Trennung ist der Grund, warum `onError` der richtige Ort für zentrale Behandlung ist. Man muss nicht in jedem `useQuery`-Aufruf einzeln prüfen, ob der Token abgelaufen ist, man macht es einmal, an einer Stelle.\n\nWenn ich mir dieselbe Kette als Diagramm aufmale, sieht der Weg einer Operation so aus.\n\n```mermaid\nflowchart LR\n  Op[Operation] --> E[errorLink onError]\n  E --> A[authLink setContext]\n  A --> H[httpLink terminating]\n  H --> S[(GraphQL Server)]\n  S -. response .-> H\n  H -. response .-> A\n  A -. response .-> E\n  E -. response .-> Op\n```\n\nDie durchgezogenen Pfeile zeigen die Anfrage nach außen, die gestrichelten die Antwort auf dem Rückweg. Dass der `errorLink` auf beiden Wegen beteiligt ist, macht deutlich, warum er ganz außen sitzt.\n\n## Die gängigen Links im Überblick\n\nÜber die drei genannten hinaus gibt es einige Links, die regelmäßig gebraucht werden. Hier die wichtigsten mit ihrer jeweiligen Aufgabe:\n\n- `errorLink` (`onError`): zentrale Behandlung von GraphQL- und Netzwerkfehlern, etwa Logging oder das Ausloggen bei abgelaufenem Token.\n- `authLink` (`setContext`): bereitet Header und Token vor und mischt sie in den Operation-Context.\n- `retryLink` (`RetryLink`): wiederholt Operationen bei Netzwerkfehlern, mit konfigurierbarem Backoff und Jitter.\n- `splitLink` (`split`): routet Operationen nach einem Prädikat auf verschiedene Zweige, klassisch Subscriptions gegen Queries.\n- `httpLink` (`HttpLink`): der terminierende Link, der die Anfrage über HTTP versendet.\n\nDer `RetryLink` gehört in die Kette vor den terminierenden Link, damit er die Wiederholung anstoßen kann, bevor die Anfrage endgültig hinausgeht. Eine sinnvolle vollständige Kette wäre also `from([errorLink, retryLink, authLink, httpLink])`. Wichtig dabei: Die Retry-Bedingung sollte man explizit setzen. Gibt man in `onError` bedingungslos ein `forward(operation)` zurück, um eine Operation zu wiederholen, kann daraus eine Endlosschleife werden, wenn der Fehler dauerhaft ist. Der `RetryLink` mit seiner `retryIf`-Bedingung ist der robustere Weg, weil er die Anzahl der Versuche begrenzt.\n\n```typescript\nimport { RetryLink } from '@apollo/client/link/retry';\n\nconst retryLink = new RetryLink({\n  delay: { initial: 300, max: 3000, jitter: true },\n  attempts: {\n    max: 3,\n    retryIf: (error) => Boolean(error),\n  },\n});\n```\n\n## Subscriptions abzweigen mit split\n\nSobald Subscriptions ins Spiel kommen, kann ein zweiter Transport nötig werden. Queries und Mutations laufen in diesem Beispiel über HTTP, die Subscriptions über eine dauerhafte WebSocket-Verbindung. Andere Stacks transportieren Subscriptions über HTTP und Server-Sent Events. Die Aufgabe, die Operation im hier gezeigten WebSocket-Setup auf den richtigen Zweig zu leiten, übernimmt `split`. Die Funktion bekommt ein Prädikat und zwei Links: Ist das Prädikat wahr, geht es in den ersten Zweig, sonst in den zweiten.\n\nUm zu entscheiden, ob eine Operation eine Subscription ist, hilft `getMainDefinition`. Sie zieht die Haupt-Definition aus dem Query-Dokument, sodass sich `kind` und `operation` prüfen lassen.\n\n```typescript\nimport { split } from '@apollo/client';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { GraphQLWsLink } from '@apollo/client/link/subscriptions';\nimport { createClient } from 'graphql-ws';\n\nconst wsLink = new GraphQLWsLink(\n  createClient({ url: 'wss://example.com/graphql' }),\n);\n\nconst splitLink = split(\n  ({ query }) => {\n    const definition = getMainDefinition(query);\n    return (\n      definition.kind === 'OperationDefinition' &&\n      definition.operation === 'subscription'\n    );\n  },\n  wsLink,\n  ApolloLink.from([errorLink, authLink, httpLink]),\n);\n```\n\nDer WebSocket-Transport heißt hier `GraphQLWsLink` und baut auf der `graphql-ws`-Bibliothek auf. Für einen WebSocket-Zweig ist das die passende Variante. Die ältere Kombination aus `WebSocketLink` und `subscriptions-transport-ws` findet man noch in vielen Projekten, sie gilt aber als veraltet. Ob WebSocket überhaupt der richtige Transport ist, hängt vom Server und vom eingesetzten Subscription-Protokoll ab; SSE ist eine mögliche Alternative.\n\nEin Punkt, der leicht übersehen wird: Der WebSocket-Zweig läuft an `errorLink` und `authLink` vorbei, denn er hängt im `split` an einem eigenen Ast. Eine Subscription authentifiziert sich deshalb nicht über den HTTP-Header, sondern über die `connectionParams` des `graphql-ws`-Clients, die beim Verbindungsaufbau gesetzt werden. Wer den Token nur im `authLink` mitgibt, wundert sich sonst, warum die Query autorisiert ist, die Subscription aber nicht.\n\n## Vom Apollo-Detail zum Prinzip\n\nEin Schritt zurück, und es geht nicht mehr um Apollo. Die Link-Kette ist ein Sonderfall eines Musters, das weit über GraphQL hinausreicht: Cross-Cutting-Concerns wandern aus dem fachlichen Code heraus in eine Kette aus Middleware, die jede Operation durchläuft. Auth, Logging, Error Handling, Wiederholung, Routing. Das sind Belange, die überall gebraucht werden und nirgends fachlich hingehören. Express macht es mit seiner Middleware, Redux mit seiner Middleware-Kette, ein API-Gateway mit seiner Filter-Kette, und Apollo Client eben mit seinen Links. Wer das Muster einmal erkannt hat, sieht es überall.\n\nDer Reiz liegt in einer klaren Grenzziehung. Fachlicher Code fragt Daten an und stellt sie dar. Er soll nichts davon wissen, wie ein Token entsteht oder was bei einem 401 passiert. Die Kette nimmt ihm das ab, und zwar an einer einzigen, benannten Stelle. Der Gewinn ist nicht die Technik, sondern die Lokalität der Änderung. Ein neuer Concern kommt als zusätzlicher Link hinzu, ohne dass ein einziger `useQuery`-Aufruf angefasst werden muss. Das ist der Unterschied zwischen einer Anpassung, die man an einem Nachmittag erledigt, und einer, die sich durch vierzig Dateien zieht und mit jeder davon ein Risiko trägt.\n\nUmsonst ist das nicht. Der Preis ist Indirektion. Der Weg einer Operation steht nicht mehr linear im Komponentencode, sondern verteilt sich über eine Kette, deren Reihenfolge man kennen muss, um das Verhalten zu verstehen. Ein falsch platzierter Link ist schwerer zu finden als ein falsch gesetzter Header direkt an der Aufrufstelle. Bei einer Handvoll Operationen ohne gemeinsame Belange wäre die Kette deshalb Aufwand ohne Ertrag.\n\nDie Zuordnung lässt sich an wenigen Kriterien festmachen. Betrifft ein Belang viele oder alle Operationen, gehört er in die Kette. Betrifft er genau eine, gehört er an die Aufrufstelle. Ändert er sich unabhängig vom fachlichen Code und aus anderen Gründen als dieser, ist das ein starkes Signal für die Kette. Und je mehr solcher Belange gleichzeitig auf dem Tisch liegen, desto klarer zahlt sich die Trennung aus, weil sie verhindert, dass Auth, Fehler und Transport sich im selben Stück Code vermischen. Genau in dieser Situation, wenn mehrere Concerns zusammenkommen, ist die Kette kein Overhead, sondern das, was die Codebasis übersichtlich hält.\n\n## Fragments: Queries aus Bausteinen\n\nDamit zur zweiten Hälfte. Ein Fragment ist eine benannte, wiederverwendbare Menge von Feldern eines bestimmten Typs. Statt in jeder Query, die einen `User` lädt, dieselben Felder erneut aufzuzählen, definiert man sie einmal und setzt sie per Spread ein.\n\n```typescript\nimport { gql } from '@apollo/client';\n\nconst USER_FIELDS = gql`\n  fragment UserFields on User {\n    id\n    name\n    email\n  }\n`;\n\nconst GET_USER = gql`\n  query GetUser($id: ID!) {\n    user(id: $id) {\n      ...UserFields\n    }\n  }\n  ${USER_FIELDS}\n`;\n```\n\nZwei Dinge sind wichtig. Der Spread `...UserFields` verweist auf das Fragment, und das Fragment-Dokument muss der Query per `${USER_FIELDS}` mitgegeben werden, sonst kennt der Parser den Namen nicht. Das ist ein häufiger Anfängerfehler: Der Spread steht da, aber die Interpolation fehlt, und die Fehlermeldung ist nicht besonders sprechend.\n\nDer eigentliche Gewinn zeigt sich erst im größeren Projekt und heißt Colocation. Die Idee: Ein Fragment steht direkt bei der Komponente, die genau diese Felder anzeigt. Eine `UserCard`-Komponente definiert ihr eigenes `UserFields`-Fragment und exportiert es. Die übergeordnete Query, die mehrere Komponenten füllt, sammelt die Fragmente ihrer Kinder ein und setzt sie zusammen. Ändert sich, welche Felder die `UserCard` braucht, ändert sich nur ihr Fragment, und die Query oben zieht die Änderung automatisch mit. Die Datenanforderung steht dort, wo die Daten gebraucht werden, und nicht in einer entfernten, zentralen Query-Datei, die niemand mehr pflegen mag.\n\nSeit Apollo Client 3.8 gibt es dafür auch den Hook `useFragment`. Er erlaubt einer Komponente, genau die Felder eines Fragments aus dem Cache zu lesen, ohne selbst eine Query abzusetzen. Die Komponente wird nur dann neu gerendert, wenn sich die Felder ihres Fragments ändern, ein feinerer Schnitt als das erneute Rendern bei jeder Änderung der übergeordneten Query.\n\n```tsx\nimport { useFragment } from '@apollo/client';\n\nfunction UserCard({ id }: { id: string }) {\n  const { data } = useFragment({\n    fragment: USER_FIELDS,\n    fragmentName: 'UserFields',\n    from: { __typename: 'User', id },\n  });\n\n  return <div>{data.name} · {data.email}</div>;\n}\n```\n\n## Fragment-Matching und possibleTypes\n\nEin letzter Punkt, der oft übersehen wird und dann für schwer auffindbare Fehler sorgt. Sobald ein Fragment auf einem Interface oder einer Union sitzt statt auf einem konkreten Typ, muss der Cache wissen, welche konkreten Typen zu diesem abstrakten Typ gehören. Nehmen wir ein Interface `SearchResult`, das von `User` und `Post` implementiert wird. Eine Query möchte je nach konkretem Typ unterschiedliche Felder laden.\n\n```graphql\nquery Search($term: String!) {\n  search(term: $term) {\n    __typename\n    ... on User {\n      name\n    }\n    ... on Post {\n      title\n    }\n  }\n}\n```\n\nDamit Apollo diese Inline-Fragmente, `... on User` und `... on Post`, korrekt zuordnen kann, braucht der `InMemoryCache` eine `possibleTypes`-Angabe. Sie sagt ihm, welche konkreten Typen hinter jedem Interface oder jeder Union stehen.\n\n```typescript\nconst cache = new InMemoryCache({\n  possibleTypes: {\n    SearchResult: ['User', 'Post'],\n  },\n});\n```\n\nFehlt diese Angabe, kann der Cache das Matching nicht zuverlässig durchführen. Felder fehlen dann in den Ergebnissen, oder Apollo greift auf eine Heuristik zurück und gibt eine Warnung aus. Das Tückische daran ist, dass es in einfachen Fällen scheinbar trotzdem funktioniert und erst bei komplexeren Queries bricht. Deshalb pflegt man `possibleTypes` am besten gar nicht von Hand, sondern lässt es aus dem Schema generieren, per Introspection oder über GraphQL Codegen. So bleibt die Angabe automatisch aktuell, wenn ein neuer Typ das Interface implementiert.\n\n## Fazit\n\nDie Transport-Schicht von Apollo Client ist kein monolithischer Netzwerk-Baustein, sondern eine Kette aus kleinen, klar umrissenen Stücken. Der Ertrag zeigt sich erst in der Wirkung. Weil jeder Concern an genau einer Stelle sitzt, sind spätere Anpassungen lokal statt verstreut. Das verkürzt die Zyklen, senkt die Reibung bei jeder Änderung an Auth oder Error Handling und hält die Grenze zwischen fachlichem Code und Infrastruktur sauber. Der Preis dafür ist die Indirektion der Kette, und die meisten frustrierenden Debugging-Sessions, die ich dazu erlebt habe, lassen sich auf eine vertauschte Reihenfolge zurückführen. Das ist ein fairer Handel, solange man die Reihenfolge bewusst setzt und den terminierenden `HttpLink` ans Ende.\n\nFragments sind das Gegenstück auf der Query-Seite und folgen demselben Prinzip. Sie halten Feldmengen wiederverwendbar und ermöglichen Colocation nah an den Komponenten, sodass die Datenanforderung dort steht, wo die Daten gebraucht werden, und nicht in einer zentralen Riesen-Query, die niemand mehr pflegen mag. Ändert eine Komponente ihren Bedarf, ändert sich ihr Fragment statt einer weit entfernten Datei. Sobald abstrakte Typen ins Spiel kommen, ist `possibleTypes` die leicht vergessene Voraussetzung, ohne die das Matching bricht. Link-Reihenfolge und Fragmentgrenzen bleiben damit zwei konkrete Stellen, an denen ich Änderungen prüfe; Apollo nimmt mir diese Entscheidungen nicht ab.\n\nWie der Token, den der `authLink` setzt, überhaupt entsteht und serverseitig geprüft wird, ist ein Thema für sich; dazu passt der Beitrag über [GraphQL-Auth im Context](https://www.mikebild.dev/de/blog/graphql-auth-im-context/). Und wenn die geladenen Listen größer werden, lohnt der Blick in die [GraphQL-Paginierung und Connections](https://www.mikebild.dev/de/blog/graphql-paginierung-und-connections/), wo Fragments und `fetchMore` zusammenspielen.\n\n## Weiterführende Quellen\n\n- [Apollo Link: Overview](https://www.apollographql.com/docs/react/api/link/introduction)\n- [ApolloLink API (from, concat, split)](https://www.apollographql.com/docs/react/api/link/apollo-link)\n- [Error handling mit onError](https://www.apollographql.com/docs/react/data/error-handling)\n- [Fragments (Colocation, possibleTypes, useFragment)](https://www.apollographql.com/docs/react/data/fragments)\n- [Subscriptions (split und getMainDefinition)](https://www.apollographql.com/docs/react/data/subscriptions)"},{"locale":"de","translation_key":"ocr-mit-cache-und-misstrauen","slug":"ocr-mit-cache-und-misstrauen","title":"OCR mit Cache und Misstrauen","summary":"Warum sich eine OCR-Pipeline für Belegdaten erst dann zuverlässig anfühlt, wenn man jeden erkannten Wert mit Hash-Cache, Confidence-Gate und Plausibilitätsregeln absichert statt ihm zu glauben.","tags":["Software","Daten","Tools"],"published_at":"2024-06-12T10:00:00+00:00","updated_at":"2026-07-13T13:22:38.960627+00:00","url":"https://www.mikebild.dev/de/blog/ocr-mit-cache-und-misstrauen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ddede08abe63fe47a42f2cf0a676842321513d7e954362b7f275b0c901b38961/ocr-mit-cache-und-misstrauen-vorlesen.mp3","audio_duration_secs":769,"text":"# OCR mit Cache und Misstrauen\n\nTesseract liefert für erkannte Wörter im TSV-Ausgabeformat einen Confidence-Wert, üblicherweise zwischen null und hundert; Strukturzeilen können `-1` tragen. Dieser interne Score ist ein nützliches Signal, aber keine kalibrierte Wahrscheinlichkeit dafür, dass das Wort korrekt ist. `image_to_string` gibt ihn nicht heraus. Wer nur den String nimmt, wirft damit eine wichtige Information über die Erkennung weg.\n\nAufgefallen ist mir das in einem kleinen Inventur-Projekt, in dem Buchungen aus einem Kontoblatt mit den dazugehörigen Rechnungspositionen zusammengeführt werden sollten. Klingt nach einem Nachmittag Arbeit: PDFs einlesen, Beträge, Datumsangaben und Belegnummern herausziehen, gegen die Buchungen matchen, fertig. Der Haken steckte nicht im Matching. Er steckte darin, dass ein Teil der Rechnungen als gescannte Bilder vorlag und ich die Felder per OCR herausholen musste. OCR ist keine Funktion, die Text zurückgibt. OCR ist ein Messgerät: Es trifft mit einer gewissen Wahrscheinlichkeit das Richtige und ist im Rest der Fälle eine teure Fehlerquelle.\n\nDiese Sichtweise hat die Architektur des kleinen Werkzeugs stärker geprägt als jede Matching-Regel. Sobald man OCR als unsicheren Sensor begreift, ergeben sich drei Pflichten fast von selbst: Man speichert die Messung, weil sie teuer ist und sich mit Vorverarbeitung, Konfiguration oder Engine-Version ändern kann. Man behält den Confidence-Score, weil sonst ein Lesefehler genauso aussieht wie ein korrekter Treffer. Und man prüft das Ergebnis gegen Fachregeln, weil ein plausibel aussehender Betrag noch lange nicht der richtige Betrag ist.\n\n## Der Fehler, der mich überzeugt hat\n\nDie ganze Vorsicht klingt zuerst übertrieben. Überzeugt hat mich ein einzelner Datensatz. Auf einer gescannten Rechnung stand ein Bruttobetrag von 138,00 Euro. Die OCR las daraus 133,00 Euro, weil die 8 in der verwendeten Schrift schmal gesetzt war und der Scan die obere Schleife verschluckt hatte. Eine 8, die zur 3 wird, ist optisch nicht weit entfernt; für ein Modell, das Glyphen aus Pixeln rekonstruiert, ist das ein naheliegender Fehlgriff.\n\nDas Tückische war nicht der Lesefehler. Lesefehler passieren. Das Tückische war, was danach geschah. Im Kontoblatt gab es tatsächlich eine Buchung über 133,00 Euro von einem anderen Vorgang. Das Fuzzy-Matching, das Belegnummer, Datum und Betrag gewichtet, fand für die falsch gelesene Rechnung einen vermeintlich sauberen Partner und ordnete sie der falschen Buchung zu. Der eigentliche 138-Euro-Posten blieb als verwaister Kontoeintrag liegen. Zwei Fehler, die sich gegenseitig plausibel machten. Kein Stacktrace, keine Exception, kein rotes Log. Nur ein Report, der ordentlich aussah und falsch war.\n\nGenau darin liegt die Gefahr: Ein OCR-Fehler ohne Confidence und ohne Validierung richtet mehr Schaden an als ein Absturz. Ein Absturz zwingt dich, hinzuschauen. Ein stiller Lesefehler reist durch die ganze Pipeline und tarnt sich als korrektes Ergebnis. Bei Geldbeträgen ist das keine akademische Sorge.\n\n## Warum OCR ein Sensor ist und keine Funktion\n\nEs lohnt sich, kurz auseinanderzuhalten, womit man es zu tun hat. Eine reine Textextraktion aus einem digital erzeugten PDF liest einen vorhandenen Textlayer. OCR arbeitet dagegen auf Pixeln, und das Ergebnis hängt von Auflösung, Kontrast, Schrift, Seitenausrichtung, Vorverarbeitung, Konfiguration und Engine-Version ab. Ein lokaler Tesseract-Lauf mit identischen Bytes und identischer Umgebung ist in der Regel reproduzierbar; ändert sich einer dieser Faktoren, kann auch das Ergebnis wechseln.\n\nDeshalb behandle ich beide Wege getrennt. Erst versuche ich, den eingebetteten Textlayer auszulesen. Nur wenn dieser fehlt oder leer ist, fällt die Pipeline auf OCR zurück. Dieser Fallback ist die Stelle, an der Unsicherheit ins System kommt, und genau diese Stelle muss man markieren, messen und einhegen.\n\nHilfreich ist, dass ernsthafte OCR-Engines ihre eigene Unsicherheit mitliefern. Bei Tesseract kommt die Wort-Confidence über das TSV-Ausgabeformat, zusammen mit Bounding Box und Position auf der Seite. Cloud-Dienste liefern vergleichbare Werte, oft als Float zwischen 0 und 1 pro Feld. Dieser Wert ist die wichtigste Information der ganzen Erkennung, und er landet trotzdem meist im Nichts, weil `image_to_string` eben nur einen String zurückgibt. Wer stattdessen `image_to_data` mit `tsv` nutzt, bekommt die Confidence pro Wort und kann eine Entscheidung darauf aufbauen.\n\nIn meinem Belegdatensatz waren Wortwerte unter etwa 95 oft kritisch und Werte oberhalb von 99 deutlich verlässlicher. Das sind keine allgemein gültigen Grenzen. Die Schwelle muss auf gelabelten Beispielen für Engine, Dokumenttyp und Feld kalibriert werden und hängt zusätzlich vom Schaden eines Fehlers ab. Bei einem Freitextfeld darf die Latte tiefer liegen als bei einem Betrag, der in eine Buchung wandert.\n\n## Cache per Inhalts-Hash, nicht per Dateiname\n\nBevor ich über Schwellen rede, zuerst die unspektakuläre Maßnahme, die am meisten Ruhe in die Pipeline bringt: ein Cache, der die OCR eines Dokuments genau einmal berechnet.\n\nOCR ist langsam und, bei Cloud-Diensten, teuer pro Seite. Ein Inventurlauf, den man während der Entwicklung zwanzig Mal wiederholt, würde zwanzigmal dieselben Seiten erkennen. Das kostet Zeit und Geld. Ein Cache pinnt zusätzlich das einmal beobachtete Ergebnis, sodass ein Wechsel von Engine, Konfiguration oder externem Dienst nicht unbemerkt historische Auswertungen verändert.\n\nDer entscheidende Punkt ist der Cache-Schlüssel. Der Dateiname taugt nicht. Dateien werden umbenannt, verschoben, neu exportiert, und zwei inhaltlich identische Scans können unterschiedlich heißen. Umgekehrt kann hinter demselben Namen ein veränderter Inhalt stecken. Der einzige stabile Schlüssel ist der Inhalt selbst, also ein kryptografischer Hash der Bytes, üblicherweise SHA-256. Gleicher Inhalt, gleicher Hash, gleicher Cache-Eintrag, unabhängig davon, wie die Datei gerade heißt.\n\nIn den Schlüssel gehört aber mehr als nur der Datei-Hash. Wenn ich die OCR-Konfiguration ändere, etwa den Page-Segmentation-Mode oder die Engine-Version, sind alte Ergebnisse nicht mehr vergleichbar. Deshalb fließt auch eine Versionskennung der Pipeline in den Schlüssel ein. So invalidiert eine geänderte Konfiguration den Cache automatisch, ohne dass ich von Hand aufräumen muss.\n\n```python\nimport hashlib\nimport json\nfrom dataclasses import dataclass, asdict\nfrom pathlib import Path\n\nimport pytesseract\nfrom PIL import Image\n\n# Changes to this configuration must invalidate the cache,\n# otherwise results from different setups get compared.\nOCR_VERSION = \"tesseract-5.3.4+psm6+v3\"\nCONF_MIN = 95.0          # word values below this count as uncertain\nCACHE_DIR = Path(\".ocr-cache\")\n\n\n@dataclass\nclass Word:\n    text: str\n    conf: float          # 0..100, straight from the TSV output format\n\n\ndef file_key(path: Path) -> str:\n    \"\"\"Content hash plus pipeline version. The file name deliberately plays no role.\"\"\"\n    digest = hashlib.sha256(path.read_bytes()).hexdigest()\n    return hashlib.sha256(f\"{digest}:{OCR_VERSION}\".encode()).hexdigest()\n\n\ndef run_ocr(path: Path) -> list[Word]:\n    \"\"\"Expensive; cache the observed result together with its pipeline version.\"\"\"\n    data = pytesseract.image_to_data(\n        Image.open(path),\n        config=\"--psm 6\",\n        output_type=pytesseract.Output.DICT,\n    )\n    words: list[Word] = []\n    for text, conf in zip(data[\"text\"], data[\"conf\"]):\n        text = text.strip()\n        if not text:\n            continue\n        words.append(Word(text=text, conf=float(conf)))\n    return words\n\n\ndef ocr_cached(path: Path) -> list[Word]:\n    \"\"\"Idempotent access: same content always yields the same cache entry.\"\"\"\n    CACHE_DIR.mkdir(exist_ok=True)\n    cache_file = CACHE_DIR / f\"{file_key(path)}.json\"\n    if cache_file.exists():\n        raw = json.loads(cache_file.read_text())\n        return [Word(**w) for w in raw]\n    words = run_ocr(path)\n    cache_file.write_text(json.dumps([asdict(w) for w in words], ensure_ascii=False))\n    return words\n```\n\nDer Cache liegt hier bewusst als JSON pro Dokument auf der Platte. Das ist für ein lokales Werkzeug völlig ausreichend und hat einen angenehmen Side Effect: Die Cache-Dateien sind lesbar und lokal diffbar. Bei Rechnungen und anderen personenbezogenen Dokumenten gehören solche OCR-Ausgaben allerdings nicht unverschlüsselt ins Git-Repository. Nachvollziehbarkeit braucht einen geschützten Speicher mit passender Aufbewahrung und Zugriffskontrolle.\n\n## Das Confidence-Gate\n\nMit Cache und Wort-Confidence in der Hand wird aus dem stillen Fehler von oben ein lauter. Der Trick ist, die Confidence nicht zu ignorieren, sondern sie zur Entscheidung zu machen: Felder über der Schwelle gelten als vertrauenswürdig und dürfen automatisch weiterfließen, Felder darunter werden markiert und landen in der manuellen Prüfung.\n\n```python\nimport re\n\nAMOUNT_RE = re.compile(r\"^\\d{1,3}(?:[.\\s]\\d{3})*,\\d{2}$\")  # e.g. 1.234,56\n\n\n@dataclass\nclass Field:\n    raw: str\n    conf: float\n    needs_review: bool\n    reason: str = \"\"\n\n\ndef extract_amount(words: list[Word]) -> Field:\n    \"\"\"Finds the gross amount and decides how to proceed based on the confidence.\"\"\"\n    candidates = [w for w in words if AMOUNT_RE.match(w.text)]\n    if not candidates:\n        return Field(raw=\"\", conf=0.0, needs_review=True, reason=\"no amount detected\")\n\n    # The last plausible amount on the receipt is usually the total.\n    best = candidates[-1]\n\n    if best.conf < CONF_MIN:\n        return Field(\n            raw=best.text,\n            conf=best.conf,\n            needs_review=True,\n            reason=f\"Confidence {best.conf:.0f} below threshold {CONF_MIN:.0f}\",\n        )\n    return Field(raw=best.text, conf=best.conf, needs_review=False)\n```\n\nHätte die falsch gelesene 133,00 eine niedrige Confidence gehabt, wäre sie hier hängengeblieben. Damit ist das Gate aber noch nicht fertig. OCR-Engines sind manchmal selbstbewusst falsch. Eine sauber gedruckte 3, die eigentlich eine 8 sein sollte, kann mit Confidence 98 zurückkommen. Das Modell ist sich sicher, die Glyphe heißt 3, weil sie wie eine 3 aussieht. Die Information, dass es eigentlich 8 sein müsste, steckt nicht im Pixelbild, sondern im Fachkontext. Confidence allein reicht deshalb nicht. Sie ist notwendig, aber sie fängt nur die Fälle, in denen das Modell selbst zögert.\n\n## Validierung gegen die Welt, nicht gegen sich selbst\n\nDie zweite Verteidigungslinie prüft nicht, wie sicher sich die Erkennung war, sondern ob das Ergebnis zur Realität passt. Solche Regeln kosten wenig und fangen genau die selbstbewussten Fehler, an denen das Confidence-Gate scheitert.\n\nBei Belegdaten gibt es eine Reihe naheliegender Prüfungen. Ein Bruttobetrag muss der Summe aus Nettobetrag und Steuer entsprechen; weicht das ab, stimmt mindestens einer der drei Werte nicht. Ein Rechnungsdatum muss vor dem Buchungsdatum liegen und darf nicht in der Zukunft stehen. Eine Belegnummer hat oft ein festes Format oder gar eine Prüfziffer; passt die nicht, war die Erkennung falsch. Und ein Betrag, der gegen eine Buchung gematcht werden soll, muss innerhalb einer engen Toleranz liegen, nicht innerhalb von fünf Euro.\n\nIm konkreten Fehlerfall hätte eine einzige dieser Regeln gereicht. Wenn der Beleg Netto und Steuer separat ausweist, dann ergibt 138,00 als Brutto bei 19 Prozent einen Nettowert von 115,97, während 133,00 zu 111,76 führt. Liest die OCR Netto und Brutto unabhängig und stimmt die Summenrechnung nicht, fällt die falsche 3 sofort auf, ganz egal wie sicher sich die Engine war. Die Redundanz auf dem Beleg ist das Kontrollmaß, das die Pixel nicht liefern können.\n\n```python\nfrom decimal import Decimal\n\n\ndef parse_eur(s: str) -> Decimal:\n    return Decimal(s.replace(\".\", \"\").replace(\",\", \".\"))\n\n\ndef cross_check_total(netto: Field, steuer: Field, brutto: Field) -> Field:\n    \"\"\"A high confidence is unconvincing when the sum does not add up.\"\"\"\n    if any(f.needs_review or not f.raw for f in (netto, steuer, brutto)):\n        return brutto  # missing parts are already handled by the review anyway\n\n    expected = parse_eur(netto.raw) + parse_eur(steuer.raw)\n    actual = parse_eur(brutto.raw)\n    if abs(expected - actual) > Decimal(\"0.02\"):  # tolerance only for rounding\n        return Field(\n            raw=brutto.raw,\n            conf=brutto.conf,\n            needs_review=True,\n            reason=f\"Sum {expected} differs from read gross {actual}\",\n        )\n    return brutto\n```\n\nWichtig ist die Reihenfolge im Kopf: Confidence und Validierung sind kein Entweder-oder. Ein Feld mit hoher Confidence, das eine Fachregel verletzt, gehört trotzdem in die Prüfung. Und ein Feld mit niedriger Confidence, das alle Regeln erfüllt, ist immer noch verdächtig genug, um es einem Menschen zu zeigen. Beide Tore müssen offen sein, damit ein Wert ohne Aufsicht durchläuft.\n\n## Der Entscheidungsfluss im Überblick\n\n```mermaid\nflowchart TD\n  A[Dokument] --> B{Textlayer vorhanden?}\n  B -->|ja| C[Text direkt lesen<br/>deterministisch]\n  B -->|nein| D{Im Hash-Cache?}\n  D -->|ja| E[Cache-Eintrag laden]\n  D -->|nein| F[OCR ausführen<br/>teuer, unsicher]\n  F --> G[Ergebnis unter Inhalts-Hash cachen]\n  G --> E\n  C --> H[Felder extrahieren]\n  E --> H\n  H --> I{Confidence über Schwelle?}\n  I -->|nein| R[markieren: manuelle Prüfung]\n  I -->|ja| J{Fachregeln erfüllt?}\n  J -->|nein| R\n  J -->|ja| K[automatisch ins Matching]\n  R --> L[Korrektur als Daten speichern]\n  L --> K\n```\n\nZwei Tore stehen zwischen einem erkannten Wert und seiner automatischen Verwendung. Wer sie ernst nimmt, akzeptiert, dass ein Teil der Belege manuell durch die Hände eines Menschen geht. Das ist keine Niederlage. Reife Systeme verarbeiten den Großteil der Dokumente ohne Eingriff und leiten je nach Beleglage einen kleineren Anteil in die Prüfung. Dass dieser Anteil existiert, ist das Eingeständnis, dass OCR ein Sensor bleibt und kein Orakel.\n\n## Korrekturen sind Daten, keine Einmal-Aktionen\n\nWas passiert mit den Feldern, die in der Prüfung landen? Ein Mensch schaut auf den Beleg und auf den markierten Wert und korrigiert die 133 zurück auf 138. Wenn diese Korrektur nur in den aktuellen Lauf einfließt und danach verschwindet, hat man das Problem nicht gelöst, sondern nur einmal umschifft. Beim nächsten Lauf mit derselben Datei liest die OCR wieder 133, und jemand korrigiert wieder.\n\nDeshalb behandle ich Korrekturen als vollwertige Daten. Eine Korrektur bindet sich an den Inhalts-Hash des Dokuments und überschreibt das OCR-Ergebnis für genau dieses Feld. Sie liegt geschützt neben dem Cache, ist versioniert und nachvollziehbar. Beim nächsten Lauf greift die Korrektur, bevor die unsichere Messung überhaupt zum Zug kommt. Das verwandelt die manuelle Prüfung von einer wiederkehrenden Last in eine einmalige Investition pro Dokument. Nebenbei entsteht ein sensibler Datensatz, an dem man später ablesen kann, an welchen Stellen die Erkennung systematisch schwächelt – mit denselben Schutz- und Löschpflichten wie für die Quelldokumente.\n\nDiese Trennung hat noch einen Vorteil für die Nachvollziehbarkeit. Im Report lässt sich für jeden Wert sagen, woher er stammt: aus dem deterministischen Textlayer, aus der OCR oberhalb der Schwelle, oder aus einer menschlichen Korrektur. Drei Herkünfte, drei Vertrauensstufen, und alle drei sind sichtbar. Ein Wert, der aus einer Korrektur stammt, trägt seine Geschichte mit sich, statt sich als anonymer String zu tarnen.\n\n## Was ich beim nächsten Mal gleich so bauen würde\n\nIm Rückblick sind es wenige Entscheidungen, die den Unterschied gemacht haben, und keine davon war aufwendig. Der Inhalts-Hash als Cache-Schlüssel hat eine halbe Stunde gekostet und jeden weiteren Entwicklungslauf billig und reproduzierbar gemacht. Das Confidence-Gate war eine Handvoll Zeilen, sobald ich von `image_to_string` auf `image_to_data` umgestiegen bin und aufgehört habe, die Confidence wegzuwerfen. Die Fachregeln waren am Ende die wertvollste Schicht, weil sie genau die Klasse von Fehlern fängt, bei denen das Modell sich sicher und gleichzeitig irrt.\n\nDer gemeinsame Nenner ist eine Haltung, kein Framework. Wo ein Modell einen Confidence- oder Unsicherheitswert liefert, sollte das System ihn aufbewahren, ohne ihn vorschnell als Wahrscheinlichkeit zu lesen. Wo ein solcher Wert fehlt oder schlecht kalibriert ist, müssen Fachregeln, Stichproben und menschliche Prüfung die Unsicherheit sichtbar machen. Bei Geldbeträgen ist mir eine markierte Zeile im Report lieber als eine saubere Zahl, der ich nicht trauen kann.\n\n## Weiterführende Quellen\n\n- Tesseract, TSV-Ausgabeformat mit Wort-Confidence: [Tesseract OCR](https://tesseractocr.org/) und [Erläuterung des TSV-Formats](https://tomrochette.com/tesseract-tsv-format/)\n- Confidence-Schwellen in der Praxis: [Diskussion zur Berechnung der Tesseract-Confidence](https://groups.google.com/g/tesseract-ocr/c/SN8L0IA_0D4)\n- Validierung und menschliche Prüfung bei Beleg-OCR: [Invoice OCR Error Handling](https://invoicedataextraction.com/blog/invoice-ocr-error-handling)"},{"locale":"de","translation_key":"rxjs-die-vier-subject-typen","slug":"rxjs-die-vier-subject-typen","title":"Die vier Subject-Typen in RxJS","summary":"Subject, BehaviorSubject, ReplaySubject und AsyncSubject unterscheiden sich darin, was späte Subscriber sehen und wie Abschluss oder Fehler ihr gespeichertes Verhalten beenden.","tags":["Software","Reactive"],"published_at":"2024-05-21T10:00:00+00:00","updated_at":"2026-07-13T08:51:45.630871+00:00","url":"https://www.mikebild.dev/de/blog/rxjs-die-vier-subject-typen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/38f92df673aa566d73a6a8e29513d15911a4552b342b2158c5e177786791df8c/rxjs-die-vier-subject-typen-vorlesen.mp3","audio_duration_secs":853,"text":"Ein Subject ist kein Observable mit angeschraubter `next()`-Methode. Es ist ein anderes Modell: hot statt kalt, multicast statt unicast, mit einem Lifecycle, der weiterläuft, ob gerade jemand zuhört oder nicht. Wer es nur als bequeme Abkürzung nimmt, um endlich selbst Werte in einen Stream zu schieben, handelt sich damit ein Timing-Verhalten ein, das er nicht bestellt hat.\n\nVor der Wahl zwischen den vier Typen steht deshalb eine andere Frage: Lohnt sich der Stream an dieser Stelle überhaupt, oder tut es ein schlichteres Modell genauso? Wer sie überspringt, baut Reaktivität dort ein, wo eine Variable oder ein Promise gereicht hätte. Wer sie stellt und mit Ja beantwortet, hat danach noch genau eine Entscheidung zu treffen – und die spart, richtig getroffen, eine ganze Klasse von Timing-Bugs, die schwer zu reproduzieren und teuer zu debuggen sind.\n\nEin Subject ist der Baustein, mit dem man aus imperativem Code heraus in die reaktive Welt hineinruft. Ein normales Observable ist dafür nicht gebaut – es beschreibt eine Quelle, die man abonniert, und es startet seine Arbeit erst dann, verzögert, pro Subscription neu. Genau an dieser Stelle betritt das Subject die Bühne. Und sobald diese Brücke steht, kommt die nächste Frage: Warum gibt es davon gleich vier Varianten? Die kurze Antwort lautet: Sie unterscheiden sich im Gedächtnis. Die lange Antwort ist dieser Artikel.\n\nWer die Grundlagen des Push-Modells noch einmal auffrischen möchte, findet sie in [RxJS: Push und Pull](https://www.mikebild.dev/de/blog/rxjs-push-und-pull/). Hier setze ich voraus, dass Observable und Subscription vertraut sind, und konzentriere mich auf die Entscheidung dahinter und auf die Subjects selbst. Stand ist RxJS 7.\n\n## Lohnt sich Reaktivität hier überhaupt?\n\nBevor ich zwischen den vier Typen wähle, stelle ich eine Frage davor: Braucht diese Stelle überhaupt einen Stream? Reaktivität ist kein Selbstzweck, sondern ein Modell mit Kosten. Ein Subject bringt einen Lifecycle mit, um den man sich kümmern muss – Subscriptions, die man wieder abbestellt, Puffer, die Speicher halten, ein Timing, das man im Kopf behalten muss. Diese Kosten lohnen sich, aber nicht überall.\n\nFür einen einzelnen Wert, der einmal berechnet und dann gelesen wird, reicht eine Variable. Für eine einzelne asynchrone Operation mit genau einem Ergebnis ist ein Promise das einfachere und vertrautere Werkzeug. Für eine fertige Liste, die vollständig vorliegt, tut es ein Array mit den üblichen Methoden. In all diesen Fällen einen Stream aufzuziehen, verteuert den Code, ohne etwas zurückzugeben – man handelt sich den Subscription-Lifecycle ein und bekommt dafür nichts, was das schlichtere Modell nicht auch geliefert hätte.\n\nReaktivität zahlt sich in dem Moment aus, in dem drei Dinge zusammenkommen: Werte entstehen über die Zeit verteilt, nicht auf einen Schlag; es gibt mehr als einen Interessenten für dieselben Werte; und man will diese Werte zusammensetzen, filtern, abbrechen oder zusammenführen, statt sie nur einmal entgegenzunehmen. Ein Klickstrom, ein WebSocket, ein State, den mehrere Komponenten teilen – das sind die Fälle, in denen ein Geflecht aus Variablen und Callbacks schnell unübersichtlich wird und ein Stream die Reibung herausnimmt.\n\nDie Vorabfrage kostet nichts und hält die Menge an reaktivem Code klein. Dort, wo Reaktivität trägt, spielt sie ihre Stärke aus, und der Rest bleibt einfach. Erst wenn die Frage mit Ja beantwortet ist, wird die zweite Frage relevant, um die es hier geht: welches Gedächtnis der Stream für späte Subscriber haben soll.\n\n## Ein Subject ist beides zugleich\n\nDer entscheidende Satz über Subjects steht schon in der Klassendefinition: `Subject<T>` erweitert `Observable<T>` und implementiert zugleich das Observer-Interface. Das heißt, ein Subject ist Observable und Observer in einer einzigen Instanz. Man kann es abonnieren wie jedes Observable – und man kann per `next`, `error` und `complete` Werte hineinfüttern wie in einen Observer.\n\n```ts\nimport { Subject } from 'rxjs';\n\nconst subject = new Subject<number>();\n\n// als Observable: abonnieren\nsubject.subscribe((value) => console.log('received', value));\n\n// als Observer: Werte hineingeben\nsubject.next(1);\nsubject.next(2);\nsubject.complete();\n```\n\nDiese Doppelrolle hat eine wichtige Konsequenz. Ein reines Observable ist kalt und unicast: Jeder Subscriber bekommt seine eigene Ausführung, der Code im Observable läuft pro Subscription erneut. Ein Subject dagegen ist multicast. Es hält eine Liste seiner Subscriber, und wenn `next` aufgerufen wird, geht derselbe Wert an alle gleichzeitig. Es gibt eine Quelle und viele Empfänger.\n\n```mermaid\nflowchart LR\n  P[\"Quelle<br/>next / error / complete\"] --> S((\"Subject\"))\n  S --> A[\"Subscriber A\"]\n  S --> B[\"Subscriber B\"]\n  S --> C[\"Subscriber C\"]\n```\n\nDamit hängt der zweite zentrale Charakterzug zusammen: Subjects sind hot. Werte fließen unabhängig davon, ob gerade jemand zuhört. Rufe ich `subject.next(1)` auf, bevor irgendein Subscriber existiert, ist dieser Wert bei einem einfachen `Subject` schlichtweg weg. Er wurde emittiert, aber niemand war da, um ihn entgegenzunehmen. Genau dieser Punkt – was passiert mit Werten, die vor einer Subscription geflossen sind – trennt die vier Typen voneinander.\n\n## Die vier Typen und ihr Gedächtnis\n\nBevor wir in die Details gehen, hier der Überblick. Alle vier erben von `Subject`, alle vier sind hot und multicast. Der Unterschied liegt darin, was ein Subscriber sieht, der zu spät kommt:\n\n- Ein `Subject` hat kein Gedächtnis. Wer nach einem `next` abonniert, hat den Wert verpasst. Nur was ab dem Subscribe-Zeitpunkt fließt, kommt an.\n- Ein `BehaviorSubject` merkt sich den letzten Wert und braucht einen Initialwert. Jeder neue Subscriber bekommt sofort den aktuellen Stand – ideal für den Fall \"aktueller State\".\n- Ein `ReplaySubject` puffert die letzten n Werte und spielt sie jedem neuen Subscriber ab, sogar nach `complete`.\n- Ein `AsyncSubject` emittiert nur den allerletzten Wert, und erst, wenn `complete` aufgerufen wurde.\n\nDie Liste beschreibt nur `next` und `complete`. Ein `error` beendet jeden dieser Streams. Danach liefert ein `BehaviorSubject` keinen letzten Wert mehr, ein `AsyncSubject` kein Endergebnis; ein `ReplaySubject` spielt seinen Puffer noch aus und meldet anschließend den Fehler. Diese terminalen Signale gehören deshalb genauso zur Wahl wie das Verhalten bei späten Subscriptions.\n\nSchauen wir uns jeden Typ mit einem kleinen Timing-Beispiel an, denn das Timing ist genau das, worauf es ankommt.\n\n## Subject – der Vergessliche\n\nBeginnen wir mit dem einfachen `Subject`. Es hat kein Gedächtnis. Um das sichtbar zu machen, abonnieren wir zu unterschiedlichen Zeitpunkten und beobachten, wer was mitbekommt.\n\n```ts\nimport { Subject } from 'rxjs';\n\nconst subject = new Subject<number>();\n\nsubject.next(1); // niemand hört zu -> verloren\n\nsubject.subscribe((v) => console.log('A', v));\nsubject.next(2);\n\nsubject.subscribe((v) => console.log('B', v));\nsubject.next(3);\n\n// Ausgabe:\n// A 2\n// A 3\n// B 3\n```\n\nDer Wert `1` ist verpufft, weil zum Zeitpunkt seiner Emission kein Subscriber existierte. Subscriber A steigt vor der `2` ein und sieht deshalb `2` und `3`. Subscriber B kommt erst nach der `2` und sieht nur noch `3`. Das ist kein Bug, das ist die Definition. Ein `Subject` ist ein reiner Verteiler für den Moment.\n\nWofür ist das gut? Für echte Events, bei denen Vergangenheit keine Rolle spielt. Ein Klick, ein WebSocket-Frame, ein Kommando, das ausgelöst wird. Wer nicht zuhört, wenn das Event passiert, hat es eben nicht miterlebt – und das ist völlig in Ordnung.\n\n## BehaviorSubject – der Zustandshalter\n\nJetzt der Typ, den ich in der Praxis am häufigsten sehe und empfehle: das `BehaviorSubject`. Es unterscheidet sich in zwei Punkten. Erstens braucht sein Konstruktor einen Initialwert – man kann kein `BehaviorSubject` ohne definierten Startzustand erzeugen. Zweitens merkt es sich stets den zuletzt emittierten Wert und liefert ihn synchron an jeden neuen Subscriber aus.\n\n```ts\nimport { BehaviorSubject } from 'rxjs';\n\nconst state$ = new BehaviorSubject<number>(0); // Initialwert Pflicht\n\nstate$.subscribe((v) => console.log('A', v)); // A bekommt sofort 0\nstate$.next(1);\n\nstate$.subscribe((v) => console.log('B', v)); // B bekommt sofort 1\nstate$.next(2);\n\n// Ausgabe:\n// A 0\n// A 1\n// B 1\n// A 2\n// B 2\n```\n\nSubscriber B steigt spät ein und bleibt trotzdem nicht leer. Er erhält beim Abonnieren sofort den aktuellen Wert `1` und danach den Rest. Genau das macht das `BehaviorSubject` zum Standardwerkzeug für State. Ein State hat immer einen aktuellen Wert, und wer ihn abfragt, will diesen Wert – nicht die Aussicht, irgendwann beim nächsten `next` etwas zu erfahren.\n\nPraktisch dazu: das `BehaviorSubject` bietet mit `getValue()` und der Property `value` einen synchronen Zugriff auf den aktuellen Stand, ohne zu abonnieren.\n\n```ts\nconst counter$ = new BehaviorSubject<number>(0);\ncounter$.next(42);\n\nconsole.log(counter$.getValue()); // 42\nconsole.log(counter$.value); // 42\n```\n\nWer schon einmal in [RxJS in React](https://www.mikebild.dev/de/blog/rxjs-in-react-datenfluss/) mit Streams als Datenquelle gearbeitet hat, kennt die Situation: Eine Komponente montiert und abonniert, und sie soll natürlich sofort etwas anzeigen können. Mit einem `BehaviorSubject` ist genau das garantiert.\n\nEin Detail, das gern übersehen wird: Nach `complete()` sendet ein `BehaviorSubject` seinen letzten Wert nicht mehr an neue Subscriber. Es liefert dann nur noch das Complete-Signal. Der aktuelle Wert steht also nur so lange bereit, wie der Stream aktiv ist.\n\n## ReplaySubject – das Gedächtnis mit Puffer\n\nDas `BehaviorSubject` merkt sich genau einen Wert. Manchmal braucht man mehr Historie. Dafür gibt es das `ReplaySubject`. Sein Konstruktor nimmt eine Puffergröße entgegen und spielt diese letzten n Werte jedem neuen Subscriber ab.\n\n```ts\nimport { ReplaySubject } from 'rxjs';\n\nconst replay$ = new ReplaySubject<number>(2); // die letzten 2 Werte puffern\n\nreplay$.next(1);\nreplay$.next(2);\nreplay$.next(3);\n\nreplay$.subscribe((v) => console.log('late', v));\nreplay$.next(4);\n\n// Ausgabe:\n// late 2\n// late 3\n// late 4\n```\n\nDer spät hinzukommende Subscriber bekommt nachträglich `2` und `3` – die beiden letzten gepufferten Werte – und danach `4` live. Der Wert `1` fällt aus dem Puffer, weil dieser nur zwei Plätze hat.\n\nZwei Eigenschaften machen das `ReplaySubject` besonders. Erstens gibt es neben der Puffergröße einen optionalen Zeitfenster-Parameter: `new ReplaySubject<number>(bufferSize, windowTime)`. Damit werden nur Werte abgespielt, die innerhalb der letzten x Millisekunden geflossen sind. Zweitens – und das ist der große Unterschied zum `BehaviorSubject` – spielt das `ReplaySubject` seinen Puffer auch nach `complete()` noch ab.\n\n```ts\nconst cache$ = new ReplaySubject<number>(3);\n\ncache$.next(10);\ncache$.next(20);\ncache$.next(30);\ncache$.complete();\n\n// nach complete abonnieren\ncache$.subscribe((v) => console.log('after complete', v));\n\n// Ausgabe:\n// after complete 10\n// after complete 20\n// after complete 30\n```\n\nDas eignet sich gut als kleiner Cache: Ein Ergebnis wird einmal produziert und dann jedem, der später fragt, erneut ausgeliefert. Vorsicht ist allerdings bei einer Puffergröße von `Infinity` geboten – die ist der Default. Ein `ReplaySubject` ohne Größenangabe merkt sich jeden jemals emittierten Wert und wächst unbegrenzt. In langlebigen Streams ist das eine Quelle für Speicherlecks. Deshalb setze ich die Puffergröße bewusst.\n\n## AsyncSubject – nur das Endergebnis\n\nDer vierte Typ ist der eigenwilligste. Das `AsyncSubject` emittiert nur einen einzigen Wert – den letzten – und das auch erst, wenn `complete()` aufgerufen wird. Solange kein `complete` kommt, gibt es nichts.\n\n```ts\nimport { AsyncSubject } from 'rxjs';\n\nconst async$ = new AsyncSubject<number>();\n\nasync$.subscribe((v) => console.log('result', v));\n\nasync$.next(1);\nasync$.next(2);\nasync$.next(3);\nasync$.complete(); // erst jetzt wird emittiert\n\n// Ausgabe:\n// result 3\n```\n\nDie Zwischenwerte `1` und `2` interessieren das `AsyncSubject` nicht. Es merkt sich nur den jeweils letzten, und beim `complete` gibt es diesen einen an alle Subscriber weiter – auch an die, die erst nach dem `complete` abonnieren. Das Verhalten erinnert bewusst an eine Promise: eine Berechnung, die läuft und am Ende genau ein Ergebnis liefert.\n\nDer häufigste Stolperstein hier ist das fehlende `complete`. Ohne diesen Aufruf emittiert das `AsyncSubject` niemals. Der Fehler sieht harmlos aus und kostet trotzdem eine halbe Stunde: Die Werte sind geflossen, die Konsole bleibt leer, und man sucht zunächst überall – nur nicht beim fehlenden Abschluss.\n\n## Wann welcher – die Entscheidung\n\nFassen wir die Wahl zusammen. Die Frage, die man sich stellen sollte, lautet immer: Was soll ein Subscriber sehen, der zu spät kommt?\n\n- Es geht um ein Event, und Vergangenheit ist irrelevant? **Subject.**\n- Es geht um einen aktuellen State, der immer verfügbar sein muss? **BehaviorSubject.**\n- Neue Subscriber sollen die letzten n Werte oder ein zeitliches Fenster nachgeliefert bekommen? **ReplaySubject.**\n- Es interessiert nur ein einziges Endergebnis nach Abschluss? **AsyncSubject.**\n\nIn der Praxis dominieren zwei davon. `BehaviorSubject` für State, `Subject` für Events. `ReplaySubject` und `AsyncSubject` sind Spezialwerkzeuge für konkrete Bedürfnisse.\n\n## Zwei Fallstricke aus der Praxis\n\nZum Schluss die zwei Fehler, die mir am häufigsten begegnen. Beide sind leicht zu vermeiden, wenn man sie einmal gesehen hat.\n\nDer erste ist die Verwechslung von `Subject` und `BehaviorSubject` bei State. Man baut einen Service, der einen aktuellen Wert hält, verwendet aber ein einfaches `Subject`. Dann montiert eine Komponente, abonniert – und bleibt leer, weil das letzte `next` schon vorbei war. Der Fehler äußert sich als \"manchmal ist der Wert da, manchmal nicht\", je nach Timing. Für State gilt: immer `BehaviorSubject`, damit es einen definierten aktuellen Wert gibt.\n\nDer zweite Fallstrick ist subtiler und betrifft die Architektur: Subjects überall statt reiner Observables nach außen zu geben. Wenn ich ein `Subject` als öffentliche Property exponiere, kann jeder von außen `next()` oder `complete()` darauf aufrufen. Damit ist die Kapselung dahin – jede beliebige Stelle im Code kann in den Stream hineinfunken oder ihn abschließen. Die saubere Lösung ist ein privates Subject und ein öffentliches Observable über `asObservable()`:\n\n```ts\nimport { Subject, Observable } from 'rxjs';\n\ninterface Command {\n  type: string;\n}\n\nclass CommandBus {\n  private commandsSubject = new Subject<Command>();\n\n  // nach außen nur lesbar\n  readonly commands$: Observable<Command> = this.commandsSubject.asObservable();\n\n  dispatch(command: Command): void {\n    this.commandsSubject.next(command);\n  }\n}\n```\n\nVon außen kann man `commands$` abonnieren, aber nicht hineinschreiben. Das `next` läuft ausschließlich über die kontrollierte `dispatch`-Methode. Das ist dasselbe Prinzip, das auch in [RxJS in Node.js](https://www.mikebild.dev/de/blog/rxjs-in-node-ereignisstroeme/) trägt: Events fließen über eine definierte Schnittstelle hinein und über abonnierbare Observables wieder hinaus. Ein Subject als Motor im Inneren, ein Observable als Fassade nach außen.\n\nDamit man es nicht falsch versteht: Subjects sind kein Anti-Pattern. Sie sind das richtige Werkzeug, wann immer man von imperativem Code aus in einen Stream schreiben muss. Nur sollte das Subject selbst nach Möglichkeit im Inneren bleiben.\n\n## Fazit\n\nEin Subject ist Observable und Observer in einem und multicastet dieselben Werte an alle seine Subscriber. Es ist hot – Werte fließen, ob jemand zuhört oder nicht. Die vier Varianten unterscheiden sich nur in einer einzigen Dimension: im Gedächtnis für Subscriber, die zu spät kommen. Kein Gedächtnis beim `Subject`, der letzte Wert beim `BehaviorSubject`, die letzten n Werte beim `ReplaySubject`, das Endergebnis nach Abschluss beim `AsyncSubject`.\n\nWer diese eine Frage – was sieht ein später Subscriber? – zur Gewohnheit macht, trifft die Wahl fast automatisch. Und wer die Frage davorstellt – lohnt sich der Stream hier überhaupt? – hält die Menge an reaktivem Code auf das begrenzt, was wirklich davon profitiert. Was dabei herauskommt, ist unspektakulär und genau deshalb brauchbar: Der passende Typ steht schneller fest, eine ganze Klasse von Timing-Bugs entsteht gar nicht erst, und der Datenfluss bleibt dort kontrolliert, wo er entsteht – hinter Observables nach außen, mit einem Subject als Motor im Inneren. Und wo eine Variable, ein Promise oder ein Array reicht, bleibt es dabei. Reaktivität ist das Werkzeug für Werte über die Zeit und viele Empfänger, nicht der Default für jeden Wert.\n\n## Weiterführende Quellen\n\n- [RxJS Guide: Subject](https://rxjs.dev/guide/subject)\n- [RxJS API: BehaviorSubject](https://rxjs.dev/api/index/class/BehaviorSubject)\n- [RxJS API: ReplaySubject](https://rxjs.dev/api/index/class/ReplaySubject)\n- [RxJS API: AsyncSubject](https://rxjs.dev/api/index/class/AsyncSubject)\n- [RxJS: Push und Pull](https://www.mikebild.dev/de/blog/rxjs-push-und-pull/)\n- [RxJS in Node.js](https://www.mikebild.dev/de/blog/rxjs-in-node-ereignisstroeme/)\n- [RxJS in React](https://www.mikebild.dev/de/blog/rxjs-in-react-datenfluss/)"},{"locale":"de","translation_key":"graphql-client-caching-mit-apollo","slug":"graphql-client-caching-mit-apollo","title":"Apollo Client: der normalisierte Cache und optimistische Updates","summary":"HTTP-Caching ist auch mit GraphQL möglich, aber für Client-Zustand oft weniger direkt. Apollo normalisiert deshalb Objekte und unterstützt optimistische Updates in der UI.","tags":["Software","GraphQL","API"],"published_at":"2024-05-14T10:00:00+00:00","updated_at":"2026-07-13T08:51:30.971485+00:00","url":"https://www.mikebild.dev/de/blog/graphql-client-caching-mit-apollo/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/8c0a54e18a47ab6915638c5d222e9270d31fc6efe08538037cfbfd3b9fb20a83/graphql-client-caching-mit-apollo-vorlesen.mp3","audio_duration_secs":699,"text":"Wer bei GraphQL ganze Antworten unter einem gehashten Query-String ablegt, hat keinen Cache gebaut, sondern eine Sammlung von Kopien. Ändert ein Nutzer seinen Namen, wissen diese Kopien nichts voneinander: Die Listenansicht zeigt weiter den alten Wert, die Detailansicht schon den neuen, und niemand merkt es, bis jemand hin und her klickt. Der Schlüssel, unter dem eine Antwort abgelegt wird, ist bei GraphQL das eigentliche Problem – und die Lösung liegt eine Ebene tiefer als die Antwort selbst.\n\nIn diesem Beitrag geht es ausschließlich um den Cache im Browser, also den Client. Es gibt daneben serverseitiges Caching – Request-Batching und Deduplizierung mit DataLoader zum Beispiel – aber das ist eine völlig andere Baustelle mit anderen Zielen. Hier reden wir über den `InMemoryCache` von Apollo Client 3, über Normalisierung, über optimistische Updates und über den einen Fallstrick, der schnell mal eine halbe Stunde Debugging kostet.\n\n## Warum die URL allein als Cache-Key nicht reicht\n\nBei einer klassischen REST-API ist Caching konzeptionell einfach. Jede Ressource hat ihre eigene URL, und ein `GET /users/1` liefert immer denselben Ausschnitt. Der Browser, ein CDN oder eine HTTP-Cache-Schicht kann die Antwort unter genau dieser URL ablegen und beim nächsten Aufruf zurückgeben. Der Key ist die Adresse.\n\nBei vielen GraphQL-APIs teilen sich unterschiedliche Queries einen Endpoint, und häufig laufen sie als `POST /graphql`. Klassisches HTTP-Caching ist damit nicht ausgeschlossen: GET-Anfragen, der Query-Body als Teil des Cache-Keys oder persistierte Queries können Antworten cachebar machen. Für den Zustand einer interaktiven Anwendung bleibt ein reiner Response-Cache aber unhandlich, sobald dieselbe Entity in mehreren Queries auftaucht und gezielt aktualisiert werden soll.\n\nDer Fall, an dem das sichtbar wird: Eine Listenansicht lädt alle Nutzer, eine Detailansicht lädt einen einzelnen Nutzer. Beide zeigen den Namen von `User:1`. Ändert dieser Nutzer seinen Namen, müssten bei einem Response-basierten Cache beide Einträge separat invalidiert werden – und der Cache müsste überhaupt erst wissen, dass in beiden Responses dasselbe Objekt steckt. Genau das leistet ein reiner Response-Cache nicht.\n\n## Normalisierung: ein Objekt, einmal, mit stabiler Identität\n\nApollos Antwort darauf ist Normalisierung. Statt ganze Antworten abzulegen, zerlegt der `InMemoryCache` jede Response in ihre einzelnen Objekte und speichert jedes Objekt genau einmal – flach, unter einer stabilen Cache-ID. Diese ID bildet Apollo per Default aus zwei Feldern: dem `__typename` und dem Primärschlüssel des Objekts. Das Ergebnis sieht aus wie `User:1` oder `Product:42`.\n\nAls Schlüsselfeld nimmt Apollo standardmäßig `id`, und falls das nicht existiert, `_id`. Fehlen beide und ist nichts anderes konfiguriert, passiert etwas Wichtiges, auf das ich weiter unten zurückkomme: Das Objekt wird nicht normalisiert, sondern inline im Elternobjekt eingebettet.\n\nDer Effekt der Normalisierung lässt sich am besten an dem eben genannten Fall zeigen. Zwei Queries, ein geteiltes Objekt:\n\n```mermaid\ngraph TD\n  QA[\"Query GET_USERS<br/>(Listenansicht)\"] --> N[\"User:1<br/>{ name, email }\"]\n  QB[\"Query GET_USER<br/>(Detailansicht)\"] --> N\n  N --> S[(\"Normalisierter<br/>InMemoryCache\")]\n```\n\nBeide Queries verweisen auf denselben Knoten `User:1`. Im Store liegt der Nutzer genau einmal. Ändert sich sein Name, ändert er sich für alle Views, die auf diesen Knoten zeigen. Das ist der Kern, um den sich alles andere dreht.\n\nDamit das funktioniert, muss jede Query die Identitätsfelder mitselektieren. Apollo fügt `__typename` automatisch hinzu, aber `id` müssen wir selbst anfragen:\n\n```graphql\nquery GET_USERS {\n  users {\n    id\n    name\n    email\n  }\n}\n\nquery GET_USER($id: ID!) {\n  user(id: $id) {\n    id\n    name\n    email\n  }\n}\n```\n\nDer Cache-Aufbau selbst ist unspektakulär. Man instanziiert einen `InMemoryCache` und übergibt ihn an den `ApolloClient`:\n\n```ts\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"/graphql\" }),\n  cache: new InMemoryCache(),\n});\n```\n\nWas Normalisierung konkret bringt, fasse ich so zusammen:\n\n- Jede Entity liegt genau einmal im Speicher, egal über wie viele Queries sie geladen wurde.\n- Ein Feld-Update an einer Stelle propagiert automatisch in jede View, die dasselbe Objekt zeigt – ohne manuelle Invalidierung.\n- Der Cache wird kleiner und konsistenter, weil doppelte Daten zu einer Referenz zusammenfallen.\n- Die UI kann Daten sofort aus dem Cache rendern und im Hintergrund nachladen, ohne dass verschiedene Ansichten auseinanderlaufen.\n\n## Feld-Updates passieren automatisch, Struktur-Updates nicht\n\nHier trennt sich in der Praxis, was Apollo für uns erledigt und wo wir selbst ran müssen. Der Unterschied ist wichtig, weil er die häufigste Verwirrung auflöst.\n\nÄndere ich den Wert eines Feldes an einem bereits gecachten Objekt, erledigt Apollo das automatisch. Eine Mutation, die `User:1` mit neuem Namen zurückgibt, überschreibt das Feld im Store, und jede View aktualisiert sich. Ich muss dafür nichts schreiben – vorausgesetzt, die Mutation liefert `id` und `__typename` mit zurück, damit Apollo weiß, welchen Eintrag es treffen soll.\n\n```ts\nconst UPDATE_USER = gql`\n  mutation UpdateUser($id: ID!, $name: String!) {\n    updateUser(id: $id, name: $name) {\n      id\n      name\n    }\n  }\n`;\n\n// Apollo matches the response onto User:1 and updates\n// every view that shows this user - no update function needed.\nconst [updateUser] = useMutation(UPDATE_USER);\n```\n\nAnders sieht es aus, wenn sich die Struktur ändert, also ein Element zu einer Liste hinzukommt oder aus ihr verschwindet. Lege ich per Mutation einen neuen Nutzer an, normalisiert Apollo das neue Objekt zwar brav in den Store – aber es weiß nicht, in welche Liste dieser Nutzer gehört. Die Zugehörigkeit zu einer bestimmten `GET_USERS`-Query ist keine Eigenschaft des Objekts, und deshalb kann Apollo sie nicht erraten. Ergebnis: Das neue Objekt existiert im Cache, taucht in der Listenansicht aber nicht auf, bis man neu lädt.\n\nFür diese Fälle gibt es die `update`-Funktion an der Mutation. Sie bekommt den Cache und die Response und schreibt die Liste explizit fort:\n\n```ts\nconst ADD_USER = gql`\n  mutation AddUser($name: String!) {\n    addUser(name: $name) {\n      id\n      name\n    }\n  }\n`;\n\nconst [addUser] = useMutation(ADD_USER, {\n  update(cache, { data }) {\n    const newUser = data.addUser;\n    cache.modify({\n      fields: {\n        users(existingRefs = [], { toReference }) {\n          return [...existingRefs, toReference(newUser)];\n        },\n      },\n    });\n  },\n});\n```\n\nDie Trennlinie verläuft also genau hier: Wertänderungen erledigt Apollo, die Listenzugehörigkeit erledigen wir.\n\n## Optimistische Updates: die UI reagiert, bevor der Server antwortet\n\nDas zweite große Thema ist gefühlte Geschwindigkeit. Jede Mutation läuft übers Netz, und selbst 150 Millisekunden fühlen sich bei einem Toggle-Button träge an. Optimistische Updates lösen das, indem sie den erwarteten Endzustand sofort in den Cache schreiben – bevor der Server geantwortet hat. Die UI reagiert ohne Latenz. Kommt die echte Antwort, ersetzt sie die optimistische Schicht. Schlägt die Mutation fehl, verwirft Apollo die optimistische Schicht automatisch und stellt den vorherigen Zustand wieder her. Das ist der entscheidende Punkt: Man muss den Rollback nicht selbst schreiben.\n\nDer Ablauf lässt sich als Sequenz gut zeigen:\n\n```mermaid\nsequenceDiagram\n  participant UI\n  participant Cache\n  participant Server\n  UI->>Cache: optimistisches Ergebnis schreiben\n  Cache-->>UI: sofort neu rendern\n  UI->>Server: Mutation senden\n  alt Erfolg\n    Server-->>Cache: echtes Ergebnis schreiben\n  else Fehler\n    Server-->>Cache: optimistische Schicht verwerfen\n    Cache-->>UI: vorigen Zustand wiederherstellen\n  end\n```\n\nIn Code sieht das so aus. Ein Todo lässt sich abhaken, und wir schreiben den `completed`-Zustand optimistisch:\n\n```ts\nconst TOGGLE_TODO = gql`\n  mutation ToggleTodo($id: ID!, $completed: Boolean!) {\n    toggleTodo(id: $id, completed: $completed) {\n      id\n      completed\n    }\n  }\n`;\n\nconst [toggleTodo] = useMutation(TOGGLE_TODO, {\n  optimisticResponse: {\n    toggleTodo: {\n      __typename: \"Todo\",\n      id: todo.id,\n      completed: !todo.completed,\n    },\n  },\n});\n```\n\nZwei Dinge sind hier nicht verhandelbar. Erstens muss das `optimisticResponse` dieselbe Form haben wie die echte Server-Antwort – dieselben Felder, dieselbe Verschachtelung. Zweitens muss es `__typename` und die Schlüsselfelder enthalten. Ohne `__typename` und `id` kann Apollo den optimistischen Eintrag nicht auf `Todo:...` normalisieren, der Merge trifft das falsche Ziel und der Rollback verhält sich unerwartet. Das ist einer der Fehler, die still passieren: Es sieht fast richtig aus, aber die UI flackert oder springt zurück.\n\nWer will, kann `optimisticResponse` auch als Funktion schreiben, die die Variablen bekommt – praktisch, wenn der optimistische Zustand aus den Mutation-Argumenten abgeleitet wird:\n\n```ts\noptimisticResponse: (vars) => ({\n  toggleTodo: {\n    __typename: \"Todo\",\n    id: vars.id,\n    completed: vars.completed,\n  },\n}),\n```\n\n## fetchPolicy: wie stark der Cache das Sagen hat\n\nEin Detail, das dabei leicht untergeht, ist die `fetchPolicy` einer Query. Sie steuert, in welchem Verhältnis Cache und Netzwerk stehen. Der Default ist `cache-first`: Apollo schaut erst in den Cache, und nur wenn die Daten fehlen, geht es ans Netz. Das ist meistens genau richtig und der Grund, warum die zweite Detailansicht eines schon geladenen Nutzers ohne Request auskommt.\n\nDie wichtigsten Werte, die man kennen sollte:\n\n- `cache-first` – Default; Cache zuerst, Netzwerk nur bei fehlenden Daten.\n- `cache-and-network` – rendert sofort aus dem Cache und lädt parallel frisch nach; gut für Listen, die aktuell sein sollen, aber sofort etwas zeigen dürfen.\n- `network-only` – ignoriert den Cache beim Lesen, schreibt das Ergebnis aber in den Cache.\n- `no-cache` – liest und schreibt gar nicht am Cache; die Daten existieren nur innerhalb dieser Query.\n- `cache-only` – nur Cache, nie Netzwerk; wirft, wenn nichts da ist.\n\nDen Default lasse ich so lange stehen, bis es einen konkreten Grund gibt, ihn zu ändern. `cache-and-network` ist der häufigste bewusste Griff, weil es das Beste aus beidem verbindet: sofort sichtbar und trotzdem frisch.\n\n## Der Fallstrick: Objekte ohne stabile Identität\n\nJetzt zu dem Problem, das ich weiter oben angekündigt habe – und das lange unbemerkt bleibt, weil es sich nirgends meldet. Normalisierung funktioniert nur, wenn Apollo eine stabile Identität bilden kann. Fehlt `id` und `_id`, und ist kein alternatives Schlüsselfeld konfiguriert, normalisiert Apollo das Objekt nicht. Es bettet es stattdessen still in das Elternobjekt ein. Kein Fehler, keine Warnung in der Konsole – die App läuft, aber der Cache tut nicht, was man erwartet.\n\nDie Symptome kommen später und wirken zusammenhanglos: Dieselbe Entity liegt mehrfach im Cache, ein Update trifft nur eine Kopie, und zwei Views zeigen unterschiedliche Werte für dasselbe Ding. Besonders gern passiert das bei berechneten oder aggregierten Feldern, bei Wrapper-Typen aus der Paginierung oder bei Objekten, deren id man in der Query schlicht vergessen hat mitzuselektieren. Wer mit Cursor-basierter Blätterung arbeitet, kennt solche Wrapper-Typen aus der Praxis – ich habe das Thema in [GraphQL-Paginierung](https://www.mikebild.dev/de/blog/graphql-paginierung-und-connections/) ausführlicher behandelt.\n\nEs gibt zwei saubere Lösungen. Die einfachste: das Identitätsfeld einfach mitanfragen. Oft ist die id da, sie stand nur nicht in der Selektion. Wenn der Typ tatsächlich keinen `id`-Schlüssel hat, aber ein anderes eindeutiges Feld – eine Artikelnummer etwa – dann sagt man Apollo das über `typePolicies` und `keyFields`:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Product: {\n      keyFields: [\"upc\"],\n    },\n    Book: {\n      keyFields: [\"isbn\"],\n    },\n  },\n});\n```\n\n`keyFields` kann mehr als nur ein Ersatzfeld sein:\n\n- `keyFields: [\"upc\"]` – ein alternatives Schlüsselfeld statt `id`.\n- `keyFields: [\"name\", \"email\"]` – ein zusammengesetzter Schlüssel aus mehreren Feldern.\n- `keyFields: []` – ein Singleton, von dem es genau einen Eintrag pro Typ gibt (etwa ein globaler `Settings`-Typ).\n- `keyFields: false` – Normalisierung für diesen Typ bewusst abschalten, wenn Einbettung gewünscht ist.\n\nAm Rande: In Apollo Client 2 hat man dafür `dataIdFromObject` benutzt. In Version 3 existiert das noch zur Migrationserleichterung, aber es ist der alte Weg. Für neuen Code sind `typePolicies` mit `keyFields` die richtige Wahl, weil sie pro Typ präzise und lokal konfigurierbar sind statt global über eine einzige Funktion.\n\nEin verwandter Fall, in dem Identität auf dem Server entscheidet, ist die Autorisierung: Wer welches Objekt überhaupt sehen darf, gehört nicht in den Client-Cache, sondern in den Resolver-Context. Wie ich das dort verankere, steht in [GraphQL-Auth im Context](https://www.mikebild.dev/de/blog/graphql-auth-im-context/).\n\n## Was hängen bleiben sollte\n\nGraphQL kann HTTP-Antworten cachen; Apollo löst im Browser ein anderes Problem. Der Client normalisiert Entities auf Objektebene, damit mehrere Queries dieselbe Instanz teilen und gezielte Feld-Updates konsistent bleiben. Strukturänderungen an Listen bleiben unsere Aufgabe über die `update`-Funktion. Optimistische Updates reagieren sofort und rollen bei Fehlern zurück, solange das `optimisticResponse` die richtige Form samt `__typename` hat. Der häufigste leise Fehler bleibt ein Objekt ohne stabile Identität, das nicht normalisiert wird. Konsistente IDs und bewusst gesetzte `keyFields` sparen hier viel Debugging.\n\n## Weiterführende Quellen\n\n- Cache configuration – cache IDs und keyFields: https://www.apollographql.com/docs/react/caching/cache-configuration\n- Cache normalization (Konzept): https://www.apollographql.com/docs/react/caching/overview\n- Optimistic mutation results: https://www.apollographql.com/docs/react/performance/optimistic-ui\n- Mutations und die update-Function: https://www.apollographql.com/docs/react/data/mutations\n- fetchPolicy und Zusammenspiel mit dem Cache: https://www.apollographql.com/docs/react/data/queries#setting-a-fetch-policy"},{"locale":"de","translation_key":"graphql-absichern-depth-complexity-rate-limiting","slug":"graphql-absichern-depth-complexity-rate-limiting","title":"GraphQL absichern: Query-Tiefe, Komplexität und Rate-Limiting","summary":"Ein einziger GraphQL-Endpoint nimmt beliebig verschachtelte Queries an – das ist bequem und zugleich ein Missbrauchsrisiko. Ich zeige, wie ich mit Depth-Limit, Complexity-Budget, Pagination-Caps und Rate-Limiting eine mehrschichtige Verteidigung gegen teure Queries baue.","tags":["Software","GraphQL","API"],"published_at":"2024-04-16T10:00:00+00:00","updated_at":"2026-07-13T13:20:10.670504+00:00","url":"https://www.mikebild.dev/de/blog/graphql-absichern-depth-complexity-rate-limiting/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/fa6ae5fe5f8cc98184ce9767a5384cfde8df10c4a8606854cd0f29d91b8dab02/graphql-absichern-depth-complexity-rate-limiting-vorlesen.mp3","audio_duration_secs":675,"text":"Bei einer REST-API ist das Kostenprofil einer Route meist enger begrenzt: Wer `/users/1/posts` baut, kennt den vorgesehenen Ausführungspfad, auch wenn Parameter und Datenmenge die tatsächlichen Kosten weiter verändern. GraphQL gibt dem Aufrufer mehr Einfluss auf Form und Tiefe der Query. Für die Developer Experience ist das ein Gewinn. Für den Betrieb heißt es: Die Kosten eines Requests lassen sich erst aus dem eingehenden Dokument und dem Resolver-Verhalten abschätzen.\n\nDie Frage, an der sich alles entscheidet, lautet: Was passiert, wenn jemand eine zwanzigfach verschachtelte Query mit `first: 1000` auf jeder Ebene schickt? Wer darauf keine Antwort hat, betreibt eine API, die beim ersten unfreundlichen Client umfällt – und merkt es genau dann zum ersten Mal.\n\nIn diesem Beitrag geht es nicht um Authentifizierung oder Autorisierung – das habe ich in [GraphQL-Auth im Context](https://www.mikebild.dev/de/blog/graphql-auth-im-context/) behandelt. Hier geht es um etwas Orthogonales: den Schutz vor teuren und böswilligen Queries. Ein sauber authentifizierter, autorisierter Nutzer kann den Server trotzdem in die Knie zwingen. Wer nur Auth hat, ist gegen diese Klasse von Problemen ungeschützt.\n\n## Warum ein Endpoint gefährlich wird\n\nDas Kernproblem sind zyklische Beziehungen im Schema. Sobald ein `User` seine `posts` hat und ein `Post` seinen `author` – der wiederum seine `posts` hat – ist die Tiefe formal unbegrenzt:\n\n```graphql\nquery MaliciousDepth {\n  user(id: \"1\") {\n    posts {\n      author {\n        posts {\n          author {\n            posts {\n              author {\n                # ... and so on, as deep as the client wants\n                name\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n```\n\nJede zusätzliche Ebene kann die Zahl der Resolver-Aufrufe vervielfachen. Ob daraus auch entsprechend viele Datenbankzugriffe werden, hängt von Batching, Caching und den Resolvern ab. Kombiniert mit unbegrenzten Listen kann dennoch eine extrem teure Query entstehen – ein Denial-of-Service mit einem einzigen HTTP-Request. Das ist kein hypothetisches Lehrbuch-Szenario. Ich habe produktive APIs gesehen, die genau so kippten, weil ein Frontend-Bug versehentlich eine rekursive Query erzeugte.\n\nDie gute Nachricht: Verteidigung funktioniert hier gut in Schichten. Keine einzelne Maßnahme genügt, aber die Kombination macht die Angriffsfläche beherrschbar. Der Ablauf, den ich anstrebe, sieht so aus:\n\n```mermaid\nflowchart TD\n  A[Client-Request] --> B{Rate-Limit<br/>am Edge}\n  B -->|Budget überschritten| R1[429 Too Many Requests]\n  B -->|ok| C{Depth Gate<br/>graphql-depth-limit}\n  C -->|zu tief| R2[Validation Error]\n  C -->|ok| D{Complexity Gate<br/>Cost-Budget}\n  D -->|über Budget| R3[Validation Error]\n  D -->|ok| E[Resolver-Ausführung<br/>mit Pagination-Caps]\n  E --> F[Response]\n```\n\nDie entscheidende Eigenschaft: Depth- und Complexity-Prüfung greifen in der Validierungsphase, also **bevor** ein einziger Resolver läuft. Parsing und Validierung kosten ebenfalls Ressourcen, bleiben mit Größen- und Ratenlimits aber deutlich besser begrenzbar als die eigentliche Resolver-Ausführung.\n\n## Schicht 1: Query-Tiefe begrenzen\n\nDer einfachste und wirkungsvollste erste Schritt ist ein Limit auf die Schachtelungstiefe. In Apollo Server 4 hängt man dafür eine Validation Rule in die `validationRules` des Konstruktors. Die verbreitete Bibliothek dafür ist `graphql-depth-limit`:\n\n```ts\nimport { ApolloServer } from \"@apollo/server\";\nimport depthLimit from \"graphql-depth-limit\";\nimport { typeDefs } from \"./schema\";\nimport { resolvers } from \"./resolvers\";\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  validationRules: [\n    // Reject any operation nested deeper than 7 levels.\n    depthLimit(7),\n  ],\n});\n```\n\n`depthLimit(maxDepth)` liefert eine graphql-js Validation Rule, die während der Validierung die tiefste Verschachtelung zählt und Operationen über dem Limit ablehnt. Introspektionsfelder wie `__schema` und `__type` werden per Default ignoriert, damit Tools weiter funktionieren.\n\nEin Wort der Warnung, das 2024 dazugehört: `graphql-depth-limit` (v1.1.0) wird seit 2018 nicht mehr gepflegt und zählt ausschließlich die Selektionstiefe – nicht die Tiefe von Listen. Für viele Projekte reicht das als erste Schicht, solange die Lücke bekannt ist. Wer strenger sein will, kann sich `@graphile/depth-limit` ansehen, das auch List-Tiefe berücksichtigt.\n\nWichtig ist die konzeptionelle Grenze: Depth-Limiting kennt keine Feld-Kosten. Eine flache Query, die dafür tausend teure Felder auf einer Ebene selektiert, läuft anstandslos durch. Tiefe ist eben nur eine Dimension des Missbrauchs.\n\n## Schicht 2: Complexity- und Cost-Analyse\n\nDamit sind wir bei der zweiten Schicht, die die Schwäche der ersten ausgleicht. Statt nur Tiefe zu zählen, vergebe ich Kosten pro Feld und lehne jede Query ab, die ein Gesamtbudget überschreitet. Das etablierte Werkzeug dafür ist `graphql-query-complexity` von slicknode.\n\nDer Kern ist `createComplexityRule`, das ich mit einem `maximumComplexity`-Budget und einer Liste von Estimators konfiguriere. Estimators sind die Regeln, nach denen Kosten berechnet werden – sie werden der Reihe nach befragt, bis einer einen Wert liefert:\n\n```ts\nimport { ApolloServer } from \"@apollo/server\";\nimport depthLimit from \"graphql-depth-limit\";\nimport {\n  createComplexityRule,\n  simpleEstimator,\n  fieldExtensionsEstimator,\n} from \"graphql-query-complexity\";\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  validationRules: [\n    depthLimit(7),\n    createComplexityRule({\n      maximumComplexity: 1000,\n      estimators: [\n        // Prefer explicit costs declared on the schema fields...\n        fieldExtensionsEstimator(),\n        // ...and fall back to a flat cost of 1 per field.\n        simpleEstimator({ defaultComplexity: 1 }),\n      ],\n      onComplete: (complexity) => {\n        console.log(`Query complexity: ${complexity}`);\n      },\n    }),\n  ],\n});\n```\n\nDie eigentliche Modellierung passiert an den Feldern selbst. Über `fieldExtensionsEstimator` lese ich Kosten aus den Schema-Extensions – und genau hier bilde ich Listen realistisch ab. Ein Feld, das eine Liste zurückgibt, kostet nicht konstant, sondern proportional zum angeforderten `first`-Wert:\n\n```ts\nimport { GraphQLObjectType, GraphQLList } from \"graphql\";\nimport type { ComplexityEstimatorArgs } from \"graphql-query-complexity\";\n\nconst UserType = new GraphQLObjectType({\n  name: \"User\",\n  fields: {\n    posts: {\n      type: new GraphQLList(PostType),\n      args: { first: { type: GraphQLInt } },\n      extensions: {\n        // Cost scales with the number of requested items.\n        complexity: ({ args, childComplexity }: ComplexityEstimatorArgs) => {\n          const requested = args.first ?? 20;\n          return childComplexity * requested;\n        },\n      },\n    },\n  },\n});\n```\n\nDas ist der Punkt, an dem die Cost-Analyse ihre Stärke ausspielt. Eine tiefe Query mit kleinen Listen kann günstiger sein als eine flache mit riesigen. Das Budget von 1000 ist dabei kein magischer Wert – ich leite ihn aus realen Query-Patterns ab, indem ich `onComplete` erst einmal nur loggen lasse und beobachte, wo legitime Clients landen, bevor ich den Riegel scharf schalte.\n\nEin Detail zur Apollo-Server-4-Integration, das gern Zeit kostet: Für die reine Ablehnung reicht die Validation Rule oben. Wer die Komplexität aber im Request-Lifecycle weiterverarbeiten will – etwa fürs Kosten-Accounting pro API-Key – nutzt ein eigenes Plugin und berechnet die Komplexität im `didResolveOperation`-Hook mit `getComplexity()`. Der fertige AS3-Plugin-Wrapper `createComplexityPlugin` passt nicht mehr direkt in AS4, deshalb ist der Plugin-Weg von Hand kurz erwähnenswert:\n\n```ts\nimport type { ApolloServerPlugin } from \"@apollo/server\";\nimport { getComplexity, simpleEstimator } from \"graphql-query-complexity\";\nimport { separateOperations } from \"graphql\";\n\nconst complexityPlugin: ApolloServerPlugin = {\n  async requestDidStart() {\n    return {\n      async didResolveOperation({ request, document, schema }) {\n        const complexity = getComplexity({\n          schema,\n          operationName: request.operationName,\n          query: request.operationName\n            ? separateOperations(document)[request.operationName]\n            : document,\n          variables: request.variables,\n          estimators: [simpleEstimator({ defaultComplexity: 1 })],\n        });\n\n        if (complexity > 1000) {\n          throw new Error(\n            `Query is too expensive: ${complexity}. Maximum allowed: 1000.`,\n          );\n        }\n      },\n    };\n  },\n};\n```\n\n## Schicht 3: Pagination-Obergrenzen\n\nDie Cost-Regel kann Listen nur dann korrekt bewerten, wenn ich Listen überhaupt begrenze. Ein `first`-Argument ohne serverseitiges Maximum ist eine offene Flanke: Ein einziger Aufruf mit `first: 100000` löst zehntausende Resolver aus. Deshalb klemme ich jeden Pagination-Parameter serverseitig ab, unabhängig davon, was der Client wünscht:\n\n```ts\nconst MAX_PAGE_SIZE = 100;\nconst DEFAULT_PAGE_SIZE = 20;\n\nconst resolvers = {\n  User: {\n    posts: (parent, args, context) => {\n      // Never trust the client-supplied page size.\n      const first = Math.min(args.first ?? DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);\n      return context.dataSources.posts.byAuthor(parent.id, { first });\n    },\n  },\n};\n```\n\nWer sein Schema sauber nach dem Connections-Pattern baut, hat hier ohnehin einen natürlichen Ort für diese Grenze – wie das strukturell aussieht, habe ich in [GraphQL-Paginierung und Connections](https://www.mikebild.dev/de/blog/graphql-paginierung-und-connections/) beschrieben. Die Cap gehört in den Resolver oder eine gemeinsame Helper-Function, nicht in die Dokumentation als Bitte an den Client.\n\n## Schicht 4: Rate-Limiting\n\nDepth und Complexity begrenzen die Kosten einer einzelnen Query. Sie sagen nichts darüber, wie viele Queries pro Sekunde jemand feuert. Rate-Limiting ist kein Apollo-Kern-Feature, und meiner Erfahrung nach ist die zuverlässigste Stelle dafür die Transport-Ebene – ein Reverse-Proxy oder eine Middleware vor dem GraphQL-Handler:\n\n```ts\nimport express from \"express\";\nimport rateLimit from \"express-rate-limit\";\n\nconst app = express();\n\nconst limiter = rateLimit({\n  windowMs: 60_000, // one minute\n  max: 120, // limit each IP to 120 requests per window\n  standardHeaders: true,\n  legacyHeaders: false,\n});\n\napp.use(\"/graphql\", limiter);\n```\n\nFür feingranulare Limits pro Feld gibt es Directive-basierte Ansätze wie `graphql-rate-limit` mit einer `@rateLimit`-Directive im Schema. Das ist mächtig, aber auch mehr Betriebskomplexität. Den größten Teil trägt ein grobes Limit am Edge; feingranulare Directives lohnen erst dort, wo ein konkretes Feld nachweislich Ärger macht.\n\n## Persisted Queries und Allowlisting – mit Vorsicht\n\nAn dieser Stelle kommt regelmäßig der Vorschlag: „Lass uns Automatic Persisted Queries (APQ) einschalten, dann ist das Problem gelöst.“ Das ist ein verbreitetes Missverständnis, das ich klarstellen möchte.\n\nAPQ ist ein Performance-Feature. Der Client sendet statt der vollen Query nur einen SHA-256-Hash; kennt der Server den Hash nicht, antwortet er mit `PERSISTED_QUERY_NOT_FOUND`, der Client schickt die Query einmalig nach, und der Server cached sie. Das spart Bandbreite. Es ist **keine** Allowlist – APQ registriert jede beliebige eingehende Operation automatisch, auch die böswillige.\n\n```ts\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  // Performance optimization, NOT a security control.\n  persistedQueries: { ttl: 900 },\n});\n```\n\nEchtes Safelisting ist etwas anderes: eine vorab registrierte Liste erlaubter Operationen, gegen die der Server prüft. Alles, was nicht auf der Liste steht, wird abgelehnt – egal wie tief oder teuer. In der Apollo-Welt läuft das über eine Persisted Query List in GraphOS zusammen mit dem Apollo Router, ein Enterprise-Feature, bei dem APQ dann bewusst deaktiviert ist. Für interne APIs mit einem bekannten Satz von Client-Operationen ist das die stärkste Verteidigung überhaupt, weil die Menge möglicher Queries endlich und geprüft wird. Für eine öffentliche API mit beliebigen Clients ist es dagegen keine Option – dort tragen Depth und Complexity die Last.\n\n## Introspection in Produktion\n\nDer letzte Baustein wird oft überschätzt. Das Abschalten der Introspection in Produktion (`introspection: false`) verhindert, dass ein Angreifer das Schema bequem abfragt. Das ist ein sinnvoller Default für nicht-öffentliche APIs – aber ich nenne es bewusst nicht Sicherheit, sondern Bequemlichkeitsentzug für Angreifer. Es ist Security by Obscurity: Wer das Schema kennt oder rät, kommt an jeder deaktivierten Introspection vorbei. Introspection abzuschalten ersetzt kein einziges der echten Limits oben. Es ist ein netter Zusatz, kein Fundament.\n\n```ts\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  introspection: process.env.NODE_ENV !== \"production\",\n});\n```\n\nDazu gehört auch ein serverseitiger Request-Timeout, damit eine Query, die trotz aller Gates lange läuft, nicht unbegrenzt Ressourcen bindet. Das ist die Notbremse hinter allen anderen Schichten.\n\n## Die Schichten im Überblick\n\nFür einen produktiven GraphQL-Endpoint ziehe ich die Schichten von außen nach innen ein:\n\n- Rate-Limiting am Edge begrenzt, wie viele Requests pro Zeitfenster überhaupt durchkommen.\n- Persisted Queries oder eine Allowlist lassen bei geschlossenem Client-Kreis nur bekannte Operationen zu.\n- Ein Depth-Limit kappt die Schachtelungstiefe schon vor der Ausführung.\n- Das Complexity-Budget vergibt Kosten pro Feld und lehnt zu teure Queries ab.\n- Pagination-Caps verhindern unbegrenzte Listen und machen die Cost-Analyse überhaupt erst korrekt.\n- Ein Resolver-Timeout ist die Notbremse für alles, was trotzdem durchrutscht.\n\nKeine dieser Schichten ist für sich vollständig. Depth ohne Complexity übersieht breite Queries. Complexity ohne Pagination-Caps rechnet mit falschen Multiplikatoren. Rate-Limiting ohne Cost-Analyse lässt einzelne teure Queries durch. Erst im Zusammenspiel entsteht ein Endpoint, dessen schlimmster Fall ich kenne und beherrsche.\n\n## Fazit\n\nDie Flexibilität von GraphQL verlagert Kontrolle vom Server zum Client – und damit auch die Möglichkeit, den Server zu überlasten. Der häufigste Fehler in der Praxis ist die Annahme, Authentifizierung reiche als Schutz. Sie tut es nicht: Der Angriff über teure Queries ist orthogonal zur Frage, wer der Nutzer ist. Ein legitimer, angemeldeter Client kann durch einen simplen Bug dieselbe DoS-Query erzeugen wie ein Angreifer mit Absicht.\n\nDie Reihenfolge, die sich bewährt hat: Erst das Kostenprofil sichtbar machen (Complexity loggen), dann die Gates von grob nach fein einziehen – Depth-Limit und Pagination-Caps als schnelle Gewinne, Complexity-Budget als eigentliches Rückgrat, Rate-Limiting als Rahmen, Allowlist wo der Client-Kreis es zulässt. Introspection und Timeouts runden ab, tragen aber nicht. Wer diese Schichten hat, kann die Last pro Anfrage wesentlich besser begrenzen und Abweichungen zwischen geschätzten und realen Resolver-Kosten im Betrieb beobachten.\n\n## Weiterführende Quellen\n\n- [Apollo Server – Automatic Persisted Queries](https://www.apollographql.com/docs/apollo-server/performance/apq)\n- [Apollo GraphOS – Safelisting mit Persisted Queries](https://www.apollographql.com/docs/graphos/platform/security/persisted-queries)\n- [graphql-query-complexity (slicknode)](https://github.com/slicknode/graphql-query-complexity)\n- [graphql-depth-limit (npm)](https://www.npmjs.com/package/graphql-depth-limit)\n- [@graphile/depth-limit](https://github.com/graphile/depth-limit)\n- [Apollo Server – Konfiguration und Introspection](https://www.apollographql.com/docs/apollo-server/api/apollo-server)"},{"locale":"de","translation_key":"typescript-in-node","slug":"typescript-in-node","title":"TypeScript in Node.js: Setup, Typen und Tests","summary":"TypeScript in einem Node-Projekt aufsetzen: tsconfig-Essentials verstehen, async und Handler typisieren und die Tests laufen lassen, Schritt für Schritt aus der Projektpraxis.","tags":["Software","Node.js","Backend"],"published_at":"2024-03-19T10:00:00+00:00","updated_at":"2026-07-13T07:29:12.674203+00:00","url":"https://www.mikebild.dev/de/blog/typescript-in-node/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/b9bc6c3cf251b945ad193db0bed60685a9826cebf8895e808a36415d21bee5c6/typescript-in-node-vorlesen.mp3","audio_duration_secs":895,"text":"TypeScript ist keine Node-Laufzeit und keine Sprache, die Node ausführt. Es ist eine Prüfschicht davor: Sie greift beim Übersetzen und ist danach spurlos weg. Aus dieser einen Eigenschaft folgt alles Weitere – bis hin zu der Frage, die beim Aufsetzen eines Projekts eigentlich zur Debatte steht. Sie lautet nämlich nicht, welchen Schalter man in die `tsconfig.json` schreibt, sondern wo ein Fehler auftauchen soll: am Schreibtisch, während der Cursor noch in der Zeile steht, oder beim Nutzer, während die Anfrage schon läuft. TypeScript zieht diesen Fehlerort nach vorne. Der Preis ist ein Build-Schritt und eine Handvoll bewusster Konfigurationsentscheidungen; der Ertrag ist ein Feedback-Zyklus, in dem zwischen „ich baue Mist“ und „ich sehe den Mist“ Sekunden liegen statt Minuten.\n\n**Redaktionelle Einordnung (Juli 2026):** Der Haupttext beschreibt Node 20 und TypeScript 5.4 im März 2024. Aktuelle Node-Versionen können TypeScript mit löschbarer Syntax direkt ausführen. Node entfernt dabei Typen, führt aber keine Typprüfung durch und ignoriert `tsconfig.json`; für TypeScript-spezifische Laufzeitkonstrukte oder einen vollständigen Build bleibt ein externes Werkzeug nötig. Bei modernen Node-Projekten sind außerdem `node16` oder `nodenext` die passenden Auflösungsmodi. `node10` gehört zum historischen CommonJS-Setup dieses Artikels.\n\nDer Rest ist Handwerk, und genau das folgt hier: eine Konfiguration, in der jeder Eintrag eine Begründung hat, typisierte Funktionen und Handler und zuletzt ein Test-Setup, das `.ts`-Dateien ohne Umweg ausführt.\n\nIch setze voraus, dass Node 20 (das aktive LTS) installiert ist und ein `npm init` schon gelaufen ist. Alles andere bauen wir zusammen auf. Wer die Ebene darunter noch einmal auffrischen möchte, also Event Loop, Modulsystem und Laufzeitverhalten, findet das in meinem [Node.js-Training](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/); hier bleiben wir eine Etage höher, bei Typen und Werkzeugen.\n\n## Was TypeScript in Node überhaupt macht\n\nDer entscheidende Punkt gleich am Anfang: Node führt kein TypeScript aus. Node kennt nur JavaScript. TypeScript ist eine Schicht, die zur Compile-Zeit prüft und dann verschwindet. Die Typen werden beim Übersetzen gelöscht, man nennt das Type Erasure. Zur Laufzeit existiert kein einziger Typ mehr, keine `interface`, kein `: number`. Übrig bleibt gewöhnliches JavaScript.\n\nDaraus folgt ein Ablauf, der 2024 der Normalfall ist: Eine `.ts`-Datei geht durch den Compiler `tsc` und wird zu einer `.js`-Datei. Diese `.js`-Datei führt `node` aus. Für die tägliche Entwicklung gibt es eine Abkürzung, `ts-node` übersetzt und startet in einem Rutsch, ohne dass eine sichtbare `.js`-Datei entsteht. Aber ausgeliefert wird am Ende immer kompiliertes JavaScript.\n\n```mermaid\nflowchart LR\n  A[source.ts] -->|tsc| B[dist/source.js]\n  B -->|node| C[Laufzeit]\n  A -.->|ts-node<br/>Entwicklung| C\n```\n\nDer gestrichelte Zweig ist der Dev-Komfort, der durchgezogene das, was in Produktion läuft. Diese Trennung im Kopf erspart viel Verwirrung, etwa warum ein Typfehler den Build stoppt, im laufenden Programm aber nie auftaucht.\n\nEin Hinweis noch: Node bringt 2024 keine eingebaute Möglichkeit mit, `.ts`-Dateien direkt zu starten. An `tsc` oder `ts-node` führt kein Weg vorbei, das ist der Standard. Wer einen Blogpost von „einfach `node index.ts`“ liest, liest über eine Zukunft, die es jetzt noch nicht gibt.\n\n## Typen als ausführbare Verträge\n\nDer Perspektivwechsel, der mir in Projekten am meisten gebracht hat: Ein Typ ist keine Dokumentation, sondern ein Vertrag, den eine Maschine bei jedem Build durchsetzt. `function total(items: LineItem[]): number` hält zwei Zusagen fest, eine an jeden Aufrufer und eine an mich als Autor, und der Compiler verweigert den Build, sobald eine Seite ihren Teil verletzt. Der Hebel liegt dabei im Zeitpunkt: Entscheidend ist, wann Korrektheit eingefordert wird. Ohne solche Verträge rutscht die Prüfung nach hinten, bis ein falscher Feldname oder ein vergessenes `undefined` erst beim Nutzer über einen Fehlerreport auffällt. Verträge, die vorher greifen, melden den Bruch, während der Cursor noch in der Zeile steht, und drücken die Länge des Feedback-Zyklus auf Sekunden.\n\nKostenlos ist das nicht: ein Compile-Schritt, die Disziplin, Typen zu pflegen statt sie mit `any` wegzudrücken, und Momente, in denen der Compiler auf etwas besteht, das zur Laufzeit nie gebrochen wäre. Die Entscheidung fällt deshalb an einer klaren Kante. Je länger ein Stück Code lebt, je mehr Hände es anfassen und je teurer ein Produktionsfehler ist, desto klarer gewinnt der Vertrag. Ein Wegwerfskript braucht ihn nicht; ein Zahlungspfad oder ein öffentliches API holt jede dieser Sekunden zurück.\n\n## Das Fundament: die richtigen Pakete\n\nBevor wir eine Zeile Konfiguration schreiben, brauchen wir drei Dinge als `devDependency`:\n\n```bash\nnpm install --save-dev typescript @types/node ts-node\n```\n\n`typescript` liefert den Compiler. `ts-node` ist das Dev-Werkzeug für den direkten Start. Und `@types/node` ist das Paket, das ich in Projekt-Setups am häufigsten vergessen sehe, mit spürbaren Folgen. Es enthält die Typdeklarationen für die Node-Kern-APIs: `fs`, `http`, `events`, `process`, `Buffer` und den ganzen Rest. Ohne dieses Paket weiß der Compiler schlicht nicht, dass es `process` gibt, und meldet `Cannot find name 'process'`. Die Version folgt der Node-Hauptversion, für Node 20 also die 20er-Reihe.\n\nFaustregel: Jede JavaScript-Bibliothek ohne eigene Typen braucht ein passendes `@types/*`-Paket, angekündigt durch die Meldung `Could not find a declaration file for module 'x'`.\n\n## tsconfig.json: jeder Schalter mit Absicht\n\nJetzt das Herzstück. Ich begründe jeden Eintrag, statt die Datei per Generator zu erzeugen und dann zu ignorieren. Eine Baseline für ein klassisches CommonJS-Node-Projekt:\n\n```jsonc\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"CommonJS\",\n    \"moduleResolution\": \"Node10\",\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"outDir\": \"dist\",\n    \"rootDir\": \"src\",\n    \"skipLibCheck\": true,\n    \"resolveJsonModule\": true,\n    \"sourceMap\": true\n  },\n  \"include\": [\"src/**/*\"]\n}\n```\n\nDie wichtigsten Schalter und was sie tatsächlich bewirken:\n\n- `target` legt fest, auf welche JavaScript-Version übersetzt wird. Der Default ist konservativ (historisch `ES3`), was auf einem modernen Node unnötig alten Code erzeugt. `ES2022` passt zu Node 20 und lässt `async/await`, optionales Verketten und Klassenfelder unverändert durch, statt sie umständlich umzuschreiben.\n- `module` bestimmt das Modulformat der Ausgabe. `CommonJS` ist der klassische Node-Weg mit `require`. Wer echtes ESM will, setzt hier `NodeNext`, das hat aber Folgen.\n- `moduleResolution` steuert, wie der Compiler Importpfade auflöst. Der Wert hat keinen festen Default, sondern hängt an `module`. Zu `CommonJS` passt `Node10` (früher schlicht `\"node\"` geschrieben). Zu `module: NodeNext` gehört `moduleResolution: NodeNext`. Diese Paare müssen zusammenpassen, sonst gibt es Auflösungsfehler.\n- `strict` ist der Schalter, der TypeScript erst wertvoll macht. Er ist standardmäßig `false`, und ohne ihn ist TypeScript kaum mehr als JavaScript mit Doppelpunkten. `strict: true` aktiviert eine ganze Familie: `noImplicitAny`, `strictNullChecks`, `strictFunctionTypes` und weitere. Dazu unten mehr.\n- `esModuleInterop` regelt den Import zwischen CommonJS und ESM. Er ist ebenfalls standardmäßig `false` und wird, das übersehen viele, nicht durch `strict` mitaktiviert. Man muss ihn selbst setzen. Ohne ihn bricht `import express from 'express'`.\n- `outDir` bestimmt, wohin die kompilierten `.js`-Dateien geschrieben werden. Ohne Angabe landen sie neben den Quelldateien, was das Projekt vermüllt. Die Konvention ist `dist`. Gemeinsam mit `rootDir: \"src\"` ergibt sich eine saubere Trennung: Quellen liegen in `src`, das Ergebnis in `dist`.\n\n`skipLibCheck` überspringt die Typprüfung der Deklarationsdateien in `node_modules` und kann den Build beschleunigen. Gefahrlos ist das nicht in jedem Projekt: Widersprüchliche oder fehlerhafte Deklarationen können dadurch unbemerkt bleiben. `resolveJsonModule` erlaubt `import config from './config.json'`. `sourceMap` erzeugt Source-Maps, damit der Debugger auf die `.ts`-Zeilen zeigt und nicht auf das kompilierte JavaScript.\n\n## Warum `strict` den Unterschied macht\n\nAm deutlichsten wird das am Fehlerfall. Ohne `strict`, genauer: ohne `noImplicitAny`, geht Folgendes durch:\n\n```ts\nfunction total(items) {\n  return items.reduce((sum, item) => sum + item.price, 0);\n}\n```\n\nDer Parameter `items` hat hier den impliziten Typ `any`, und `item.price` ebenso. Der Compiler schweigt, und man hat exakt null Typsicherheit, ein Tippfehler wie `item.prise` fällt erst zur Laufzeit auf. Das ist der `any`-Wildwuchs: Ein untypisiertes `any` breitet sich aus, denn alles, was man daraus liest, ist wieder `any`.\n\nMit `strict: true` verlangt der Compiler eine Angabe:\n\n```ts\ninterface LineItem {\n  price: number;\n  quantity: number;\n}\n\nfunction total(items: LineItem[]): number {\n  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n}\n```\n\nJetzt ist `item.prise` ein Fehler zur Compile-Zeit, und die Rückgabe ist garantiert eine `number`. Wenn wirklich einmal ein Wert von außen kommt, dessen Form man nicht kennt, greift man zu `unknown` statt zu `any`, denn `unknown` zwingt dazu, den Typ vor der Benutzung zu prüfen, statt ihn stillschweigend zu unterlaufen.\n\n## Async richtig typisieren\n\nAsynchroner Code ist in Node allgegenwärtig, und TypeScript beschreibt das präzise. Eine `async`-Funktion gibt immer einen `Promise<T>` zurück, auch wenn im Rumpf ein nackter Wert steht, wird er in ein Promise verpackt. Umgekehrt entpackt `await` einen `Promise<T>` wieder zu `T`.\n\n```ts\ninterface User {\n  id: number;\n  name: string;\n  email: string;\n}\n\nasync function fetchUser(id: number): Promise<User> {\n  const response = await fetch(`https://api.example.com/users/${id}`);\n  if (!response.ok) {\n    throw new Error(`Request failed with status ${response.status}`);\n  }\n  return response.json() as Promise<User>;\n}\n```\n\nDer Rückgabetyp `Promise<User>` ist die Zusage an alle Aufrufer: Wer `await fetchUser(1)` schreibt, bekommt einen `User`, nichts anderes. Fällt die Annotation weg, würde sich an einer Stelle wie `response.json()`, die von Haus aus `Promise<any>` liefert, wieder ein `any` einschleichen. Ein `await` kann zudem eine Ausnahme auslösen; unter `strict` fängt der `catch`-Zweig sie als `unknown`, was erneut zur bewussten Typprüfung zwingt.\n\n## Einen HTTP-Handler und einen EventEmitter typisieren\n\nZwei Muster begegnen einem in Node ständig: der HTTP-Handler und der Event-basierte Ablauf. Beide lassen sich sauber typisieren, sobald `@types/node` installiert ist.\n\n```ts\nimport { createServer, IncomingMessage, ServerResponse } from \"node:http\";\n\nconst server = createServer((req: IncomingMessage, res: ServerResponse): void => {\n  if (req.method === \"GET\" && req.url === \"/health\") {\n    res.statusCode = 200;\n    res.setHeader(\"Content-Type\", \"application/json\");\n    res.end(JSON.stringify({ status: \"ok\" }));\n    return;\n  }\n  res.statusCode = 404;\n  res.end(\"Not Found\");\n});\n\nserver.listen(3000, () => {\n  console.log(\"Server listening on port 3000\");\n});\n```\n\n`IncomingMessage` und `ServerResponse` sind die Node-Typen für Anfrage und Antwort. Der Editor weiß dadurch, dass `req.method` ein `string | undefined` ist, und genau dieses `undefined` macht die Prüfung `req.method === \"GET\"` unter `strict` nötig, nicht nur zu gutem Stil.\n\nDer `EventEmitter` ist der zweite Klassiker. Er ist von Natur aus dynamisch, aber man kann die Event-Namen und ihre Nutzlast über ein eigenes Interface festhalten:\n\n```ts\nimport { EventEmitter } from \"node:events\";\n\ninterface OrderEventMap {\n  created: [orderId: string];\n  cancelled: [orderId: string, reason: string];\n}\n\nclass OrderBus extends EventEmitter {\n  on<K extends keyof OrderEventMap>(\n    event: K,\n    listener: (...args: OrderEventMap[K]) => void\n  ): this {\n    return super.on(event, listener as (...args: unknown[]) => void);\n  }\n\n  emit<K extends keyof OrderEventMap>(event: K, ...args: OrderEventMap[K]): boolean {\n    return super.emit(event, ...args);\n  }\n}\n\nconst bus = new OrderBus();\nbus.on(\"created\", (orderId) => {\n  console.log(`Order ${orderId} was created`);\n});\nbus.emit(\"created\", \"order-42\");\n```\n\nDer Gewinn: `bus.emit(\"created\")` ohne die `orderId` ist jetzt ein Compile-Fehler, und im Listener ist `orderId` automatisch ein `string`. Man hat den losen Ereignismechanismus in einen typisierten Vertrag verwandelt, ohne die Node-Mechanik zu verändern. Wer solche Muster auch im Frontend anwenden will, findet die React-Seite davon in [TypeScript in React](https://www.mikebild.dev/de/blog/typescript-in-react/).\n\n## Der Interop-Stolperstein: CommonJS und ESM\n\nDieser Stolperstein sorgt in der Praxis für die meisten roten Unterstreichungen, deshalb gehört die Warnung hierher. Viele npm-Pakete, etwa Express, sind CommonJS-Module mit einem einzigen `module.exports`. Der intuitive Import\n\n```ts\nimport express from \"express\";\n```\n\nfunktioniert nur, wenn `esModuleInterop: true` gesetzt ist. Ohne diesen Schalter besteht TypeScript auf der sperrigen Form `import * as express from \"express\"`, die dann oft zur Laufzeit an anderer Stelle bricht. Der Schalter fügt intern die passenden Interop-Helfer ein und erlaubt so den natürlichen Default-Import.\n\nDer zweite Teil des Stolpersteins betrifft echtes ESM. Wer in der `package.json` `\"type\": \"module\"` setzt und `module: \"NodeNext\"` konfiguriert, muss relative Importe mit Dateiendung schreiben:\n\n```ts\nimport { total } from \"./billing.js\";\n```\n\nDas irritiert jedes Mal: Man schreibt `.js`, obwohl die Quelldatei `billing.ts` heißt, weil der Import den Zustand nach dem Kompilieren beschreibt. Fehlt die Endung oder passen `module` und `moduleResolution` nicht zusammen, quittiert Node das mit `ERR_MODULE_NOT_FOUND`. Für den Einstieg empfehle ich deshalb die CommonJS-Baseline; den ESM-Weg nimmt man bewusst, wenn das Projekt ihn braucht.\n\n## Tests, die TypeScript direkt verstehen\n\nBleibt die Frage, wie man `.ts`-Tests ausführt, ohne bei jeder Änderung von Hand zu kompilieren. Mit Mocha gibt es zwei gangbare Wege.\n\nDer bequeme Weg für die Entwicklung nutzt `ts-node` als Register-Hook. Eine `.mocharc.json` im Projektwurzelverzeichnis genügt:\n\n```json\n{\n  \"require\": \"ts-node/register\",\n  \"extensions\": [\"ts\"],\n  \"spec\": [\"test/**/*.spec.ts\"]\n}\n```\n\nDamit versteht Mocha `.ts`-Dateien direkt, ohne separaten Build-Schritt. Ein Test dazu, hier mit dem eingebauten `node:assert`:\n\n```ts\nimport assert from \"node:assert\";\nimport { total } from \"../src/billing\";\n\ndescribe(\"total\", () => {\n  it(\"sums price times quantity\", () => {\n    const result = total([{ price: 10, quantity: 2 }]);\n    assert.strictEqual(result, 20);\n  });\n});\n```\n\nDer zweite Weg ist der kompilierte: erst `tsc`, dann die erzeugten `.js`-Tests laufen lassen.\n\n```bash\ntsc && mocha \"dist/**/*.spec.js\"\n```\n\nIch empfehle den `ts-node`-Weg für den schnellen Entwicklungszyklus und den kompilierten Weg für die Kette vor der Auslieferung, dort testet man exakt das JavaScript, das auch produktiv geht. Die passenden Skripte in der `package.json` machen das greifbar:\n\n```json\n{\n  \"scripts\": {\n    \"dev\": \"ts-node src/index.ts\",\n    \"build\": \"tsc\",\n    \"start\": \"node dist/index.js\",\n    \"test\": \"mocha\"\n  }\n}\n```\n\n`dev` startet direkt aus dem Quellcode, `build` erzeugt das `dist`-Verzeichnis, `start` fährt das kompilierte Ergebnis, `test` liest die `.mocharc.json`. Vier Zeilen, der ganze Lifecycle.\n\n## Der rote Faden\n\nDie Ordnung dahinter ist einfach: TypeScript prüft zur Compile-Zeit und verschwindet, in der `tsconfig.json` tragen `strict` und `esModuleInterop` am meisten, `@types/node` gibt den Node-APIs überhaupt Typen, und die Tests laufen über den Register-Hook oder den kompilierten Stand.\n\nDer Fehler, den ich am häufigsten sehe, ist nicht der komplizierte Generic Type, sondern das stille `any`, das sich ohne `strict` ausbreitet, bis von der Typsicherheit nichts mehr übrig ist. Wer die Baseline aus diesem Artikel übernimmt, also `strict: true`, `esModuleInterop: true`, `@types/node` und eine saubere Trennung von `outDir` und `rootDir`, verschiebt damit den Ort, an dem Fehler auftauchen: an den Schreibtisch statt zum Nutzer. Eine Formalie ist das nicht, es ist die eigentliche Wirkung – kürzere Feedback-Zyklen, weniger Reibung im Review und höhere Qualität in dem Code, der wirklich ausgeliefert wird. Die Grenze gehört dazu, denn der Vertrag lohnt sich dort, wo Code lange bleibt und durch viele Hände geht, im Wegwerfskript dagegen nicht. Wer sie kennt, holt aus TypeScript in Node genau das heraus, was es verspricht, Fehler früh sichtbar zu machen, statt sie in die Laufzeit durchzureichen.\n\n## Weiterführende Quellen\n\n- TSConfig-Referenz: https://www.typescriptlang.org/tsconfig/\n- TypeScript Handbook, Compiler-Optionen wählen: https://www.typescriptlang.org/docs/handbook/modules/guides/choosing-compiler-options.html\n- Announcing TypeScript 5.4: https://devblogs.microsoft.com/typescript/announcing-typescript-5-4/\n- ts-node (npm): https://www.npmjs.com/package/ts-node\n- ts-node Mocha-Rezept: https://typestrong.org/ts-node/docs/recipes/mocha/\n- @types/node (npm): https://www.npmjs.com/package/@types/node\n- Mocha: https://mochajs.org/\n- [Node.js: Modules – TypeScript](https://nodejs.org/dist/latest/docs/api/typescript.html)\n- [TypeScript: `moduleResolution`](https://www.typescriptlang.org/tsconfig/moduleResolution.html)"},{"locale":"de","translation_key":"typescript-in-react","slug":"typescript-in-react","title":"TypeScript in React: Props, Hooks und Events typisieren","summary":"Wie aus Props und State überprüfbare Verträge werden – und der Editor Fehler meldet, bevor der Nutzer sie sieht. Von interface/type über useState-Generics und Event-Typen bis zu useRef und Utility-Types.","tags":["Software","Frontend","React"],"published_at":"2024-02-27T10:00:00+00:00","updated_at":"2026-07-13T08:50:39.319923+00:00","url":"https://www.mikebild.dev/de/blog/typescript-in-react/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/7852a1156d1b6eb59a0524fe55646f7387c77e9bf1af634d008377677f895db1/typescript-in-react-vorlesen.mp3","audio_duration_secs":883,"text":"Ein Prop an einer Button-Komponente wird umbenannt, der Build läuft durch, die Seite rendert. Drei Tage später kommt aus einem anderen Team ein Ticket: leerer Knopf im Checkout-Dialog. Fünf Aufrufstellen benutzen diese Komponente, keine davon hat gemeckert – JavaScript hatte keinen Grund dazu. Wer nach so einem Ticket TypeScript vorschlägt, hört als Erstes: „Bringt das nicht nur mehr Tipparbeit?“\n\nDahinter steht zuerst eine Entscheidung, keine Frage der Syntax. Die Entscheidung lautet: Wo will ich meine Integrationsfehler bezahlen? Ohne Typen bezahle ich sie spät, im Browser, beim Nutzer, oft in einem anderen Team als dem, das den Fehler eingebaut hat. Mit Typen bezahle ich sie früh, im Editor, mit einer roten Wellenlinie, bevor irgendetwas gebaut wird. Der Preis dafür ist ehrlich benennbar: ein paar Zeilen Typdeklaration und die Disziplin, sie aktuell zu halten. Die Wirkung ist es meistens wert, denn ein Fehler, den der Compiler abfängt, wird nie zum Bugreport, nie zum Rollback, nie zur Support-Anfrage.\n\nTypeScript in React ist also kein Selbstzweck und keine Bürokratie. Aus einer Props-Signatur wird ein Versprechen, das der Compiler bei jedem Speichern nachprüft: „Diese Komponente erwartet einen `label`-String und optional ein `disabled`-Flag.“ Wer sich nicht daran hält, bekommt die Rückmeldung sofort und an der richtigen Stelle. Im Alltag spielt sich das an fünf Stellen einer Komponente ab: bei den Props, beim State, bei den Event-Handlern, bei den Refs und bei den Typen, die man aus bestehenden Datenstrukturen ableitet. Mehr braucht es selten, und der Rest dieses Artikels geht die fünf der Reihe nach durch.\n\n## Der Kern: Fehler wandern nach vorn\n\nBevor wir Code schreiben, lohnt es sich, den Unterschied im Ablauf klarzuziehen. Ohne Typen baut die App durch, egal was ich in ein Prop stecke – der Fehler passiert erst zur Laufzeit, wenn jemand die Seite benutzt. Mit Typen prüft der Compiler die JSX-Nutzung gegen das Interface, und der Fehler entsteht, bevor irgendetwas gebaut wird.\n\n```mermaid\nflowchart TD\n    A[Falscher Prop im JSX] --> B{TypeScript aktiv?}\n    B -->|Nein| C[App baut durch]\n    C --> D[Laufzeitfehler<br/>beim Nutzer im Browser]\n    B -->|Ja| E[tsc / Editor prüft<br/>gegen das Interface]\n    E --> F[Compile-Fehler<br/>rot im Editor]\n    F --> G[Fix vor dem Commit]\n```\n\nDer linke Pfad kostet dich einen Bugreport, im schlimmsten Fall einen verärgerten Kunden. Der rechte Pfad kostet dich zehn Sekunden. Diese Verschiebung nach vorn ist der eigentliche Gewinn – nicht die Autovervollständigung, so schön die auch ist.\n\n## Die UI-Grenze ist die teuerste Grenze\n\nBevor es in die Details geht, lohnt es sich, den Ort zu benennen, an dem sich der Aufwand am stärksten rechnet. Jede Komponente hat eine Grenze: Props fließen hinein, Events fließen hinaus. Genau diese Grenze ist die Nahtstelle, an der zwei Stücke Code zusammenkommen – oft zwei Autoren, manchmal zwei Teams. Ein Formular, das ein `onSubmit` erwartet, eine Tabelle, die eine Zeile über einen Callback nach oben meldet, ein Design-System-Button, den fünf Feature-Teams konsumieren: Das sind keine internen Implementierungsdetails, das sind Schnittstellen. Und Schnittstellen sind die Stellen, an denen die teuren Fehler entstehen, weil der Fehler auf der einen Seite passiert und auf der anderen auffällt.\n\nEin Typ an dieser Grenze ist ein ausführbarer Vertrag. „Ausführbar“ heißt: Er ist kein Kommentar, den jemand pflegen müsste, und keine Zeile in einer Wiki-Seite, die niemand liest. Der Compiler führt ihn bei jedem Speichern aus. Wenn ich die Props-Signatur eines Buttons ändere, meldet mir das Werkzeug an Ort und Stelle jede der fünf Aufrufstellen, die nicht mehr passt – bevor irgendwer die App startet. Der Vertrag ist damit gleichzeitig die Dokumentation, der Test und die Refactoring-Absicherung dieser Grenze, in genau einem Artefakt.\n\nDer Trade-off ist real und gehört ausgesprochen. Typen kosten Schreibarbeit, sie müssen aktuell gehalten werden, und an einer schlecht gewählten Stelle erzeugen sie Reibung statt Sicherheit. Die Entscheidung, wo man sie setzt, ist deshalb eine Kosten-Nutzen-Frage. Je mehr Konsumenten eine Komponente hat, je länger sie lebt und je mehr Menschen an ihr vorbeikommen, desto klarer zahlt sich der Vertrag aus – ein geteilter UI-Baustein verdient präzise Props und Event-Typen. Ein Wegwerf-Prototyp oder eine rein interne Hilfskomponente mit einem einzigen Aufrufer verdient ihn kaum. Die Faustregel: Typisiere die Grenzen, an denen sich Verantwortung trifft, und lass die Inferenz den Rest erledigen. Nicht jede lokale Variable braucht einen Vertrag, aber jede Props- und Event-Signatur, die ein anderer aufruft, wird zu einem.\n\n## Props als Vertrag: interface oder type\n\nDer Einstieg ist unspektakulär und genau deshalb so tragfähig. Eine Komponente ist eine Funktion, ihre Props sind ein Objekt, und dieses Objekt bekommt einen Typ.\n\n```tsx\ninterface ButtonProps {\n  label: string;\n  disabled?: boolean;\n}\n\nfunction Button({ label, disabled }: ButtonProps) {\n  return <button disabled={disabled}>{label}</button>;\n}\n```\n\nDas `?` hinter `disabled` macht den Prop optional. Vergisst jemand `label`, meldet der Compiler einen fehlenden Required-Prop – kein `undefined`, das später als leerer Button endet, sondern ein Fehler an Ort und Stelle.\n\nIn Code-Reviews kommt an dieser Stelle verlässlich die Frage: `interface` oder `type`? Beides funktioniert für Props, und die pragmatische Faustregel aus dem React-TypeScript-Cheatsheet lautet: „interface until you need type.“ Anders gesagt:\n\n- `interface` unterstützt Declaration Merging, was für öffentliche Bibliotheks-APIs praktisch ist, und liest sich bei einfachen Objektformen etwas natürlicher.\n- `type` ist die richtige Wahl, sobald du Union-Typen, Mapped Types oder Kompositionen aus mehreren Typen brauchst – Dinge, die ein `interface` nicht ausdrücken kann.\n\nFür 90 Prozent der Komponenten-Props ist die Wahl reine Geschmackssache. Wichtig ist Konsistenz im Team, nicht die Grundsatzdebatte.\n\n## children ist kein Automatismus mehr\n\nSobald eine Komponente andere Elemente umschließt, braucht sie `children`. Und hier lohnt ein genauer Blick, weil sich mit `@types/react` in Version 18 etwas Grundlegendes geändert hat: Die implizite `children`-Deklaration wurde entfernt. Früher brachte `React.FC` ein automatisches `children` mit. Heute musst du es selbst deklarieren, wenn deine Komponente Kinder rendert.\n\n```tsx\ninterface CardProps {\n  title: string;\n  children?: React.ReactNode;\n}\n\nfunction Card({ title, children }: CardProps) {\n  return (\n    <section className=\"card\">\n      <h2>{title}</h2>\n      <div className=\"card-body\">{children}</div>\n    </section>\n  );\n}\n```\n\n`React.ReactNode` ist der richtige Typ für „alles, was man rendern kann“: Strings, Zahlen, Elemente, Arrays davon, `null`, `boolean`. Wenn du dagegen exakt ein einzelnes Element erzwingen willst, greifst du zu `React.ReactElement`. In den Types 18 liegt der JSX-Namespace übrigens unter `React.JSX`, ein einzelnes Element ist also auch als `React.JSX.Element` beschreibbar. Für den Alltag reicht `ReactNode` fast immer – es ist bewusst großzügig.\n\nDass `children` nicht mehr magisch erscheint, ist einer der Gründe, warum `React.FC` an Bedeutung verloren hat. Dazu gleich mehr.\n\n## State typisieren: wann Inferenz reicht und wann nicht\n\n`useState` ist ein schöner Fall, an dem man sieht, dass TypeScript nicht überall Handarbeit verlangt. Meistens leitet der Compiler den Typ aus dem Startwert ab:\n\n```tsx\nconst [count, setCount] = useState(0);        // number\nconst [name, setName] = useState('');          // string\nconst [open, setOpen] = useState(false);       // boolean\n```\n\nHier ein Generic anzugeben wäre nur Ballast. Die Inferenz ist eindeutig, und `setCount('drei')` scheitert trotzdem am Compiler. Interessant wird es, wenn der Startwert dem Compiler zu wenig verrät. Diesen Fallstrick habe ich in bestehendem Code schon oft repariert:\n\n```tsx\n// Wrong: type is inferred as `null`\nconst [user, setUser] = useState(null);\n// later setUser({ id: 1, name: 'Mike' }) -> compile error\n\n// Correct: specify the generic explicitly\nconst [user, setUser] = useState<User | null>(null);\n```\n\nStartest du mit `null`, inferiert TypeScript den Typ `null` – und dann darfst du nie wieder etwas anderes hineinschreiben. Dasselbe passiert bei `useState([])`, das zu `never[]` wird, oder bei einem leeren Objekt. Die Regel, die ich mir dafür angewöhnt habe: Wenn der Startwert leer, `null` oder ein leeres Array ist, gib den Typ mit dem Generic vor.\n\n```tsx\nconst [items, setItems] = useState<string[]>([]);\nconst [selected, setSelected] = useState<User | null>(null);\n```\n\n## Events typisieren: Schluss mit `any`\n\nDer nächste Klassiker sind Event-Handler. In JavaScript schreibt man `onChange={(e) => setValue(e.target.value)}` und denkt nicht weiter nach. In TypeScript ist `e` ohne Typ ein `any` – und `any` ist das Loch, durch das genau die Fehler zurückkommen, die wir eigentlich loswerden wollten. React bringt für die synthetischen Events präzise Typen mit. Man muss nur den passenden nehmen.\n\n```tsx\nfunction LoginForm() {\n  const [email, setEmail] = useState('');\n\n  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setEmail(e.target.value);\n  };\n\n  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    console.log('submitting', email);\n  };\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <input type=\"email\" value={email} onChange={handleChange} />\n      <button type=\"submit\">Sign in</button>\n    </form>\n  );\n}\n```\n\nZwei Dinge sind hier wichtig. Erstens muss das Generic zum Element passen: Ein `<input>` liefert `HTMLInputElement`, nur damit ist `e.target.value` überhaupt bekannt. Wer versehentlich `HTMLElement` schreibt, verliert `value`. Zweitens gibt es für `onChange`, `onSubmit`, `onClick` jeweils die passenden Typen:\n\n- `React.ChangeEvent<HTMLInputElement>` für Eingaben, analog `HTMLSelectElement` und `HTMLTextAreaElement`.\n- `React.FormEvent<HTMLFormElement>` für das Absenden eines Formulars.\n- `React.MouseEvent<HTMLButtonElement>` für Klicks.\n\nWenn du den Handler inline direkt am JSX-Attribut definierst, kannst du dir den Typ oft sparen, weil React ihn aus dem Kontext ableitet. Sobald du den Handler aber als eigenständige Funktion herausziehst, musst du den Event-Typ selbst angeben. Für Props, die einen Handler entgegennehmen, gibt es zusätzlich die Kurzformen `React.ChangeEventHandler<HTMLInputElement>` und `React.FormEventHandler<HTMLFormElement>` – praktisch, wenn du einen Callback als Prop durchreichst.\n\n## useRef: DOM-Referenz mit Null-Check\n\n`useRef` verwirrt am Anfang, weil es zwei Rollen spielt. Die häufigste ist die DOM-Referenz, um etwa ein Feld beim Mounten zu fokussieren.\n\n```tsx\nfunction SearchBox() {\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  useEffect(() => {\n    inputRef.current?.focus();\n  }, []);\n\n  return <input ref={inputRef} type=\"search\" />;\n}\n```\n\nDrei Details zählen. Das Generic `<HTMLInputElement>` sagt, worauf die Ref zeigt. Der Startwert `null` ist Absicht: Vor dem ersten Render existiert das DOM-Element noch nicht. Diese Kombination ergibt eine read-only `RefObject`, und genau die passt an das JSX-Attribut `ref`. Weil `current` vor dem Mount `null` sein kann, brauchst du beim Zugriff einen Null-Check – deshalb das `?.` in `inputRef.current?.focus()`. Ohne den Guard meckert der Compiler zu Recht.\n\nDie zweite Rolle von `useRef` ist die einer veränderlichen Instanzvariable, die kein Re-Render auslöst – etwa um eine Timer-ID oder einen vorherigen Wert festzuhalten:\n\n```tsx\nconst timerRef = useRef<number | null>(null);\n\nconst start = () => {\n  timerRef.current = window.setTimeout(() => {\n    console.log('done');\n  }, 1000);\n};\n```\n\nHier ist `current` beschreibbar. Der Unterschied entsteht aus dem Overload: Mit `null` im Union-Typ und ohne DOM-Bezug bekommst du ein `MutableRefObject`. Man muss diese Feinheit nicht auswendig können, aber es hilft zu wissen, dass der DOM-Fall bewusst read-only ist.\n\n## Utility-Types: Props ableiten statt kopieren\n\nWenn Datenstrukturen wachsen, will man Props nicht dreimal von Hand nachziehen. Dafür gibt es die Utility-Types aus der TypeScript-Standardbibliothek – nicht aus React, aber im React-Alltag ständig nützlich. Angenommen, es gibt einen `User`:\n\n```ts\ninterface User {\n  id: string;\n  name: string;\n  email: string;\n  role: 'admin' | 'member';\n}\n```\n\nEin Formular, das nur Name und E-Mail bearbeitet, braucht nicht den ganzen `User`. `Pick` schneidet die relevanten Felder heraus:\n\n```ts\ntype EditUserProps = Pick<User, 'name' | 'email'>;\n```\n\nUmgekehrt entfernt `Omit`, was du nicht willst – etwa die serverseitig vergebene `id`:\n\n```ts\ntype NewUserProps = Omit<User, 'id'>;\n```\n\n`Partial` macht alle Felder optional, was für Patch-Operationen oder Formular-Zwischenstände passt:\n\n```ts\ntype UserDraft = Partial<User>;\n```\n\nDer Gewinn: Ändert sich `User`, ziehen die abgeleiteten Typen automatisch nach. Kein Feld gerät aus dem Tritt. Neben `Pick`, `Omit` und `Partial` gehören `Required<T>` und `Readonly<T>` zum Standardrepertoire.\n\nEin React-spezifischer Trick ergänzt das Bild: Wenn deine Komponente die nativen Props eines HTML-Elements erben soll – alle Standard-Button-Attribute etwa –, nimmst du `React.ComponentPropsWithoutRef`:\n\n```tsx\ntype IconButtonProps = React.ComponentPropsWithoutRef<'button'> & {\n  icon: string;\n};\n\nfunction IconButton({ icon, ...rest }: IconButtonProps) {\n  return (\n    <button {...rest}>\n      <span className=\"icon\">{icon}</span>\n    </button>\n  );\n}\n```\n\nSo bekommst du `onClick`, `disabled`, `type` und alle anderen Button-Attribute geschenkt und typgeprüft, ohne sie einzeln aufzuzählen.\n\n## Die Alltags-Typen im Überblick\n\nDiese Übersicht zeigt die fünf Ecken, an denen man in einer typisierten React-Komponente am häufigsten mit Typen zu tun hat.\n\n```mermaid\ngraph TD\n    K[Typen im React-Alltag] --> P[Props<br/>interface / type]\n    K --> S[State<br/>useState&lt;T&gt;]\n    K --> E[Events<br/>ChangeEvent / FormEvent]\n    K --> R[Refs<br/>useRef&lt;HTMLInputElement&gt;]\n    K --> U[Ableitung<br/>Pick / Omit / Partial]\n    P --> C[children:<br/>ReactNode]\n```\n\nDiese fünf decken den größten Teil der täglichen Arbeit ab. Alles andere baut darauf auf.\n\n## Und was ist mit React.FC?\n\nDie Frage kommt garantiert, oft mit einem Codebeispiel aus einem älteren Tutorial: `const Button: React.FC<ButtonProps> = (props) => ...`. Ist das falsch? Nein. Es funktioniert, es ist 2024 verfügbar, und niemand muss bestehenden Code umschreiben. Aber der moderne Default ist die schlichte Funktion mit typisierten Props, und dafür gibt es Gründe.\n\nDer historisch wichtigste war das implizite `children`, das `React.FC` mitbrachte – Komponenten akzeptierten Kinder, auch wenn sie gar keine rendern sollten. Mit `@types/react` 18 wurde dieses implizite `children` entfernt, was einen der Hauptkritikpunkte entschärft hat. Übrig bleibt vor allem, dass `React.FC` bei generischen Komponenten im Weg steht. Wer eine typsichere Listen-Komponente über einen beliebigen Elementtyp schreiben will, fährt mit einer normalen Funktion besser:\n\n```tsx\ninterface ListProps<T> {\n  items: T[];\n  render: (item: T) => React.ReactNode;\n}\n\nfunction List<T>({ items, render }: ListProps<T>) {\n  return <ul>{items.map((item, i) => <li key={i}>{render(item)}</li>)}</ul>;\n}\n```\n\nSo etwas lässt sich mit `React.FC` nur umständlich ausdrücken. Damit bleibt `React.FC` heute eine Stil-Frage, kein Fehler. Wählt eine Variante im Team und bleibt dabei. Ich selbst schreibe normale Funktionen, weil sie bei Generics flexibler sind und weniger Sonderregeln mitbringen.\n\n## Der Bogen zurück zu Hooks\n\nWer schon eigene Hooks schreibt, merkt schnell, dass sich die hier gezeigten Bausteine dort direkt fortsetzen: Ein Custom Hook gibt typisierten State zurück, nimmt typisierte Argumente entgegen und kapselt Event-Logik. Wenn du den Weg von wiederverwendbarer Logik noch nicht gegangen bist, lohnt der Blick auf [Von HOCs und Render Props zu Custom Hooks](https://www.mikebild.dev/de/blog/von-hocs-und-render-props-zu-custom-hooks/) – die Typisierung aus diesem Artikel ist genau das, was einen Custom Hook von einer losen Sammlung von Funktionen zu einem klaren Vertrag macht.\n\n## Fazit\n\nDer Gewinn von TypeScript in React lässt sich in vier Wirkungen fassen, und keine davon steht in der API-Dokumentation. Kürzere Zyklen, weil ein Integrationsfehler in Sekunden im Editor auffällt statt in Tagen über einen Bugreport. Weniger Reibung an der teuersten Stelle, der Grenze zwischen Komponenten und Teams, weil der Vertrag automatisch prüft, was sonst mündlich abgesprochen und dann vergessen wird. Höhere Qualität, weil ein falscher Prop-Typ, ein vergessenes Pflichtfeld oder ein `null`, das nie hätte `null` bleiben dürfen, gar nicht erst in den Build gelangt. Und klare Grenzen, weil eine typisierte Props- und Event-Signatur unmissverständlich sagt, was hinein- und was herauskommt.\n\nDer Einstieg ist überschaubar. Props als `interface` oder `type`, `children` als `ReactNode` explizit deklarieren, `useState` mit Generic nur dort, wo die Inferenz zu eng wird, die passenden Event-Typen statt `any`, `useRef` mit Null-Check und den Utility-Types Props ableiten statt kopieren. Mit diesen sechs Handgriffen deckt man den Alltag ab. Alles Weitere – generische Komponenten, komplexe Unions, eigene Hooks – ist eine Fortsetzung derselben Idee: Typisiere die Grenzen, an denen sich Verantwortung trifft, sag klar, was du erwartest, und lass den Compiler dafür sorgen, dass sich alle daran halten.\n\n## Weiterführende Quellen\n\n- React TypeScript Cheatsheet: [react-typescript-cheatsheet.netlify.app](https://react-typescript-cheatsheet.netlify.app/) und das Repository [github.com/typescript-cheatsheets/react](https://github.com/typescript-cheatsheets/react)\n- react.dev – „Using TypeScript“: [react.dev/learn/typescript](https://react.dev/learn/typescript)\n- react.dev – Hooks-Referenz: [useState](https://react.dev/reference/react/useState) und [useRef](https://react.dev/reference/react/useRef)\n- TypeScript Handbook – Utility Types: [typescriptlang.org/docs/handbook/utility-types.html](https://www.typescriptlang.org/docs/handbook/utility-types.html)\n- DefinitelyTyped – `@types/react`: [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react)"},{"locale":"de","translation_key":"resilience-muster-timeout-retry-circuit-breaker","slug":"resilience-muster-timeout-retry-circuit-breaker","title":"Resilience-Pattern: Timeout, Retry, Circuit Breaker, Idempotenz","summary":"Warum Resilienz kein Zufall ist: Timeout, Retry mit Backoff und Jitter, Circuit Breaker und Idempotenz als bewusst entworfene Muster gegen die Ausfallmodi verteilter Systeme.","tags":["Software","Architektur"],"published_at":"2024-01-30T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/resilience-muster-timeout-retry-circuit-breaker/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/dc9e51d19111a37e00307bb1e95cca290229c79cd25282489c8606323c1f02c7/resilience-muster-timeout-retry-circuit-breaker-vorlesen.mp3","audio_duration_secs":905,"text":"Ein verteiltes System fällt selten wegen des spektakulären Crashs um. Es fällt um, weil ein Service noch antwortet – nur ein bisschen langsamer als sonst. Dazu ein Aufruf, dem nie jemand eine Zeitgrenze verpasst hat. Ein Client, der brav weiter Anfragen nachschiebt, während die Dependency längst am Boden liegt. So reißt ein einzelner wackliger Baustein das halbe System mit, ohne dass irgendwo ein Prozess abstürzt.\n\nVerteilte Aufrufe scheitern. Über einen längeren Zeitraum betrachtet gehört das zum Normalbetrieb. Das Netzwerk ist mal langsam, ein Knoten wird neu gestartet, eine Datenbank läuft an ihr Limit. Die Frage ist nie, ob ein Remote-Call fehlschlägt, sondern was passiert, wenn er es tut. Und genau hier entscheidet sich, ob ein System resilient ist oder nur so lange stabil aussieht, bis es das erste Mal ernst wird.\n\nResilienz wird entworfen, nicht gehofft. Vier Muster prüfe ich bei verteilten Aufrufen: Timeout, Retry, Circuit Breaker und Idempotenz. Nicht jeder Call braucht alle vier; die Wahl hängt von Fehlerbild, Kosten und Semantik der Operation ab. Der TypeScript-Code weiter unten ist illustrativ – es geht um die Mechanik dahinter, nicht um eine produktionsfertige Bibliothek.\n\nDie Muster unterscheiden sich vor allem durch den Fehlerzustand, auf den sie reagieren. Ihre Namen allein sagen noch nicht, ob sie an einer Grenze sinnvoll sind.\n\n::::comparison{title=\"Resilience-Pattern nach Fehlerfrage\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Timeout\"}\n- Frage · Wie lange darf ein einzelner Versuch dauern?\n- Wirkung · begrenzt blockierte Ressourcen\n:::\n:::side{label=\"Retry\"}\n- Frage · Ist der Fehler vorübergehend und der Versuch sicher wiederholbar?\n- Wirkung · wiederholt mit begrenztem Backoff und Jitter\n:::\n:::side{label=\"Circuit Breaker\"}\n- Frage · Soll ein erkennbar gestörtes Ziel weiter belastet werden?\n- Wirkung · unterbricht Aufrufe und prüft später kontrolliert erneut\n:::\n:::side{label=\"Bulkhead\"}\n- Frage · Wie bleibt ein Ausfall auf einen Teil des Systems begrenzt?\n- Wirkung · trennt Ressourcen und Konkurrenzbereiche\n:::\n:::side{label=\"Dead Letter Queue\"}\n- Frage · Was geschieht mit dauerhaft nicht verarbeitbaren Messages?\n- Wirkung · bewahrt Fehlerfälle für Prüfung und gezielte Wiederaufnahme\n:::\n::::\n\nErst die Fehlerfrage macht sichtbar, welche Muster sich ergänzen und welche nur zusätzlichen Verkehr oder versteckte Queues erzeugen würden.\n\n## Die Muster im Überblick\n\nBevor ich in den Code gehe, ein kurzer Überblick. Vier Muster, jedes mit einer klaren Zuständigkeit:\n\n- Ein Timeout begrenzt, wie lange ein einzelner Aufruf warten darf. Ohne Timeout wartet ein Call im Zweifel unendlich – und blockiert dabei einen Thread, eine Connection, einen Slot im Pool.\n- Ein Retry wiederholt einen fehlgeschlagenen Aufruf – aber nur bei transienten Fehlern, nur mit Exponential Backoff und Jitter, und nur mit begrenzter Versuchszahl.\n- Ein Circuit Breaker stoppt weitere Aufrufe an eine erkennbar ausgefallene Dependency, damit man sie nicht endlos weiter hämmert.\n- Idempotenz macht Retries überhaupt erst sicher, indem ein mehrfach gesendeter Aufruf denselben Effekt hat wie ein einziger.\n\nDiese vier können ineinandergreifen, sind aber kein untrennbares Paket. Ein Timeout darf bewusst ohne Retry schnell scheitern. Ein Retry auf eine nicht idempotente Operation kann Doppeleffekte produzieren. Ein Circuit Breaker braucht ein verwertbares Fehlersignal, das häufig aus einem Timeout stammt. Zusammengesetzt werden nur die Muster, die zum jeweiligen Aufruf passen.\n\n## Timeout: nie unendlich warten\n\nDer teuerste Timeout ist der, den es nicht gibt. Ein Remote-Call ohne Zeitgrenze ist nicht langsam, er ist potenziell unendlich. Und Unendlichkeit ist ein Ausfallmodus: Threads stauen sich, Connection-Pools laufen leer, und ein Service, der eigentlich nur auf einen langsamen Downstream wartet, wird selbst unerreichbar.\n\nWichtig ist die Unterscheidung zwischen Connection-Timeout (wie lange darf der Verbindungsaufbau dauern) und Request-Timeout (wie lange darf die gesamte Antwort dauern). Beide gehören gesetzt. Und beide gehören zum jeweiligen Aufruf, nicht global auf einen Wert genagelt – ein Health-Check hat eine andere Toleranz als ein Report-Export.\n\nIn der Praxis kapsle ich das in einen kleinen Wrapper. `Promise.race` gegen einen Timer, plus ein `AbortController`, damit die unterliegende Operation auch wirklich abgebrochen wird und nicht im Hintergrund weiterläuft:\n\n```ts\nexport async function withTimeout<T>(\n  fn: (signal: AbortSignal) => Promise<T>,\n  timeoutMs: number,\n): Promise<T> {\n  const controller = new AbortController();\n  const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n  try {\n    return await fn(controller.signal);\n  } finally {\n    clearTimeout(timer);\n  }\n}\n\n// usage: the signal is forwarded to fetch so the socket is released\nconst result = await withTimeout(\n  (signal) => fetch(\"https://payments.internal/charge\", { signal }),\n  2_000,\n);\n```\n\nDer `AbortSignal` ist der Teil, den man leicht vergisst. Ein `Promise.race`, das nur das Warten abbricht, aber die HTTP-Verbindung offen lässt, hat das Problem nur verschoben: Der Socket bleibt belegt. Erst das durchgereichte Signal gibt die Ressource frei.\n\nEine subtile Wechselwirkung, auf die Marc Brooker in der AWS Builders' Library hinweist: Ein zu niedrig gewählter Timeout kann selbst zum Auslöser für Retry-Storms werden. Wenn die reguläre Latenz gelegentlich über der Timeout-Grenze liegt, interpretiert der Client gesunde Antworten als Fehler und wiederholt – und erzeugt damit genau die Last, die den Server dann wirklich umkippt. Timeouts setzt man an der realen Latenzverteilung aus, nicht am Wunschdenken.\n\n## Retry: Backoff und Jitter, aber mit Verstand\n\nRetry ist das Muster, das am schnellsten nach hinten losgeht. Die naive Variante – \"bei Fehler sofort nochmal, und nochmal, und nochmal\" – hat mit Resilienz nichts zu tun. Sie ist eine Lastwaffe gegen den eigenen Downstream. Ein Server, der gerade unter Druck steht, bekommt durch synchrone Wiederholungen aller Clients erst recht den Rest.\n\nDrei Zutaten machen Retry brauchbar. **Exponential Backoff**: Die Wartezeit wächst mit jedem Versuch (`base * 2^attempt`), damit ein überlasteter Service Luft bekommt. Ein **Cap**: Die Wartezeit läuft nicht ins Unendliche, sondern gegen eine Obergrenze. Und **Jitter**: eine Zufallskomponente, die verhindert, dass alle Clients ihre Retries auf dieselbe Millisekunde ausrichten und synchronisierte Lastspitzen erzeugen.\n\nFür den Jitter gibt es mehrere Varianten – Marc Brooker hat sie 2015 im AWS Architecture Blog gegeneinander gestellt: Full Jitter, Equal Jitter, Decorrelated Jitter. Die praktische Empfehlung aus dieser Analyse ist meist Full Jitter, weil es die Wiederholungen am gleichmäßigsten über das Zeitfenster streut. Die Formel ist angenehm schlicht:\n\n```ts\ntype RetryOptions = {\n  maxAttempts: number;\n  baseDelayMs: number;\n  capMs: number;\n  isRetryable: (error: unknown) => boolean;\n};\n\nexport async function retryWithBackoff<T>(\n  fn: () => Promise<T>,\n  opts: RetryOptions,\n): Promise<T> {\n  let lastError: unknown;\n\n  for (let attempt = 0; attempt < opts.maxAttempts; attempt++) {\n    try {\n      return await fn();\n    } catch (error) {\n      lastError = error;\n      if (!opts.isRetryable(error) || attempt === opts.maxAttempts - 1) {\n        throw error;\n      }\n\n      // full jitter: random point in the exponentially growing window\n      const window = Math.min(opts.capMs, opts.baseDelayMs * 2 ** attempt);\n      const delay = Math.random() * window;\n      await new Promise((resolve) => setTimeout(resolve, delay));\n    }\n  }\n\n  throw lastError;\n}\n```\n\nDer `isRetryable`-Callback ist bewusst nach außen gezogen. Nicht jeder Fehler ist wiederholbar. Ein `503 Service Unavailable`, ein Verbindungsabbruch oder ein Timeout kann transient sein. Ein unveränderter `400 Bad Request` bleibt dagegen falsch. Auch `409 Conflict` ist kein pauschales Nein: Nach erneutem Lesen, neuer Versionsnummer oder angepasster Operation kann ein weiterer Versuch sinnvoll sein; die identische Anfrage blind zu wiederholen meist nicht. Retry-Entscheidungen brauchen deshalb Fehlercode, Operation und verbleibendes Zeitbudget.\n\nDie AWS Well-Architected-Guidance bringt das unter REL05-BP03 (\"Control and limit retry calls\") auf den Punkt: Backoff, Jitter und eine maximale Versuchszahl gehören zusammen. Die AWS-SDKs setzen genau das in ihren Retry-Modi `standard` und `adaptive` schon eingebaut um – wer auf dieser Ebene arbeitet, sollte nicht darüber noch eine zweite eigene Retry-Schleife legen. Womit wir beim gefährlichsten Fallstrick wären.\n\n## Der Retry-Storm\n\nRetries stapeln sich. Der Client wiederholt, das SDK darunter wiederholt, das API-Gateway davor wiederholt. Drei Schichten mit je drei Versuchen sind nicht drei, sondern bis zu siebenundzwanzig Aufrufe für eine einzige Nutzeraktion. Wenn dann noch der Jitter fehlt und alle Clients gleichzeitig loslegen, entsteht ein Retry-Storm: multiplikative Last, die exakt in dem Moment auf den Server trifft, in dem er sie am wenigsten verträgt.\n\nDas Gegenmittel ist Disziplin, nicht mehr Technik. Für jede Aufrufkette sollte klar sein, welche Schicht den Retry besitzt und welches gemeinsame Zeit- und Versuchsbudget gilt. Niedrige Schichten wie ein SDK dürfen eigene Wiederholungen haben, wenn die darüberliegenden Schichten sie kennen und nicht unkoordiniert vervielfachen. Jitter und Cap gehören an die zuständige Stelle. Wer viele Clients koordiniert, ergänzt ein Retry-Budget oder clientseitiges Rate-Limiting per Token-Bucket.\n\n## Circuit Breaker: aufhören zu hämmern\n\nRetry mit Backoff federt kurze Störungen ab. Aber was, wenn eine Dependency nicht kurz hustet, sondern richtig ausfällt – für Minuten? Dann ist jeder weitere Versuch verschwendete Last, verschwendete Latenz und verschwendete Ressource. Genau hier setzt der Circuit Breaker an, ein Muster, das Michael Nygard in \"Release It!\" geprägt hat.\n\nDie Idee stammt aus der Elektrotechnik: Ein Sicherungsschalter unterbricht den Stromkreis, bevor die Leitung durchbrennt. Übertragen auf Software heißt das – wenn eine Dependency erkennbar am Boden liegt, schaltet der Breaker auf und lässt Aufrufe sofort scheitern (Fail Fast), statt sie in ein totes Timeout laufen zu lassen. Der Breaker kennt drei Zustände:\n\n```mermaid\nstateDiagram-v2\n    [*] --> CLOSED\n    CLOSED --> OPEN: Fehler >= Schwelle\n    OPEN --> HALF_OPEN: Cooldown abgelaufen\n    HALF_OPEN --> CLOSED: Probe erfolgreich\n    HALF_OPEN --> OPEN: Probe scheitert\n```\n\nIm Zustand **CLOSED** läuft alles normal, der Breaker zählt nur die Fehler mit. Überschreitet die Fehlerzahl eine Schwelle, springt er auf **OPEN**: Aufrufe werden nicht mehr durchgelassen, sondern scheitern sofort – der Client bekommt schnell eine Antwort oder einen Fallback statt einer hängenden Verbindung. Nach einem Cooldown geht der Breaker in **HALF_OPEN** und lässt eine einzelne Probeanfrage durch. Klappt sie, schließt er wieder (CLOSED). Scheitert sie, öffnet er erneut und wartet den nächsten Cooldown ab.\n\nAls kleine State Machine ist das überschaubar:\n\n```ts\ntype BreakerState = \"CLOSED\" | \"OPEN\" | \"HALF_OPEN\";\n\nexport class CircuitBreaker {\n  private state: BreakerState = \"CLOSED\";\n  private failureCount = 0;\n  private openedAt = 0;\n\n  constructor(\n    private readonly failureThreshold: number,\n    private readonly cooldownMs: number,\n  ) {}\n\n  async execute<T>(fn: () => Promise<T>): Promise<T> {\n    if (this.state === \"OPEN\") {\n      if (Date.now() - this.openedAt < this.cooldownMs) {\n        throw new Error(\"circuit is open\");\n      }\n      this.state = \"HALF_OPEN\";\n    }\n\n    try {\n      const result = await fn();\n      this.onSuccess();\n      return result;\n    } catch (error) {\n      this.onFailure();\n      throw error;\n    }\n  }\n\n  private onSuccess(): void {\n    this.failureCount = 0;\n    this.state = \"CLOSED\";\n  }\n\n  private onFailure(): void {\n    this.failureCount++;\n    if (this.state === \"HALF_OPEN\" || this.failureCount >= this.failureThreshold) {\n      this.state = \"OPEN\";\n      this.openedAt = Date.now();\n    }\n  }\n}\n```\n\nAWS ordnet den Circuit Breaker in Well-Architected unter REL05-BP01 ein – \"graceful degradation\", also das Verwandeln einer harten Abhängigkeit in eine weiche. Statt dass ein ausgefallener Empfehlungsdienst die ganze Produktseite mitreißt, liefert der Breaker im OPEN-Zustand einen Fallback (etwa eine statische Liste) und die Seite bleibt bedienbar. Das ist der eigentliche Gewinn: nicht die perfekte Antwort, sondern eine akzeptable, die das Gesamtsystem am Leben hält.\n\nIn Produktion muss man das nicht selbst schreiben – etablierte Bibliotheken wie `opossum` für Node.js, Polly für .NET oder resilience4j für Java bringen das mit, inklusive Metrics und Half-Open-Sampling. Der Code oben ist illustrativ, damit die Zustandslogik sichtbar bleibt.\n\n## Idempotenz: was Retries erst sicher macht\n\nJetzt schließt sich der Kreis zum Retry. Ein Retry ist nur dann harmlos, wenn die wiederholte Operation denselben Effekt hat wie eine einzelne. Genau das ist Idempotenz. Bei einem Lesezugriff ist das trivial – zweimal `GET` schadet nicht. Bei einem Write wird es ernst: Wenn der erste Versuch einer Zahlung eigentlich durchging, die Antwort aber im Timeout verloren ging, dann bucht der Retry ein zweites Mal ab. Der Kunde zahlt doppelt.\n\nDie HTTP-Semantik gibt hier einen Rahmen vor: `GET`, `PUT` und `DELETE` gelten als idempotent, `POST` grundsätzlich nicht. Idempotent bedeutet denselben beabsichtigten Effekt bei Wiederholung; Statuscode oder Antwort müssen dabei nicht identisch sein. Wo man Operationen entsprechend entwerfen kann – ein `PUT` auf eine natürliche ID statt eines `POST`, das jedes Mal eine neue Ressource erzeugt –, sollte man das tun. Wo das nicht geht, etwa bei „charge“ oder „send“, hilft ein expliziter **Idempotency-Key**. Der Client generiert pro fachlicher Operation einen eindeutigen Schlüssel und schickt ihn mit; der Server merkt sich Schlüssel plus Ergebnis und verhindert damit den zweiten Side Effect.\n\nDas Muster ist seit Jahren etabliert – Stripe etwa nutzt einen `Idempotency-Key`-Header. Ein IETF-Standard war zum damaligen Zeitpunkt lediglich ein Internet-Draft (`draft-ietf-httpapi-idempotency-key-header`), aber das Muster selbst funktioniert unabhängig davon. Serverseitig sieht der Kern so aus:\n\n```ts\ntype Result = { status: string; id: string };\n\ninterface IdempotencyStore {\n  get(key: string): Promise<Result | undefined>;\n  set(key: string, value: Result): Promise<void>;\n}\n\nexport async function handleRequest(\n  key: string,\n  op: () => Promise<Result>,\n  store: IdempotencyStore,\n): Promise<Result> {\n  const existing = await store.get(key);\n  if (existing) {\n    // key already processed: return the stored result, no second side effect\n    return existing;\n  }\n\n  const result = await op();\n  await store.set(key, result);\n  return result;\n}\n```\n\nZwei Details, die in echt zählen. Erstens braucht der Store einen Ablauf (TTL) – Idempotency-Keys ewig aufzuheben ist weder nötig noch billig. Zweitens gibt es ein Nebenläufigkeitsproblem: Wenn zwei Retries fast gleichzeitig ankommen, kann der zweite den `get` abschließen, bevor der erste seinen `set` schreibt. In Produktion löst man das mit einer atomaren Reservierung des Keys (etwa einem bedingten Insert), nicht mit dem naiven Get-dann-Set oben. Der Code zeigt das Prinzip, nicht die produktionsfertige Sperre.\n\n## Bulkhead und DLQ, kurz\n\nZwei Muster runden das Bild ab, ohne dass ich sie hier ausbreite. Das **Bulkhead** – benannt nach den Schotten im Schiffsrumpf – isoliert Ressourcen, damit ein überlasteter Pfad nicht das ganze System flutet. Getrennte Connection-Pools oder Thread-Pools pro Downstream sorgen dafür, dass eine hängende Dependency nur ihren eigenen Pool erschöpft und nicht alle anderen Aufrufe mit in den Abgrund zieht. Auch das stammt aus \"Release It!\".\n\nUnd die **Dead-Letter-Queue** (DLQ) ist das Auffangbecken für den Fall, dass alle Retries erschöpft sind. Statt eine nicht verarbeitbare Message endlos im Kreis zu drehen oder still zu verlieren, landet sie in einer separaten Queue – zur Inspektion, für einen manuellen Eingriff oder eine spätere Wiederholung. In AWS ist das ein Standardbaustein von SQS und SNS. Wer die Verkettung solcher Schritte sauber orchestrieren will, findet in [Serverless-Workflows mit Step Functions](https://www.mikebild.dev/de/blog/step-functions-serverless-workflows/) den passenden Rahmen, und wie man Last über mehrere Prozesse verteilt, habe ich in [child_process und Skalierung](https://www.mikebild.dev/de/blog/nodejs-child-process-und-skalierung/) beschrieben.\n\n## Fazit\n\nDrei Fehler tauchen in Post-Mortems immer wieder auf. Kein Timeout – ein Call, der unendlich warten darf und dabei Ressourcen bindet. Retry ohne Jitter und Cap – der freundlich gemeinte Wiederholungsversuch, der zum Retry-Storm wird und den schwachen Server endgültig erledigt. Und nicht-idempotente Writes, die wiederholt werden – die Doppelbuchung, die niemand kommen sah.\n\nAlle drei haben eine gemeinsame Wurzel: Resilienz wurde gehofft, nicht entworfen. Die vier Muster – Timeout, Retry, Circuit Breaker, Idempotenz – sind keine Bibliothek, die man importiert, sondern Entscheidungen pro Aufruf. Remote-Calls brauchen eine begründete Zeitgrenze. Wiederholungen brauchen Budget, Backoff und Jitter. Ein Breaker lohnt sich bei Abhängigkeiten, deren anhaltender Ausfall sonst weiter Last und Latenz erzeugt. Ein Idempotency-Key gehört zu Operationen, bei denen Wiederholung möglich und ein doppelter Effekt schädlich ist. So kann ein System unter Last kontrolliert degradieren, statt seinen Ausfall zu vervielfachen.\n\n## Weiterführende Quellen\n\n- [AWS Well-Architected, REL05-BP03 – Control and limit retry calls](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_mitigate_interaction_failure_limit_retries.html)\n- [AWS Well-Architected, REL05-BP01 – Graceful degradation (Circuit Breaker)](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_mitigate_interaction_failure_graceful_degradation.html)\n- [AWS Well-Architected, REL05-BP02 – Throttle requests (Token Bucket)](https://docs.aws.amazon.com/wellarchitected/latest/framework/rel_mitigate_interaction_failure_throttle_requests.html)\n- [AWS Builders' Library – Timeouts, retries, and backoff with jitter (Marc Brooker)](https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/)\n- [AWS Architecture Blog – Exponential Backoff And Jitter](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)\n- [Michael Nygard – Release It! (2. Auflage, 2018)](https://pragprog.com/titles/mnee2/release-it-second-edition/)"},{"locale":"de","translation_key":"graphql-subscriptions-ueber-sse","slug":"graphql-subscriptions-ueber-sse","title":"GraphQL-Subscriptions über SSE: Echtzeit ohne WebSocket-Zwang","summary":"Subscriptions brauchen keinen WebSocket. Server-Sent Events genügen für den einseitigen Server-zu-Client-Kanal, während Query und Mutation normales HTTP bleiben, und das Schema entscheidet, was überhaupt ein Domänen-Event ist.","tags":["Software","GraphQL","API"],"published_at":"2024-01-12T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/graphql-subscriptions-ueber-sse/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/848937170bf0bd2502a000d2ed977574598eda253259c5a5605bd889b855826e/graphql-subscriptions-ueber-sse-vorlesen.mp3","audio_duration_secs":979,"text":"Wer für einen einseitigen Update-Fluss einen WebSocket aufzieht, holt sich ein zweites Protokoll in den Betrieb: Upgrade-Handshake, Sticky Sessions, Proxys und Load-Balancer, die davon wissen müssen, dazu Reconnect und Heartbeat in eigener Verantwortung. Der Anlass dafür ist meist bescheiden – eine Bestellung wechselt ihren Status, eine Kachel im Dashboard aktualisiert sich ohne Reload. Der Anlass ist nach einem Sprint erledigt, der Transport bleibt und will jahrelang betrieben werden.\n\nHinter „Echtzeit“ steht deshalb selten ein Syntaxproblem und fast immer eine Betriebsentscheidung. Ein bidirektionaler Vollduplex-Kanal, wie ihn ein WebSocket öffnet, ist kein Feature, das man geschenkt bekommt; er ist eine eigene Betriebsklasse mit eigenem Protokoll, eigenem Handshake und eigenen Ausfallmustern. Deshalb geht es in diesem Text weniger darum, wie man Subscriptions anbindet, als um die Entscheidung davor: SSE, WebSocket oder schlichtes Polling – entlang von Betriebskosten, Komplexität und Skalierung entschieden, nicht entlang der Frage, was gerade modern klingt.\n\nDabei schreiben GraphQL-Subscriptions den WebSocket gar nicht vor. Die Spezifikation ist an dieser Stelle transport-agnostisch: Sie sagt, dass eine Subscription einen Event Stream liefert – nicht, über welche Leitung dieser Strom fließt. Und für den häufigen Fall „Server informiert Client“ gibt es einen Kandidaten, der seit Jahren in jedem Browser eingebaut ist und über gewöhnliches HTTP läuft: Server-Sent Events.\n\n## Query und Mutation bleiben, wie sie sind\n\nBevor es um den Event Stream geht, lohnt sich ein Blick auf das, was sich gar nicht ändert. Eine Query holt Daten, eine Mutation verändert Zustand – beide sind Anfrage und Antwort, ein Request, eine Response, fertig. Das ist normales HTTP, meist ein `POST /graphql`. Nichts an einer Subscription-Fähigkeit zwingt dazu, daran etwas zu drehen. Nur der dritte Operationstyp, die Subscription, braucht einen offenen Kanal, über den der Server nach und nach Events schickt.\n\nGenau hier setzt Server-Sent Events an. SSE ist ein einseitiger Kanal vom Server zum Client über gewöhnliches HTTP. Der Server antwortet mit dem Content-Type `text/event-stream` und lässt die Verbindung offen; der Client öffnet sie über die eingebaute `EventSource`-Schnittstelle. Der Browser übernimmt dabei einiges, was man bei einer selbstgebauten Lösung mühsam nachrüsten müsste: Er reconnectet automatisch, wenn die Verbindung abreißt, und schickt beim Wiederverbinden die zuletzt gesehene Event-ID im Header `Last-Event-ID` mit, damit der Server dort weitermachen kann, wo es abgerissen ist.\n\n```mermaid\nflowchart LR\n  subgraph Client\n    UI[Browser-App]\n  end\n  subgraph Server\n    GQL[GraphQL-Server]\n  end\n  UI -- \"HTTP POST /graphql<br/>Query &amp; Mutation\" --> GQL\n  GQL -- \"HTTP Antwort (JSON)\" --> UI\n  GQL -- \"text/event-stream<br/>Events via EventSource\" --> UI\n```\n\nDas Bild zeigt den Kern: zwei Kanäle, ein Transport. Query und Mutation gehen den bekannten Weg über Request und Response. Der Event Stream nutzt dieselbe HTTP-Infrastruktur, nur bleibt die Antwort offen und tröpfelt Events nach. Es gibt keinen Protokollwechsel, kein Upgrade-Handshake, keine gesonderte Behandlung durch Proxys, die WebSocket-Frames nicht kennen.\n\n## Der Serverteil: ein AsyncIterable aus PubSub\n\nAuf der Serverseite ist ein Subscription-Resolver kein gewöhnlicher Feld-Resolver. Statt einer Funktion, die einen Wert zurückgibt, ist es ein Objekt mit einer `subscribe`-Methode, die ein `AsyncIterable` liefert. Aus diesem Iterable zieht der GraphQL-Server die Events und schickt sie an den passenden Client. Das gebräuchliche Werkzeug dafür ist das Paket `graphql-subscriptions`, zum jetzigen Zeitpunkt in Version 2.0.0. Es bringt eine `PubSub`-Klasse mit, deren `asyncIterator(topic)` genau so ein Iterable erzeugt.\n\n```ts\nimport { PubSub, withFilter } from 'graphql-subscriptions';\n\nconst pubsub = new PubSub();\n\nconst ORDER_STATUS_CHANGED = 'ORDER_STATUS_CHANGED';\n\nconst resolvers = {\n  Subscription: {\n    orderStatusChanged: {\n      subscribe: withFilter(\n        () => pubsub.asyncIterator(ORDER_STATUS_CHANGED),\n        (payload, variables) =>\n          payload.orderStatusChanged.customerId === variables.customerId,\n      ),\n    },\n  },\n  Mutation: {\n    advanceOrder: (_root, { id }) => {\n      const orderStatusChanged = advanceOrderInStore(id);\n      pubsub.publish(ORDER_STATUS_CHANGED, { orderStatusChanged });\n      return orderStatusChanged;\n    },\n  },\n};\n```\n\nZwei Dinge sind hier wichtig. Erstens der `withFilter`-Helfer: Er nimmt die Iterator-Function und eine Prädikatfunktion, die pro Event entscheidet, ob es diesen Abonnenten überhaupt betrifft. So bekommt jeder Kunde nur die Statuswechsel seiner eigenen Bestellungen, obwohl alle über dasselbe Topic laufen. Zweitens die Publish-Stelle in der Mutation: Wenn sich fachlich etwas ereignet – hier: eine Bestellung rückt weiter –, wird das Event mit `pubsub.publish` in den Strom gegeben. Der `subscribe`-Resolver und die Mutation sind über das Topic entkoppelt; die Mutation weiß nichts davon, wer gerade zuhört.\n\nEin Hinweis, der in der Praxis oft zu spät auffällt: Die mitgelieferte `PubSub`-Implementierung hält ihren Zustand im Arbeitsspeicher und funktioniert nur innerhalb eines einzelnen Prozesses. Sobald mehrere Server-Instanzen hinter einem Load-Balancer stehen, verpuffen Events – eine Instanz published, aber die Abonnenten hängen an einer anderen. Für den Produktivbetrieb braucht es dann ein externes Backend, etwa eine Redis-gestützte Variante, die das Publish über die Prozessgrenze hinweg verteilt. Für die lokale Entwicklung und den Einstieg genügt die eingebaute Variante völlig.\n\n## Der SSE-Endpoint: der Strom nach draußen\n\nDamit die Events aus dem Iterable auch beim Browser ankommen, braucht es einen Endpoint, der den Strom als `text/event-stream` ausliefert. Konzeptionell sieht das in Express so aus:\n\n```ts\napp.get('/graphql/stream', (req, res) => {\n  res.set({\n    'Content-Type': 'text/event-stream',\n    'Cache-Control': 'no-cache',\n    Connection: 'keep-alive',\n  });\n  res.flushHeaders();\n\n  const iterator = pubsub.asyncIterator(ORDER_STATUS_CHANGED);\n\n  (async () => {\n    for await (const event of iterator) {\n      res.write(`event: next\\n`);\n      res.write(`data: ${JSON.stringify(event)}\\n\\n`);\n    }\n  })();\n\n  req.on('close', () => {\n    if (typeof iterator.return === 'function') iterator.return();\n  });\n});\n```\n\nDas Format eines SSE-Frames ist bewusst schlicht: Zeilen mit Feldnamen und Doppelpunkt. Das Feld `data:` trägt die Nutzlast, hier das serialisierte Event; mehrere `data:`-Zeilen würde der Browser mit einem Zeilenumbruch zusammenfügen. Mit `event:` benennt man den Event-Typ, sodass der Client gezielt darauf hören kann; ohne diese Zeile landet alles beim allgemeinen `onmessage`-Handler. Das Feld `id:` setzt die Event-ID, die der Browser bei einem Reconnect als `Last-Event-ID` zurückschickt, und `retry:` gibt in Millisekunden vor, wie lange der Browser vor einem Wiederverbindungsversuch warten soll. Ein Frame endet mit einer Leerzeile, also einem doppelten `\\n`. Zeilen, die mit einem Doppelpunkt beginnen, sind Kommentare und eignen sich als Heartbeat, um Zwischenschichten davon abzuhalten, eine ruhige Verbindung zu kappen.\n\nDer `req.on('close')`-Teil ist kein Beiwerk. Wenn der Client die Verbindung schließt, muss der Iterator sauber beendet werden, sonst sammeln sich Abonnements an und der Prozess leckt Ressourcen. Dieses Aufräumen ist die Stelle, an der eine SSE-Anbindung entweder solide oder brüchig wird.\n\n## Der Client: EventSource, mehr nicht\n\nAuf der Clientseite ist die Arbeit erstaunlich gering, weil der Browser den größten Teil übernimmt:\n\n```js\nconst es = new EventSource('/graphql/stream', { withCredentials: true });\n\nes.addEventListener('next', (e) => {\n  const payload = JSON.parse(e.data);\n  render(payload.orderStatusChanged);\n});\n\nes.onerror = () => {\n  // The browser reconnects on its own; the retry: field controls the interval.\n};\n```\n\nKein manuelles Wiederverbinden, kein Timer, kein eigenes Heartbeat-Protokoll. Fällt die Verbindung aus, versucht der Browser von sich aus, sie erneut aufzubauen, und schickt die zuletzt empfangene Event-ID mit. Die Option `withCredentials` sorgt dafür, dass Cookies über die Origin-Grenze hinweg mitgeschickt werden – praktisch, wenn die Authentifizierung über ein Session-Cookie läuft und der Endpoint weiß, wer da gerade lauscht. Wer die Autorisierung im GraphQL-Server sauber in den Ausführungskontext legt, findet in [GraphQL-Auth im Context](https://www.mikebild.dev/de/blog/graphql-auth-im-context/) das passende Muster; für den SSE-Endpoint gilt dieselbe Logik – die Identität wird an der HTTP-Stelle festgestellt und steht dem Resolver zur Verfügung.\n\n```mermaid\nsequenceDiagram\n  participant B as Browser (EventSource)\n  participant S as GraphQL-Server\n  participant P as PubSub\n  B->>S: HTTP POST advanceOrder (Mutation)\n  S->>P: pubsub.publish(topic, payload)\n  P-->>S: asyncIterator liefert Event\n  S-->>B: data:-Frame (event: next)\n  Note over B,S: Verbindung bricht ab\n  B->>S: Reconnect mit Last-Event-ID\n  S-->>B: Ereignisse ab letzter ID\n```\n\n## Das Schema ist ein Fachmodell, kein Ereignisrohr\n\nDer technische Teil ist damit umrissen, aber der wichtigere Punkt aus der Projektpraxis ist ein anderer. Sobald ein einfacher Weg da ist, Events an den Client zu schicken, wächst die Versuchung, alles Mögliche durch Subscriptions zu pumpen: jeden Tastendruck, jeden internen Tick, jede Log-Zeile. Das Schema ist aber ein Fachmodell und keine Sammelstelle für technische Signale. Eine Subscription sollte ein Event abbilden, das fachlich etwas bedeutet – „Bestellung hat den Status gewechselt“, „Kommentar wurde hinzugefügt“, „Zahlung ist eingegangen“. Ein `orderStatusChanged` sagt einem Konsumenten etwas über die Domäne. Ein `serverTick` oder `internalMetric` sagt ihm nichts, was er im Schema suchen würde.\n\nDieselbe Modellierungsdisziplin, die man bei Listen und Blättern anlegt – siehe die Überlegungen in [GraphQL-Paginierung und Connections](https://www.mikebild.dev/de/blog/graphql-paginierung-und-connections/) –, gilt hier genauso: Das Schema beschreibt die Sprache der Domäne, nicht die Interna der Übertragung. Wenn ein Event nicht Teil dieser Sprache ist, gehört es nicht in eine Subscription.\n\n## Die falsche Abstraktion vermeiden\n\nDamit sind wir bei der eigentlichen Entscheidung, und die fällt eine Ebene tiefer als GraphQL: in der Architektur. SSE, WebSocket und Messaging lösen unterschiedliche Probleme, und die häufigste Fehlerquelle ist, das eine als Ersatz für das andere zu behandeln.\n\n- Server-Sent Events sind einseitig vom Server zum Client, laufen HTTP-nativ, reconnecten von selbst und transportieren ausschließlich Text in UTF-8. Sie passen genau dann, wenn die Oberfläche Live-Updates anzeigen soll: Statuswechsel, Benachrichtigungen, ein sich aktualisierendes Dashboard.\n- WebSockets sind bidirektional und haben ein eigenes Protokoll mit eigenem Handshake. Sie sind die richtige Wahl, wenn der Client selbst laufend Daten in Echtzeit an den Server schickt – Chat, kollaboratives Bearbeiten, ein Spielzustand, alles mit dichtem Rückkanal.\n- Messaging und Broker wie Kafka, AMQP oder Redis lösen Integration zwischen Systemen. Sie bieten Persistenz, Fan-out und Entkopplung im Backend. Eine GraphQL-Subscription ersetzt das nicht. Sie deckt den letzten Meter zum Browser ab; das Nervensystem zwischen den Diensten bleibt Aufgabe des Brokers.\n\nWer diese drei sauber trennt, baut nichts Falsches. Wer sie vermischt – etwa einen WebSocket aufzieht, um einen rein einseitigen Update-Fluss zu bedienen, oder Subscriptions zweckentfremdet, um Dienste zu integrieren –, zahlt später mit Komplexität, die kein Feature rechtfertigt.\n\n## Entscheidungsrahmen: SSE, WebSocket oder Polling\n\nDie saubere Trennung der Transporte ist das eine; im Projekt muss ich mich am Ende für einen entscheiden, und dafür hilft ein Rahmen entlang von drei Achsen: Betriebskosten, Komplexität und Skalierung. Diese drei Fragen beantworten die Transportwahl zuverlässiger als jede Feature-Liste, weil sie nach dem Preis im Betrieb fragen und nicht nach dem Funktionsumfang.\n\nPolling ist der ehrliche Ausgangspunkt, den man zu schnell übergeht. Der Client fragt in einem Intervall „gibt es etwas Neues?“, und das ist über HTTP, Caching und Load-Balancer hinweg das am besten verstandene Muster überhaupt. Die Betriebskosten liegen konzeptionell nahe null, doch die Last auf dem Server wächst linear mit Client-Zahl und Frequenz und steckt die meiste Arbeit in leere Antworten. Die Komplexität ist minimal, weil es keinen offenen Kanal gibt, der aufräumen oder reconnecten müsste, und die Skalierung ist horizontal trivial, weil jede Anfrage für sich steht. Für Aktualisierungen im Sekunden- bis Minutenbereich, bei denen etwas Latenz niemandem wehtut, ist Polling oft die wirtschaftlich richtige Antwort – und die Option, die man zuerst prüfen sollte, bevor man etwas Aufwendigeres baut.\n\nSSE sitzt in der Mitte und trifft genau den Fall „Server informiert Client zeitnah“. Die Betriebskosten bestehen aus einer offenen HTTP-Verbindung pro Client, die aber HTTP-nativ bleibt und keine Sonderbehandlung in der Infrastruktur verlangt. Die Komplexität ist gering auf dem Client, weil `EventSource` Reconnect und `Last-Event-ID` mitbringt; auf dem Server liegt der Aufwand vor allem im sauberen Aufräumen der Ströme. Die Skalierung hat ihre Kostenstelle in den vielen offenen Verbindungen, und der Zustand des PubSub muss über Instanzgrenzen verteilt werden, sobald mehr als ein Prozess läuft. Der Gewinn gegenüber Polling ist niedrige Latenz ohne Leerlauf; der Preis ist der offene Kanal, den man betreiben muss.\n\nWebSocket ist die teuerste Klasse und rechtfertigt sich erst mit einem echten Rückkanal. Die Betriebskosten umfassen ein eigenes Protokoll mit Handshake, Sticky Sessions und Proxys, die das Upgrade kennen müssen. Die Komplexität steigt, weil Reconnect, Heartbeat und Zustandswiederherstellung bei mir liegen, nicht beim Browser. Die Skalierung ist am schwersten, weil langlebige, zustandsbehaftete Verbindungen sich horizontal am wenigsten leicht verteilen lassen. Dieser Aufwand zahlt sich aus, wenn der Client selbst laufend in Echtzeit sendet – Chat, kollaboratives Bearbeiten, Spielzustand. Für einen einseitigen Update-Fluss ist er Aufwand ohne Gegenwert.\n\nDas Entscheidungskriterium ist damit knapp: erst prüfen, ob Polling reicht; wenn zeitnahe Server-zu-Client-Updates ohne Rückkanal gebraucht werden, SSE; und nur bei dichtem, bidirektionalem Verkehr WebSocket. Wer in dieser Reihenfolge fragt, wählt den billigsten Transport, der die Anforderung trägt, statt den mächtigsten, den man kennt – und genau diese Reihenfolge trennt eine Betriebsentscheidung von einer Geschmacksfrage.\n\n## Woher die SSE-Idee kommt – und was heute gilt\n\nDie Verbindung von GraphQL und SSE ist nicht neu, und ihre Geschichte hilft, den heutigen Stand richtig einzuordnen. In der Frühzeit von Apollo Client, der 1.x-Ära, gab es das Paket `subscriptions-transport-sse`. Es wurde damals in einen Apollo-Client über das Konzept `networkInterface` eingehängt:\n\n```js\n// HISTORICAL — Apollo Client 1.x, not today's API.\nimport {\n  SubscriptionClient,\n  addGraphQLSubscriptions,\n} from 'subscriptions-transport-sse';\n\nconst sseClient = new SubscriptionClient('/subscriptions');\nconst client = new ApolloClient({\n  networkInterface: addGraphQLSubscriptions(httpInterface, sseClient),\n});\n```\n\nDas ist ausdrücklich Legacy und gehört in kein neues Projekt. Sowohl `networkInterface` als auch der damalige `SubscriptionManager` – der Vorläufer des heutigen Musters mit `PubSub.asyncIterator` – sind Konzepte einer längst abgelösten Generation. Ich zeige das Fragment nur, um die Herkunft der Idee sichtbar zu machen: SSE als Transport für GraphQL-Events ist ein alter Gedanke, kein experimenteller.\n\nFür die WebSocket-Seite lohnt ein Blick auf den aktuellen Stand, weil er die Transportfrage einrahmt. Das früher übliche `subscriptions-transport-ws` gilt inzwischen als nicht mehr gepflegt; sein Repository trägt seit Längerem einen Deprecation-Hinweis und wird nicht mehr aktiv weiterentwickelt. Der empfohlene Nachfolger für den WebSocket-Weg ist `graphql-ws` mit einem anderen Subprotokoll, das zum alten nicht kompatibel ist. Das ist hier nur Kontext: `graphql-ws` ist die Antwort, wenn man tatsächlich einen WebSocket braucht. Es steht nicht in Konkurrenz zu SSE; es deckt den anderen, den bidirektionalen Fall ab.\n\n## Was ich aus der Praxis mitgebe\n\nWenn jemand in einem Anforderungsgespräch „Echtzeit“ sagt, ist die erste nützliche Rückfrage nicht „WebSocket oder SSE?“, sondern „In welche Richtung fließen die Daten, und wie schnell müssen sie ankommen?“. Meist fließen sie vom Server zum Client und dürfen etwas Latenz vertragen, und dann ist Server-Sent Events die ruhigere, einfacher zu betreibende Lösung: gewöhnliches HTTP, eingebauter Reconnect, keine Sonderbehandlung in der Infrastruktur. Query und Mutation bleiben unangetastet, nur der Event Stream bekommt seinen eigenen, offenen Kanal. Serverseitig liefert der `subscribe`-Resolver ein `AsyncIterable` aus einer PubSub, Events kommen per `publish` hinein, und `withFilter` sorgt dafür, dass jeder nur bekommt, was ihn angeht.\n\nDer Gewinn dieser Zuordnung ist im Projektalltag zu spüren. Wer den billigsten tragfähigen Transport wählt, verkürzt die Zyklen bis zum funktionierenden Live-Update, weil die halbe Infrastrukturdiskussion entfällt, mit der dieser Text begann. Er senkt die Reibung im Betrieb, weil ein HTTP-nativer Strom weniger Sonderfälle in Proxys, Load-Balancern und Deployments erzeugt. Und er hebt die Qualität, weil das Schema ein Fachmodell bleibt und nur Events trägt, die in der Sprache der Domäne etwas bedeuten. Zwei Grenzen behalte ich dabei bewusst im Blick: Die eingebaute PubSub hält ihren Zustand im Speicher und braucht über mehrere Instanzen hinweg ein externes Backend, und die Transportwahl bleibt eine schlichte Zuordnung – Polling, wenn Latenz erlaubt ist, SSE für den einseitigen Weg zum Client, WebSocket nur für den echten Rückkanal. Diese klaren Grenzen tragen die kürzeren Zyklen und die geringere Reibung überhaupt erst.\n\n## Weiterführende Quellen\n\n- MDN – Using server-sent events: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events\n- MDN – EventSource: https://developer.mozilla.org/en-US/docs/Web/API/EventSource\n- graphql-subscriptions (README/API): https://github.com/apollographql/graphql-subscriptions\n- graphql-subscriptions (npm): https://www.npmjs.com/package/graphql-subscriptions\n- Apollo Server – Subscriptions: https://www.apollographql.com/docs/apollo-server/data/subscriptions\n- subscriptions-transport-ws (Legacy/archiviert): https://github.com/apollographql/subscriptions-transport-ws\n- subscriptions-transport-sse (historischer Anlass): https://github.com/CodeCommission/subscriptions-transport-sse\n- GraphQL Spec: https://spec.graphql.org/"},{"locale":"de","translation_key":"contract-testing-statt-e2e-marathon","slug":"contract-testing-statt-e2e-marathon","title":"Contract Testing statt E2E-Marathon","summary":"Consumer-Driven Contracts prüfen Schnittstellen an der Grenze zwischen Services statt in einer teuren, flaky End-to-End-Suite. Das Ergebnis: ein schnelleres, deterministisches Deploy-Gate und Teams, die unabhängig releasen.","tags":["Software","Delivery"],"published_at":"2023-12-05T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/contract-testing-statt-e2e-marathon/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/c3e0e021c1d8452296598b7a8e47bd924c2fe90bcbbafe885f4344c4f46b2e7d/contract-testing-statt-e2e-marathon-vorlesen.mp3","audio_duration_secs":696,"text":"```text\nFAIL  e2e/checkout.spec.ts\n  ✕ Bestellung abschließen (30014 ms)\n    TimeoutError: waiting for selector \"#order-confirmation\" failed:\n    timeout 30000ms exceeded\n\nTests: 1 failed, 213 passed        Dauer: 46m 08s\n```\n\nDieser Fehlschlag sagt nichts darüber aus, ob der Code kaputt ist. Er sagt, dass irgendwo im hochgefahrenen Gesamtsystem etwas dreißig Sekunden gebraucht hat statt drei – ein Container, der träge startet, eine Animation, ein Netzwerk-Hop. Beim nächsten Lauf ist derselbe Test grün, ohne dass eine Zeile geändert wurde. Genau so verliert eine nächtliche End-to-End-Suite ihre Autorität: Sie beantwortet die Frage, ob heute deployt werden darf, mit einem Wahrscheinlichkeitswurf, und irgendwann klickt das Team die roten Läufe einfach weg.\n\nDer E2E-Marathon – die Suite, die nachts das komplette System hochfährt, sich durch echte UIs klickt und morgens rot oder grün dasteht – ist deshalb kein Disziplinproblem. Er scheitert an seiner Struktur. Und die Frage, um die es eigentlich geht, ist viel kleiner als das, was er prüft: Passen diese beiden Services noch zusammen? Die Mechanik der Antwort ist schnell erklärt; der Gewinn liegt woanders.\n\nDer wesentliche Unterschied liegt nicht in der Anzahl der Tests, sondern im Ort, an dem Kompatibilität geprüft wird.\n\n::::comparison{title=\"Kompatibilität an der richtigen Grenze prüfen\" role=\"primary\" preferredPattern=\"before-after\"}\n:::side{label=\"Gemeinsame E2E-Umgebung\"}\n- Aufbau · alle beteiligten Systeme gleichzeitig starten\n- Signal · ein kompletter Pfad ist gerade erfolgreich durchgelaufen\n- Schwäche · Fehlerursache, Timing und verantwortliche Grenze bleiben oft unklar\n- Kopplung · Releases warten auf denselben integrierten Zustand\n:::\n:::side{label=\"Consumer-Driven Contract\"}\n- Aufbau · Erwartungen an einer Servicegrenze aufzeichnen\n- Signal · Consumer und Provider erfüllen denselben Vertrag unabhängig\n- Stärke · schneller, deterministischer und einer Grenze zuordenbar\n- Grenze · ersetzt keine kleine Auswahl echter End-to-End-Prüfungen\n:::\n::::\n\nDer Vergleich streicht E2E-Tests nicht. Er verschiebt die häufige Kompatibilitätsprüfung an die Stelle, an der der Vertrag tatsächlich entsteht.\n\n## Warum der E2E-Marathon strukturell scheitert\n\nWas ein Team wirklich braucht, ist eine schnelle, verlässliche Antwort auf die Frage, ob ein neuer Release die Zusammenarbeit zwischen Services bricht. Genau diese Antwort liefert eine große E2E-Suite am schlechtesten.\n\nMartin Fowler und Ham Vocke haben das in \"The Practical Test Pyramid\" präzise auf den Punkt gebracht: UI- und End-to-End-Tests sind \"brittle, expensive to write, and time consuming to run\". Sie sind anfällig für Nicht-Determinismus – Timing, Animationen, Browser-Quirks, ein Netzwerk-Hop, der mal 50 und mal 800 Millisekunden braucht. Und genau dieser Nicht-Determinismus ist das Gift: Sobald eine Suite in einem von zwanzig Läufen aus Gründen rot wird, die nichts mit dem Code zu tun haben, fängt das Team an, Fehlschläge wegzuklicken. Der Test, der Vertrauen schaffen sollte, produziert das Gegenteil.\n\nDazu kommt der Koppelungseffekt. Eine E2E-Suite braucht alle beteiligten Services gleichzeitig, in kompatiblen Versionen, hochgefahren im selben Environment. Damit erzwingt sie einen Lockstep: Team A kann erst deployen, wenn die gemeinsame Suite mit Team Bs aktuellem Stand grün ist. Man hat die Services technisch entkoppelt und sie sich durch die Testinfrastruktur wieder aneinandergekettet.\n\nDie DORA-Forschung im Buch \"Accelerate\" von Forsgren, Humble und Kim liefert dazu die empirische Gegenseite. Zwei der stärksten Prädiktoren für erfolgreiche Continuous Delivery sind eine \"loosely coupled architecture\" und \"continuous testing\". Elite-Performer können ihre Services unabhängig voneinander ändern und deployen, ohne mit anderen Teams synchronisieren zu müssen. Der E2E-Marathon arbeitet gegen genau dieses Ziel. Er ist der synchronisierte Lockstep in Testform.\n\n## Die Grenze prüfen, nicht das ganze System\n\nDie entscheidende Einsicht ist eine der Testabstraktion. Wenn zwei Services zusammenarbeiten, muss ich nicht das gesamte integrierte System hochfahren, um zu prüfen, ob sie sich verstehen. Ich muss nur prüfen, ob die *Grenze* zwischen ihnen stimmt – ob der Consumer das schickt, was der Provider erwartet, und der Provider das zurückgibt, worauf der Consumer sich verlässt.\n\nFowlers Definition ist hier zitierfähig präzise: \"An integration contract test is a test at the boundary of an external service verifying that it meets the contract expected by a consuming service.\" Der Consumer testet gegen einen Mock, der Provider verifiziert die aufgezeichneten Interaktionen – und beide Seiten laufen vollständig isoliert. Kein gemeinsames Environment, kein Lockstep.\n\nDas Muster dahinter ist alles andere als neu. Ian Robinson hat \"Consumer-Driven Contracts: A Service Evolution Pattern\" bereits 2006 auf martinfowler.com beschrieben. Der Consumer definiert seine Erwartungen; der Provider verifiziert gegen die Vereinigung – die Union – aller Consumer-Erwartungen. Das ist kein Hype, das ist ein rund siebzehn Jahre reifes Muster. Was sich geändert hat, ist die Werkzeuglandschaft, die es heute pragmatisch in eine CI-Pipeline gießt.\n\nIn der klassischen Testpyramide wird die Rolle sofort sichtbar: Contract Tests sitzen in der Mitte, als schneller Isolationstest zwischen den vielen Unit-Tests der Basis und der schmalen, teuren E2E-Spitze.\n\n```mermaid\nflowchart TB\n    subgraph Pyramid[\"Test Pyramid\"]\n        direction TB\n        E2E[\"E2E<br/>slow / flaky<br/>few\"]\n        CT[\"Integration / Contract<br/>fast / isolated<br/>focus\"]\n        UNIT[\"Unit<br/>fast / deterministic<br/>many\"]\n        UNIT --> CT --> E2E\n    end\n```\n\nDie Botschaft der Pyramide ist nicht \"keine E2E-Tests\". Sie ist: Prüfe die Kompatibilität da, wo sie entsteht – an der Grenze – und nicht durch ein hochgefahrenes Gesamtsystem an der Spitze.\n\n## Wie ein Contract entsteht\n\nKonkret sieht das so aus. Der Consumer – sagen wir eine WebApp – beschreibt in einem Test, was er vom Provider, hier einem OrderService, erwartet. Dieser Test läuft gegen einen lokalen Mock und generiert dabei als Nebenprodukt eine Vertragsdatei, den Pact.\n\n```js\nconst provider = new Pact({ consumer: 'WebApp', provider: 'OrderService' });\n\nprovider\n  .given('an order with id 42 exists')          // provider state\n  .uponReceiving('a request for order 42')\n  .withRequest({ method: 'GET', path: '/orders/42' })\n  .willRespondWith({\n    status: 200,\n    body: {\n      id: like(42),                              // type matcher\n      status: term({ matcher: 'PAID|OPEN', generate: 'PAID' }),\n      total: like(19.99),\n    },\n  });\n// the consumer runs against the Pact mock, then publishes the pact file to the broker\n```\n\nZwei Details sind hier wichtig, weil sie den Unterschied zwischen \"brauchbar\" und \"brüchig\" ausmachen. Erstens die Matcher. `like(42)` prüft nicht auf den exakten Wert 42, sondern auf den Typ – eine Zahl. `term(...)` prüft gegen ein Muster. Damit sagt der Consumer aus, was er strukturell braucht, statt sich an konkreten Beispielwerten festzuklammern. Zu lax gesetzte Matcher geben falsche Sicherheit, zu strikte machen den Test brüchig; die richtige Körnung ist Handwerk.\n\nZweitens der Provider State, das `given('an order with id 42 exists')`. Der Consumer beschreibt damit die Vorbedingung, unter der seine Erwartung gilt. Und genau hier liegt, ehrlich gesagt, der Hauptaufwand des gesamten Ansatzes – dazu gleich mehr.\n\nAuf der Providerseite wird der Vertrag dann nicht neu geschrieben, sondern verifiziert. Der Provider stellt jeden geforderten State real her und spielt die aufgezeichneten Interaktionen gegen seine echte Implementierung.\n\n```java\n@Provider(\"OrderService\")\n@PactBroker\nclass OrderServiceContractTest {\n\n    @State(\"an order with id 42 exists\")\n    void orderExists() {\n        // set up the provider state so the recorded interaction is reproducible\n        orderRepository.save(new Order(42, \"PAID\", 19.99));\n    }\n}\n```\n\nBeide Seiten laufen isoliert in ihrer eigenen Pipeline. Der Consumer weiß nichts von der Providerimplementierung, der Provider fährt keine WebApp hoch. Und trotzdem entsteht eine belastbare Aussage über ihre Kompatibilität.\n\n## Das Deploy-Gate: eine deterministische Ja/Nein-Frage\n\nJetzt kommt der Teil, der den Marathon tatsächlich ersetzt. Die Verträge und die Verifikationsergebnisse landen in einem zentralen Pact Broker. Damit lässt sich vor jedem Release eine simple, deterministische Frage stellen: Sind diese konkreten Versionen von Consumer und Provider miteinander kompatibel?\n\n```bash\n# provider side: verify the recorded interactions and publish results to the broker\npact-provider-verifier --provider OrderService --publish-verification-results\n\n# both sides gate their release on a deterministic check\npact-broker can-i-deploy \\\n  --pacticipant WebApp --version $GIT_SHA \\\n  --to-environment production\n```\n\n`can-i-deploy` ist der Kern. Statt \"wir warten, bis die nächtliche E2E-Suite grün ist\" bekommt die Pipeline eine sofortige, reproduzierbare Antwort aus dem Broker: Ja, diese Version der WebApp ist gegen die aktuell in Produktion laufende Version des OrderService verifiziert – deploy. Oder: Nein, es fehlt eine Verifikation – halt an.\n\nDer ganze Ablauf ist eine Prüfung an der Grenze, kein hochgefahrenes Gesamtsystem:\n\n```mermaid\nsequenceDiagram\n    participant C as Consumer (WebApp)\n    participant B as Pact Broker\n    participant P as Provider (OrderService)\n    C->>B: publish pact (from mock test)\n    P->>B: verify pact, publish results\n    C->>B: can-i-deploy? (WebApp @ sha)\n    B-->>C: yes -> deploy\n    P->>B: can-i-deploy? (OrderService @ sha)\n    B-->>P: yes -> deploy\n```\n\nDer Effekt ist das eigentliche Argument. Feedback in Minuten statt über Nacht. Ein deterministisches Gate statt eines flaky Wahrscheinlichkeitswurfs. Und – das ist der eigentliche Hebel – jedes Team kann unabhängig deployen, sobald sein Teil des Vertrags erfüllt ist. Kein Lockstep, kein \"wir müssen erst mit Team B synchronisieren\". Genau die lose Koppelung, die \"Accelerate\" als Prädiktor für Delivery-Performance identifiziert, wird hier testbar.\n\n## Wo Contract Testing aufhört – die ehrliche Abgrenzung\n\nConsumer-Driven Contracts ersetzen den E2E-*Marathon* – nicht jeden E2E-Test. Wer sie als Wundermittel verkauft, verspricht zu viel.\n\nDer wichtigste Vorbehalt zuerst: Contract Tests prüfen Schnittstellen-Kompatibilität. Struktur, Felder, Status-Codes, das Format an der Grenze. Sie prüfen *nicht* echte End-to-End-Business-Flows über mehrere Hops, nicht das UI-Verhalten, nicht Netzwerk- und Infrastruktureffekte im Zusammenspiel. Ein schmales E2E-Smoke-Set, das einmal den kritischen Pfad durch das laufende Gesamtsystem zieht, bleibt sinnvoll und richtig. Die These lautet \"statt E2E-Marathon\", nicht \"null E2E\". Man tauscht eine breite, langsame, unzuverlässige Suite gegen viele schnelle, isolierte Verträge plus eine Handvoll gezielter Smoke-Tests.\n\nDer zweite Punkt ist der, an dem ich in der Praxis die meiste Zeit verbringe: die Provider States. Jedes `given('...')` muss providerseitig real herstellbar sein. Driften die Annahmen des Consumers und das tatsächliche Setup des Providers auseinander, wird der vermeintlich leichtgewichtige Test doch aufwändig. Hier liegt die Wartungsarbeit, und wer sie unterschätzt, wird enttäuscht. Es lohnt sich, die States bewusst schlank und wiederverwendbar zu halten.\n\nUnd der dritte Punkt ist gar kein technischer. Contract Testing ohne Broker und ohne `can-i-deploy` im CI bleibt Stückwerk. Verträge, die nur lokal laufen und nicht versioniert zwischen den Pipelines ausgetauscht werden, geben keine verlässliche Deploy-Freigabe. Vor allem aber sind Consumer-Driven Contracts genauso sehr eine Frage der Zusammenarbeit wie der Technik: Beide Teams müssen sich auf den Vertrag als verbindliche Absprache einlassen. Der Consumer sagt, was er braucht; der Provider verpflichtet sich, es zu liefern und nicht kaputtzumachen. Das ist eine organisatorische Vereinbarung, keine Bibliothek. Wenn die Kultur nicht mitspielt, hilft das beste Tool nicht.\n\nEin Wort zur Werkzeugwahl, ohne in Produktwerbung zu verfallen: Im JS-Umfeld generiert Pact die Verträge; als Consumer-Mocks laufen dort WireMock, Nock oder MSW. Auf der JVM ist Spring Cloud Contract eine etablierte Alternative zu pact-jvm. Der Pact Broker ist Open Source und trägt die CI-Mechanik. Es gibt kommerzielle Erweiterungen im Umfeld – für den hier beschriebenen Kern braucht man sie nicht. Die Strategie steht und fällt nicht mit dem Vendor, sondern mit der Disziplin, an der Grenze zu prüfen und sich als Teams auf Verträge zu einigen.\n\n## Fazit\n\nDer E2E-Marathon ist kein Testproblem, sondern ein Architekturproblem in Testform: Er koppelt Services über die Infrastruktur wieder aneinander, die man mit gutem Grund entkoppelt hat, und tauscht dafür Determinismus und Geschwindigkeit gegen ein trügerisches Gefühl von Vollständigkeit ein. Consumer-Driven Contracts drehen das um. Sie prüfen Kompatibilität da, wo sie entsteht – an der Grenze zwischen zwei Services –, isoliert, schnell und reproduzierbar. Das Deploy-Gate wird zu einer Ja/Nein-Frage, die in Minuten beantwortet ist, und jedes Team gewinnt die Freiheit zurück, unabhängig zu releasen.\n\nDer Gewinn taucht am Ende in keiner Test-Metric auf, er zeigt sich in der Auslieferung: kürzere Zyklen, weniger Reibung zwischen Teams, höhere Verlässlichkeit. Ein schmales E2E-Smoke-Set bleibt daneben bestehen – aber der Marathon darf gehen. Man tauscht ein großes, langsames, unzuverlässiges Sicherheitsnetz gegen viele kleine, präzise gespannte.\n\n## Weiterführende Quellen\n\n- [Consumer-Driven Contracts: A Service Evolution Pattern (Ian Robinson, martinfowler.com)](https://martinfowler.com/articles/consumerDrivenContracts.html)\n- [The Practical Test Pyramid (Ham Vocke, martinfowler.com)](https://martinfowler.com/articles/practical-test-pyramid.html)\n- [TestPyramid (Martin Fowler, Bliki)](https://martinfowler.com/bliki/TestPyramid.html)\n- [DORA: Loosely coupled architecture](https://dora.dev/capabilities/loosely-coupled-teams/)\n- [DORA: Continuous delivery](https://dora.dev/capabilities/continuous-delivery/)\n- [pact-jvm (pact-foundation, GitHub)](https://github.com/pact-foundation/pact-jvm)\n- Forsgren, Humble, Kim: *Accelerate* (2018)"},{"locale":"de","translation_key":"nodejs-fehler-als-architektur","slug":"nodejs-fehler-als-architektur","title":"Fehler als Architektur in Node.js: Netze gegen den Absturz","summary":"Error Handling in Node.js ist keine try/catch-Kosmetik, sondern eine Entscheidung über Ebenen, Eskalation und geordnetes Beenden. Wer die vier Fehler-Ebenen kennt und Graceful Shutdown ernst nimmt, baut Dienste, die kontrolliert sterben statt korrupt weiterzulaufen.","tags":["Software","Node.js","Backend"],"published_at":"2023-11-07T10:00:00+00:00","updated_at":"2026-07-13T13:22:07.374858+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-fehler-als-architektur/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ed5bcf3778f82b40e14169a0479d786edb7dc6f4c2012320702ed003769b6be2/nodejs-fehler-als-architektur-vorlesen.mp3","audio_duration_secs":651,"text":"Ein `try/catch` fängt synchrone Exceptions im gerade laufenden Stack und Rejections von Promises, die innerhalb desselben Blocks `await`et werden. Ein späterer Callback, eine losgelöste Promise und das `'error'`-Event eines EventEmitters erreichen diesen Block dagegen nicht. Ein `try/catch` um deren bloßen Startaufruf ist dann nur Dekoration.\n\nDamit hat eine Node.js-Anwendung mindestens vier Ebenen, auf denen Fehler entstehen, und jede davon hat ihre eigene Mechanik. Wer nur die erste kennt, hat drei Löcher im Netz – und wundert sich, warum der Prozess trotzdem abstürzt, obwohl doch „überall try/catch“ steht.\n\nWo diese Netze hängen, entscheidet sich beim Entwurf und nicht in der Woche vor dem Go-live, wenn jemand noch schnell etwas Error Handling darüberlegt. Daran hängt, ob ein Dienst unter Last stehen bleibt und in Sekunden frisch wieder da ist – oder ob er halb kaputt weiterarbeitet und Daten hinterlässt, die hinterher niemand mehr geradebiegt.\n\nDabei sind zwei Achsen zu trennen. Callback, Promise und EventEmitter beschreiben, **wie** ein Fehler den Code erreicht. Operational Errors und Programmer Errors beschreiben, **ob** der konkrete Zustand noch beherrschbar ist. Ein erwartbares Timeout kann am Request-Rand beantwortet oder wiederholt werden. Eine gebrochene Invariante im eigenen Code sollte bis zur Prozessgrenze eskalieren, damit der Dienst nach einem geordneten Shutdown frisch startet. Nicht jeder Fehler verlangt den Prozessabbruch; ein unbekannter Programmzustand darf aber nicht als normaler Betriebsfehler weiterlaufen.\n\n## Die vier Ebenen, auf denen Fehler entstehen\n\nBevor wir über Netze reden, muss klar sein, welche Fehlerquellen es in einer Node.js-Anwendung überhaupt gibt. Es sind im Kern vier, und sie unterscheiden sich nicht im Schweregrad, sondern im Mechanismus, mit dem der Fehler zu dir kommt:\n\n- Synchron: Ein Fehler wird direkt im aktuellen Aufrufstapel geworfen. Ihn fängt ein klassisches `try/catch`. Wer hier nichts fängt, bekommt die Exception eine Ebene höher gereicht – bis ganz nach oben.\n- Error-first-Callbacks: Die alte, immer noch allgegenwärtige Node-Konvention. Der Fehler kommt nicht als Exception, sondern als erstes Argument der Callback-Function: `callback(err, result)`. Kein `throw`, kein `catch` – nur ein Wert, den man aktiv prüfen muss.\n- Promises und async/await: Ein Fehler wird zur Rejection der Promise. Man fängt ihn mit `.catch()` oder mit `try/catch` um ein `await`. Wird er nirgends gefangen, entsteht eine `unhandledRejection`.\n- EventEmitter: Server, Sockets, Streams. Der Fehler kommt als `'error'`-Event. Und hier lauert die böseste Falle: Fehlt der `'error'`-Listener, wird der Fehler nicht still verschluckt – er wird als Exception geworfen und reißt den Prozess mit.\n\nDiese vier Ebenen zu trennen, ist der erste Schritt. Der zweite ist zu verstehen, dass darüber noch eine fünfte Schicht liegt: das letzte Netz, das greift, wenn auf keiner der vier Ebenen jemand zuständig war.\n\n## Ebene für Ebene: wo der Fehler wirklich ankommt\n\nNehmen wir die Ebenen einzeln durch. Synchron ist einfach – das kennt jeder:\n\n```js\nfunction parseConfig(raw) {\n  try {\n    return JSON.parse(raw);\n  } catch (err) {\n    // synchronous exception, caught right here\n    return { ok: false, reason: err.message };\n  }\n}\n```\n\nDer Denkfehler beginnt, sobald Asynchronität ins Spiel kommt. Ein `try/catch` um einen error-first-Callback ist wirkungslos, weil der Callback erst später und in einem anderen Stack aufgerufen wird:\n\n```js\nconst fs = require('node:fs');\n\n// This try/catch catches NOTHING from the callback below.\ntry {\n  fs.readFile('/etc/config.json', (err, data) => {\n    if (err) return handle(err); // the error arrives HERE, as first argument\n    process.stdout.write(data);\n  });\n} catch (err) {\n  // never reached for the async error\n}\n```\n\nDer Fehler steckt im `err`-Argument, nicht in einer geworfenen Exception. Vergisst man das `if (err) return ...`, läuft der Code mit `data === undefined` weiter – und der eigentliche Absturz passiert dann später an einer Stelle, die mit der Ursache nichts zu tun hat. Das ist die häufigste Art, wie sich Fehler in Node.js verstecken.\n\nPromises drehen das wieder zurück in Richtung `try/catch` – aber nur um `await` herum:\n\n```js\nasync function loadUser(id) {\n  try {\n    const user = await db.users.findById(id);\n    if (!user) throw new Error(`user ${id} not found`);\n    return user;\n  } catch (err) {\n    // rejection AND thrown error both land here\n    logger.warn({ err, id }, 'loadUser failed');\n    throw err; // re-throw: let the caller decide\n  }\n}\n```\n\nWichtig ist die Konsequenz, wenn niemand die Rejection beobachtet. Seit Node.js 15 ist der Default-Modus von `--unhandled-rejections` gleich `throw`. Eine unbehandelte Promise-Rejection ist keine bloße Warnung mehr, sondern beendet den Prozess. Praktisch heißt das: Jede asynchrone Kette muss entweder zu einem zuständigen Aufrufer zurückgegeben oder spätestens an einer klaren Grenze mit `.catch` beziehungsweise `try/catch` behandelt werden. Losgelöste Promises in Timern oder Callbacks brauchen diese Grenze ausdrücklich.\n\nDie EventEmitter-Ebene ist die am meisten unterschätzte. Ein Stream ohne `'error'`-Listener bringt den Prozess zum Absturz, obwohl der Fehler völlig behandelbar gewesen wäre:\n\n```js\nconst fs = require('node:fs');\n\nconst stream = fs.createReadStream('/does/not/exist');\n\n// WITHOUT this line, the emitted 'error' is thrown and crashes the process.\nstream.on('error', (err) => {\n  logger.error({ err }, 'stream failed, handled gracefully');\n});\n\nstream.on('data', (chunk) => process.stdout.write(chunk));\n```\n\nDas ist Standard-Semantik von Node: Ein EventEmitter, der ein `'error'`-Event emittiert, ohne dass ein Listener registriert ist, wirft den Fehler. Deshalb ist der `'error'`-Handler bei Servern, Sockets und Streams nicht optional, sondern architektonisch Pflicht. Wer viel mit Prozessgrenzen und Streams arbeitet, kennt das Muster aus dem Umgang mit [child_process und Skalierung](https://www.mikebild.dev/de/blog/nodejs-child-process-und-skalierung/) – auch dort ist das `'error'`-Event auf dem Kind-Prozess der Unterschied zwischen „sauber behandelt“ und „harter Absturz“.\n\n## Das letzte Netz – und wofür es nicht da ist\n\nWas passiert, wenn auf keiner der vier Ebenen jemand zuständig war? Dann greift das letzte Netz: `uncaughtException` und `unhandledRejection`.\n\n```mermaid\nflowchart TD\n  E[\"Fehler entsteht\"] --> D{\"Welche Ebene<br/>fängt ihn?\"}\n  D -->|\"try/catch\"| H[\"behandeln &<br/>weitermachen\"]\n  D -->|\"error-first callback\"| H\n  D -->|\"promise .catch\"| H\n  D -->|\"emitter 'error'\"| H\n  D -->|\"niemand zuständig\"| ESC[\"eskaliert zum<br/>letzten Netz\"]\n  ESC --> LOG[\"loggen<br/>uncaughtException /<br/>unhandledRejection\"]\n  LOG --> GS[\"Graceful Shutdown<br/>starten\"]\n  GS --> CLOSE[\"server.close()\"]\n  CLOSE --> EXIT[\"process.exit(1)\"]\n  EXIT --> SUP[\"Supervisor<br/>pm2 / systemd / K8s<br/>startet frisch\"]\n```\n\nHier liegt der entscheidende und oft missverstandene Punkt. Registriert man einen `uncaughtException`-Handler, überschreibt man damit das Default-Verhalten von Node. Ohne Handler schreibt Node den Stacktrace nach stderr und beendet den Prozess mit Exit-Code 1. Sobald ein Handler existiert, passiert dieser automatische Exit nicht mehr. Die Node-Dokumentation ist an dieser Stelle explizit: „Adding a handler overrides this default behavior.“\n\nDas bedeutet: Wenn du einen `uncaughtException`-Handler registrierst, musst du selbst dafür sorgen, dass der Prozess beendet wird. Tust du das nicht, läuft er in einem undefinierten Zustand weiter. Und genau das ist das Anti-Pattern, das ich in echten Codebasen am häufigsten sehe:\n\n```js\n// ANTI-PATTERN: swallow and keep running.\nprocess.on('uncaughtException', (err) => {\n  logger.error({ err }, 'oops'); // logged, but then... nothing\n  // no process.exit — the process stays alive in a corrupt state\n});\n```\n\nNach einer uncaught Exception ist der Zustand der Anwendung potenziell korrupt: halb abgeschlossene Transaktionen, geleakte File-Handles, ein Connection-Pool in unklarem Zustand. Die Node-Doku warnt ausdrücklich davor, danach den Normalbetrieb wieder aufzunehmen. `uncaughtException` und `unhandledRejection` sind ein letztes Netz zum sauberen Beenden – nicht zum Weitermachen.\n\nRichtig sieht das Netz so aus: loggen, dann kontrolliert beenden. Für die Rejection eskaliere ich bewusst zur Exception, damit beide Wege im selben Shutdown münden:\n\n```js\nprocess.on('unhandledRejection', (reason) => {\n  logger.error({ reason }, 'unhandled rejection, escalating');\n  // escalate to uncaughtException so we exit through one path\n  throw reason;\n});\n\nprocess.on('uncaughtException', (err, origin) => {\n  logger.fatal({ err, origin }, 'uncaught exception, shutting down');\n  process.exit(1);\n});\n```\n\nEs gibt noch eine leisere Variante, die man kennen sollte: `uncaughtExceptionMonitor`. Dieser Handler dient nur zum Beobachten und Loggen – er ändert das Crash-Verhalten nicht. Ist kein `uncaughtException`-Handler registriert, crasht der Prozess weiterhin, aber der Monitor hat vorher noch geloggt. Das ist ideal, wenn man den Absturz protokollieren will, ohne ihn versehentlich zu unterdrücken:\n\n```js\n// Log the crash without changing the crash behavior.\nprocess.on('uncaughtExceptionMonitor', (err, origin) => {\n  logger.fatal({ err, origin }, 'about to crash');\n});\n```\n\n## Graceful Shutdown: kontrolliert sterben, nicht reparieren\n\nDer Absturz über das letzte Netz ist die harte Variante. Der Normalfall im Betrieb ist ein anderer: Der Supervisor – pm2, systemd oder ein Kubernetes-Orchestrator – will den Prozess beenden, etwa bei einem Deployment oder beim Herunterskalieren. Dazu schickt er ein `SIGTERM`. Und hier ist die Anwendung dafür verantwortlich, laufende Arbeit sauber abzuschließen, nicht für Selbstreparatur.\n\n```mermaid\nsequenceDiagram\n  participant O as Orchestrator\n  participant A as App\n  O->>A: SIGTERM\n  A->>A: stop accepting new requests\n  A->>A: drain in-flight requests\n  A->>A: close DB / pools\n  A-->>O: exit 0\n  O->>O: restart fresh\n```\n\nDer Ablauf ist immer derselbe: `SIGTERM` abfangen, keine neuen Verbindungen mehr annehmen, laufende Anfragen zu Ende bringen, Ressourcen schließen, dann beenden. Der Supervisor startet danach einen frischen Prozess. Wichtig ist der Default, den man dabei überschreibt: Ohne eigenen Listener beendet Node bei `SIGTERM` mit Exit-Code `128 + 15 = 143`. Sobald man einen Listener registriert, ist man selbst für das Beenden zuständig.\n\n```js\nconst http = require('node:http');\n\nconst server = http.createServer(handler);\nserver.listen(3000);\n\nlet isShuttingDown = false;\n\nfunction shutdown(signal) {\n  if (isShuttingDown) return; // guard against double invocation\n  isShuttingDown = true;\n  logger.info({ signal }, 'graceful shutdown started');\n\n  // stop accepting new connections, finish in-flight ones\n  server.close((err) => {\n    if (err) {\n      logger.error({ err }, 'error during server.close');\n      return process.exit(1);\n    }\n    logger.info('all connections drained, exiting');\n    process.exit(0);\n  });\n\n  // fallback: never hang forever if a connection refuses to close\n  setTimeout(() => {\n    logger.error('shutdown timed out, forcing exit');\n    process.exit(1);\n  }, 10_000).unref();\n}\n\nprocess.on('SIGTERM', () => shutdown('SIGTERM'));\nprocess.on('SIGINT', () => shutdown('SIGINT'));\n```\n\nZwei Details sind hier entscheidend. Erstens das `isShuttingDown`-Flag: Ein Container kann `SIGTERM` und kurz darauf noch ein Signal schicken; ohne Guard läuft der Shutdown doppelt und `server.close` wird auf einem bereits schließenden Server aufgerufen. Zweitens der Timeout mit `.unref()`. Wenn eine hängende Verbindung dafür sorgt, dass `server.close` nie zurückkommt, bleibt der Prozess sonst ewig stehen – bis der Orchestrator irgendwann hart mit `SIGKILL` nachhilft. Der Fallback-Timeout sorgt dafür, dass wir vorher selbst kontrolliert aussteigen. Das `.unref()` verhindert dabei, dass der Timer selbst den Prozess am Leben hält, falls der saubere Weg doch rechtzeitig fertig wird.\n\nDiese Aufgabenteilung ist der Kern der ganzen Architektur: Die Anwendung ist dafür zuständig, ihre laufende Arbeit sauber zu Ende zu bringen und dann zu sterben. Für das Wiederanlaufen ist der Supervisor zuständig – nicht die Anwendung selbst. Ein Prozess, der versucht, sich nach einem schweren Fehler selbst zu heilen und weiterzulaufen, macht die Sache schlimmer. Ein Prozess, der kontrolliert stirbt und frisch neu gestartet wird, ist in Sekunden wieder in einem definierten Zustand.\n\n## Warum das eine Architekturentscheidung ist\n\nDie Verantwortlichkeiten hängen als Kette zusammen: Der Fehler entsteht auf einer der vier Ebenen. Idealerweise fängt ihn genau dort ein zuständiger Handler – im `try/catch`, in der `if (err)`-Prüfung, im `.catch`, im `'error'`-Listener. Erst wenn niemand zuständig war, eskaliert er zum letzten Netz, und das letzte Netz hat genau eine Aufgabe: sauber loggen und geordnet beenden.\n\nDas ist keine Sammlung von Einzeltricks, sondern eine durchgehende Entscheidung darüber, wo ein Fehler behandelt wird und wo er nur noch zum kontrollierten Ende führt. Man entscheidet einmal, wie das Netz gespannt ist, und dann hält es überall – oder man entscheidet es nicht, und dann reißt es an der Stelle, an der man nie hingeschaut hat.\n\nWer das Zusammenspiel von Event Loop, Callbacks und Promises grundsätzlich vertiefen will, findet den Unterbau dazu im [Node.js-Training zur Event-Loop-Architektur](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/). Denn erst wenn klar ist, warum ein Callback in einem anderen Stack läuft als der `try/catch`, der ihn umgibt, wird verständlich, warum Error Handling in Node.js eben nicht mit „überall try/catch“ erledigt ist.\n\nBehandle jeden Fehler so nah wie möglich an der Ebene, auf der er entsteht. Spann das letzte Netz nur zum sauberen Sterben, nie zum Weiterleben. Und überlass das Wiederauferstehen dem Supervisor. Ein Dienst, der weiß, wie er stirbt, ist stabiler als einer, der um jeden Preis am Leben bleiben will.\n\n## Weiterführende Quellen\n\n- Repository mit Beispielen: [MikeBild/introduction-nodejs](https://github.com/MikeBild/introduction-nodejs)\n- [process – Event: 'uncaughtException'](https://nodejs.org/api/process.html#event-uncaughtexception)\n- [process – Event: 'unhandledRejection'](https://nodejs.org/api/process.html#event-unhandledrejection)\n- [process – Signal-Events](https://nodejs.org/api/process.html#signal-events)\n- [events – 'error'-Events des EventEmitter](https://nodejs.org/api/events.html#error-events)\n- [CLI – --unhandled-rejections=mode](https://nodejs.org/api/cli.html#--unhandled-rejectionsmode)\n- [Node.js Process API](https://nodejs.org/api/process.html)"},{"locale":"de","translation_key":"dora-metriken-was-zyklen-verkuerzt","slug":"dora-metriken-was-zyklen-verkuerzt","title":"DORA-Metrics: was Entwicklungszyklen wirklich verkürzt","summary":"Lead Time, Deploy-Frequenz, Change-Fail-Rate und Recovery-Zeit sind Diagnosewerte statt Vanity-Velocity. Sie zeigen, wo der Zyklus klemmt – und warum Tempo und Stabilität kein Gegensatz sein müssen.","tags":["Software","Delivery"],"published_at":"2023-10-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/dora-metriken-was-zyklen-verkuerzt/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/edf438fba37832372b531e27f01f5fbb19b5371e259180e3d1d58d07288829db/dora-metriken-was-zyklen-verkuerzt-vorlesen.mp3","audio_duration_secs":667,"text":"Deployment Frequency, Lead Time for Changes, Change Failure Rate, Failed Deployment Recovery Time: vier Messwerte, die niemand schätzen und über die niemand abstimmen muss. Sie fallen in Systemen an, die ohnehin laufen – Commit-Timestamp im Versionskontrollsystem, Deploy-Event der CD-Pipeline, Incident-Log. Kein Board, keine Punkte, keine Selbstauskunft. Die Recovery-Metric hieß in älteren DORA-Texten „Time to Restore Service“.\n\n**Redaktionelle Einordnung (Juli 2026):** Dieser Beitrag beschreibt das damalige Modell aus vier Delivery-Metrics. DORA ergänzte 2024 die **Deployment Rework Rate** als fünfte Kennzahl. Der aktuelle Kanon besteht damit aus drei Throughput- und zwei Instability-Metrics; die historische Vierergruppe im Haupttext bleibt als Ausgangspunkt erhalten.\n\nEine Velocity-Kurve entsteht auf dem umgekehrten Weg. Sie summiert Story Points, die ein Team sich selbst zugeschrieben hat, und kann steil nach oben zeigen, während Releases zäh bleiben, Hotfixes sich stauen und freitags niemand deployen will. Die vier Messwerte oben können das nicht. Sie beschreiben den Weg einer Änderung vom Commit bis in Produktion – und was passiert, wenn diese Änderung Schaden anrichtet.\n\nDiese vier DORA-Keys stammen aus der DevOps-Research-and-Assessment-Arbeit rund um Nicole Forsgren, Jez Humble und Gene Kim, sind im Buch *Accelerate* (2018) statistisch unterfüttert und werden seither jährlich im *State of DevOps Report* fortgeschrieben. Ihr Wert liegt in der Diagnose: Sie zeigen, an welcher Stelle der Kette es hakt. Im Folgenden geht es darum, wo genau die Keys den Engpass sichtbar machen und wie man sie erhebt, ohne dass daraus ein neues Zahlenspiel wird.\n\nDie Messgrößen lassen sich zuerst nach der Frage ordnen, die sie beantworten. Das verhindert, dass Tempo und Instabilität zu einer scheinbar eindeutigen Gesamtnote verschmelzen.\n\n::::comparison{title=\"Delivery-Leistung hat zwei Achsen\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Throughput\"}\n- Deployment Frequency · Wie oft erreicht eine Änderung Produktion?\n- Lead Time for Changes · Wie lange dauert der Weg vom Commit bis zum Deploy?\n:::\n:::side{label=\"Instability\"}\n- Change Failure Rate · Welcher Anteil der Änderungen verursacht eine Störung?\n- Failed Deployment Recovery Time · Wie lange dauert die Erholung nach einem fehlgeschlagenen Deploy?\n- Deployment Rework Rate · Welcher Anteil erzeugt ungeplante Nacharbeit?\n:::\n::::\n\nDie Einteilung ist keine Rangliste. Erst gemeinsam zeigen beide Seiten, ob ein Team schnell liefern kann, ohne die Kosten fehlgeschlagener Änderungen auszublenden.\n\n## Zwei Achsen statt einer Zahl\n\nDer erste Denkfehler ist, Delivery-Performance als eine einzige Größe zu behandeln. Die vier Keys spannen bewusst zwei Achsen auf.\n\nAuf der Throughput-Achse liegen **Deployment Frequency** – wie oft geht Code in Produktion – und **Lead Time for Changes** – wie lange dauert es vom Commit bis zum erfolgreichen Deploy. Das ist die Tempo-Seite: kleine Batches, kurze Wege.\n\nAuf der Stability-Achse liegen **Change Failure Rate** – welcher Anteil der Deploys eine Störung oder einen Rollback auslöst – und **Failed Deployment Recovery Time** – wie lange die Erholung nach einem fehlgeschlagenen Deployment dauert. Das ist die Seite der Robustheit: wie teuer ein Fehler wird.\n\nDie zentrale, kontraintuitive Erkenntnis aus *Accelerate*: Diese beiden Achsen stehen nicht im Gegensatz. Die Daten zeigen, dass Elite-Teams auf **beiden** gleichzeitig gewinnen – häufiger deployen *und* seltener scheitern *und* schneller wieder online sind. Der alte Reflex \"Wenn wir schneller liefern, sinkt die Qualität\" ist empirisch widerlegt. Genau deshalb ist es fahrlässig, nur zwei der vier Metrics zu messen. Wer allein Deploy-Frequenz und Lead Time trackt, optimiert Tempo und blendet die Stabilität aus – und produziert exakt die Vanity-Illusion, gegen die die DORA-Keys eigentlich antreten.\n\n```mermaid\nquadrantChart\n  title Throughput vs. Stability\n  x-axis Low Throughput --> High Throughput\n  y-axis Low Stability --> High Stability\n  quadrant-1 Elite\n  quadrant-2 Slow but Safe\n  quadrant-3 Low Performer\n  quadrant-4 Fragile Speed\n  Elite Team: [0.85, 0.85]\n  Big-Batch Team: [0.2, 0.6]\n  Move-Fast-Break-Things: [0.8, 0.25]\n  Stuck Team: [0.2, 0.2]\n```\n\nDie Matrix macht klar: Das Ziel ist rechts oben, nicht ein Kompromiss auf der Diagonale. Und sie erklärt, warum eine einzelne Zahl in die Irre führt – ein Team im Quadranten \"Fragile Speed\" sieht auf einer reinen Tempo-Metric glänzend aus und brennt trotzdem.\n\n## Wo der Zyklus klemmt\n\nDer eigentliche Wert der Keys liegt nicht im Benchmark, sondern in der Lokalisierung. Jede Metric hängt an einem anderen Segment der Wertschöpfungskette vom Commit bis zur Produktion – und zeigt damit, an welcher Stelle es hakt.\n\n```mermaid\nflowchart LR\n  A[Commit] --> B[CI Build]\n  B --> C[Test]\n  C --> D[Deploy Gate]\n  D --> E[Production]\n  E -->|Incident| F[Restore]\n  F --> E\n  A -. Lead Time for Changes .-> E\n  D -. Deployment Frequency .-> E\n  E -. Change Failure Rate .-> F\n  F -. Failed Deployment Recovery Time .-> E\n  style D fill:#e8543f,color:#fff\n```\n\nEin Beispiel aus der Praxis: Ein Team klagt über \"langsame Releases\". Die Lead Time liegt im Median bei elf Tagen. Zerlegt man sie, stecken davon neun Tage zwischen \"Feature fertig\" und \"Deploy Gate\" – die Pipeline und der manuelle Freigabeschritt sind der Engpass, nicht das Programmieren. Ein anderes Team hat eine gute Lead Time, aber eine Change Failure Rate von 30 Prozent und eine Restore-Zeit von Stunden: Hier ist nicht das Tempo das Problem, sondern die Umkehrbarkeit von Änderungen. Dieselben vier Zahlen, völlig unterschiedliche Therapie. Eine aggregierte Velocity hätte in beiden Fällen nur \"das Team ist ausgelastet\" gesagt.\n\nLead Time for Changes ist dabei mein wichtigster Frühindikator. Sie ist definiert als die Zeit vom Code-Commit bis zum erfolgreichen Lauf in Produktion und korreliert eng mit der Batch-Größe. Große Batches verlängern das Feedback, erhöhen das Fehlerrisiko und machen jedes Deployment zum Event – darauf pochen Donald Reinertsen und Jez Humble seit Jahren, und *Accelerate* belegt es mit Daten. Kurze Lead Time zwingt fast automatisch zu kleinen, kontinuierlichen Änderungen.\n\n## Change Failure Rate und Recovery-Zeit sind gekoppelt\n\nEin verbreitetes Missverständnis ist, Stabilität heiße „keine Fehler“. Das ist nicht die Aussage der DORA-Daten. Die Kopplung aus Change Failure Rate und Failed Deployment Recovery Time sagt etwas Feineres: Nicht die Abwesenheit von Fehlern zählt, sondern deren Preis. Hohe Deploy-Frequenz plus niedrige Change Failure Rate plus kurze Recovery-Zeit bedeutet, dass Änderungen klein und umkehrbar sind. Ein Fehler, den ich in Minuten zurückrolle, ist billig. Ein Zero-Defect-Anspruch, der jeden Release zur Zitterpartie macht, ist teuer – gerade weil er selten geübtes, riskantes Deployen erzwingt.\n\nDeshalb schlägt eine kurze Restore-Zeit in der Praxis den Anspruch auf Fehlerfreiheit. Und deshalb gehören die Nachbar-Techniken hier direkt dazu: Feature Flags, um Änderungen ohne Deploy scharf oder wieder unscharf zu schalten; Canary- und Blue-Green-Releases, um Blast-Radius zu begrenzen; Circuit Breaker und Bulkheads aus Michael Nygards *Release It!*, um Ausfälle einzudämmen. Keine Buzzwords: genau das sind die Hebel, mit denen man Change Failure Rate senkt und Restore-Zeit verkürzt.\n\nIm Code sieht die Kopplung von umkehrbarem Rollout und automatischem Recovery zum Beispiel so aus:\n\n```typescript\n// Canary rollout gated by the live error rate.\n// Ties Change Failure Rate and recovery time together in one control loop.\ninterface RolloutConfig {\n  canaryPercentage: number;\n  maxErrorRate: number;      // e.g. 0.02 -> roll back above 2%\n  observationWindowMs: number;\n}\n\nasync function progressiveRollout(\n  release: Release,\n  config: RolloutConfig,\n): Promise<RolloutResult> {\n  await featureFlags.enableForCohort(release.id, config.canaryPercentage);\n\n  const errorRate = await metrics.observeErrorRate(\n    release.id,\n    config.observationWindowMs,\n  );\n\n  if (errorRate > config.maxErrorRate) {\n    await featureFlags.disable(release.id); // instant, no redeploy\n    return { status: \"rolled_back\", observedErrorRate: errorRate };\n  }\n\n  await featureFlags.enableForCohort(release.id, 100);\n  return { status: \"promoted\", observedErrorRate: errorRate };\n}\n```\n\nEs geht nicht um die konkrete Bibliothek, es geht um das Prinzip: Recovery passiert per Flag-Toggle in Sekunden, nicht per Notfall-Deploy. Genau das drückt sich später in einer niedrigen Restore-Zeit aus.\n\n## Die Metrics messen, ohne sie zu erfinden\n\nDamit die Keys ehrlich bleiben, müssen sie aus Systemen kommen, die man nicht von Hand pflegt. Lead Time zum Beispiel lässt sich vollständig aus zwei Quellen ableiten: dem Commit-Timestamp im Versionskontrollsystem und dem Deploy-Event der CD-Pipeline. Keine Schätzung, keine Selbstauskunft.\n\n```typescript\n// Lead Time for Changes, derived from VCS + deploy events.\n// leadTime = deployedAt(prodDeployment) - firstCommitTime(changeSet)\nfunction leadTimeForChange(deployment: ProdDeployment): number {\n  const firstCommit = deployment.changeSet\n    .map((commit) => commit.authoredAt.getTime())\n    .reduce((min, t) => Math.min(min, t), Infinity);\n\n  return deployment.deployedAt.getTime() - firstCommit;\n}\n\n// Aggregate as a median over a rolling window -- means get skewed by outliers.\nfunction medianLeadTime(deployments: ProdDeployment[]): number {\n  const values = deployments.map(leadTimeForChange).sort((a, b) => a - b);\n  const mid = Math.floor(values.length / 2);\n  return values.length % 2 === 0\n    ? (values[mid - 1] + values[mid]) / 2\n    : values[mid];\n}\n```\n\nZwei Details sind wichtig. Erstens der Median statt des Mittelwerts – ein einzelner liegengebliebener Branch würde jeden Durchschnitt ruinieren. Zweitens das rollierende Zeitfenster: Die Zahl ist ein Trend, kein Tagestreffer.\n\nNoch wirksamer wird das Ganze, wenn man eine Metric nicht nur anzeigt, sondern in die Pipeline zurückkoppelt. Neal Ford, Rebecca Parsons und Patrick Kua nennen das in *Building Evolutionary Architecture* eine Fitness Function – eine ausführbare Regel, die eine Architektur-Eigenschaft überprüfbar macht. Eine DORA-Fitness-Function kann die Pipeline rot färben, wenn die Change Failure Rate über der Schwelle liegt:\n\n```python\n# Executable fitness function: assert a DORA metric as a CI gate.\ndef assert_change_failure_rate(window_days: int = 30, threshold: float = 0.15):\n    deployments = metrics_db.query_deployments(window_days)\n    failed = [d for d in deployments if d.caused_incident or d.rolled_back]\n\n    if not deployments:\n        return  # nothing to assert yet\n\n    change_failure_rate = len(failed) / len(deployments)\n    assert change_failure_rate < threshold, (\n        f\"Change Failure Rate {change_failure_rate:.0%} \"\n        f\"exceeds threshold {threshold:.0%} over {window_days}d\"\n    )\n```\n\nSo verbindet sich DORA mit der Idee der evolutionären Architektur: Die Metric ist keine Folie fürs Quartalsmeeting mehr, sondern eine Bedingung, die das System an sich selbst stellt.\n\n## Der Fallstrick: Metrics als Ziel\n\nDamit zur größten Gefahr. Sobald eine Metric zum Ziel wird, hört sie auf, ein gutes Maß zu sein – Goodhart's Law in Reinform. Deployment Frequency lässt sich mit trivialen Leer-Deploys aufblähen. Change Failure Rate lässt sich schönen, indem man \"Failure\" so lange umdefiniert, bis kaum noch etwas hineinfällt. Wer die Keys als Team-Ranking oder Bonus-KPI benutzt, bekommt genau dieses Gaming – und DORA selbst warnt ausdrücklich davor, Teams damit zu vergleichen. Die vier Zahlen sind Diagnose, nicht Wettbewerb.\n\nZwei weitere Verwechslungen sehe ich häufig. Erstens: Die Keys sind kein Ersatz für Story-Point-Velocity im Sinne von \"gleiche Sache, bessere Zahlen\". Es ist ein anderes Konstrukt – Velocity misst den Output eines einzelnen Teams und ist weder vergleichbar noch fälschungssicher; die Keys messen den Fluss vom Commit bis Produktion über das ganze Delivery-System. Zweitens: Schnelle Deploys ohne Wirkung sind \"faster to nowhere\". Deshalb hat DORA in den Reports 2021 und 2022 eine fünfte Dimension ergänzt, die **Reliability** beziehungsweise operative Performance. Die Aussage von 2022: Hohe Delivery-Performance zahlt nur dann auf den Organisationserfolg ein, wenn auch die Zuverlässigkeit im Betrieb stimmt. Ich behandle Reliability bewusst als jüngere, weichere Ergänzung – nicht als fünften, gleichrangigen Kanon. Aber der Gedanke gehört ins \"ehrlich statt Vanity\"-Framing: Tempo ohne Betriebsstabilität ist eine Vanity-Metric mit besserem Marketing.\n\n## Fazit\n\nDer rote Faden ist einfach. Velocity misst, was ein Team von sich behauptet. Die vier DORA-Keys messen, was tatsächlich passiert – vom Commit bis Produktion und zurück, wenn es kracht. Sie tun das auf zwei Achsen, Tempo und Stabilität, und die Kernaussage von *Accelerate* ist, dass diese Achsen kein Tradeoff sind: Die guten Teams gewinnen auf beiden.\n\nPraktisch nutze ich die Keys als Suchscheinwerfer. Lange Lead Time zeigt große Batches oder eine verstopfte Pipeline. Hohe Change Failure Rate zeigt fehlende Umkehrbarkeit. Lange Restore-Zeit zeigt, dass Recovery nicht geübt ist. Jede Zahl deutet auf eine konkrete, technische Gegenmaßnahme – kleine Batches, Trunk-Based Development, Feature Flags, Canary-Releases, Circuit Breaker. Das ist der Unterschied zwischen einer Metric, die den Zyklus verkürzt, und einer, die nur ein Dashboard füllt.\n\nUnd die Disziplin dabei: Die Keys diagnostizieren, sie belohnen nicht. In dem Moment, in dem sie zum Ziel werden, verlieren sie ihren Wert. Wer das aushält – Zahlen anschauen, ohne sie zu jagen – bekommt etwas Seltenes: einen ehrlichen Blick darauf, wo der eigene Zyklus wirklich klemmt.\n\n## Weiterführende Quellen\n\n- [DORA Metrics – dora.dev](https://dora.dev/guides/dora-metrics/)\n- [Accelerate State of DevOps Report 2022 – dora.dev](https://dora.dev/research/2022/dora-report/)\n- [DORA 2022 Report – Google Cloud Blog](https://cloud.google.com/blog/products/devops-sre/dora-2022-accelerate-state-of-devops-report-now-out)\n- [Four Keys to measure DevOps performance – Google Cloud](https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance)\n- [A history of DORA's metrics – dora.dev](https://dora.dev/insights/dora-metrics-history/)"},{"locale":"de","translation_key":"nodejs-child-process-und-skalierung","slug":"nodejs-child-process-und-skalierung","title":"child_process in Node.js: Skalierung ohne Illusionen","summary":"Node.js läuft auf einem einzigen Event Loop – CPU-Arbeit blockiert alles. Dieser Beitrag zeigt, wann fork, cluster und worker_threads wirklich helfen und wann sie nur Overhead sind.","tags":["Software","Node.js","Backend"],"published_at":"2023-09-19T10:00:00+00:00","updated_at":"2026-07-13T08:00:45.524078+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-child-process-und-skalierung/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/03aced76d96ec7a37df011e137c4b2045b7368918db7f9f930109c28376a74ba/nodejs-child-process-und-skalierung-vorlesen.mp3","audio_duration_secs":784,"text":"Nicht-blockierend heißt nicht parallel. Node.js nimmt Tausende gleichzeitiger Netzwerkverbindungen an, ohne dabei ins Straucheln zu geraten – Rechenarbeit auf mehrere Kerne verteilt es deshalb noch lange nicht. Die beiden Eigenschaften werden ständig in einen Topf geworfen, und aus dieser Verwechslung entsteht der Endpoint, der unter Last die gesamte Anwendung einfriert, ohne dass jemand versteht, warum.\n\nDer Unterschied liegt darin, woraus die Arbeit besteht: aus Warten oder aus Rechnen. Warten bekommt Node von allein in den Griff. Rechnen nicht. Dafür gibt es `child_process`, `cluster` und `worker_threads` – drei Werkzeuge mit ähnlichen Namen, sehr verschiedenen Kosten und einem gemeinsamen Missbrauchsmuster.\n\n## Ein Event Loop, ein Thread, ein Nadelöhr\n\nFangen wir bei der Wurzel an. Ein Node.js-Prozess hat einen Event Loop, und JavaScript läuft in diesem Prozess auf genau einem Thread. Das ist kein Bug, das ist das Designprinzip. Solange die Arbeit aus Warten besteht – auf eine Datenbankantwort, auf eine Datei, auf einen HTTP-Response – kann der Event Loop in der Zwischenzeit andere Dinge erledigen. Die eigentliche Ein- und Ausgabe passiert im Hintergrund über libuv, und dein Code bekommt am Ende nur den fertigen Callback. Wer verstehen will, wie diese Maschinerie im Detail tickt, findet in meinem [Node.js-Training zur Event-Loop-Architektur](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) die ausführliche Fassung.\n\nDas Problem beginnt, sobald die Arbeit nicht aus Warten besteht, sondern aus Rechnen. Ein Bild skalieren, ein großes JSON parsen und transformieren, ein Passwort mit einer teuren Hash-Funktion prüfen, eine kryptografische Operation, eine synchrone Schleife über Millionen Einträge. Diese Arbeit findet auf demselben einen Thread statt. Und solange sie läuft, kann der Event Loop nichts anderes tun – keine neuen Requests annehmen, keine Timer feuern, keine Callbacks abarbeiten. Alles steht.\n\nDer folgende Code sieht harmlos aus und rutscht in Code-Reviews trotzdem regelmäßig durch:\n\n```js\nconst http = require('node:http');\n\nfunction fibonacci(n) {\n  if (n < 2) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nhttp\n  .createServer((req, res) => {\n    if (req.url === '/compute') {\n      const result = fibonacci(45); // blocks the event loop for seconds\n      res.end(`result: ${result}`);\n    } else {\n      res.end('ok');\n    }\n  })\n  .listen(3000);\n```\n\nSolange `fibonacci(45)` rechnet, bekommt kein einziger anderer Client eine Antwort – auch nicht auf den harmlosen `/`-Pfad, der eigentlich in Mikrosekunden fertig wäre. Ein einziger langsamer Request legt den ganzen Server lahm. Genau das meint die offizielle Doku mit „Don't Block the Event Loop“.\n\n## Vier Werkzeuge, vier Aufgaben\n\nNode.js bietet für dieses Problem mehrere Werkzeuge an, und die werden regelmäßig verwechselt. Es lohnt sich, sie sauber auseinanderzuhalten:\n\n- `child_process` startet einen komplett eigenen Betriebssystemprozess mit eigenem V8, eigenem Heap, eigenem Event Loop. Kommunikation läuft über Pipes bzw. – bei `fork` – über einen IPC-Kanal per Message-Passing. Kein geteilter Speicher.\n- `cluster` startet mehrere Node-Instanzen hinter einem gemeinsamen Port und verteilt eingehende Verbindungen auf sie. Es baut intern auf `child_process.fork()` auf und dient dem Request-Durchsatz.\n- `worker_threads` startet einen weiteren Thread innerhalb desselben Prozesses. Jeder Worker hat sein eigenes V8-Isolate und seinen eigenen Event Loop, kann aber optional echten Speicher mit dem Hauptthread teilen. Gedacht für CPU-Arbeit.\n- Die normalen asynchronen APIs sind für alles, was I/O ist – und das braucht keine der drei oberen Optionen.\n\nDiesen letzten Punkt betone ich bewusst, weil dort der häufigste Denkfehler lauert. Aber der Reihe nach.\n\n## child_process: spawn, exec, execFile, fork\n\nDas Modul `node:child_process` bietet vier Wege, einen Kindprozess zu starten, und die Unterschiede sind praxisrelevant.\n\n`spawn(command, args, options)` startet ein Programm und gibt dir dessen `stdout` und `stderr` als Streams. Es puffert nichts und startet standardmäßig keine Shell. Das ist die richtige Wahl, wenn die Ausgabe groß sein kann oder du sie streamend verarbeiten willst.\n\n`exec(command, options, callback)` startet eine echte Shell und puffert die gesamte Ausgabe im Speicher, bevor der Callback aufgerufen wird. Das ist bequem für kurze Kommandos, hat aber zwei Tücken: Der Default für `maxBuffer` liegt bei 1 MB – wird die Ausgabe größer, killt Node den Prozess mit `ERR_CHILD_PROCESS_STDIO_MAXBUFFER`. Und weil eine Shell im Spiel ist, ist `exec` mit ungeprüftem Input eine Einladung zur Shell-Injection.\n\n`execFile(file, args, options, callback)` verhält sich wie `exec`, startet aber keine Shell. Das ist sicherer und effizienter, wenn du ohnehin nur ein konkretes Programm mit Argumenten aufrufst.\n\n```js\nconst { execFile } = require('node:child_process');\n\nexecFile('git', ['rev-parse', 'HEAD'], (err, stdout) => {\n  if (err) throw err;\n  console.log('current commit:', stdout.trim());\n});\n```\n\nDie Auswahl passt in drei Zeilen: kurze Ausgabe eines konkreten Programms – `execFile`. Große oder streamende Ausgabe – `spawn`. `exec` mit Shell nur, wenn du die Shell-Features (Pipes, Globbing) wirklich brauchst und den Input kontrollierst.\n\nDer interessanteste der vier ist `fork`. Es ist ein Spezialfall von `spawn`, der gezielt eine neue Node-Instanz startet – über `process.execPath`, denselben Node-Binary – und automatisch einen IPC-Kanal einrichtet. Damit kannst du zwischen Eltern- und Kindprozess Messages austauschen, ohne dich um Pipes und Serialisierung von Hand zu kümmern.\n\n## Das Hauptbeispiel: schwere Berechnung in einem fork\n\nNehmen wir das blockierende Fibonacci-Beispiel von oben und lagern die Rechnung in einen Kindprozess aus. Der Elternprozess bleibt reaktionsfähig, weil die CPU-Last in einem völlig anderen OS-Prozess landet.\n\nZuerst der Worker in `worker.js`:\n\n```js\n// worker.js\nfunction fibonacci(n) {\n  if (n < 2) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nprocess.on('message', ({ n }) => {\n  const result = fibonacci(n);\n  process.send({ n, result });\n});\n```\n\nUnd der Elternprozess, der ihn startet und beauftragt:\n\n```js\n// main.js\nconst { fork } = require('node:child_process');\nconst http = require('node:http');\n\nconst child = fork('./worker.js');\n\nconst pending = new Map();\nchild.on('message', ({ n, result }) => {\n  const res = pending.get(n);\n  if (res) {\n    res.end(`fibonacci(${n}) = ${result}`);\n    pending.delete(n);\n  }\n});\n\nhttp\n  .createServer((req, res) => {\n    if (req.url === '/compute') {\n      pending.set(45, res);\n      child.send({ n: 45 }); // heavy work happens elsewhere\n    } else {\n      res.end('ok'); // stays responsive during the computation\n    }\n  })\n  .listen(3000);\n```\n\nDer entscheidende Punkt an dieser Stelle: Der `/`-Pfad antwortet jetzt sofort, auch während `/compute` noch rechnet. Der Event Loop des Hauptprozesses ist frei, weil die teure Schleife in einem separaten Prozess mit eigenem V8-Heap läuft. Die Kommunikation zwischen beiden geht ausschließlich über Messages – hier per `child.send()` und dem `message`-Event.\n\nGenau hier lohnt ein zweiter Blick: `send` ist kein Shared Memory. Die Message wird serialisiert und im Kindprozess als Kopie neu aufgebaut. Der Default ist `serialization: 'json'`, und JSON verliert Typen – ein `Date` wird zum String, `undefined` verschwindet, `BigInt` funktioniert gar nicht. Wer strukturierte Werte über IPC schicken will, kann `serialization: 'advanced'` setzen, was den Structured-Clone-Algorithmus nutzt und deutlich mehr Typen erhält.\n\nDer folgende Ablauf zeigt das Prinzip als Sequenz:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Main as Main Prozess<br/>(Event Loop frei)\n    participant Child as Forked Prozess<br/>(eigener V8-Heap)\n    Client->>Main: GET /compute\n    Main->>Child: send({ n: 45 })\n    Note over Main: Event Loop bleibt frei<br/>für andere Requests\n    Child->>Child: heavy computation\n    Child-->>Main: message({ result })\n    Main-->>Client: HTTP 200 result\n```\n\n## worker_threads: dasselbe Ziel, geteilter Speicher\n\nEin `fork` ist robust, aber teuer. Jeder Kindprozess bringt ein vollständiges V8 und einen eigenen Heap mit – das kostet Speicher und Startzeit. Wenn du CPU-Arbeit parallelisieren willst und dabei nicht die volle Isolation eines eigenen Prozesses brauchst, sind `worker_threads` die leichtere Alternative. Sie sind seit Node 12 stabil und 2023 längst produktiver Standard.\n\nEin Worker läuft im selben Prozess, aber in einem eigenen Thread mit eigenem V8-Isolate und eigenem Event Loop. Dieselbe Rechnung sieht so aus:\n\n```js\n// task.js\nconst { parentPort, workerData } = require('node:worker_threads');\n\nfunction fibonacci(n) {\n  if (n < 2) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nparentPort.postMessage(fibonacci(workerData.n));\n```\n\n```js\n// main-threads.js\nconst { Worker } = require('node:worker_threads');\n\nfunction computeFib(n) {\n  return new Promise((resolve, reject) => {\n    const worker = new Worker('./task.js', { workerData: { n } });\n    worker.on('message', resolve);\n    worker.on('error', reject);\n  });\n}\n\ncomputeFib(45).then((result) => {\n  console.log('fibonacci(45) =', result);\n});\n```\n\nDer große Unterschied zum `fork`: Worker-Threads können echten Speicher teilen. Ein `SharedArrayBuffer` ist für Haupt- und Worker-Thread derselbe Speicherbereich – keine Kopie, keine Serialisierung. Alternativ lässt sich ein `ArrayBuffer` per `transferList` übergeben, was ein Zero-Copy-Transfer ist: Der Buffer wandert zum Empfänger und ist beim Sender danach unbrauchbar. Für große Datenmengen zwischen Threads ist das ein echter Vorteil, den ein separater Prozess prinzipbedingt nicht bieten kann.\n\n## Der Fallstrick, der am meisten Schaden anrichtet\n\nDer Fehler, der in echten Codebasen die meiste Zeit verbrennt, ist dieser: I/O-bound Arbeit mit `worker_threads` oder `cluster` „beschleunigen“ zu wollen. Er ist mir in mehreren Projekten begegnet, jedes Mal mit derselben Begründung.\n\nDie Motivation ist verständlich. Jemand hat gehört, dass Worker parallelisieren, sieht einen Endpoint, der viele Datenbankabfragen oder HTTP-Calls macht, und packt das Ganze in einen Worker-Pool. Das Ergebnis ist regelmäßig langsamer als vorher. Der Grund: Netzwerk- und Datei-I/O ist in Node.js bereits asynchron und blockiert den Event Loop überhaupt nicht. Da ist nichts zu entlasten. Die Doku sagt es unmissverständlich: Worker-Threads helfen bei I/O-intensiver Arbeit nicht nennenswert. Was du bekommst, ist der Overhead für Thread-Erstellung und Message-Passing – ohne jeden Gewinn.\n\nDie Regel ist also einfach und trotzdem wird ständig gegen sie verstoßen:\n\n- Ist die Arbeit I/O-bound – Datenbank, Netzwerk, Dateisystem? Dann bleib bei den normalen asynchronen APIs. Worker und Prozesse bringen hier nichts außer Komplexität.\n- Ist die Arbeit CPU-bound – Hashing, Bildverarbeitung, Kompression, Krypto, große synchrone Transformationen? Erst dann sind `worker_threads` oder `child_process` das richtige Werkzeug.\n\nEin zweiter Fallstrick sitzt gleich daneben: pro Task einen Worker oder Prozess zu erzeugen. Die Erstellung ist teuer – V8 muss initialisiert werden, Speicher wird allokiert. Wer bei jedem Request einen frischen Worker startet, macht die Sache oft langsamer, nicht schneller. Die Antwort heißt Worker-Pool: eine feste Zahl wiederverwendbarer Worker, die Aufgaben aus einer Queue abarbeiten. Dieselbe Überlegung gilt für `fork` – halte die Kindprozesse am Leben und schick ihnen nacheinander Arbeit, statt sie ständig neu zu starten.\n\n## cluster: Durchsatz, nicht Entlastung\n\nBleibt `cluster`, und auch hier gibt es ein hartnäckiges Missverständnis. `cluster` löst nicht das Problem der einzelnen blockierenden Berechnung. Es löst das Problem des Durchsatzes: Ein einzelner Node-Prozess nutzt nur einen Kern, aber deine Maschine hat mehrere. `cluster` startet pro Kern eine Node-Instanz, alle lauschen hinter demselben Port, und der Primary verteilt eingehende Verbindungen im Round-Robin.\n\n```js\nconst cluster = require('node:cluster');\nconst http = require('node:http');\nconst os = require('node:os');\n\nif (cluster.isPrimary) {\n  for (let i = 0; i < os.cpus().length; i++) {\n    cluster.fork();\n  }\n  cluster.on('exit', (worker) => {\n    console.log(`worker ${worker.process.pid} died, restarting`);\n    cluster.fork();\n  });\n} else {\n  http\n    .createServer((req, res) => res.end(`handled by pid ${process.pid}`))\n    .listen(3000);\n}\n```\n\nDamit verdoppelt oder vervierfacht sich der Durchsatz an gleichzeitigen Requests. Aber wenn ein einzelner Request eine sekundenlange synchrone Berechnung auslöst, blockiert diese immer noch den Worker, der sie bearbeitet. `cluster` macht aus vielen langsamen Requests nur dann viele parallele, wenn jeder auf einem anderen Worker landet – und die begrenzte Zahl an Workern ist irgendwann erschöpft. Für das eigentliche CPU-Problem pro Request brauchst du weiterhin `worker_threads` oder ausgelagerte Prozesse. Übrigens ist `cluster.isPrimary` seit Node 16 der bevorzugte Name; `isMaster` existiert noch, gilt aber als veraltet.\n\n## Wann was: die Entscheidung auf einen Blick\n\nDie Entscheidung lässt sich auf wenige Fragen eindampfen:\n\n```mermaid\nflowchart TD\n    A[Arbeit einordnen] --> B{I/O-bound?}\n    B -->|Ja| C[Normale async APIs<br/>keine Worker nötig]\n    B -->|Nein, CPU-bound| D{Geteilter Speicher<br/>oder leichtgewichtig?}\n    D -->|Ja| E[worker_threads<br/>SharedArrayBuffer möglich]\n    D -->|Nein, Isolation<br/>oder externes Skript| F[child_process / fork<br/>eigener Prozess + IPC]\n    A --> G{Nur mehr Durchsatz<br/>auf allen Kernen?}\n    G -->|Ja| H[cluster<br/>mehrere Instanzen, ein Port]\n```\n\nDie drei Werkzeuge beantworten verschiedene Fragen – sie konkurrieren nicht um dieselbe:\n\n- `child_process` / `fork` gibt dir einen eigenen Prozess mit eigenem Heap und Kommunikation über kopierte IPC-Messages – maximale Isolation, ideal für externe Programme oder eigenständige Node-Skripte.\n- `cluster` gibt dir mehrere Node-Instanzen hinter einem Port für mehr Request-Durchsatz – es skaliert Instanzen, nicht einzelne Berechnungen.\n- `worker_threads` gibt dir Threads im selben Prozess mit optional geteiltem Speicher – die richtige Wahl, um CPU-Arbeit zu parallelisieren, ohne einen ganzen Prozess hochzufahren.\n\n## Fazit\n\nDie Illusion, gegen die dieser Beitrag anschreibt, ist die bequemste: dass Node.js CPU-Arbeit schon irgendwie von allein auf alle Kerne verteilt. Tut es nicht. Ein Prozess, ein Event Loop, ein JS-Thread – und jede synchrone Rechenlast blockiert alles andere. Wer das akzeptiert, trifft danach die richtigen Entscheidungen fast von selbst: I/O braucht keine Worker, sondern nur die asynchronen APIs, die Node ohnehin mitbringt. Erst CPU-Arbeit rechtfertigt schwereres Geschütz – `worker_threads` für Parallelität im Prozess mit geteiltem Speicher, `fork` für isolierte Prozesse, `cluster` für reinen Durchsatz.\n\nDer teuerste Fehler ist nicht, das falsche Werkzeug zu wählen. Er ist, ein Werkzeug zu greifen, wo gar kein Problem ist – I/O mit Workern zu „beschleunigen“ und dafür Komplexität und Overhead einzukaufen, ohne eine einzige Millisekunde zu gewinnen. Miss erst, ob du überhaupt CPU-gebunden bist. Wenn du es bist, weißt du jetzt, wohin die Arbeit gehört. Wer ohnehin große Datenmengen durch seine Anwendung schiebt, findet in meinem Beitrag zu [Node.js-Streams und Backpressure](https://www.mikebild.dev/de/blog/nodejs-streams-und-backpressure/) die passende Ergänzung – denn oft ist die beste Skalierung die, bei der man Daten gar nicht erst komplett in den Speicher lädt.\n\n## Weiterführende Quellen\n\n- Repository mit den Codebeispielen: [github.com/mikebild/introduction-nodejs](https://github.com/mikebild/introduction-nodejs)\n- [child_process – offizielle Node.js-Doku](https://nodejs.org/api/child_process.html)\n- [worker_threads – offizielle Node.js-Doku](https://nodejs.org/api/worker_threads.html)\n- [cluster – offizielle Node.js-Doku](https://nodejs.org/api/cluster.html)\n- [Don't Block the Event Loop – Node.js Learn](https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop)"},{"locale":"de","translation_key":"lambda-performance-und-cold-starts","slug":"lambda-performance-und-cold-starts","title":"Lambda-Performance und Cold Starts verstehen","summary":"Was ein Cold Start bei AWS Lambda wirklich ist, welche Hebel du steuern kannst – von Bundle-Size über Init-Code und Memory bis Provisioned Concurrency – und wie du das Ganze sauber misst.","tags":["Software","AWS","Cloud"],"published_at":"2023-08-08T10:00:00+00:00","updated_at":"2026-07-13T10:04:44.118576+00:00","url":"https://www.mikebild.dev/de/blog/lambda-performance-und-cold-starts/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/e10542d20c6b719fc93b26be410695407c31eff2ba0adeb9d4fe3422384e398a/lambda-performance-und-cold-starts-vorlesen.mp3","audio_duration_secs":829,"text":"Ein Endpoint antwortet in 40 Millisekunden, beim nächsten Aufruf in 900 – am Code hat sich nichts geändert, und das Monitoring meldet keinen Fehler. Der Unterschied liegt allein darin, ob AWS Lambda eine vorhandene Execution Environment wiederverwenden konnte oder eine neue erzeugen musste. Und jede Millisekunde Arbeit, die außerhalb des Handlers passiert, bezahlt der erste Aufrufer dieser neuen Umgebung – vollständig und sichtbar.\n\nDieser Ausreißer heißt Cold Start, und sein schlechter Ruf ist unverdient. Er ist weder ein Bug noch das Zeichen einer schlecht gebauten Funktion, sondern eine direkte Folge des Ausführungsmodells von Lambda. Wer dieses Modell einmal durchschaut hat, dem zerfällt das diffuse \"manchmal lahm\" in eine Handvoll konkreter Stellschrauben – und ein paar hartnäckige Fehlannahmen sortieren sich gleich mit aus.\n\n## Was bei einem Cold Start wirklich passiert\n\nLambda führt deinen Code nicht in einem dauerhaft laufenden Prozess aus, sondern in einer sogenannten Execution Environment. Das ist eine isolierte, kurzlebige Runtime, die Lambda bei Bedarf erzeugt, eine Weile am Leben hält und irgendwann wieder wegwirft. Der Lifecycle dieser Umgebung besteht aus drei Phasen: Init, Invoke und Shutdown.\n\nEin Cold Start ist nichts anderes als die Init-Phase einer frisch erzeugten Environment. Dabei passiert einiges, bevor deine eigentliche Logik überhaupt anläuft:\n\n- Lambda lädt deinen Code herunter – aus einem internen Speicher beziehungsweise bei Container-Images aus der Registry.\n- Die Runtime wird initialisiert, also zum Beispiel der Node.js-Prozess hochgefahren.\n- Dein Function-Init-Code läuft: alles, was du außerhalb des Handlers auf Modulebene geschrieben hast – Imports, das Anlegen von SDK-Clients, das Einlesen von Konfiguration.\n\nErst danach folgt die Invoke-Phase, in der dein Handler mit dem konkreten Event aufgerufen wird. Ein wichtiges Detail für die Praxis: Die Init-Phase hat einen harten Timeout von 10 Sekunden. Wer teure Arbeit auf Modulebene erledigt, kann diese Grenze tatsächlich reißen – dazu später mehr.\n\nNach dem Invoke wirft Lambda die Umgebung nicht sofort weg. Sie wird eingefroren (\"frozen\") und bei einem weiteren Aufruf innerhalb kurzer Zeit wieder aufgetaut (\"thawed\"). Dann sprechen wir von einem Warm Invoke: Die komplette Init-Phase entfällt, weil Runtime und Init-Code bereits gelaufen sind. Es läuft nur noch dein Handler. Das ist der Grund, warum derselbe Endpoint mal 40 und mal 900 Millisekunden braucht – der Unterschied ist schlicht, ob eine warme Environment bereitstand oder eine neue erzeugt werden musste.\n\n```mermaid\nflowchart TD\n    Req[Eingehender Invoke] --> Q{Warme Environment<br/>verfügbar?}\n    Q -->|Nein: Cold Start| C1[Code herunterladen]\n    C1 --> C2[Runtime initialisieren]\n    C2 --> C3[Init-Code außerhalb<br/>des Handlers ausführen]\n    C3 --> H[Handler ausführen]\n    Q -->|Ja: Warm Invoke| H\n    H --> F[Environment einfrieren<br/>für spätere Invokes]\n    F -.wiederverwenden.-> Q\n```\n\nDas Diagramm macht den zentralen Punkt sichtbar: Der teure Teil – Download, Runtime-Init, Function-Init – passiert nur auf dem Cold-Pfad. Die \"Init Duration\", die du gleich noch in den Logs findest, ist genau die Summe dieser drei Schritte. Bei jedem Warm Invoke springt Lambda direkt zum Handler.\n\n## Der erste Hebel: das Bundle klein halten\n\nDer offensichtlichste Beitrag zum Cold Start ist die Zeit, die es braucht, deinen Code zu laden und die Module zu parsen. Je größer das Bundle und je verzweigter der Import-Graph, desto länger dauert das. Das klingt banal, aber ich sehe regelmäßig Deployment-Pakete von mehreren Megabyte, in denen ein komplettes SDK, drei Datumsbibliotheken und ungenutzte Teile eines Frameworks mitreisen.\n\nDie pragmatische Antwort heißt Bundling mit Tree-Shaking. Ein Bundler wie esbuild wirft alles raus, was nicht tatsächlich erreicht wird, und schnürt den Rest zu einer kompakten Datei. Ein typischer Aufruf sieht so aus:\n\n```bash\nesbuild src/handler.ts \\\n  --bundle \\\n  --minify \\\n  --platform=node \\\n  --target=node18 \\\n  --external:@aws-sdk/* \\\n  --outfile=dist/handler.js\n```\n\nZwei Dinge sind hier bewusst gewählt. Das Target ist `node18` – die zu diesem Zeitpunkt aktuelle LTS-Runtime von Lambda. Und das AWS SDK v3 wird über `--external:@aws-sdk/*` aus dem Bundle herausgehalten, weil es in der Node18-Runtime ohnehin vorinstalliert ist. Es mit einzupacken würde das Paket nur unnötig aufblähen, ohne einen Vorteil zu bringen.\n\nWer mit AWS SAM oder dem CDK arbeitet, muss sich um den Aufruf oft nicht selbst kümmern: Das Construct `NodejsFunction` nutzt esbuild intern und bündelt automatisch. Der Punkt bleibt derselbe – weniger Code und weniger Dependencies bedeuten kürzeren Download und schnelleres Modul-Laden, und damit einen kürzeren Cold Start.\n\n## Der zweite Hebel: Init-Code an die richtige Stelle\n\nJetzt kommt der Teil, der in der Praxis den größten Unterschied macht und gleichzeitig am häufigsten falsch gemacht wird: Wo legst du deine Clients und Verbindungen an?\n\nAlles, was du auf Modulebene außerhalb des Handlers schreibst, läuft genau einmal pro Execution Environment – in der Init-Phase. Bei jedem folgenden Warm Invoke wird das Ergebnis wiederverwendet. Genau dorthin gehört daher alles, was wiederverwendbar und über Aufrufe hinweg stabil ist: SDK-Clients, Datenbank-Pools, geparste Konfiguration.\n\n```ts\n// module scope — runs once per execution environment (Init phase)\nimport { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\nimport { GetItemCommand } from \"@aws-sdk/client-dynamodb\";\n\n// created once, reused across every warm invoke\nconst client = new DynamoDBClient({});\n\nexport const handler = async (event: { id: string }) => {\n  const result = await client.send(\n    new GetItemCommand({\n      TableName: \"orders\",\n      Key: { id: { S: event.id } },\n    })\n  );\n\n  return { statusCode: 200, body: JSON.stringify(result.Item) };\n};\n```\n\nDer `DynamoDBClient` wird hier einmal erzeugt und bleibt danach in der Umgebung erhalten. Jeder warme Invoke greift auf dieselbe Instanz zu – inklusive der bereits aufgebauten HTTP-Verbindungen. Genau hier liegt ein oft übersehener Vorteil des AWS SDK v3: HTTP Keep-Alive ist standardmäßig aktiv. Die TCP- und TLS-Handshakes fallen also nur beim ersten Aufruf an und werden danach wiederverwendet.\n\nEin kurzer, aber praxisrelevanter Hinweis zur Migration: Beim älteren AWS SDK v2 war Keep-Alive nicht automatisch an. Dort musst du die Umgebungsvariable `AWS_NODEJS_CONNECTION_REUSE_ENABLED=1` setzen (verfügbar ab v2.463.0), um dasselbe Verhalten zu bekommen. Wer noch v2-Code betreibt, sollte das prüfen – es ist eine der billigsten Latenzverbesserungen überhaupt.\n\n### Lazy-Init für das, was nicht jeder Invoke braucht\n\nNicht jede Ressource sollte in die Init-Phase. Wenn du eine teure Verbindung nur in einem von zwanzig Aufrufen tatsächlich brauchst, verlängert ihr Aufbau auf Modulebene jeden einzelnen Cold Start – auch die, die sie nie nutzen. Hier lohnt sich Lazy-Init: Die Ressource wird erst beim ersten tatsächlichen Bedarf erzeugt und danach für die Lebensdauer der Environment gecacht.\n\n```ts\nimport { createPool, type Pool } from \"./db\";\n\nlet dbPromise: Promise<Pool> | undefined;\n\n// created on first use, then cached for the environment's lifetime\nconst getDb = (): Promise<Pool> => (dbPromise ??= createPool());\n\nexport const handler = async (event: { needsDb: boolean }) => {\n  if (!event.needsDb) {\n    return { statusCode: 204 };\n  }\n\n  const db = await getDb();\n  const rows = await db.query(\"SELECT 1\");\n  return { statusCode: 200, body: JSON.stringify(rows) };\n};\n```\n\nDer `??=`-Operator sorgt dafür, dass der Pool nur ein einziges Mal aufgebaut wird. Beim ersten Aufruf, der ihn wirklich braucht, entsteht eine kleine Verzögerung – dafür bleibt die Init-Phase schlank und schnell, und alle Invokes, die den Pool nicht benötigen, zahlen nichts dafür. Es ist die Balance zwischen \"alles vorab\" und \"alles pro Aufruf\", und die richtige Grenze hängt davon ab, wie oft eine Ressource tatsächlich gebraucht wird.\n\n## Der dritte Hebel: Memory ist auch CPU\n\nDas ist die Stellschraube, die am meisten unterschätzt wird, weil sie missverständlich benannt ist. Der Konfigurationswert heißt `MemorySize` und lässt sich zwischen 128 MB und 10.240 MB in 1-MB-Schritten einstellen. Aber er steuert eben nicht nur den Speicher: CPU wird linear proportional zum Memory zugeteilt. Bei genau 1.769 MB bekommt deine Funktion eine vollständige vCPU; am oberen Ende stehen bis zu 6 vCPUs zur Verfügung.\n\nDas hat unmittelbare Konsequenzen. Eine Funktion, die CPU-gebundene Arbeit leistet – JSON parsen, Kryptografie, Datenaufbereitung – wird mit mehr Memory schneller, obwohl sie den zusätzlichen Speicher gar nicht braucht. Und interessanterweise gilt das auch für den Cold Start selbst: Das Laden und Initialisieren der Runtime ist CPU-Arbeit, die von mehr zugeteilter Rechenleistung profitiert.\n\nDer Fehler, den ich hier am häufigsten sehe, ist eines von zwei Extremen. Entweder bleibt die Funktion aus Sparsamkeit bei 128 MB und ist dadurch bei CPU-Last unnötig langsam – oder jemand schraubt das Memory blind auf ein hohes Niveau in der Hoffnung, dass \"viel hilft viel\". Beides ist Raten. Mehr Memory kostet mehr pro Millisekunde, und ab einem bestimmten Punkt bringt es keinen Latenzgewinn mehr, weil die Funktion nicht mehr CPU-, sondern I/O-gebunden ist. Dann wartest du auf eine Datenbank oder eine externe API, und da hilft keine zusätzliche vCPU.\n\nDie einzige seriöse Antwort ist Messen. Für genau diesen Zweck gibt es das Open-Source-Tool AWS Lambda Power Tuning, das deine Funktion mit verschiedenen Memory-Werten durchprobiert und Kosten gegen Latenz aufträgt. Statt zu raten, siehst du die tatsächliche Kurve für deine konkrete Workload und wählst den Punkt, der zu deinem Ziel passt.\n\n## Der vierte Hebel: Provisioned Concurrency für planbare Latenz\n\nManchmal reicht es nicht, den Cold Start zu verkürzen – du willst ihn für bestimmte Funktionen ganz vermeiden. Das ist der Fall bei latenzkritischen, gut vorhersehbaren Lasten: eine Funktion hinter einem Login-Flow, ein Endpoint, der werktags um neun Uhr eine planbare Lastspitze bekommt.\n\nDafür gibt es Provisioned Concurrency. Du konfigurierst über `ProvisionedConcurrentExecutions` eine Anzahl von Environments, die Lambda dauerhaft vor-initialisiert bereithält – mit bereits gelaufener Init-Phase. Aufrufe treffen dann auf eine warme Umgebung, ohne dass ein Cold Start entsteht. Wichtig ist das Detail, dass Provisioned Concurrency auf einem Alias oder einer konkreten Version konfiguriert wird, nicht auf `$LATEST`. Wer diese Environments zusätzlich an eine schwankende Last anpassen will, kann sie über Application Auto Scaling dynamisch skalieren.\n\nDas kostet allerdings bares Geld, und zwar lastunabhängig: Vorgehaltene Environments werden auch dann berechnet, wenn sie im Leerlauf stehen. Provisioned Concurrency ist deshalb kein Allheilmittel, das man über jede Funktion legt, sondern ein gezieltes Werkzeug für die wenigen Stellen, an denen planbare, niedrige Latenz den Aufpreis rechtfertigt. Für die meisten Hintergrund- und Event-getriebenen Funktionen ist der gelegentliche Cold Start völlig unkritisch – dort wäre Provisioned Concurrency verschenktes Geld.\n\nEine Randnotiz, weil die Frage in Reviews oft kommt: Für Java gibt es seit Ende 2022 zusätzlich Lambda SnapStart, das über einen Snapshot der initialisierten Umgebung arbeitet. Für Node.js ist das derzeit kein Thema – SnapStart ist zu diesem Zeitpunkt eine Java-only-Option. Für unsere TypeScript-Funktionen bleiben die Hebel oben die relevanten.\n\n## Messen, nicht vermuten\n\nDer rote Faden durch all diese Hebel ist derselbe: Ohne Messung bleibt jede Optimierung ein Bauchgefühl. Zum Glück liefert Lambda die entscheidenden Zahlen frei Haus. Jeder Invoke schreibt eine REPORT-Zeile in die CloudWatch-Logs, und bei einem Cold Start enthält sie ein zusätzliches Feld:\n\n```json\n{\n  \"Duration\": \"42.11 ms\",\n  \"BilledDuration\": \"43 ms\",\n  \"MaxMemoryUsed\": \"98 MB\",\n  \"InitDuration\": \"312.44 ms\"\n}\n```\n\nDas Feld `InitDuration` erscheint ausschließlich bei einem Cold Start – es ist genau die Zeit für Download, Runtime-Init und deinen Function-Init-Code. Findest du diese Zeile in den Logs, weißt du zweierlei: Erstens war das ein Cold Start. Zweitens siehst du an der Zahl, wie teuer deine Init-Phase tatsächlich ist. Steigt `InitDuration` in Richtung Sekunden, ist das ein deutliches Signal, dass zu viel auf Modulebene passiert.\n\nWer tiefer schauen will, aktiviert AWS X-Ray. Dort taucht die Initialisierung als eigenes Subsegment im Trace auf, sauber getrennt von der Handler-Zeit. Das ist besonders wertvoll, wenn du herausfinden willst, ob deine Latenz aus dem Cold Start kommt oder aus einem langsamen Downstream-Aufruf im Handler – zwei völlig unterschiedliche Probleme, die im reinen Gesamtwert nicht auseinanderzuhalten sind.\n\n## Die Hebel im Überblick\n\nWenn ich die konkreten Stellschrauben zusammenfassen soll, ergibt sich eine kompakte Liste, die ich in Reviews gerne als Checkliste verwende:\n\n- Bundle klein halten mit esbuild und Tree-Shaking, das in der Runtime vorhandene AWS SDK als `external` markieren.\n- Wenige Dependencies einsetzen und den Import-Graph bewusst schlank halten.\n- Wiederverwendbare Clients und Verbindungen außerhalb des Handlers anlegen und über Warm Invokes wiederverwenden.\n- Lazy-Init für teure, selten genutzte Ressourcen, damit die Init-Phase schlank bleibt.\n- Memory als CPU-Regler verstehen und empirisch tunen – mit Lambda Power Tuning statt Bauchgefühl.\n- Provisioned Concurrency gezielt für die wenigen latenzkritischen, planbaren Funktionen einsetzen.\n- Init Duration in CloudWatch und X-Ray messen, statt zu vermuten.\n\n## Fazit\n\nCold Starts sind kein Makel, sondern eine Eigenschaft des Ausführungsmodells von Lambda – und genau deshalb sind sie steuerbar, sobald man das Modell versteht. Die Init-Phase läuft einmal pro Execution Environment, warme Invokes überspringen sie, und fast alles, was du an der Latenz drehen kannst, hängt daran, wie schwer oder leicht du diese Init-Phase machst.\n\nIn der Praxis gibt es hier keine einzelne große Lösung. Was wirkt, ist ein Zusammenspiel kleiner, verständlicher Entscheidungen: ein schlankes Bundle, Clients an der richtigen Stelle, ein sinnvoll gewählter Memory-Wert und – nur dort, wo es sich wirklich lohnt – Provisioned Concurrency. Und darüber steht immer das Messen. Wer die Init Duration im Blick behält, verwandelt das diffuse \"manchmal lahm\" in eine Zahl, an der man arbeiten kann. Das ist der eigentliche Gewinn: aus einem Bauchgefühl wird ein Engineering-Problem mit klaren Hebeln.\n\nIm größeren Bild bleibt Lambda nur ein Baustein. API, Persistenz, Identität, asynchrone Verarbeitung und Beobachtbarkeit müssen gemeinsam betrachtet werden; eine schnelle Funktion allein ergibt noch kein belastbares System.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-aws-serverless.html\n- [Lambda execution environment lifecycle](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html)\n- [Configure function memory (Memory = CPU)](https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html)\n- [Understanding and remediating cold starts (AWS Compute Blog)](https://aws.amazon.com/blogs/compute/understanding-and-remediating-cold-starts-an-aws-lambda-perspective/)\n- [Operating Lambda: Performance optimization – Part 1](https://aws.amazon.com/blogs/compute/operating-lambda-performance-optimization-part-1/)\n- [Reuse connections with keep-alive (AWS SDK v3)](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-reusing-connections.html)\n- [Reuse connections with keep-alive (AWS SDK v2)](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-reusing-connections.html)\n- [Lambda function scaling and Provisioned Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html)"},{"locale":"de","translation_key":"rxjs-in-node-ereignisstroeme","slug":"rxjs-in-node-ereignisstroeme","title":"RxJS in Node.js: Event Streams reaktiv verarbeiten","summary":"RxJS in Node.js: Wie fromEvent einen EventEmitter in ein Observable verwandelt, Operatoren serverseitige Ströme deklarativ transformieren und warum RxJS keine echte Backpressure hat.","tags":["Software","Node.js","Backend"],"published_at":"2023-07-25T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/rxjs-in-node-ereignisstroeme/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/2d01791590ae6291761154cb43575f731ad45beb04ed4a289540d9208270a4ce/rxjs-in-node-ereignisstroeme-vorlesen.mp3","audio_duration_secs":844,"text":"```js\nlet buffer = [];\nlet timer = null;\n\nemitter.on('data', line => {\n  const entry = JSON.parse(line);\n  if (entry.level !== 'error') return;\n  buffer.push(entry);\n  if (!timer) {\n    timer = setTimeout(() => {\n      saveErrors(buffer);\n      buffer = [];\n      timer = null;\n    }, 1000);\n  }\n});\n```\n\nDrei Anforderungen stecken in diesem Handler: parsen, filtern, im Sekundentakt gebündelt wegschreiben. Der Zwischenzustand liegt in zwei Modulvariablen, geprüft wird er nur noch mit Zeitgeber-Attrappen. Kommt morgen ein zweiter Konsument dazu oder soll zusätzlich nach Dienst gruppiert werden, wächst die Verschachtelung weiter – und mit ihr die Zahl der Stellen, an denen der geteilte Zustand kippen kann.\n\nRxJS setzt genau hier an: überall dort, wo aus einem Event Stream ein komponierbares Programm werden soll. Wer sich das imperative Fundament schon angesehen hat – etwa im Beitrag zu [EventEmitter und Event-Modell](https://www.mikebild.dev/de/blog/nodejs-eventemitter-und-ereignismodell/) – erkennt in RxJS dieselbe Idee, nur von der anderen Seite aufgezäumt.\n\n## Von on/emit zu deklarativen Strömen\n\nDer `EventEmitter` ist imperativ. Ich sage: „Wenn `data` passiert, führe diese Funktion aus.“ Das ist ein Befehl. Jeder Handler ist eine eigene kleine Insel, und wenn ich mehrere Schritte verketten will, verknüpfe ich sie von Hand über gemeinsamen Zustand.\n\nRxJS beschreibt denselben Event Stream deklarativ. Ich sage nicht mehr „tu dies, wenn jenes passiert“, sondern „dieser Strom ist die Quelle, transformiert durch diese Kette von Schritten“. Die Kette ist eine Beschreibung, kein Ablauf. Erst beim `subscribe` wird sie aktiviert.\n\nDie Brücke zwischen beiden Welten ist `fromEvent`. Der Operator nimmt einen Node-`EventEmitter` und einen Event-Namen und liefert ein Observable:\n\n```js\nconst { EventEmitter } = require('events');\nconst { fromEvent } = require('rxjs');\n\nconst emitter = new EventEmitter();\nconst data$ = fromEvent(emitter, 'data');\n\nconst subscription = data$.subscribe({\n  next: value => console.log('received', value),\n});\n\nemitter.emit('data', { level: 'info', message: 'server started' });\n```\n\n`fromEvent(emitter, 'data')` ändert nichts an der Semantik des Emitters. Es registriert bei jedem `subscribe` einen Listener über `addListener` und entfernt ihn bei `unsubscribe` wieder. Das Observable ist damit ein Adapter: Der Emitter bleibt die Quelle, RxJS legt nur eine komponierbare Schicht darüber. Wer den Unterschied zwischen dem Push-Modell von Observables und dem Pull-Modell von Iteratoren vertiefen will, findet das im Beitrag zu [RxJS: Push und Pull](https://www.mikebild.dev/de/blog/rxjs-push-und-pull/).\n\nEin Hinweis zur Konvention: Ich hänge an Variablen, die ein Observable halten, ein `$` an (`data$`). Das ist kein Zwang, hat sich in der RxJS-Welt aber eingebürgert und macht im Code sofort sichtbar, was ein Strom ist und was ein einzelner Wert.\n\n## Die Pipeline: Operatoren als Pure Functions\n\nDer eigentliche Gewinn liegt in den Operatoren. Sie sind Pure Functions, die ein Observable entgegennehmen und ein neues zurückgeben. Verkettet werden sie über `.pipe(...)`. In RxJS 7 importiere ich alles – Erzeugungsfunktionen wie `fromEvent` und Operatoren wie `map` – direkt aus `'rxjs'`. Der frühere Import aus `'rxjs/operators'` funktioniert noch, ist aber überholt.\n\nEin typisches serverseitiges Beispiel ist Log-Verarbeitung. Ich möchte eingehende Rohzeilen zu Objekten parsen, nur die Fehler behalten und diese pro Sekunde gebündelt wegschreiben, statt bei jeder einzelnen Zeile die Datenbank anzufassen:\n\n```js\nconst { fromEvent } = require('rxjs');\nconst { map, filter, bufferTime } = require('rxjs');\n\nconst logStream$ = fromEvent(logEmitter, 'line').pipe(\n  map(line => JSON.parse(line)),\n  filter(entry => entry.level === 'error'),\n  bufferTime(1000),\n);\n\nconst subscription = logStream$.subscribe({\n  next: batch => saveErrors(batch),\n  error: err => console.error('stream failed', err),\n});\n```\n\nWas hier steht, liest sich fast wie eine Beschreibung der Anforderung. `map` transformiert jeden Wert, `filter` lässt nur passende durch, `bufferTime(1000)` sammelt über ein Zeitfenster von einer Sekunde und emittiert dann ein Array. Der `next`-Handler bekommt also nicht einzelne Einträge, sondern jeweils ein Bündel – oder ein leeres Array, wenn im Fenster nichts kam.\n\nJeder Schritt ist für sich verständlich und für sich testbar. Und wenn morgen die Anforderung kommt, zusätzlich nach Dienst zu gruppieren, füge ich einen Operator ein, statt eine verschachtelte Callback-Struktur umzubauen.\n\nEin zweites Muster aus der Praxis: Sensordaten drosseln und dabei einen laufenden Mittelwert bilden. Angenommen, ein Gerät feuert deutlich häufiger, als ich verarbeiten will:\n\n```js\nconst { fromEvent } = require('rxjs');\nconst { throttleTime, scan } = require('rxjs');\n\nconst average$ = fromEvent(sensor, 'reading').pipe(\n  map(event => event.value),\n  throttleTime(500),\n  scan((sum, value, index) => (sum * index + value) / (index + 1), 0),\n);\n\naverage$.subscribe({ next: avg => console.log('running average', avg) });\n```\n\n`throttleTime(500)` lässt einen Wert durch und ignoriert dann für 500 Millisekunden alle weiteren. `scan` verhält sich wie `reduce`, emittiert aber jeden Zwischenstand – so bekomme ich bei jeder durchgelassenen Messung den aktualisierten Durchschnitt. Diese Kombination aus laufender Aggregation und Zeitfenster ist im Repository unter `operators.js` vorgezeichnet, wenn auch dort noch mit der älteren RxJS-6-Importweise.\n\nWenn ich pro Event eine asynchrone Weiterverarbeitung anstoßen will – etwa Details nachladen – hilft `mergeMap`. Es mappt jeden Wert auf ein inneres Observable und flacht die Ergebnisse nebenläufig ab. Der zweite Parameter begrenzt, wie viele innere Verarbeitungen gleichzeitig laufen dürfen:\n\n```js\nconst { mergeMap } = require('rxjs');\n\nconst details$ = ids$.pipe(\n  mergeMap(id => fetchDetails(id), 4),\n);\n```\n\nMit `mergeMap(id => fetchDetails(id), 4)` laufen höchstens vier Abrufe parallel. Diese Begrenzung ist wichtig, und zwar aus einem Grund, der gleich noch eine eigene Rolle spielt.\n\nDer grobe Fluss durch so eine Pipeline sieht immer gleich aus:\n\n```mermaid\nflowchart LR\n  E[EventEmitter] -->|emit data| F[\"fromEvent<br/>(Observable)\"]\n  F --> M[map]\n  M --> FI[filter]\n  FI --> B[bufferTime]\n  B --> S[Subscriber]\n```\n\n## Ein Subject: aus einem Strom viele Konsumenten machen\n\nBis hierher hatte jeder Strom genau einen Verbraucher. Sobald mehrere Teile der Anwendung denselben Event Stream brauchen, kommt das `Subject` ins Spiel. Ein `Subject` ist zugleich Observer und Observable: Ich kann Werte hineingeben und andere können es abonnieren. Es verteilt jeden Wert an alle Subscriber gleichzeitig – Multicast.\n\n```js\nconst { fromEvent, Subject } = require('rxjs');\n\nconst bus = new Subject();\n\n// one source feeds the bus\nfromEvent(emitter, 'data').subscribe(bus);\n\n// multiple consumers share the same stream\nconst loggerSub = bus.subscribe({ next: v => logger.write(v) });\nconst metricsSub = bus.subscribe({ next: v => metrics.record(v) });\n\n// clean up later\nloggerSub.unsubscribe();\nmetricsSub.unsubscribe();\n```\n\nDer Unterschied zum direkten Abonnieren des Quell-Observables ist grundlegend. Würden `logger` und `metrics` beide `fromEvent(emitter, 'data')` abonnieren, hinge am Emitter zweimal ein Listener und die Quelle würde zweimal ausgeführt. Über das `Subject` gibt es eine Ausführung, deren Werte an alle Subscriber verteilt werden.\n\nGenau das ist der Kern der Unterscheidung zwischen Unicast und Multicast:\n\n```mermaid\nflowchart LR\n  P[Producer] --> SUB[Subject]\n  SUB --> C1[Logger-Subscriber]\n  SUB --> C2[Metrics-Subscriber]\n  SUB --> C3[Audit-Subscriber]\n```\n\nNeben dem einfachen `Subject` gibt es Varianten, die je nach Anwendungsfall passen:\n\n- `BehaviorSubject(seed)` hält den letzten Wert und liefert ihn jedem neuen Subscriber sofort. Praktisch für Zustand, den ein spät hinzukommender Konsument kennen muss.\n- `ReplaySubject(bufferSize)` puffert die letzten n Werte und spielt sie neuen Subscribern vor.\n- `AsyncSubject` gibt nur den allerletzten Wert aus, und das erst beim `complete`.\n\nIm Repository unter `subject.js` sieht man das Grundprinzip: dieselbe Quelle, mehrere `subscribe`-Aufrufe. Dort steht noch die positionsbasierte `subscribe(next, error, complete)`-Form. In RxJS 7 nutze ich stattdessen durchgängig den Objekt-Observer `subscribe({ next, error, complete })` – dazu gleich mehr bei den Fallstricken.\n\n## Hot und cold: der Unterschied, der Ergebnisse verfälscht\n\nEin Punkt, an dem in Teams zuverlässig Verwirrung entsteht, ist die Frage, wann die Quelle eines Observables entsteht.\n\nEin kaltes Observable erzeugt seinen Producer pro `subscribe`. Jeder Subscriber bekommt eine eigene, frische Ausführung – Unicast. Ein `from([1, 2, 3])` ist kalt: Jeder, der es abonniert, sieht die Werte 1, 2, 3 von vorne.\n\nEin heißes Observable hat seinen Producer außerhalb. Die Werte entstehen unabhängig davon, ob jemand zuhört. Wer spät abonniert, verpasst, was vorher lief – Multicast. Ein `Subject` ist heiß, und ein `fromEvent` über einen bereits laufenden Emitter verhält sich ebenfalls heiß: Die Events feuern ohnehin, ich klinke mich nur ein.\n\nDiese Unterscheidung ist keine Theorie. Wer erwartet, dass „jeder Subscriber frisch startet“, aber tatsächlich einen heißen Strom vor sich hat, bekommt bei spät hinzukommenden Konsumenten schlicht falsche Ergebnisse – fehlende Anfangswerte, eine Aggregation, die mitten im Strom beginnt. Wenn ich will, dass auch ein später Subscriber den letzten Stand oder die Historie sieht, ist genau das der Fall für `BehaviorSubject`, `ReplaySubject` oder den Operator `shareReplay`.\n\n## Die wichtige Abgrenzung: RxJS hat keine echte Backpressure\n\nDieser Punkt gehört früh geklärt, sonst entstehen Erwartungen, die das Werkzeug nicht einlöst. Wer Node-Streams kennt, kennt Backpressure: Ein lesbarer Stream kann pausieren, ein `highWaterMark` begrenzt den Puffer, `pipe` regelt den Fluss zwischen Producer und Konsument automatisch. Der schnelle Producer wird gebremst, wenn der langsame Konsument nicht hinterherkommt.\n\nRxJS hat das nicht. Es gibt keinen eingebauten Mechanismus, mit dem ein Subscriber die Quelle zum Langsamerwerden zwingt. Ein `Subject` oder ein `fromEvent` pusht Werte, sobald sie da sind, egal ob die Verarbeitung mitkommt.\n\nWas RxJS stattdessen anbietet, sind zeitbasierte und puffernde Operatoren:\n\n- `throttleTime(ms)` lässt einen Wert durch und verwirft dann für eine Weile alle weiteren.\n- `debounceTime(ms)` wartet, bis eine Ruhephase eintritt, und emittiert dann den letzten Wert.\n- `sampleTime(ms)` greift in festen Abständen den jeweils aktuellen Wert ab.\n- `bufferTime(ms)` sammelt über ein Fenster und liefert Bündel.\n- das `concurrent`-Limit von `mergeMap` begrenzt die Zahl paralleler innerer Verarbeitungen.\n\nDer entscheidende Unterschied: Diese Operatoren verwerfen oder aggregieren Werte, aber sie bremsen die Quelle nicht. Der Producer feuert unverändert weiter; ich reduziere nur, was hinten ankommt. Für eine Log-Anzeige oder Sensordaten ist das oft genau richtig – ein paar Zwischenwerte wegzuwerfen ist unkritisch. Für eine Verarbeitung, bei der jeder einzelne Wert zählen muss und die Quelle tatsächlich gedrosselt gehört, sind Node-Streams das richtige Werkzeug, nicht RxJS.\n\nMan kann beide Welten verbinden. Das Repository zeigt unter `node.js` die Brücke über `rxjs-stream`:\n\n```js\nconst { spawn } = require('child_process');\nconst { streamToRx } = require('rxjs-stream');\nconst { map } = require('rxjs');\n\nstreamToRx(spawn('ls', ['-lha']).stdout)\n  .pipe(map(chunk => chunk.toString()))\n  .subscribe({ next: text => console.log(text) });\n```\n\n`streamToRx` macht aus einem Node-Readable ein Observable und behält dabei die Stream-Backpressure im unteren Teil. So bekomme ich die Komponierbarkeit von RxJS für die Transformation, ohne die Flusskontrolle des Streams aufzugeben. Wer die Grundlagen des Event-Loops und der Stream-Architektur dahinter auffrischen will, findet sie im [Node.js-Training](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/).\n\n## Fallstricke, die mir immer wieder begegnen\n\nZwei Fehler tauchen so regelmäßig auf, dass ich sie hier ausdrücklich nenne.\n\nDer erste ist der Subscription-Leak. `fromEvent` registriert bei jedem `subscribe` einen Listener am Emitter. Ohne `unsubscribe()` bleibt dieser Listener hängen – auch dann, wenn die Verarbeitung längst nicht mehr gebraucht wird. Das Ergebnis ist ein Memory-Leak und eine Pipeline, die unbemerkt weiterläuft. Die Regel ist einfach: Ich halte die Subscription, die `.subscribe()` zurückgibt, und rufe `unsubscribe()` auf, wenn ich fertig bin. Alternativ begrenze ich den Strom deklarativ über `take(n)` oder `takeUntil(stop$)`, sodass er sich selbst beendet:\n\n```js\nconst { fromEvent, timer } = require('rxjs');\nconst { takeUntil } = require('rxjs');\n\nconst stop$ = timer(60000);\n\nfromEvent(emitter, 'data')\n  .pipe(takeUntil(stop$))\n  .subscribe({ next: v => process(v) });\n```\n\nHier räumt `takeUntil` nach 60 Sekunden auf, ohne dass ich die Subscription selbst verwalten muss. Bei langlebigen Servern ist eine der beiden Strategien Pflicht, sonst sammeln sich Listener über die Laufzeit an.\n\nDer zweite Fallstrick ist das Verwechseln von hot und cold, das ich oben schon beschrieben habe – es äußert sich fast immer als „mein zweiter Subscriber bekommt nicht dieselben Werte“. Die Antwort ist meist ein `Subject` mit passender Variante oder `shareReplay`.\n\nUnd ein dritter, eher handwerklicher Punkt: Viele Beispiele im Netz und auch die älteren Snippets im Repository nutzen noch RxJS-6-Muster. Konkret heißt das für RxJS 7:\n\n- Statt `subscribe(next, error, complete)` mit einzelnen Argumenten den Objekt-Observer `subscribe({ next, error, complete })` verwenden – die positionsbasierte Form ist seit 6.4 überholt.\n- Statt `tap(fn, errFn)` mit mehreren Callbacks ebenfalls den Objekt-Observer nutzen.\n- Operatoren aus `'rxjs'` importieren statt aus `'rxjs/operators'`.\n\nDiese Anpassungen sind mechanisch, aber wichtig, damit der Code nicht auf einem Muster aufsetzt, das perspektivisch verschwindet.\n\n## Wann RxJS statt rohem EventEmitter?\n\nNicht jede Node-Anwendung braucht RxJS. Ein einzelner `on('data', ...)`-Handler bleibt mit purem `EventEmitter` schlanker und hat keine zusätzliche Abhängigkeit. Ich greife dann zu RxJS, wenn mindestens einer dieser Punkte zutrifft:\n\n- Ich muss mehrere Verarbeitungsschritte verketten – transformieren, filtern, aggregieren – und will das nicht über verschachtelte Callbacks und geteilten Zustand lösen.\n- Ich brauche zeitbasierte Steuerung: drosseln, entprellen, in Fenstern bündeln.\n- Denselben Event Stream sollen mehrere Konsumenten unabhängig verarbeiten (Multicast über ein `Subject`).\n- Der Strom soll sich sauber und deklarativ beenden lassen, etwa über `takeUntil`.\n- Der Verarbeitungscode soll in kleine, für sich testbare Bausteine zerfallen.\n\nUmgekehrt bleibe ich beim rohen Emitter oder greife zu Node-Streams, wenn es nur ein einziger simpler Handler ist oder wenn ich echte Backpressure über den ganzen Weg brauche.\n\n## Fazit\n\nRxJS verschiebt in Node.js die Perspektive vom Befehl zur Beschreibung. Der `EventEmitter` sagt, was bei jedem Event zu tun ist; RxJS beschreibt den ganzen Event Stream als komponierbare Kette von Pure Functions. `fromEvent` ist die Brücke dorthin, ohne dass sich an der Semantik des Emitters etwas ändert, und ein `Subject` macht aus einem Strom viele Konsumenten.\n\nZwei Dinge sollte man dabei nie vergessen. Erstens die Disziplin beim Aufräumen: Ohne `unsubscribe`, `take` oder `takeUntil` bleiben Listener und Verarbeitung am Leben. Zweitens die ehrliche Grenze des Werkzeugs: RxJS steuert Überlast nur zeitbasiert und puffernd, nicht über echte Backpressure. Wer diese beiden Punkte im Kopf behält, bekommt mit RxJS eine sehr angenehme Art, serverseitige Event Streams zu verarbeiten – lesbar, testbar und erweiterbar, ohne im Callback-Dickicht zu versinken.\n\n## Weiterführende Quellen\n\n- Repository-Beispiele: `/Users/mikebild/Documents/introduction-nodejs/EXAMPLES/RXJS/operators.js`, `.../subject.js`, `.../node.js`\n- [fromEvent](https://rxjs.dev/api/index/function/fromEvent)\n- [Subject-Guide](https://rxjs.dev/guide/subject)\n- [Observable-Guide](https://rxjs.dev/guide/observable)\n- [Operatoren-Guide](https://rxjs.dev/guide/operators)\n- [mergeMap](https://rxjs.dev/api/operators/mergeMap)\n- [throttleTime](https://rxjs.dev/api/index/function/throttleTime)\n- [bufferTime](https://rxjs.dev/api/operators/bufferTime)\n- [scan](https://rxjs.dev/api/operators/scan)\n- [subscribe-Argumente (Deprecation)](https://rxjs.dev/deprecations/subscribe-arguments)\n- [Glossar und Semantik: hot/cold, unicast/multicast](https://rxjs.dev/guide/glossary-and-semantics)\n- [Node.js events](https://nodejs.org/docs/latest-v18.x/api/events.html)"},{"locale":"de","translation_key":"evolutionary-architecture-wandel-einplanen","slug":"evolutionary-architecture-wandel-einplanen","title":"Evolutionary Architecture: Systeme, die sich ändern dürfen","summary":"Architektur ist kein Endzustand, den man einmal festzurrt. Kleine Änderungen und passende Fitness Functions machen ausgewählte Risiken früher sichtbar, garantieren aber weder Tempo noch Qualität.","tags":["Software","Architektur"],"published_at":"2023-06-26T10:00:00+00:00","updated_at":"2026-07-13T08:50:24.240283+00:00","url":"https://www.mikebild.dev/de/blog/evolutionary-architecture-wandel-einplanen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/b3e12507901be058a349c74d29e3a58f10d51709b24ff1388fbea5bb3b5f8723/evolutionary-architecture-wandel-einplanen-vorlesen.mp3","audio_duration_secs":751,"text":"Evolutionary Architecture ist kein Freibrief für Wildwuchs und auch kein zweites Wort für \"agil\". Neal Ford, Rebecca Parsons und Patrick Kua definieren sie in *Building Evolutionary Architectures* (O'Reilly 2017, zweite Auflage 2022) als eine Architektur, die \"guided, incremental change across multiple dimensions\" unterstützt. Drei Wörter tragen diese Definition. Geführt: Es gibt benannte Eigenschaften, die geschützt werden. Inkrementell: Die einzelne Änderung ist klein genug, um sie zurücknehmen zu können. Mehrdimensional: Gemeint ist nicht nur der Code, sondern ebenso Daten, Betrieb und die Organisation, die beides trägt.\n\nDer Gegenentwurf ist das eingefrorene System. Vor drei Jahren sauber entworfen, für eine Welt, die es so nicht mehr gibt – und seither nicht mehr bewegt, weil jede Änderung zu riskant erschien. Die Diagramme hängen noch an der Wand, aber sie beschreiben ein Auto, das niemand mehr fährt. Dahinter steckt eine Grundannahme, die sich hartnäckig hält: Architektur sei etwas, das man einmal richtig macht und dann verteidigt, ein Zielbild, das man erreicht. Kein System, das produktiv genutzt wird, bleibt jedoch stehen. Anforderungen verschieben sich, Lastprofile ändern sich, Teams wachsen, Abhängigkeiten altern. Die Frage ist nie, ob sich ein System ändert, sondern nur, ob die Architektur diesen Wandel begleitet oder ihm im Weg steht.\n\nEvolutionary Architecture dreht die Perspektive deshalb um: Statt Wandel als Ausnahme zu behandeln, die man nach dem Go-live möglichst vermeidet, macht sie ihn zur Norm, für die man von Anfang an baut. Ein System, das sich ändern darf – in kleinen Schritten, und ohne dass dabei die Eigenschaften kaputtgehen, die es wertvoll machen.\n\n## Warum das Endzustands-Denken teuer wird\n\nDer klassische Reflex heißt Big Design Up Front. Man denkt möglichst weit voraus, entscheidet früh alles Wichtige und gießt das Ergebnis in ein Zielbild. Das fühlt sich verantwortungsvoll an. Es ist auch nicht grundsätzlich falsch, früh nachzudenken – im Gegenteil. Falsch ist die Erwartung, dass diese frühen Entscheidungen dauerhaft tragen.\n\nDer Denkfehler steckt im Zeitpunkt. Ganz am Anfang eines Vorhabens weiß man am wenigsten über die Domäne, die Nutzer und das reale Verhalten unter Last. Genau dann trifft man die weitreichendsten Entscheidungen. Jede spätere Erkenntnis muss sich dann gegen eine Struktur behaupten, die für sie nicht gemacht war. Das ist der Moment, in dem Teams anfangen, um die Architektur herumzuarbeiten statt mit ihr. Der Fachbegriff dafür ist architectural drift oder erosion: Das reale System entfernt sich Stück für Stück vom gedachten, bis das Diagramm an der Wand nur noch Folklore ist.\n\nDer geschäftliche Schaden ist selten ein spektakulärer Ausfall. Er ist schleichend. Änderungen dauern länger. Jede Anpassung braucht mehr Abstimmung. Neue Features kollidieren mit alten Annahmen. Die Time-to-Market steigt, während die Zuversicht sinkt. Und irgendwann steht die Frage im Raum, ob man nicht besser alles neu bauen sollte – die teuerste aller Optionen.\n\n## Der Perspektivwechsel: geführte Evolution statt fixiertes Ziel\n\nDer Ausweg ist kein anderes Zielbild, sondern ein anderer Umgang mit Zielbildern. Statt einen Endzustand zu definieren und zu verteidigen, definiert man die Eigenschaften, die das System behalten soll, und lässt die Struktur sich innerhalb dieser Leitplanken entwickeln.\n\n```mermaid\nflowchart LR\n  A[Change<br/>small increment] --> B[Deployment Pipeline]\n  B --> C{Fitness Functions<br/>guardrails}\n  C -->|pass| D[Learn & Adjust]\n  C -->|fail| E[Stop & Fix]\n  E --> A\n  D --> A\n```\n\nDer Kern ist ein Regelkreis, kein Wasserfall. Eine kleine Änderung läuft durch die Deployment-Pipeline, wird gegen definierte Leitplanken geprüft, liefert eine klare Rückmeldung – bestanden oder nicht – und daraus lernt das Team für den nächsten Schritt. Klein, geführt, wiederholbar. Das ist der Unterschied zwischen einem System, das sich entwickelt, und einem, das nur älter wird.\n\nWichtig ist die Betonung auf geführt. Evolutionary bedeutet ausdrücklich nicht \"keine Architektur\" oder \"wir lassen es wachsen, wie es will\". Das ist der häufigste Trugschluss. Wildwuchs ist keine Evolution, sondern ihr Gegenteil. Ohne bewusst benannte, priorisierte Architektur-Charakteristika gibt es nichts zu schützen und nichts zu messen. Der erste Schritt ist deshalb keine Technik, sondern eine Entscheidung: Was genau muss dieses System auszeichnen? Antwortzeit unter einer bestimmten Grenze? Lose Kopplung zwischen fachlichen Bereichen? Nachweisbare Sicherheit an den Rändern? Erst wenn diese Ziele explizit sind, kann man sie verteidigen.\n\n## Fitness Functions: Architektur, die man messen kann\n\nDer Mechanismus, mit dem diese Ziele verteidigt werden, heißt Fitness Function. Der Begriff ist aus evolutionären Algorithmen entlehnt, wo eine Fitness-Function bewertet, wie nah eine Lösung am gewünschten Ergebnis ist. Übertragen auf Architektur heißt das laut den Autoren: \"any mechanism that provides an objective integrity assessment of some architectural characteristic(s)\". Also jeder Mechanismus, der objektiv prüft, ob eine architektonische Eigenschaft noch intakt ist.\n\nDas Entscheidende an dem Wort ist objektiv. Eine Fitness Function ist kein Meeting, kein Bauchgefühl und kein Architecture Review Board, das einmal im Quartal tagt und über Slides urteilt. Sie ist ein automatisierter Test, der in der Pipeline läuft und ein eindeutiges Ergebnis liefert. Damit verschiebt sich Governance von manueller Kontrolle hin zu etwas Versioniertem, Ausführbarem, jederzeit Wiederholbarem – nicht umsonst trägt die zweite Auflage den Untertitel \"Automating Software Governance\".\n\nDas einfachste und bekannteste Beispiel sind strukturelle Regeln. Mit einer Bibliothek wie ArchUnit lässt sich eine Architekturvorgabe als ganz normaler Unit-Test formulieren:\n\n```java\n@ArchTest\nstatic final ArchRule domain_must_not_depend_on_infrastructure =\n    noClasses().that().resideInAPackage(\"..domain..\")\n      .should().dependOnClassesThat().resideInAPackage(\"..infrastructure..\");\n```\n\nDiese Regel sagt: Die Domänenschicht darf nicht auf die Infrastruktur zugreifen. Bisher stand so etwas in einem Wiki und wurde in Code Reviews hoffentlich bemerkt. Jetzt bricht der Build, sobald jemand die Grenze verletzt – am selben Tag, an dem es passiert, nicht drei Monate später in einer Refactoring-Retrospektive. Die Absicht wird vom Kommentar zum ausführbaren Fakt.\n\nUnd genau hier liegt der zweite große Trugschluss: Fitness Functions sind nicht auf solche Package- und Layering-Checks beschränkt. Das ist nur die sichtbarste Kategorie. Alles, was man an einer Architektur objektiv prüfen kann, ist Kandidat – Performance-Budgets, Security-Scans, Prüfungen auf zyklische Abhängigkeiten, sogar Chaos-Experimente oder monitoring-basierte Prüfungen im laufenden Betrieb.\n\nDie Autoren gliedern das in eine kleine Taxonomie, die im Alltag hilft, Lücken zu erkennen. Fitness Functions können atomic sein (prüfen eine einzelne Eigenschaft) oder holistic (prüfen das Zusammenspiel mehrerer). Sie können triggered sein (laufen bei einem Event, etwa im Build) oder continual (laufen dauerhaft in Produktion). Und sie können static sein (feste Schwelle) oder dynamic (Schwelle abhängig vom Kontext). Wer nur strukturelle, atomic-triggered Regeln hat, deckt eine Ecke ab und übersieht den Rest.\n\nEin Performance-Budget etwa ist eher holistisch und lässt sich als Gate in der Pipeline formulieren:\n\n```yaml\nfitness_functions:\n  - name: p95_latency_budget\n    metric: http_request_duration_p95_ms\n    threshold: 300\n    on_breach: fail_build\n  - name: max_module_coupling\n    metric: afferent_efferent_coupling_ratio\n    threshold: 0.7\n    on_breach: warn\n```\n\nDas Muster ist immer dasselbe: eine architektonische Eigenschaft, eine objektive Schwelle, eine definierte Konsequenz. Reißt die 95.-Perzentil-Latenz das Budget, bricht der Build. Steigt die Kopplung über den Grenzwert, gibt es zunächst eine Warnung. Man muss nicht alles hart erzwingen – aber man macht die Eigenschaft sichtbar und entscheidet bewusst, wie streng man sie behandelt.\n\n## Kopplung ist die eigentliche Bremse\n\nWenn ein System sich nicht mehr in kleinen Schritten ändern lässt, liegt das fast immer an Kopplung. Nicht nur an der offensichtlichen zwischen Klassen, sondern auch an versteckter zeitlicher Kopplung und an Datenkopplung. Zwei Dienste, die immer gemeinsam deployt werden müssen. Ein Schema, das drei Teams gleichzeitig anfassen müssen, um ein Feld zu ändern. Solange diese Bänder bestehen, ist inkrementeller Wandel unmöglich, egal wie gut die Absicht ist.\n\nDeshalb gehört zu den wichtigsten Fitness Functions die Kontrolle der Kopplung selbst. Und deshalb machen ein paar bewährte Muster hier den Unterschied. Die Strangler Fig Application von Martin Fowler beschreibt, wie man ein Altsystem inkrementell ablöst, indem man neue Funktionalität wie eine Würgefeige um den alten Kern wachsen lässt, bis der irgendwann verschwinden kann – ohne den einen großen, riskanten Umstieg. Auf Datenebene leistet das Expand-Contract-Pattern (auch Parallel Change) dasselbe: Man erweitert ein Schema, migriert schrittweise, entfernt das Alte erst, wenn niemand es mehr braucht. Refactoring wird so zur normalen, sicheren Bewegung statt zum Kraftakt.\n\nAuf der Betriebsebene sorgen Resilience-Pattern wie Circuit Breaker und Bulkhead aus Michael Nygards *Release It!* dafür, dass die lose gekoppelten Teile sich auch bei Störungen nicht gegenseitig mitreißen. Und an den Diensträndern hält Consumer-Driven Contract Testing die Grenzen ehrlich: Jeder Konsument beschreibt, was er von einem Dienst erwartet, und dieser Vertrag wird automatisiert geprüft. Ändert sich der Dienst inkompatibel, schlägt der Test an, bevor es der Nutzer merkt. Auch das ist eine Fitness Function – eine, die Änderbarkeit an den teuersten Bruchstellen absichert.\n\nEin Wort zu Conway's Law, denn Kopplung ist nicht nur technisch. Systeme spiegeln die Kommunikationsstrukturen der Organisationen, die sie bauen. Wer lose gekoppelte Software will, muss auch die Teams entsprechend schneiden. Das ist keine Randnotiz, sondern oft die Voraussetzung dafür, dass die technischen Leitplanken überhaupt greifen.\n\n## Der Beweis, dass es sich rechnet\n\nAn dieser Stelle kommt der Einwand: Klingt gut, aber all diese Automatisierung und dieses ständige Ändern – geht das nicht auf Kosten der Stabilität? Schneller heißt doch riskanter?\n\nDie Daten sagen das Gegenteil. Die DORA-Forschung, zusammengefasst in *Accelerate* (Forsgren, Humble, Kim, 2018), zeigt über tausende Organisationen hinweg, dass Geschwindigkeit und Stabilität keine Gegner sind, sondern gemeinsam steigen. Die leistungsstärksten Teams deployen häufiger *und* haben seltener Ausfälle *und* erholen sich schneller. Der vermeintliche Zielkonflikt zwischen Tempo und Verlässlichkeit ist ein Artefakt des alten Denkens – das Ergebnis von seltenen, großen, riskanten Releases.\n\nDie vier klassischen DORA-Metrics lesen sich selbst wie systemweite Fitness Functions:\n\n```text\nDeployment Frequency     - wie oft deployen wir?\nLead Time for Changes    - wie lange von Commit bis Produktion?\nChange Failure Rate      - wie viele Deployments verursachen einen Fehler?\nTime to Restore Service  - wie schnell sind wir wieder online?\n```\n\nSie messen nicht ein einzelnes Modul, sondern die Änderbarkeit des Gesamtsystems. Verkürzte Zyklen, weniger Reibung, höhere Qualität werden damit zu Größen, die man in dieselbe Regelkreis-Logik einhängen kann wie eine Latenzgrenze.\n\n```mermaid\nflowchart TB\n  subgraph Old[Architecture as end-state]\n    O1[Big Design Up Front] --> O2[freeze] --> O3[drift & erosion]\n  end\n  subgraph New[Architecture as guarded evolution]\n    N1[named characteristics] --> N2[fitness functions] --> N3[small guarded change] --> N1\n  end\n```\n\nDer Denkrahmen ist im Übrigen nicht auf Technik beschränkt. Er ist dasselbe Prinzip, das *The Lean Startup* für Produkte formuliert hat – Build, Measure, Learn: eine Hypothese, ein kleiner Schritt, eine Messung, eine Anpassung. Architektur-Evolution ist die technische Ausprägung derselben Haltung. Man behauptet nicht, die richtige Struktur zu kennen. Man baut so, dass man es günstig herausfinden kann.\n\n## Fazit\n\nArchitektur ist kein Endzustand. Sie ist die Fähigkeit eines Systems, sich weiter verändern zu lassen, ohne die Eigenschaften zu verlieren, die es wertvoll machen. Wer das ernst nimmt, hört auf, ein Zielbild zu verteidigen, und fängt an, die richtigen Dinge zu schützen.\n\nDer Weg dahin ist erstaunlich konkret. Erstens: die Architektur-Charakteristika benennen, die wirklich zählen – nicht alle, sondern die wenigen, die den Unterschied machen. Zweitens: für jede dieser Eigenschaften eine Fitness Function bauen, die objektiv, automatisiert und in der Pipeline prüft, ob sie noch hält – strukturell, aber eben auch bei Performance, Sicherheit und Kopplung. Drittens: Kopplung aktiv niedrig halten, technisch wie organisatorisch, damit kleine Schritte überhaupt möglich bleiben. Und viertens: dem Ganzen vertrauen, weil die Daten zeigen, dass Tempo und Stabilität zusammen wachsen.\n\nDer Ansatz schafft noch keine kurzen Zyklen und garantiert keine stabile Qualität. Er macht benannte Eigenschaften bei kleinen Änderungen früher überprüfbar. Ob dadurch Reibung sinkt oder Änderungen schneller werden, zeigt erst der reale Lieferfluss. Die beste Architektur ist für mich deshalb nicht die, die für immer richtig sein soll, sondern eine, deren Annahmen sich prüfen und bei neuen Erkenntnissen ändern lassen.\n\n## Weiterführende Quellen\n\n- Neal Ford, Rebecca Parsons, Patrick Kua: *Building Evolutionary Architectures*, O'Reilly, 1. Aufl. 2017 / 2. Aufl. 2022 (mit Pramod Sadalage)\n- Martin Fowler: [Foreword to Building Evolutionary Architectures](https://martinfowler.com/articles/evo-arch-forward.html)\n- [DORA – Four Key Metrics](https://dora.dev/guides/dora-metrics-four-keys/)\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate*, IT Revolution, 2018\n- [ArchUnit – Unit-Tests für Architekturregeln](https://www.archunit.org/)\n- [InfoQ – Fitness Functions for Your Architecture](https://www.infoq.com/articles/fitness-functions-architecture/)\n- Michael Nygard: *Release It!*, Pragmatic Bookshelf, 2. Aufl. 2018"},{"locale":"de","translation_key":"von-hocs-und-render-props-zu-custom-hooks","slug":"von-hocs-und-render-props-zu-custom-hooks","title":"Von HOCs und Render Props zu Custom Hooks","summary":"Wie teile ich Logik zwischen Komponenten ohne Copy-Paste? Custom Hooks vermeiden dafür meist verschachtelte Wrapper; HOCs und Render Props behalten einzelne Kompositionsaufgaben.","tags":["Software","Frontend","React"],"published_at":"2023-06-20T10:00:00+00:00","updated_at":"2026-07-13T08:50:07.649617+00:00","url":"https://www.mikebild.dev/de/blog/von-hocs-und-render-props-zu-custom-hooks/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/7e416769f9d0b67d68c5d5d7fb781dc6e9c108d6e40ee2abad6efd7a5a6577a3/von-hocs-und-render-props-zu-custom-hooks-vorlesen.mp3","audio_duration_secs":634,"text":"Vier Ebenen im React-DevTools-Baum, bevor die erste erscheint, die tatsächlich etwas Sichtbares rendert: `withRouter`, darunter `withLoading`, darunter `withData`, und ganz unten die eigentliche Seite. Drei dieser Ebenen tragen nichts zur Darstellung bei. Sie existieren nur, um State und Verhalten von außen nach innen zu reichen.\n\nDieser Baum ist kein Unfall, sondern die logische Folge einer Entscheidung, die React über Jahre mitgeschleppt hat. Denn stateful Logik an mehreren Stellen wiederzuverwenden, ohne sie zu duplizieren, hat das Framework in drei Generationen jeweils anders gelöst – und die ersten beiden Lösungen bezahlen dafür mit genau solchen Ebenen. Wer die Reihenfolge kennt, versteht auch, warum die älteren Muster trotzdem nicht wertlos sind.\n\n## Die immer gleiche Frage\n\nEin Beispiel, an dem sich das gut zeigen lässt: Eine Komponente soll wissen, ob der Browser gerade online ist. Das braucht State, das braucht einen Effect mit Event-Listenern, und das braucht Cleanup. Wenn drei Komponenten das brauchen, will niemand denselben Block dreimal schreiben.\n\nDie naive Lösung ist Copy-Paste. Sie funktioniert genau so lange, bis sich die Logik ändert – dann ändert man sie an einer Stelle und vergisst die anderen beiden. Ab da suchen React-Entwickler nach einem Mechanismus, der die Logik an genau einem Ort hält.\n\nHistorisch sah der Weg dorthin so aus:\n\n```mermaid\ngraph LR\n  A[Copy-Paste] --> B[Mixins<br/>deprecated]\n  B --> C[HOCs &<br/>Render Props]\n  C --> D[Custom Hooks<br/>React 16.8 / 2019]\n```\n\nMixins waren die erste Antwort in den ganz frühen Tagen mit `createClass`, wurden aber schnell als problematisch verworfen – unklare Herkunft von Properties, Namenskollisionen, implizite Abhängigkeiten. Danach kamen zwei Muster, die lange dominierten: Higher-Order Components und Render Props. Und seit React 16.8 – stabil seit Februar 2019 – gibt es Custom Hooks. Schauen wir uns die drei relevanten Antworten der Reihe nach an.\n\n## Antwort 1: Higher-Order Components\n\nEin Higher-Order Component ist im Grunde ein alter Bekannter aus der funktionalen Programmierung. So wie eine Higher-Order Function eine Funktion nimmt und eine neue Funktion zurückgibt, nimmt ein HOC eine Komponente und gibt eine neue, erweiterte Komponente zurück. Die Signatur ist:\n\n```js\n// a function that takes a component and returns a new component\nconst withSomething = (Component) => EnhancedComponent;\n```\n\nDie Namenskonvention ist `withXxx`. Nehmen wir das Klassikerbeispiel `withLoading`, das einen Ladezustand kapselt:\n\n```jsx\nimport { Fragment } from \"react\";\n\nfunction withLoading(Wrapped) {\n  return function WithLoading(props) {\n    if (props.loading) {\n      return <Spinner />;\n    }\n    return <Wrapped {...props} />;\n  };\n}\n```\n\nAngewendet wird das Ganze auf Modulebene, nicht im Render:\n\n```jsx\nconst UserPageWithLoading = withLoading(UserPage);\n```\n\nDas liest sich sauber. Und es komponiert: Man kann mehrere HOCs stapeln, `withRouter(withLoading(withData(Page)))`. Genau da hat das Ganze aber seinen Preis.\n\nDass die Anwendung außerhalb des Renders passieren muss, wirkt wie eine Formalie – bis man einmal dagegen verstößt. Erzeugt man ein HOC direkt im `render()`, entsteht bei jedem Durchlauf eine neue Komponenten-Identität. React sieht einen anderen Typ, hängt den kompletten Subtree aus dem Baum und baut ihn neu auf – der gesamte State darunter geht verloren. Das ist einer der Bugs, die man einmal live debuggt und danach nie wieder produziert.\n\nDazu kommen zwei weitere Stolpersteine, die man kennen muss:\n\n- Statische Methoden der Original-Komponente verschwinden, weil der Wrapper sie nicht automatisch mitkopiert – man braucht etwas wie `hoist-non-react-statics`.\n- Refs gehen nicht als normale Prop durch den Wrapper hindurch. Wer eine Ref auf die innere Komponente braucht, muss `React.forwardRef` bemühen (verfügbar seit React 16.3).\n\nUnd die Grundregel, die alles zusammenhält: Komposition statt Mutation. Ein HOC mutiert die übergebene Komponente nicht, es umschließt sie in einem Container. Sobald jemand anfängt, die Original-Komponente direkt zu verändern, ist das Muster kaputt.\n\n## Antwort 2: Render Props\n\nDas zweite Muster dreht den Spieß um. Statt eine Komponente in eine andere zu wickeln, gibt man einer Komponente eine Funktion mit, die ihr sagt, was sie rendern soll. Das ist eine Render Prop: „a function prop that a component uses to know what to render“. Oft nutzt man dafür direkt `children` als Funktion.\n\n```jsx\nclass OnlineStatus extends React.Component {\n  state = { isOnline: false };\n\n  handleOnline = () => this.setState({ isOnline: true });\n  handleOffline = () => this.setState({ isOnline: false });\n\n  componentDidMount() {\n    window.addEventListener(\"online\", this.handleOnline);\n    window.addEventListener(\"offline\", this.handleOffline);\n  }\n\n  componentWillUnmount() {\n    window.removeEventListener(\"online\", this.handleOnline);\n    window.removeEventListener(\"offline\", this.handleOffline);\n  }\n\n  render() {\n    return this.props.children(this.state.isOnline);\n  }\n}\n```\n\nAufgerufen wird das dann so:\n\n```jsx\n<OnlineStatus>\n  {(isOnline) => (\n    <span>{isOnline ? \"Online\" : \"Offline\"}</span>\n  )}\n</OnlineStatus>\n```\n\nDas ist flexibler als ein HOC, weil der Aufrufer die volle Kontrolle über das Rendering behält. Aber auch hier gibt es einen Preis: Wenn man die Funktion inline im JSX erzeugt, wird sie bei jedem Render neu erstellt. Für eine `PureComponent` oder eine mit `memo` optimierte Kind-Komponente ist das Gift – der Shallow-Compare schlägt fehl, weil die Funktionsreferenz jedes Mal neu ist, und die Optimierung läuft ins Leere. Man müsste die Funktion als stabile Instanzmethode auslagern, was die vermeintliche Eleganz wieder auffrisst.\n\n## Das gemeinsame Problem: Wrapper Hell\n\nBeide Muster – HOC und Render Props – teilen Logik über dieselbe Mechanik: über zusätzliche Ebenen im Komponentenbaum. Jedes HOC ist ein Wrapper, jede Render Prop eine weitere Verschachtelung. Bei einer, zwei Ebenen merkt man nichts. Bei fünf sieht der React-DevTools-Baum aus wie eine Zwiebel, und das nennt man liebevoll „wrapper hell“.\n\nGenau dieser Baum ist der entscheidende Punkt. Schauen wir ihn uns an:\n\n```mermaid\ngraph TD\n  subgraph HOC[\"HOC / Render Props: verschachtelt\"]\n    R1[withRouter] --> L1[withLoading]\n    L1 --> D1[withData]\n    D1 --> P1[Page]\n  end\n```\n\nJede Zwischenebene existiert nur, um Logik hereinzureichen. Sie hat keinen eigenen fachlichen Sinn, sie ist reine Infrastruktur im Baum. Und weil die Daten von außen nach innen durchgereicht werden, entstehen leicht Zwischenschichten mit veralteten Closures – ein weiterer Debugging-Klassiker.\n\n## Antwort 3: Custom Hooks\n\nCustom Hooks lösen das Problem an einer anderen Stelle. Ein Custom Hook ist einfach eine normale JavaScript-Funktion, deren Name mit `use` beginnt und die andere Hooks aufrufen darf. Kein Wrapper, keine zusätzliche Komponente, keine neue Ebene im Baum. Die Logik zieht in eine Funktion um, die Komponente ruft sie auf – fertig.\n\nDasselbe `withLoading`-Problem sieht als Hook so aus, dass der Hook den State liefert und die Komponente selbst entscheidet, was sie damit rendert:\n\n```jsx\nimport { useState, useEffect } from \"react\";\n\nfunction useOnlineStatus() {\n  const [isOnline, setIsOnline] = useState(true);\n\n  useEffect(() => {\n    const handleOnline = () => setIsOnline(true);\n    const handleOffline = () => setIsOnline(false);\n\n    window.addEventListener(\"online\", handleOnline);\n    window.addEventListener(\"offline\", handleOffline);\n\n    return () => {\n      window.removeEventListener(\"online\", handleOnline);\n      window.removeEventListener(\"offline\", handleOffline);\n    };\n  }, []);\n\n  return isOnline;\n}\n```\n\nUnd die Nutzung ist so unspektakulär, wie sie sein sollte:\n\n```jsx\nfunction StatusBar() {\n  const isOnline = useOnlineStatus();\n  return <span>{isOnline ? \"Online\" : \"Offline\"}</span>;\n}\n```\n\nVergleicht man das mit der `OnlineStatus`-Render-Prop von oben: dieselbe Logik, aber ohne die Verschachtelung, ohne die inline-Funktion, ohne die Klasse. Der Baum bleibt flach:\n\n```mermaid\ngraph TD\n  Page2[Page] -.ruft auf.-> H1[useData]\n  Page2 -.ruft auf.-> H2[useLoading]\n  Page2 -.ruft auf.-> H3[useRouter]\n```\n\nDie Hooks hängen seitlich an der Komponente – es sind Funktionsaufrufe, keine Baumebenen. Das ist der ganze Trick, und es ist ein großer.\n\nZwei Eigenschaften von Custom Hooks sind es wert, explizit ausgesprochen zu werden, weil sie oft missverstanden werden:\n\n- Custom Hooks teilen **Logik, nicht State**. Rufen zwei Komponenten `useOnlineStatus()` auf, hat jede ihren eigenen, unabhängigen State. Der Hook ist ein Rezept, kein geteilter Topf.\n- Custom Hooks re-rendern mit ihrer Komponente. Bei jedem Re-Render bekommt der Hook frische Props und aktuellen State – die „veralteten Closures“, die in HOC-Zwischenschichten so leicht entstehen, sind hier deutlich seltener ein Thema.\n\n## Regeln, die auch für Custom Hooks gelten\n\nDas `use`-Präfix ist keine Kosmetik. Es signalisiert dem Linter und den Lesern, dass diese Funktion selbst Hooks aufrufen darf – und dass für sie die Rules of Hooks gelten. Konkret heißt das:\n\nNur React-Komponenten und andere Hooks dürfen Hooks aufrufen. Eine gewöhnliche Funktion ohne `use` darf kein `useState` enthalten. Umgekehrt gilt genauso: Eine Funktion, die gar keine Hooks aufruft, sollte nicht `use` heißen. Denn sonst nimmt man sich die Freiheit, sie bedingt oder in einer Schleife aufzurufen – was bei echten Hooks verboten ist. Das Präfix ist also ein Vertrag in beide Richtungen. Durchgesetzt wird das Ganze vom `eslint-plugin-react-hooks`, das ich in keinem React-Projekt weglasse.\n\nEine Falle, die weniger technisch als konzeptionell ist, sehe ich in Codebasen immer wieder: der Drang, gleich generische „Lifecycle“-Hooks zu bauen, etwa ein `useMount`, das einen Effect beim Mounten kapselt. Das ist meist ein schlechter Tausch. Ein Custom Hook sollte einen konkreten, benennbaren Anwendungsfall abbilden – `useOnlineStatus`, `useChatRoom`, `useFormInput`. Wenn der Name des Hooks bereits erklärt, was er fachlich tut, ist er gut geschnitten. Wenn er nur einen React-Mechanismus umbenennt, hat man nichts gewonnen und die Abstraktion später im Weg.\n\n## Wann HOCs heute noch sinnvoll sind\n\nNach all dem klingt es, als hätten Custom Hooks die beiden älteren Muster restlos ersetzt. Für das Teilen von stateful Logik stimmt das auch weitgehend. Aber es gibt eine Handvoll Aufgaben, für die HOCs weiterhin die passende Form sind – nämlich echte Cross-Cutting-Concerns, die von außen an eine Komponente herangetragen werden.\n\nDas klassische Beispiel ist Context-Injection: ein HOC, das einer beliebigen Komponente einen Wert aus dem Context als Prop verfügbar macht, ohne dass die Komponente selbst den Context kennen muss. Solche `withXxx`-Wrapper begegnen einem in älteren Bibliotheken oft, und sie erfüllen dort einen Zweck, den ein Hook nicht sauber abdeckt – etwa wenn Klassenkomponenten im Spiel sind, die gar keine Hooks aufrufen können. Wer eine bestehende Codebasis mit Klassenkomponenten pflegt, wird HOCs also noch länger begegnen.\n\nWas ich hingegen nicht mehr empfehle, ist der Griff zu HOC-Baukästen wie `recompose`. Die Bibliothek war zu ihrer Zeit ein cleveres Werkzeug, um Funktionen wie `withState` oder `withReducer` zu komponieren:\n\n```js\n// recompose - historical, deprecated since 2018\nimport { compose, withState } from \"recompose\";\n\nconst enhance = compose(\n  withState(\"count\", \"setCount\", 0)\n);\n```\n\nDer Autor selbst hat `recompose` allerdings schon 2018 als deprecated markiert und dabei ausdrücklich auf Hooks als Nachfolger verwiesen. Man begegnet dem Paket also nur noch als historischem Kontext in älteren Repositories – als aktuelle Empfehlung taugt es nicht.\n\n## Der rote Faden\n\nDrei Antworten auf eine Frage, und die Reihenfolge erzählt eine klare Geschichte. HOCs und Render Props haben gezeigt, dass sich Logik teilen lässt, ohne sie zu kopieren – aber sie haben es über den Komponentenbaum gelöst und dafür mit Verschachtelung, verlorenen Refs und statischen Methoden, aufgehobenen `memo`-Optimierungen und „wrapper hell“ bezahlt. Custom Hooks lösen dieselbe Aufgabe über einen simplen Funktionsaufruf und lassen den Baum flach.\n\nFür geteilte Logik ist der erste Griff deshalb heute ein Custom Hook mit `use`-Präfix, der einen konkreten Use-Case kapselt. HOCs bleiben im Werkzeugkasten für die Cross-Cutting-Fälle und für die Arbeit an bestehendem Code mit Klassenkomponenten. Und Render Props tauchen noch dort auf, wo eine Komponente wirklich Kontrolle über das Rendering an den Aufrufer zurückgeben will. Aber der Standardfall – dieselbe Logik in mehreren Komponenten – hat seit 2019 eine gute, unspektakuläre Antwort. Man muss nur wissen, warum die anderen beiden vorher da waren.\n\n## Weiterführende Quellen\n\n- [Reusing Logic with Custom Hooks](https://react.dev/learn/reusing-logic-with-custom-hooks) – das aktuelle Kapitel zu Custom Hooks\n- [Higher-Order Components](https://legacy.reactjs.org/docs/higher-order-components.html) – die historische HOC-Dokumentation\n- [Render Props](https://legacy.reactjs.org/docs/render-props.html) – das Render-Props-Pattern im Original\n- [Hooks – Custom Hooks (Legacy)](https://legacy.reactjs.org/docs/hooks-custom.html) – das historische Custom-Hooks-Kapitel\n- [Rules of Hooks / Invalid Hook Call Warning](https://react.dev/warnings/invalid-hook-call-warning) – warum das `use`-Präfix und die Regeln zählen"},{"locale":"de","translation_key":"nodejs-async-context-mit-asynclocalstorage","slug":"nodejs-async-context-mit-asynclocalstorage","title":"Async-Kontext in Node.js: AsyncLocalStorage, async_hooks und diagnostics_channel","summary":"Wie man request-bezogenen Kontext wie Request-ID, User und Trace durch tiefe asynchrone Aufrufketten trägt, ohne ihn durch jede Funktionssignatur zu fädeln – mit AsyncLocalStorage, dem darunterliegenden async_hooks und diagnostics_channel für entkoppeltes Tracing.","tags":["Software","Node.js","Backend"],"published_at":"2023-05-16T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-async-context-mit-asynclocalstorage/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/5df7f260c8a8161a881ef774e940bb41c10d60b1e1dd5677006aa1c1f35177a2/nodejs-async-context-mit-asynclocalstorage-vorlesen.mp3","audio_duration_secs":912,"text":"`AsyncLocalStorage` ist keine globale Variable mit einem besseren Namen. Jeder `run`-Aufruf hält seinen eigenen Store, und zwei nebenläufige Requests kommen sich darin nicht in die Quere – genau an dieser Stelle scheitert die globale Variable, zu der man sonst reflexhaft greift. Die Verwechslung hält sich trotzdem, weil beides von außen gleich aussieht: oben etwas hinlegen, weit unten wieder herausholen.\n\nWozu das taugt, zeigt sich im Betrieb und nicht im Code. Ob eine Ursachensuche Minuten oder Stunden dauert, hängt daran, ob sich ein einzelner Request lückenlos durch Logs, Services und Traces verfolgen lässt. Node.js bringt dafür drei Bausteine mit: `AsyncLocalStorage`, das darunterliegende `async_hooks` und `diagnostics_channel`. Im Beitrag über [Node.js debuggen und beobachten](https://www.mikebild.dev/de/blog/nodejs-debuggen-und-beobachten/) hatte ich mir Async-Kontext für später aufgehoben; das hole ich hier nach.\n\nDas ist kein Randproblem. Sobald eine Anwendung mehr als ein paar Endpoints hat, will man wissen, welche Logzeile zu welchem Request gehört. Man will den eingeloggten User im Fehlerbericht sehen. Man will einen Trace über mehrere Services hinweg zusammenhalten. Und all diese Werte gehören nun einmal zum Request, nicht zur Funktion, die gerade zufällig ausgeführt wird.\n\n## Das Problem: Kontext durch die Tiefe fädeln\n\nSchauen wir uns an, wie das ohne Hilfsmittel aussieht. Ich habe einen Handler, der einen Service ruft, der ein Repository ruft, das am Ende etwas loggen will. Die Request-ID entsteht ganz oben – gebraucht wird sie ganz unten.\n\n```js\nfunction handler(req, res) {\n  const requestId = randomUUID();\n  serviceA(req.body, requestId);\n}\n\nfunction serviceA(input, requestId) {\n  // serviceA doesn't need requestId itself\n  return repository(input, requestId);\n}\n\nfunction repository(input, requestId) {\n  // repository doesn't either\n  log('writing record', requestId);\n}\n\nfunction log(message, requestId) {\n  console.log(`[${requestId}] ${message}`);\n}\n```\n\nDas funktioniert – aber es ist unangenehm. Jede Funktion dazwischen bekommt einen Parameter aufgezwungen, den sie selbst nie benutzt. Sie reicht ihn nur durch. Kommt morgen ein User-Objekt dazu und übermorgen eine Trace-ID, wächst jede Signatur mit. Und die eine Bibliotheksfunktion, die man nicht ändern kann, reicht den Parameter natürlich nicht durch – dort reißt die Kette.\n\nMan kann sich mit Umwegen behelfen: den Kontext an eine Klasseninstanz hängen, ein Objekt durchreichen, das alle Zusatzdaten sammelt, oder gar eine globale Variable setzen. Der Klasseninstanz-Weg zwingt einen in ein Objektmodell, das man vielleicht gar nicht will. Das Kontextobjekt ist nur eine hübscher verpackte Variante desselben Durchreichens. Und die globale Variable ist bei nebenläufigen Requests schlicht falsch – der nächste Request überschreibt sie, während der erste noch läuft. Keine dieser Varianten trägt wirklich.\n\nGenau für dieses „context threading“-Problem gibt es in Node.js eine saubere Antwort.\n\n## AsyncLocalStorage: der praktische Weg\n\n`AsyncLocalStorage` steckt im Modul `node:async_hooks` und ist seit Node v16.4.0 stabil. Die Idee ist einfach: Man führt einen Callback in einem sogenannten Store aus, und dieser Store bleibt für alle asynchronen Operationen erhalten, die innerhalb dieses Callbacks entstehen. Beliebig tief unten liest man ihn wieder aus – ohne einen einzigen zusätzlichen Parameter.\n\nVorweg ein ehrlicher Hinweis: Für diesen Beitrag gibt es kein Beispiel aus einem konkreten Projektbestand. Die folgenden Codeblöcke sind generische Node.js-Beispiele, die ich gegen die offizielle Dokumentation geprüft habe.\n\n```js\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\n\nconst als = new AsyncLocalStorage();\n\nfunction handler(req, res) {\n  const store = { requestId: randomUUID(), user: req.user };\n  als.run(store, () => {\n    serviceA(req.body);\n  });\n}\n\nfunction serviceA(input) {\n  return repository(input);\n}\n\nfunction repository(input) {\n  log('writing record');\n}\n\nfunction log(message) {\n  const { requestId } = als.getStore() ?? {};\n  console.log(`[${requestId}] ${message}`);\n}\n```\n\nDer Unterschied ist deutlich. `serviceA` und `repository` wissen nichts mehr von der Request-ID. Sie kennen ihren eigentlichen Job und sonst nichts. Nur ganz oben wird der Store gesetzt – mit `als.run(store, callback)` – und nur dort, wo er wirklich gebraucht wird, wird er mit `als.getStore()` gelesen.\n\nZwei Details sind wichtig. Erstens ist `run` synchron: Der Rückgabewert des Callbacks wird durchgereicht, und wenn der Callback wirft, wird der Fehler ebenfalls weitergegeben und der Kontext wieder verlassen. Zweitens liefert `getStore()` außerhalb eines `run`-Aufrufs schlicht `undefined`. Deshalb steht im Beispiel das `?? {}` – man sollte nie davon ausgehen, dass immer ein Store vorhanden ist.\n\nAls Store eignet sich jedes beliebige Objekt. In der Praxis nehme ich gern eine `Map`, wenn im Verlauf eines Requests noch Werte dazukommen sollen, oder ein schlichtes Objekt, wenn der Inhalt von Anfang an feststeht. Wichtig ist nur, dass jeder `run`-Aufruf seinen eigenen Store bekommt – dann sind nebenläufige Requests sauber voneinander getrennt, ohne dass man sich um die Trennung selbst kümmern muss. Genau das ist der Gewinn gegenüber der globalen Variable von eben.\n\nDiese Ebene zeigt das folgende Diagramm. Der Store wird oben gesetzt, die tiefen Aufrufe lesen ihn, ohne dass ein Parameter je weitergereicht wird.\n\n```mermaid\nflowchart TD\n  Req[\"HTTP Request\"] --> Run[\"als.run(store)\"]\n  Run --> A[\"serviceA()\"]\n  A --> R[\"repository()\"]\n  R --> L[\"log()\"]\n  Store[(\"Store<br/>requestId, user\")]\n  Run -.-> Store\n  L -.->|\"reads store\"| Store\n```\n\n### enterWith – die riskante Abkürzung\n\nNeben `run` gibt es `enterWith(store)`. Der Reiz ist offensichtlich: Man muss den restlichen Code nicht in einen Callback einrücken, sondern setzt den Kontext einfach und läuft danach normal weiter. Genau das ist aber auch die Gefahr. `enterWith` gilt für den gesamten Rest der synchronen Ausführung plus alle folgenden asynchronen Aufrufe – es gibt keine natürliche Klammer, die den Kontext wieder schließt. Setzt man das in einem Event-Handler, geraten unter Umständen nachfolgende Handler in denselben Kontext.\n\n`enterWith` ist als experimentell markiert, und die Dokumentation ist ungewöhnlich direkt: Man solle `run()` benutzen, sofern es keine starken Gründe dagegen gebe. Praktisch heißt das: mit `run` anfangen. `enterWith` bleibt seltenen Sonderfällen vorbehalten und ist nicht der Normalweg.\n\n## async_hooks: das Fundament darunter\n\nWoher weiß `AsyncLocalStorage` überhaupt, welche asynchronen Operationen zu welchem `run`-Aufruf gehören? Darunter liegt `async_hooks`, die eigentliche Low-Level-Schicht. Sie stellt Lifecycle-Hooks für asynchrone Ressourcen bereit: Für jede solche Ressource durchläuft Node die Phasen `init`, `before`, `after` und `destroy`. Man kann sich in diese Phasen einklinken.\n\n```js\nimport { createHook, executionAsyncId } from 'node:async_hooks';\nimport { writeSync } from 'node:fs';\n\nconst hook = createHook({\n  init(asyncId, type, triggerAsyncId) {\n    writeSync(1, `init ${type} id=${asyncId} trigger=${triggerAsyncId}\\n`);\n  },\n  destroy(asyncId) {\n    writeSync(1, `destroy id=${asyncId}\\n`);\n  },\n});\n\nhook.enable();\n```\n\nWarum `writeSync` statt `console.log`? Weil `console.log` selbst asynchrone Ressourcen erzeugt und man sich in einem `init`-Hook damit in eine Endlosschleife schreiben würde. Das allein zeigt schon, wie heikel diese Schicht im direkten Umgang ist.\n\nUnd hier muss ich deutlich werden: `async_hooks` ist experimentell, und die Node-Dokumentation rät ausdrücklich davon ab, es direkt einzusetzen – wegen „usability issues, safety risks, and performance implications“. Der `destroy`-Hook ist besonders teuer, weil er ein Tracking von Promises über den Garbage Collector aktiviert. Das kostet messbar Leistung.\n\nDie Botschaft ist also nicht „lern async_hooks und benutz es“. Die Botschaft ist: `AsyncLocalStorage` steht auf diesem Fundament, aber es ist die stabile, empfohlene und praktische API. Man greift in aller Regel nicht selbst zu `createHook`. Ich zeige es hier nur, damit klar wird, was eine Ebene tiefer passiert – nicht als Empfehlung für den Produktionscode.\n\n## diagnostics_channel: entkoppelte Instrumentierung\n\nDer dritte Baustein löst ein anderes Problem. Angenommen, eine Bibliothek möchte melden, dass sie gerade einen Request startet – aber sie soll nicht vorschreiben, wer das mitbekommt oder was damit geschieht. Ein Logger? Ein Tracer? Ein Metric-Zähler? Die Bibliothek soll das nicht wissen müssen.\n\n`diagnostics_channel` ist seit Node v18.13.0 stabil und genau dafür da: ein entkoppelter Publish/Subscribe-Kanal. Produzenten veröffentlichen Messages auf einem benannten Kanal, Beobachter abonnieren ihn. Beide Seiten kennen sich nicht.\n\n```js\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('app:request:start');\n\nfunction handleRequest(req) {\n  if (channel.hasSubscribers) {\n    channel.publish({\n      requestId: req.id,\n      route: req.url,\n      startedAt: Date.now(),\n    });\n  }\n  // ... actual work\n}\n```\n\nAuf der anderen Seite, in einem völlig getrennten Stück Code – vielleicht in der Observability-Schicht, vielleicht in einem Plugin – abonniert man denselben Kanal:\n\n```js\nimport diagnostics_channel from 'node:diagnostics_channel';\n\ndiagnostics_channel.subscribe('app:request:start', (message, name) => {\n  console.log(`[${name}] request ${message.requestId} on ${message.route}`);\n});\n```\n\nDer `hasSubscribers`-Guard ist kein Detail, sondern der Kern der Sache. Ohne Abonnenten soll gar nichts kosten. Baut man das Nachrichtenobjekt bedingungslos – womöglich mit teuren Feldern oder serialisierten Payloads –, zahlt man diesen Preis auch dann, wenn niemand zuhört. Mit dem Guard fällt bei null Abonnenten praktisch kein Aufwand an.\n\nEin Hinweis zur API: Es gibt am Channel-Objekt auch `channel.subscribe(...)`, aber diese Variante ist seit v18.7.0 als veraltet markiert. Im eigenen Code nimmt man die Funktionen auf Modul-Ebene, also `diagnostics_channel.subscribe(name, onMessage)`.\n\n## Drei Ebenen, drei Aufgaben\n\nDie drei Module klingen ähnlich und tun Grundverschiedenes – genau hier entsteht die Verwirrung. Die Rollenverteilung:\n\n- `AsyncLocalStorage` trägt Kontext: stabil seit v16.4.0, die praktische High-Level-API. Request-ID, User und Trace durch tiefe Async-Ketten – ohne Parameter-Durchreichen.\n- `async_hooks` ist das Fundament: experimentell und ausdrücklich nicht zum direkten Gebrauch empfohlen. Es liefert den Ressourcen-Lifecycle, auf dem `AsyncLocalStorage` aufsetzt.\n- `diagnostics_channel` meldet Events entkoppelt: stabil seit v18.13.0. Produzenten und Konsumenten kennen sich nicht – ideal für Instrumentierung und Tracing.\n\nDas folgende Diagramm ordnet die drei zueinander an: die Kontext-Schicht auf ihrem Fundament, daneben der eigenständige Event-Bus.\n\n```mermaid\nflowchart TB\n  subgraph Context[\"Kontext tragen\"]\n    ALS[\"AsyncLocalStorage<br/>Stable\"]\n    AH[\"async_hooks<br/>Experimental\"]\n    ALS --> AH\n  end\n  subgraph Bus[\"Ereignisse entkoppelt melden\"]\n    Pub[\"Publisher\"] --> Ch[\"diagnostics_channel\"]\n    Ch --> S1[\"Subscriber: Logger\"]\n    Ch --> S2[\"Subscriber: Tracer\"]\n  end\n```\n\n## Request-Korrelation als messbare Betriebsqualität\n\nDie drei Module sind Mittel, kein Zweck. Der Zweck ist eine Eigenschaft des laufenden Systems: Lässt sich jeder Vorgang eindeutig einem Request zuordnen? Sobald das gegeben ist, wird aus einem diffusen „das System fühlt sich langsam an“ eine beantwortbare Frage. Man greift eine Correlation-ID, filtert Logs, Metrics und Traces darauf und sieht den einen Request in seiner ganzen Tiefe – über Service-Grenzen hinweg.\n\nDiese Nachverfolgbarkeit ist messbar, und genau das macht sie zu einer Betriebsqualität statt zu einem Bauchgefühl. Der Anteil der Logzeilen, die einer Request-ID zugeordnet sind, ist eine Kennzahl. Die Zeit von der Fehlermeldung bis zur gefundenen Ursache – die Mean Time to Resolution – ist eine Kennzahl. Beide bewegen sich spürbar, wenn Korrelation lückenlos ist statt löchrig. `AsyncLocalStorage` liefert dafür den tragenden Baustein: den Schlüssel, der ohne Parameter-Durchreichen bis in die tiefste Funktion reicht. `diagnostics_channel` liefert den zweiten: die Entkopplung, mit der eine Observability-Schicht diesen Schlüssel abgreift, ohne dass der Anwendungscode wissen muss, wer zuhört.\n\nDer Trade-off ist ehrlich zu benennen. Kontext über `AsyncLocalStorage` kostet einen kleinen, aber realen Overhead pro asynchroner Operation – für die allermeisten Backends vernachlässigbar gegenüber dem Gewinn, in Ausnahmefällen mit extrem hohem Durchsatz aber ein Punkt, den man misst statt annimmt. Der größere Preis ist Disziplin: Der `run`-Aufruf muss zuverlässig am Eingang jeder Ausführungskette sitzen, sonst reißt die Korrelation genau dort, wo man sie am dringendsten braucht.\n\nDie Entscheidung fällt also nicht an der API, sondern am Anspruch. Eine Handvoll Endpoints ohne echte Betriebslast kommt ohne all das aus. Sobald aber mehrere Services zusammenspielen, ein Bereitschaftsdienst existiert oder Fehler Geld kosten, wird Request-Korrelation vom Nice-to-have zur Grundlage. Sie ist der Baustein, auf dem Logging, Tracing und Alerting erst zu einem Bild zusammenwachsen – die Brücke von einzelnen Signalen zu echter Observability.\n\n## Fallstricke aus der Praxis\n\nDer häufigste Schmerz mit `AsyncLocalStorage` ist Kontextverlust: `getStore()` liefert plötzlich `undefined`, obwohl man sich sicher innerhalb eines `run`-Aufrufs wähnt. Das passiert typischerweise an bestimmten callback-basierten APIs oder bei eigenen, selbstgebauten „thenable“-Objekten, bei denen Node die asynchrone Verkettung nicht sauber mitverfolgen kann. Die Dokumentation nennt zwei Abhilfen: solche APIs mit `util.promisify()` in echte Promises überführen oder die Ressource mit `AsyncResource` binden. Praktischer Debug-Trick: An verdächtigen Übergängen `getStore()` loggen. Ist der Store direkt nach einem bestimmten Aufruf weg, hat man den Übergang gefunden, an dem die Verkettung reißt.\n\nBeim `enterWith`-Leak habe ich es oben schon angedeutet – hier noch einmal konkret als Warnung: Der Kontext läuft über die gesamte weitere synchrone Ausführung und danach weiter. In einem Event-Handler gesetzt, können Folge-Handler denselben Kontext erben, obwohl sie zu einem ganz anderen Request gehören. Das sind dann Fehler, die man nachts um drei sucht. `run()` bevorzugen.\n\nUnd schließlich die Kosten von `async_hooks`: Der Overhead ist real, besonders durch das Promise-Tracking im `destroy`-Hook. Zusammen mit der Tatsache, dass die API experimentell und laut Node-Team riskant ist, ergibt das eine klare Linie – nicht als Kontext-Mechanismus in Produktion einsetzen. Wer Kontext braucht, nimmt `AsyncLocalStorage`. `async_hooks` ist etwas, das man kennt, um zu verstehen, was darunter passiert, und das man sonst in Ruhe lässt.\n\nAls Randnotiz für die Neugierigen: Mit v18.16.0 kamen `AsyncLocalStorage.bind(fn)` und `AsyncLocalStorage.snapshot()` dazu, um den aktuellen Kontext an eine Funktion zu binden. Beides ist noch experimentell und für den Einstieg nicht nötig – ich erwähne es nur der Vollständigkeit halber.\n\n## Fazit\n\nDer rote Faden ist eine Schichtung. Ganz unten sorgt `async_hooks` dafür, dass Node den Lifecycle asynchroner Ressourcen überhaupt verfolgen kann – eine mächtige, aber experimentelle und teure Schicht, die man selten direkt anfasst. Darauf steht `AsyncLocalStorage` als die stabile, empfohlene API, mit der man request-bezogenen Kontext durch beliebig tiefe Aufrufketten trägt, ohne ihn durch jede Signatur zu fädeln. Und daneben steht `diagnostics_channel` als entkoppelter Event-Bus, mit dem Bibliotheken und Anwendungen strukturiert instrumentieren, ohne dass Produzent und Konsument voneinander wissen müssen.\n\nDie Wirkung zeigt sich weniger im Code als im Betrieb. Wo der Kontext sauber getragen wird, verkürzen sich die Zyklen in der Fehlersuche, weil jede Logzeile ihren Request kennt. Die Reibung sinkt, weil keine Signatur mehr einen Parameter durchschleift, den sie nie benutzt. Und die Qualität steigt messbar, weil Nachverfolgbarkeit vom Zufall zur Eigenschaft wird. Für die tägliche Arbeit heißt das: `als.run(store, cb)` oben, `als.getStore()` unten – und man ist das lästige Parameter-Durchreichen los. Wer Observability entkoppeln will, greift zu `diagnostics_channel` mit einem `hasSubscribers`-Guard. `async_hooks` bleibt das Fundament, das man verstanden haben sollte, aber im Alltag nicht selbst bedient. Die Grenze ist ebenso klar: Kein Mechanismus ersetzt die Disziplin, den `run`-Aufruf zuverlässig zu setzen – reißt die Kette dort, hilft die beste API nichts.\n\nWenn du an dieser Stelle tiefer in das Event-Modell von Node einsteigen willst, passt der Beitrag über [EventEmitter und Event-Modell](https://www.mikebild.dev/de/blog/nodejs-eventemitter-und-ereignismodell/) gut dazu. Und wer die Architektur rund um Event Loop und asynchrone Ausführung von Grund auf verstehen möchte, findet im [Node.js-Training](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) den größeren Rahmen.\n\n## Weiterführende Quellen\n\n- [AsyncLocalStorage und Async-Kontext (Node.js v18.x)](https://nodejs.org/docs/latest-v18.x/api/async_context.html)\n- [async_hooks (Node.js v18.x)](https://nodejs.org/docs/latest-v18.x/api/async_hooks.html)\n- [diagnostics_channel (Node.js v18.x)](https://nodejs.org/docs/latest-v18.x/api/diagnostics_channel.html)"},{"locale":"de","translation_key":"graphql-auth-im-context","slug":"graphql-auth-im-context","title":"GraphQL-Auth: Identität im Context, Autorisierung in der Fachlogik","summary":"Der GraphQL-Context transportiert die Identität eines Requests. Ob diese Identität eine Operation ausführen darf, entscheidet eine zentrale Policy in der Fachlogik.","tags":["Software","GraphQL","API"],"published_at":"2023-04-18T10:00:00+00:00","updated_at":"2026-07-13T08:49:33.50578+00:00","url":"https://www.mikebild.dev/de/blog/graphql-auth-im-context/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/8c667c9869495d73a0c642d8a67a33c5de74446fd9099b6e86ebb1385a9f755c/graphql-auth-im-context-vorlesen.mp3","audio_duration_secs":651,"text":"Ein Resolver, der nur prüft, ob ein Token da ist, gibt jedem eingeloggten Nutzer alles frei, was das Schema anbietet. Das ist kein Detailfehler in der Auth, das ist ein offenes Backend mit einem Login-Formular davor.\n\nDie Ursache steckt fast immer an derselben Stelle: In dieser einen Prüfung stecken zwei Fragen, die mit ganz verschiedenen Dingen zu tun haben – und im Code sind sie zu einer verschmolzen. \"Wir prüfen das im Resolver\" ist deshalb eine Antwort, die alles offen lässt: Geprüft wird, ob jemand eingeloggt ist, oder ob er dieses Feld sehen darf? Solange das nicht beantwortet ist, weiß niemand, wogegen die Anwendung eigentlich geschützt ist.\n\n## Zwei Fragen, nicht eine\n\nAuthentifizierung beantwortet die Frage: **Wer bist du?** Aus einem Token wird eine Identität – ein `user`. Autorisierung beantwortet eine ganz andere Frage: **Was darfst du?** Ob dieser konkrete Nutzer dieses konkrete Feld oder diese konkrete Mutation aufrufen darf.\n\nDas sind unterschiedliche Verantwortlichkeiten, und sie haben sogar unterschiedliche Fehlerbilder. Wer kein oder ein ungültiges Token schickt, bekommt einen `401` – nicht authentifiziert. Wer ein gültiges Token hat, aber die falsche Rolle, bekommt einen `403` – authentifiziert, aber nicht berechtigt. In Code-Reviews sehe ich die beiden regelmäßig verwechselt, und dann landet am Ende beides als HTTP `500` beim Client, weil ein Fehler nicht abgefangen wurde. Das ist kein kosmetisches Problem – ein Client kann auf `401` und `403` sinnvoll reagieren (Login-Flow vs. \"kein Zugriff\"), auf `500` nicht.\n\nWenn diese Trennung sitzt, kommt die eigentliche Architekturfrage: Wo gehört die Identität hin, und wie kommt sie zu jedem Resolver, der sie braucht?\n\n## Warum der context der richtige Ort ist\n\nIn GraphQL wird pro Request ein `contextValue` gebaut – ein Objekt, das an **jeden** Resolver desselben Requests durchgereicht wird. Das ist kein Zufallsdetail, das ist der ideale Aufhängepunkt für Auth.\n\nDer Grund ist die Lebensdauer. Der context wird einmal pro Request neu erzeugt und lebt genau so lange wie dieser Request. Kein State leakt zwischen zwei Requests, kein Cleanup ist nötig, und ich habe garantiert für jede Anfrage eine frisch ermittelte Identität. Genau dort gehört der `user` hin.\n\nIn Apollo Server 4 – dem aktuellen Major – ist das eine `async`-Funktion, die man dem Server-Start mitgibt. Wichtig: In Apollo Server 4 wandert die context-Funktion aus dem `new ApolloServer({...})`-Konstruktor heraus zu `startStandaloneServer` beziehungsweise `expressMiddleware`. Wer noch ältere Beispiele aus AS2/AS3 im Kopf hat, wo `context` direkt im Konstruktor stand: konzeptionell identisch, nur eingehängt wird sie heute an anderer Stelle.\n\n```ts\nimport { ApolloServer } from '@apollo/server';\nimport { startStandaloneServer } from '@apollo/server/standalone';\n\nconst server = new ApolloServer({ typeDefs, resolvers });\n\nconst { url } = await startStandaloneServer(server, {\n  context: async ({ req }) => {\n    const raw = req.headers.authorization || '';\n    const token = raw.replace('Bearer ', '');\n    const user = await getUserFromToken(token);\n    return { user };\n  },\n});\n```\n\nZwei Details, an denen in Projekten regelmäßig jemand hängen bleibt. Erstens: `req.headers.authorization` ist in Express immer kleingeschrieben – die HTTP-Header-Keys landen dort in Kleinbuchstaben, egal wie der Client sie sendet. Zweitens: Ein leerer Header darf niemals als \"eingeloggt\" durchgehen. Der `|| ''`-Fallback liefert einen leeren String, `getUserFromToken('')` gibt dann sauber `null` zurück – und `null` heißt eben \"unbekannt\", nicht \"Admin\".\n\nDer Ablauf sieht damit für jeden Request gleich aus:\n\n```mermaid\nflowchart LR\n  C[Client] -- \"Authorization:<br/>Bearer token\" --> S[GraphQL-Server]\n  S --> CTX[\"context()<br/>Token zu user\"]\n  CTX --> R[Resolver]\n  R --> BL[Business-Logik<br/>prueft user + Rolle]\n  BL -- erlaubt --> DATA[Daten]\n  BL -- verweigert --> ERR[\"GraphQLError<br/>403 FORBIDDEN\"]\n```\n\nMan sieht hier gut: Die Authentifizierung passiert genau einmal, ganz vorn in `context()`. Ab da trägt der Request eine Identität mit sich, und alles Weitere ist Autorisierung.\n\n## Was in den context gehört – und was nicht\n\nWeil der context so verlockend praktisch ist, wird er gern zur Rumpelkammer. Es lohnt sich, den Inhalt bewusst kurz zu halten. Hinein gehört:\n\n- die Identität – `user` oder `viewer`, aus dem Token ermittelt\n- die Berechtigungen dieses Nutzers – `roles` oder `scopes`\n- request-gebundene Infrastruktur – DataLoader-Instanzen, damit Batching und Deduplizierung pro Request funktionieren\n- Zugänge zur Datenschicht – `db`-Handle oder Repositories\n- request-spezifische Werte wie Locale oder ein durchzureichendes Auth-Token für nachgelagerte Services\n\nUnd ebenso klar, was **nicht** hineingehört:\n\n- globaler State, der über Requests hinweg lebt\n- Cross-Request-Caches (ein DataLoader ist genau deshalb pro Request, nicht global)\n- Secrets im Klartext, die dort nichts verloren haben\n\nDie Faustregel dahinter: Alles, was für genau diesen einen Request gilt und danach weg darf, ist im context gut aufgehoben. Alles Langlebige gehört woanders hin. Wer DataLoader-Instanzen pro Request in den context legt, kennt das Muster übrigens schon aus dem Umfeld von effizientem Datenzugriff – ich habe das im Zusammenhang mit Listen und Cursorn in [GraphQL-Paginierung](https://www.mikebild.dev/de/blog/graphql-paginierung-und-connections/) ausführlicher beschrieben.\n\n## Autorisierung im Resolver\n\nJetzt ist der `user` im context, und jeder Resolver kann ihn lesen – als **drittes Argument**, `(parent, args, contextValue, info)`. Das ist die einfachste, direkteste Form der Autorisierung.\n\n```ts\nimport { GraphQLError } from 'graphql';\n\nconst resolvers = {\n  Query: {\n    me: (parent, args, { user }) => {\n      if (!user) {\n        throw new GraphQLError('Not authenticated', {\n          extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },\n        });\n      }\n      return user;\n    },\n    adminReport: (parent, args, { user }) => {\n      if (!user?.roles.includes('ADMIN')) {\n        throw new GraphQLError('Forbidden', {\n          extensions: { code: 'FORBIDDEN', http: { status: 403 } },\n        });\n      }\n      return buildAdminReport();\n    },\n  },\n};\n```\n\nWichtig für alle, die noch mit älteren Apollo-Beispielen arbeiten: Die früheren Klassen `AuthenticationError` und `ForbiddenError` aus dem alten `apollo-server`-Paket gibt es in Apollo Server 4 nicht mehr. Der Weg heute ist `GraphQLError` aus `graphql` mit einem `extensions.code` – `UNAUTHENTICATED` für den fehlenden Login, `FORBIDDEN` für die fehlende Berechtigung – und optional dem passenden HTTP-Status.\n\nMan erkennt an den beiden Resolvern schon die Trennung: `me` prüft nur, **ob** überhaupt jemand da ist (Authentifizierung durchgesetzt), `adminReport` prüft, **was** dieser Jemand darf (Autorisierung). Zwei Fragen, zwei Fehlercodes.\n\n## Feld-Ebene versus Query-Ebene\n\nAutorisierung ist nicht nur eine Frage von \"ganze Query erlaubt oder nicht\". GraphQL erlaubt Prüfungen auf Feld-Ebene, und das ist eine seiner stärkeren Eigenschaften.\n\nWeil jedes Feld seinen eigenen Resolver hat und die Prüfung während der Ausführung des Requests greift, sind **Partial Responses** möglich: Der Client fragt zehn Felder ab, sieben liefert der Server, für drei bekommt er einen Fehler und `null` – in einer einzigen Antwort. Das ist genau das Verhalten, das man will. Ein Nutzer soll seinen eigenen Namen sehen, aber nicht das interne Bonitäts-Feld, das nur Admins zusteht.\n\nIm Grounding-Repo taucht dafür ein deklarativer Ansatz auf: eine `@auth`-Directive mit einem Rollen-Enum.\n\n```graphql\nenum Role {\n  ADMIN\n  OWNER\n  USER\n}\n\ndirective @auth(requires: Role!) on FIELD_DEFINITION\n\ntype User {\n  id: ID!\n  name: String!\n  role: String @auth(requires: ADMIN)\n}\n\ntype Query {\n  me: User @auth(requires: USER)\n}\n```\n\nHier sieht man beide Ebenen: `me @auth(requires: USER)` schützt ein ganzes Query-Feld, `role @auth(requires: ADMIN)` schützt ein einzelnes Feld innerhalb des Typs. Die Directive selbst ist nur eine Deklaration – irgendjemand muss sie zur Laufzeit auch durchsetzen. In der aktuellen graphql-tools-Generation macht man das mit einem Schema-Transformer.\n\n```ts\nimport { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';\nimport { defaultFieldResolver, GraphQLError } from 'graphql';\n\nfunction authDirectiveTransformer(schema) {\n  return mapSchema(schema, {\n    [MapperKind.OBJECT_FIELD]: (fieldConfig) => {\n      const directive = getDirective(schema, fieldConfig, 'auth')?.[0];\n      if (!directive) return fieldConfig;\n\n      const { requires } = directive;\n      const { resolve = defaultFieldResolver } = fieldConfig;\n\n      fieldConfig.resolve = (source, args, context, info) => {\n        if (!context.user) {\n          throw new GraphQLError('Not authenticated', {\n            extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },\n          });\n        }\n        if (!context.user.roles.includes(requires)) {\n          throw new GraphQLError('Forbidden', {\n            extensions: { code: 'FORBIDDEN', http: { status: 403 } },\n          });\n        }\n        return resolve(source, args, context, info);\n      };\n      return fieldConfig;\n    },\n  });\n}\n```\n\nEin Hinweis für alle, die ältere Tutorials finden: Der frühere `SchemaDirectiveVisitor` ist längst raus – seit graphql-tools v6 gibt es ihn nicht mehr. Der Weg über `mapSchema` und `getDirective` ist der aktuelle. Wer nach `SchemaDirectiveVisitor` googelt und es kopiert, wundert sich dann, warum nichts importierbar ist.\n\nSo elegant die Directive aussieht: Sie ist nur die halbe Wahrheit. Und genau hier fangen im Team die interessanten Diskussionen an.\n\n## Warum Auth nicht ins Schema gehört\n\nDie `@auth`-Directive fühlt sich zunächst wie die perfekte Lösung an – Berechtigungen stehen direkt am Feld, deklarativ, lesbar. Für Prototypen und zum Lernen ist das auch völlig in Ordnung. Aber als **alleinige** Strategie führt sie in eine Sackgasse, und die offizielle GraphQL-Doku ist da erstaunlich deutlich: Autorisierung gehört in die Business-Logik-Schicht, nicht ins Schema.\n\nDer Grund ist Duplikation. Nehmen wir eine typische Regel: `OWNER` – ein Nutzer darf nur seine eigenen Posts bearbeiten. Diese Regel lässt sich rein deklarativ kaum abbilden, denn sie hängt von den konkreten Daten ab: Gehört *dieser* Post *diesem* Nutzer? Eine Directive kennt die Rolle, aber nicht die Beziehung zwischen Nutzer und Ressource.\n\nUnd selbst simple Rollenchecks laufen auseinander, sobald dieselbe Logik an mehreren Stellen gebraucht wird. Wenn dieselbe \"darf-Post-lesen\"-Entscheidung an drei Feldern hängt und irgendwann auch noch von einem REST-Endpoint oder einem Background-Job gebraucht wird, dann hat man die Regel dreimal, viermal – und sie driftet auseinander. Das ist der Kern des Arguments: eine einzige Quelle der Wahrheit statt verstreuter Kopien.\n\nDie saubere Variante ist deshalb: Der Resolver entscheidet nicht selbst, er **delegiert** an eine Business-Logik-Funktion, die den context bekommt und die Entscheidung trifft.\n\n```ts\nconst resolvers = {\n  Query: {\n    posts: (parent, args, context) => postRepository.getPosts(context),\n  },\n  Mutation: {\n    updatePost: (parent, { id, input }, context) =>\n      postRepository.updatePost(id, input, context),\n  },\n};\n\n// Business logic layer – authorization lives here\nconst postRepository = {\n  async getPosts(context) {\n    if (!context.user) {\n      throw new GraphQLError('Not authenticated', {\n        extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },\n      });\n    }\n    // Owner rule: only the user's own posts\n    return db.posts.findMany({ where: { authorId: context.user.id } });\n  },\n};\n```\n\nDer Resolver bleibt dünn und dumm – er nimmt args und context und reicht sie weiter. Die eigentliche Entscheidung, inklusive der datenabhängigen OWNER-Regel, liegt an einer einzigen Stelle. Wenn morgen ein anderer Entry Point dazukommt, ruft der dieselbe Funktion auf. Keine Duplikation, kein Drift.\n\nIch stelle mir das gern als drei Schichten vor, mit dem Schema bewusst in der Mitte und ohne Entscheidungsgewalt:\n\n```mermaid\nflowchart TB\n  subgraph Transport[\"Transport-Schicht\"]\n    A[\"Authentifizierung<br/>Token zu user im context\"]\n  end\n  subgraph Schema[\"Schema-Schicht\"]\n    B[\"nur deklarativ<br/>optional @auth als Hinweis\"]\n  end\n  subgraph Domain[\"Business-Logik-Schicht\"]\n    D[\"Autorisierung<br/>darf user diese Ressource?\"]\n  end\n  Transport --> Schema --> Domain\n```\n\nDie Botschaft dieses Bildes: Identität wird oben ermittelt, die Berechtigungsentscheidung fällt unten. Das Schema in der Mitte beschreibt nur, es entscheidet nicht.\n\n## Der Fallstrick, der am teuersten wird\n\nEs gibt einen Fehler, den ich immer wieder sehe und der richtig weh tut: Autorisierung im Client durchsetzen. Die UI blendet den \"Löschen\"-Button aus, wenn der Nutzer kein Admin ist – und alle sind zufrieden. Nur prüft der Resolver dahinter gar nichts.\n\nDas ist keine Sicherheit, das ist Kosmetik. Jeder, der die Developer-Tools öffnet oder direkt eine GraphQL-Mutation abschickt, umgeht diese \"Prüfung\" in Sekunden. Ausgeblendete Buttons sind eine Frage der Nutzerführung, nicht der Sicherheit. Die Durchsetzung **muss** serverseitig passieren – im Resolver beziehungsweise in der Business-Logik-Schicht dahinter. Der Client darf gern zusätzlich Buttons ausblenden, damit die Oberfläche aufgeräumt ist. Aber verlassen darf man sich nur auf den Server.\n\nDamit ist auch die Ausgangsfrage beantwortet. \"Wir prüfen das im Resolver\" reicht nicht als Architekturentscheidung. Die Identität kommt einmal pro Request in den Context. Der Resolver ruft für die konkrete Operation eine zentrale Policy oder Fachfunktion auf; dort fällt die datenabhängige Berechtigungsentscheidung. Directives und ausgeblendete Buttons können das sichtbar machen, ersetzen diese Prüfung aber nicht.\n\nIn den Projekten, in denen Auth am Ende ruhig lief, war sie nie eine Schema-Frage, sondern eine Frage der Lifecycles und der Verantwortlichkeiten. Der context weiß, wer du bist. Die Business-Logik weiß, was du darfst. Bleiben die beiden getrennt, wird der Rest einfach.\n\n## Weiterführende Quellen\n\n- [Grounding-Repository MikeBild/introduction-graphql](https://github.com/MikeBild/introduction-graphql) – `introduction-graphql/auth.md` und `recipes/auth/`\n- [graphql.org – Authorization](https://graphql.org/learn/authorization/) – warum Autorisierung in die Business-Logik-Schicht gehört\n- [Apollo Server – Authentication and authorization](https://www.apollographql.com/docs/apollo-server/security/authentication) – GraphQLError-Codes, `UNAUTHENTICATED` vs. `FORBIDDEN`\n- [Apollo Server – The context object](https://www.apollographql.com/docs/apollo-server/data/context) – context und contextValue, einmal pro Request"},{"locale":"de","translation_key":"nodejs-debuggen-und-beobachten","slug":"nodejs-debuggen-und-beobachten","title":"Node.js lokal debuggen und profilieren","summary":"Vom console.log-Reflex zum eingebauten Inspector: node --inspect, das debug-Modul, nodemon sowie erste CPU- und Speicherprofile für die lokale Diagnose.","tags":["Software","Node.js","Backend"],"published_at":"2023-02-14T10:00:00+00:00","updated_at":"2026-07-13T08:00:08.673184+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-debuggen-und-beobachten/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/b3c049c4445ff2a46c888c5c726dc56c1984a186773ead6468b82b5d93072308/nodejs-debuggen-und-beobachten-vorlesen.mp3","audio_duration_secs":817,"text":"```js\nconsole.log(x);\nconsole.log('HIER');\nconsole.log('HIER 2');\n```\n\nDiese drei Zeilen können genau eine Sache: einen Wert an einer Stelle zeigen, die man vorher erraten hat. Abschalten lassen sie sich nur, indem jemand die Datei wieder anfasst. Den Prozess anhalten können sie nicht. Über Speicherverbrauch sagen sie gar nichts. Für alle drei Lücken bringt Node.js seit Version 6.3 eigene Werkzeuge mit, ohne dass ein zusätzliches Paket installiert werden muss – sie werden nur selten benutzt.\n\nSortieren lassen sie sich als Eskalationsleiter. Ganz unten steht `console.log` – immer an, unstrukturiert, aber sofort da. Eine Stufe höher liegt das `debug`-Modul, das sich über eine Umgebungsvariable an- und ausschalten lässt, ohne dass ich Code anfasse. Darüber sitzt der eingebaute Inspector mit interaktiven Breakpoints in Chrome DevTools oder VS Code. Und ganz oben, wenn es um Performance oder Speicher geht, nutze ich denselben Inspector als Profiler. Wer diese vier Stufen sauber trennen kann, hört auf, blind zu raten.\n\n## Warum console.log an seine Grenzen kommt\n\n`console.log` hat zwei Eigenschaften, die es im Kleinen praktisch und im Großen unangenehm machen. Erstens ist es immer aktiv: Was einmal im Code steht, wird bei jedem Durchlauf ausgeführt, auch in Produktion, wo es die Ausgabe verschmutzt und je nach Menge sogar Performance kostet. Zweitens ist es unstrukturiert – ich sehe einen Wert, aber ich kann nicht mit einem Schalter entscheiden, ob ich gerade die HTTP-Schicht oder den Datenbankzugriff sehen will, ohne die Zeilen wieder auszukommentieren.\n\nWer sich einmal mit dem [Event-Modell von Node.js](https://www.mikebild.dev/de/blog/nodejs-eventemitter-und-ereignismodell/) beschäftigt hat, kennt das Problem in verschärfter Form: Bei asynchronem Code ist die Reihenfolge der Ausgaben nicht immer die, die man erwartet, und ein `console.log` mitten in einem Callback erzählt nur einen Bruchteil der Geschichte. Genau hier lohnt sich der Schritt zu Werkzeugen, die den laufenden Prozess anhalten und untersuchen können.\n\n## Der eingebaute Inspector: --inspect und --inspect-brk\n\nDas Wichtigste zuerst, weil es in Teams immer wieder für Überraschung sorgt: Der Debugger steckt bereits in Node.js. Es gibt kein Extra-Paket zu installieren. Historisch gab es einmal ein separates Modul (`node-inspector` mit dem Befehl `node-debug app.js`), aber das ist seit Node 6 überholt und heute nur noch eine Randnotiz. Seit Node 6.3 spricht der Prozess selbst das Chrome DevTools Protocol über einen WebSocket – und genau darum funktionieren sowohl die Chrome DevTools als auch VS Code als Client.\n\nGestartet wird das mit einem Flag:\n\n```bash\nnode --inspect ./src/server.js\n```\n\nAuf stderr erscheint dann eine Zeile wie diese:\n\n```text\nDebugger listening on ws://127.0.0.1:9229/8f2c...-uuid\nFor help, see: https://nodejs.org/en/docs/inspector\n```\n\nDer Prozess bindet standardmäßig an `127.0.0.1:9229`. Wichtig ist der Unterschied zwischen den beiden zentralen Flags:\n\n- `--inspect` startet nur den Debug-Server, der Code läuft ganz normal weiter. Das nutze ich bei einem Server, der ohnehin dauerhaft läuft und auf Anfragen wartet.\n- `--inspect-brk` startet ebenfalls den Debug-Server, hält aber vor der ersten Zeile meines eigenen Codes an. Das ist ideal für kurz laufende Skripte, die sonst durchgerauscht wären, bevor ich überhaupt einen Client verbinden konnte.\n\n```bash\nnode --inspect-brk ./src/server.js\n```\n\nFür ein Skript, das nach 200 Millisekunden fertig ist, ist `--inspect-brk` praktisch die einzige sinnvolle Wahl – mit `--inspect` allein wäre der Prozess längst beendet, bevor ich in den DevTools auf \"connect\" geklickt habe. Diesen Unterschied zu kennen hat mir in der Praxis schon viel Zeit gespart.\n\nWer den Inspector nicht beim Start, sondern erst bei einem bereits laufenden Prozess aktivieren will, kann unter Unix-Systemen das Signal `SIGUSR1` schicken. Unter Windows steht dieser Weg nicht zur Verfügung.\n\n## Vom Flag zum Client\n\nDer offene Inspector-Port ist nur die halbe Miete – ich brauche noch einen Client, der sich verbindet. Zwei Wege nutze ich regelmäßig.\n\nIn Chrome (oder Edge) öffne ich `chrome://inspect` beziehungsweise `edge://inspect`. Unter \"Remote Target\" taucht der laufende Node-Prozess auf, ein Klick auf \"inspect\" öffnet die vertrauten DevTools mit Sources, Breakpoints, Call Stack und Konsole. Über \"Configure\" lassen sich Host und Port anpassen, falls ich nicht die Standardwerte verwende.\n\nIn VS Code lege ich mir eine Attach-Konfiguration in der `.vscode/launch.json` an:\n\n```json\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"node\",\n      \"request\": \"attach\",\n      \"name\": \"Attach to Node\",\n      \"port\": 9229\n    }\n  ]\n}\n```\n\nDamit hänge ich mich an einen Prozess, den ich vorher mit `--inspect` gestartet habe. Alternativ gibt es in VS Code den \"Auto Attach\"-Modus, der sich automatisch an Node-Prozesse hängt, die aus dem integrierten Terminal gestartet werden. Beide Wege enden an derselben Stelle: interaktiven Breakpoints, an denen ich Variablen inspizieren und mich Schritt für Schritt durch den Code bewegen kann.\n\nDer folgende Ablauf fasst zusammen, wie Flag, Agent und Client zusammenspielen:\n\n```mermaid\nflowchart LR\n  A[\"node --inspect<br/>oder --inspect-brk\"] --> B[\"Inspector-Agent<br/>CDP über ws://127.0.0.1:9229\"]\n  B --> C[\"Chrome DevTools<br/>chrome://inspect\"]\n  B --> D[\"VS Code<br/>request: attach\"]\n  C --> E[\"Breakpoints<br/>CPU-Profil<br/>Heap-Snapshot\"]\n  D --> E\n```\n\nBeide Clients reden dasselbe Protokoll mit demselben eingebauten Agenten. Ich muss mich also nicht für ein Ökosystem entscheiden – ich wähle den Client, der mir gerade besser passt.\n\n## Das debug-Modul: schaltbares Logging ohne Codeänderung\n\nNicht jedes Problem verdient einen Breakpoint. Oft will ich nur nachvollziehen, welchen Weg eine Anfrage durch meine Schichten nimmt – aber eben nur dann, wenn ich es gerade untersuche, und ohne die Ausgabe dauerhaft im Code zu verankern. Genau dafür gibt es das `debug`-Modul, zum Stichtag in Version 4.3.4. Viele bekannte Bibliotheken nutzen es intern, und für eigenen Code ist es schnell eingebaut.\n\nDer Kern ist eine Factory, die man mit einem Namespace aufruft:\n\n```js\nconst debug = require('debug')('app:http');\n\nfunction handleRequest(req, res) {\n  debug('incoming request %s %s', req.method, req.url);\n  // ... handle the request ...\n}\n```\n\nDer Clou steckt nicht im Code, sondern im Start. Standardmäßig gibt diese Zeile nichts aus. Erst wenn ich die Umgebungsvariable `DEBUG` setze, wird der passende Namespace sichtbar:\n\n```bash\nDEBUG=app:* node server.js\n```\n\nDas `*` ist eine Wildcard, und mit einem führenden Minus schließe ich Namespaces gezielt aus. So sehe ich zum Beispiel alles aus `app`, aber nicht die gesprächige Datenbankschicht:\n\n```bash\nDEBUG=app:*,-app:db node server.js\n```\n\nDamit ist der zentrale Vorteil erreicht: Ich schalte Logging an und aus, ohne eine einzige Zeile Code zu ändern. Das `debug`-Modul bringt außerdem automatische Zeitdifferenzen zwischen den Ausgaben mit (die `+0ms`-Angaben), färbt bei einem echten Terminal die Namespaces ein und kennt Format-Platzhalter wie `%s`, `%d`, `%j`, `%o` und `%O`.\n\nEin Detail sorgt regelmäßig für Verwirrung: Die Ausgabe von `debug` geht auf **stderr**, nicht auf stdout. Wer die Ausgabe umleiten oder mit `grep` filtern will und dabei nur stdout betrachtet, sieht schlicht nichts. Und `DEBUG` greift nur für Bibliotheken, die selbst `debug` verwenden – es ist kein globaler Schalter für jede beliebige Log-Ausgabe.\n\n## nodemon: Auto-Reload in der Entwicklung\n\nEin Werkzeug, das streng genommen nicht zum Debuggen gehört, aber die Feedback-Schleife enorm verkürzt, ist nodemon (zum Stichtag rund Version 2.0.20). Es beobachtet Dateien und startet den Prozess bei jeder Änderung neu, sodass ich nicht ständig von Hand `Strg+C` und neu starten muss. Ich nehme es als Dev-Abhängigkeit ins Projekt:\n\n```bash\nnodemon --watch ./ --ignore ./node_modules ./bin/www\n```\n\nSchöner ist eine `nodemon.json` im Projektwurzelverzeichnis, weil sie die Konfiguration festhält und sich gut mit dem Inspector kombinieren lässt:\n\n```json\n{\n  \"watch\": [\"src\"],\n  \"ext\": \"js,json\",\n  \"ignore\": [\"node_modules\"],\n  \"exec\": \"node --inspect src/server.js\"\n}\n```\n\nÜber `exec` starte ich den Prozess direkt mit `--inspect`, sodass ich Auto-Reload und Debugger zusammen bekomme. Node.js selbst brachte zum Stichtag zwar bereits einen experimentellen Watch-Modus mit, aber für den Alltag setze ich weiterhin auf nodemon, weil es ausgereift und flexibel konfigurierbar ist.\n\n## Ein schneller Blick auf den Speicher\n\nBevor ich zum eigentlichen Profiling komme, gibt es einen sehr günstigen Zwischenschritt, der ohne jedes Werkzeug auskommt: `process.memoryUsage()`. Diese Funktion liefert ein Objekt mit mehreren Werten, alle in Bytes:\n\n```js\nconst { rss, heapTotal, heapUsed, external } = process.memoryUsage();\n\nconsole.error(\n  `rss=${(rss / 1e6).toFixed(1)}MB ` +\n  `heapUsed=${(heapUsed / 1e6).toFixed(1)}MB ` +\n  `heapTotal=${(heapTotal / 1e6).toFixed(1)}MB`\n);\n```\n\nDie wichtigsten Felder in der Praxis: `heapUsed` und `heapTotal` betreffen den von V8 verwalteten JavaScript-Heap, während `rss` (Resident Set Size) den gesamten Speicher des Prozesses angibt, inklusive nativer Anteile. Wenn ich in einer Schleife oder über mehrere Anfragen hinweg zusehe, wie `heapUsed` immer weiter steigt und nach der Garbage Collection nicht mehr zurückgeht, habe ich einen ersten, sehr konkreten Hinweis auf ein Speicherleck. Für einen schnellen RSS-Wert allein gibt es seit Node 15.6 zusätzlich `process.memoryUsage.rss()`.\n\nDas ersetzt kein richtiges Profiling, aber es ist ein billiger Frühwarnwert – gerade bei langlaufenden Prozessen oder bei Verarbeitung großer Datenmengen, wie sie beim Umgang mit [Streams und Backpressure](https://www.mikebild.dev/de/blog/nodejs-streams-und-backpressure/) auftreten.\n\n## Profiling über denselben Inspector\n\nWenn der grobe Blick mit `process.memoryUsage()` nicht reicht, führt der nächste Schritt zurück zum Inspector. Dieselbe Verbindung, die ich zum Setzen von Breakpoints nutze, öffnet in den DevTools auch die Tabs für Analyse: Unter \"Memory\" nehme ich einen Heap-Snapshot auf und sehe, welche Objekte wie viel Speicher belegen. Unter \"Profiler\" beziehungsweise \"Performance\" zeichne ich ein CPU-Profil auf und finde heraus, in welchen Funktionen die Zeit tatsächlich verbraucht wird.\n\nWer lieber ohne grafisches Frontend arbeitet, hat CLI-Alternativen. `node --prof` schreibt ein V8-Log, das ich anschließend mit `node --prof-process` in einen lesbaren Bericht verwandle:\n\n```bash\nnode --prof ./src/server.js\n# ... generate load, then stop the process ...\nnode --prof-process isolate-0x*.log > processed.txt\n```\n\nDaneben gibt es seit Node 12 die noch experimentellen Flags `--cpu-prof` und `--heap-prof`, die direkt Profildateien im DevTools-Format erzeugen. Im Team hat sich trotzdem meist der interaktive Weg über die DevTools durchgesetzt, weil er dieselbe Oberfläche nutzt, die aus dem Frontend ohnehin vertraut ist.\n\n## Die vier Stufen im Überblick\n\nZurück zur Eskalationsleiter vom Anfang. Ich fasse die vier Werkzeuge bewusst als Stufen zusammen, weil jede ihren eigenen Zweck hat und keine die andere vollständig ersetzt:\n\n- `console.log` – immer aktiv, unstrukturiert, sofort verfügbar. Gut für den schnellen Einzelblick, schlecht als Dauerlösung und in Produktion fehl am Platz.\n- `debug` – namespacegesteuert, über die `DEBUG`-Umgebungsvariable ohne Codeänderung schaltbar, Ausgabe auf stderr. Ideal, um in der Entwicklung gezielt Schichten sichtbar zu machen.\n- Inspector – interaktive Breakpoints in Chrome DevTools oder VS Code, über `--inspect` beziehungsweise `--inspect-brk`. Der Schritt vom Vermuten zum Untersuchen.\n- Profiler – derselbe Inspector, aber für CPU-Profile und Heap-Snapshots. Kommt zum Einsatz, wenn es nicht um Korrektheit, sondern um Performance und Speicher geht.\n\n```mermaid\nflowchart TB\n  A[\"console.log<br/>immer an, unstrukturiert\"] --> B[\"debug<br/>DEBUG-Env, namespacegesteuert\"]\n  B --> C[\"Inspector<br/>interaktive Breakpoints\"]\n  C --> D[\"Profiler<br/>CPU-Profil und Heap-Snapshot\"]\n```\n\n## Zwei Fallstricke, die teuer werden können\n\nZum Schluss zwei Dinge, die ich in Code-Reviews ausdrücklich anspreche, weil sie in Produktion echten Schaden anrichten.\n\nDer erste betrifft `console.log` in Produktion. Was in der Entwicklung harmlos aussieht, wird im Dauerbetrieb zum Problem: Die Ausgabe ist unstrukturiert, lässt sich nicht per Schalter abstellen, verschmutzt stdout und kostet je nach Menge Performance. Für die Entwicklung ist `debug` die bessere Wahl, und für Produktion gehört ein richtiger Logger her, der Log-Level, strukturierte Ausgabe und gezieltes Ein- und Ausschalten beherrscht.\n\nDer zweite Fallstrick ist gefährlicher und wird oft unterschätzt: einen offenen `--inspect`-Port stehen zu lassen oder ihn an `0.0.0.0` zu binden. Der Debug-Port erlaubt das Ausführen beliebigen Codes im Prozess – wer ihn erreicht, kann den Server übernehmen. Deshalb bindet Node.js von Haus aus nur an `127.0.0.1`, und dabei sollte es in aller Regel bleiben. Muss ich wirklich einen entfernten Prozess debuggen, tunnele ich den Port über SSH statt ihn öffentlich zu exponieren:\n\n```bash\nssh -L 9229:localhost:9229 user@remote-host\n```\n\nUnd das Debug-Flag hat in keinem Produktions-Startskript etwas verloren. Diese Trennung zwischen Entwicklungs- und Produktionsbetrieb hängt eng mit dem zusammen, was schon im [Node.js-Training zur Event-Loop-Architektur](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) zur Sprache kommt: Werkzeuge, die in den laufenden Prozess greifen, sind mächtig – und genau deshalb muss der Zugang zu ihnen eng bleiben.\n\n## Ein Ausblick\n\nWer noch tiefer gehen will, findet in Node.js zwei fortgeschrittene Bausteine, die ich hier nur als Ausblick nenne, weil sie eigene Beiträge verdienen: `async_hooks`, um den Lifecycle asynchroner Ressourcen zu verfolgen, und `diagnostics_channel`, um strukturierte Diagnose-Events zwischen Bibliotheken und Beobachtern auszutauschen. Beide sind eher etwas für Werkzeugbauer und Bibliotheksautoren als für den täglichen Fehlerfang.\n\n## Fazit\n\nDer Weg vom `console.log`-Reflex zu bewusstem Debuggen ist kein großer Sprung, sondern eine kleine Leiter mit vier Sprossen. Für den schnellen Blick bleibt `console.log`, aber sobald es strukturierter wird, übernimmt `debug` mit seinem schaltbaren Logging. Wird es wirklich knifflig, hält der eingebaute Inspector den Prozess an und lässt mich Variablen und Aufrufstapel untersuchen – wahlweise in Chrome DevTools oder VS Code, denn beide sprechen dasselbe Protokoll. Und wenn Performance oder Speicher das Thema sind, wechselt derselbe Inspector in den Profiler-Modus, während `process.memoryUsage()` schon vorher einen billigen Frühwarnwert liefert. Wer diese Stufen kennt und den Debug-Port konsequent verschlossen hält, hört auf zu raten und fängt an zu untersuchen.\n\n## Weiterführende Quellen\n\n- Grounding aus dem Repository: `introduction-nodejs/19-quality-tools.md` (Kapitel \"Quality Tools\")\n- Debugging Node.js (offizieller Guide): https://nodejs.org/en/learn/getting-started/debugging\n- CLI-Optionen (`--inspect`, `--inspect-brk`, `--prof`, `--cpu-prof`, `--heap-prof`): https://nodejs.org/api/cli.html\n- Inspector-Modul: https://nodejs.org/api/inspector.html\n- `process.memoryUsage()`: https://nodejs.org/api/process.html#processmemoryusage\n- debug-Modul: https://www.npmjs.com/package/debug bzw. https://github.com/debug-js/debug\n- nodemon: https://github.com/remy/nodemon\n- Ausblick – diagnostics_channel: https://nodejs.org/api/diagnostics_channel.html · async_hooks: https://nodejs.org/api/async_hooks.html"},{"locale":"de","translation_key":"developer-productivity-verkuerzte-zyklen","slug":"developer-productivity-verkuerzte-zyklen","title":"Developer Productivity: verkürzte Zyklen bei hoher Qualität","summary":"Kurze Feedbackschleifen bei verlässlicher Qualität sind mein Denkmodell für Developer Productivity. Wo tatsächlich gewartet wird, muss die eigene Durchlaufzeit zeigen.","tags":["Software","Delivery"],"published_at":"2022-12-26T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/developer-productivity-verkuerzte-zyklen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/3e3f2415795608033760103a086139f424a90833cf65e5153a4da8265624c051/developer-productivity-verkuerzte-zyklen-vorlesen.mp3","audio_duration_secs":755,"text":"Durchlaufzeit und Bearbeitungszeit sind zwei verschiedene Größen. Bearbeitungszeit ist die Spanne, in der jemand tatsächlich an einer Änderung arbeitet – lesen, schreiben, testen. Durchlaufzeit ist die Spanne von der ersten Zeile bis zur Rückmeldung aus der Produktion. Die Differenz zwischen beiden ist Liegezeit: Stunden und Tage, in denen eine fertige Änderung existiert und nichts mit ihr passiert.\n\nNehmen wir einen Change mit zwei Stunden Bearbeitungszeit und drei Tagen in Queues: vor dem Build, vor der Review, vor einer freien Testumgebung. In diesem Beispiel setzt der Ruf nach mehr Leuten an der kleineren Größe an. Ob das im eigenen System genauso aussieht, lässt sich aus den Zeitstempeln von Commit, Review, Build und Deployment ablesen – nicht aus einer allgemeinen Behauptung über Entwicklerarbeit.\n\nMein Denkmodell dafür lautet: **kurze Feedbackschleifen bei verlässlicher Qualität**. Das ist keine messbare Formel, sondern eine Erinnerung an zwei Grenzen. Tempo ohne Qualitätsnetz erzeugt schnellere Fehler; Qualitätssicherung ohne zeitnahe Rückmeldung erzeugt große Queues. Welche Seite gerade bremst, zeigt die gemessene Zykluszeit.\n\nProduktivität entsteht in zwei verbundenen Feedbackschleifen, deren Takt und Ergebnis nicht verwechselt werden dürfen.\n\n::::comparison{title=\"Zwei Schleifen, zwei Arten von Feedback\" role=\"primary\" preferredPattern=\"split-comparison\"}\n:::side{label=\"Delivery-Schleife\"}\n- Frage · Wie schnell erreicht eine kleine Änderung verlässlich Produktion?\n- Folge · Code, Build, Test, Review und Deploy\n- Zeitmaß · Minuten bis Stunden\n- Signal · technische Rückmeldung und Produktionsverhalten\n:::\n:::side{label=\"Discovery-Schleife\"}\n- Frage · Löst die Änderung das richtige Problem?\n- Folge · Hypothese, Umsetzung, Messung und Lernen\n- Zeitmaß · Tage bis Wochen\n- Signal · beobachtete Wirkung und validiertes Lernen\n:::\n::::\n\nEine schnelle Delivery-Schleife ohne Discovery liefert womöglich zügig das Falsche. Eine gute Hypothese ohne kurze Delivery-Schleife wartet zu lange auf belastbares Feedback.\n\n## Speed und Stability sind kein Trade-off\n\nDer hartnäckigste Denkfehler in dieser Diskussion ist die Annahme, man müsse sich zwischen Tempo und Stabilität entscheiden. „Wir könnten schneller liefern, aber dann bricht mehr“ – diesen Satz höre ich in Steering-Runden regelmäßig. Die Daten sagen das Gegenteil.\n\nDer Zentralbefund aus *Accelerate* (Forsgren, Humble, Kim, 2018), die Buchfassung der DORA-Forschung mit über 23.000 Antworten aus mehr als 2.000 Organisationen, ist eindeutig: High-Performer sind bei Geschwindigkeit **und** Qualität besser. Nirgends in den Daten erkauft sich ein Team das eine durch das andere. Die schnellen Teams sind auch die stabilen. Das ist ein statistischer Zusammenhang, keine Haltungsfrage – und das Fundament für die These, dass Zyklen und Qualität sich gegenseitig tragen.\n\nOperationalisiert wird das über die vier DORA-Metrics, die genau diese zwei Dimensionen messen. Für den Durchsatz: *Deployment Frequency* und *Lead Time for Changes* – die Zeit von Commit bis Produktion. Für die Stabilität: *Time to Restore Service* (die Zeit bis zur Wiederherstellung nach einem Incident) und *Change Failure Rate* – der Anteil der Deployments, die einen Fehler verursachen. Die Lead Time ist dabei die messbar gemachte „kurze Feedbackschleife“ aus meiner Formel. Wer sie senkt, senkt genau die Wartezeit, um die es hier geht.\n\nEin Hinweis zur Präzision, weil das oft schlampig zitiert wird: Die State-of-DevOps-Reports haben Teams jahrelang in Cluster einsortiert – 2021 noch mit einer eigenen „Elite“-Gruppe. Der 2022er Report fand nur noch drei Cluster (High, Medium, Low), kein „Elite“ mehr. Wer heute mit „laut DORA sind Elite-Teams…“ argumentiert, sollte wissen, aus welchem Jahr die Zahl stammt.\n\n## Warum der Engpass das Warten ist\n\nContinuous Integration wird oft als „Tooling“ verstanden – man richtet einen Build-Server ein, Haken dran. Der Sinn ist ein anderer. Martin Fowler definiert CI als Praxis, bei der Teammitglieder häufig integrieren und jede Integration durch einen automatisierten Build inklusive Tests verifiziert wird, um Integrationsfehler so früh wie möglich zu erkennen. Das entscheidende Wort ist „früh“. CI ist eine Latenz-Maschine: Sie verkürzt die Zeit zwischen einem Fehler und seiner Entdeckung. Der Engpass, den CI adressiert, ist Warte- und Integrationslatenz – nicht Code-Volumen.\n\nDie Deployment-Pipeline (ebenfalls Fowler) ist der bewusste Umgang mit dieser Latenz. Man zerlegt den Weg zur Produktion in Stages: Frühe Stages geben in Sekunden bis Minuten eine erste Sicherheit, spätere sind gründlicher und dürfen dafür langsamer sein. Damit wird zur Gestaltungsentscheidung, wo Feedback schnell und wo es gründlich sein soll.\n\n```yaml\npipeline:\n  - stage: commit          # target: < 10 min  -> fastest feedback\n    steps: [compile, unit_tests, static_analysis]\n  - stage: acceptance      # target: minutes   -> contract & integration\n    steps: [contract_tests, integration_tests]\n  - stage: deploy_staging  # ephemeral environment on demand\n    steps: [provision_env, smoke_tests]\n  - stage: production      # gated by feature_flag, not by branch age\n    steps: [progressive_rollout, health_check]\n```\n\nVor so einem Skelett trägt genau eine Frage: Wo geht die Zeit real verloren? Die Antwort ist selten `unit_tests`. Sie ist `compile`, wenn der Commit-Build zwölf Minuten braucht statt unter zehn. Sie ist `review`, wenn ein Pull Request zwei Tage in der Queue liegt. Sie ist `provision_env`, wenn eine Testumgebung von Hand beantragt und über Nacht bereitgestellt wird. Das sind die eigentlichen Latenzhebel. Das Schreiben der Tests, also die Zeit an der Tastatur, ist fast nie das Problem.\n\nDas erklärt auch, warum „shift left“ mehr ist als ein Buzzword. Ein Vertragsbruch zwischen zwei Services, der erst in einer nächtlichen End-to-End-Umgebung auffällt, kostet einen Tag. Derselbe Bruch, der im Commit-Build auffällt, kostet Minuten. Es ist derselbe Fehler – nur die Feedbacklatenz unterscheidet sich um Größenordnungen.\n\n## Die zwei Schleifen\n\nKurze Zyklen gibt es auf zwei Ebenen, und ich sehe oft, dass Teams nur eine davon optimieren. Die innere Schleife ist die Delivery: `code → commit → build → automated tests → review → deploy`, gemessen in Minuten. Die äußere Schleife ist die Discovery: `hypothesis → build → measure → learn`, gemessen in Tagen bis Wochen. Die innere Schleife stellt sicher, dass Sie schnell und sicher etwas ausliefern. Die äußere stellt sicher, dass es das Richtige ist.\n\nDiese äußere Schleife wird gern vergessen, dabei ist sie derselbe Gedanke auf der Produktebene. Eric Ries hat sie im *Lean Startup* (2011) als *Build–Measure–Learn* mit dem Ziel des *validated learning* beschrieben. Teresa Torres hat sie in *Continuous Discovery Habits* (2021) konkretisiert: wöchentliche Kundeninterviews, der Opportunity Solution Tree, der Chancen und Lösungsideen in eine sichtbare Ordnung bringt, systematisches Assumption Testing. Auch hier zählt nicht mehr Output, sondern kürzere Lernzyklen. Ein Team, das seine innere Schleife auf Minuten drückt, aber ein halbes Jahr wartet, bevor es merkt, dass das Feature niemand braucht, hat den falschen Engpass optimiert.\n\n```mermaid\nflowchart LR\n  subgraph inner[\"Inner loop – Delivery (minutes)\"]\n    code[\"code\"] --> commit[\"commit\"]\n    commit -->|\"wait: build\"| build[\"build\"]\n    build --> tests[\"automated tests\"]\n    tests -->|\"wait: review\"| review[\"review\"]\n    review -->|\"wait: provision env\"| deploy[\"deploy\"]\n  end\n  subgraph outer[\"Outer loop – Discovery (days / weeks)\"]\n    hypothesis[\"hypothesis\"] --> buildit[\"build\"]\n    buildit --> measure[\"measure\"]\n    measure --> learn[\"learn\"]\n    learn --> hypothesis\n  end\n  deploy --> measure\n  learn -.-> code\n```\n\nDie beschrifteten Kanten in dieser Skizze sind bewusst die Wartekanten: `build`, `review`, `provision env`. An ihnen entscheidet sich die Zykluszeit. Die DORA-Lead-Time misst die innere Schleife, die Discovery-Kadenz die äußere. Beide zusammen ergeben die Zahl, die zählt: wie oft ein Team pro Woche etwas Validiertes lernt.\n\n## Qualität ist das Netz, nicht die Bremse\n\nJetzt der Teil, den man in der Tempo-Euphorie gern überspringt. Die Formel ist multiplikativ. Kurze Zyklen ohne Qualitätsnetz bedeuten nicht „schneller liefern“, sondern „schneller kaputtgehen“. Wer die Batch-Size reduziert und häufiger deployt, ohne automatisierte Tests, Contract-Tests und eine echte Deployment-Pipeline, senkt vor allem eines: die Zeit bis zum nächsten Incident. Batch-Size-Reduktion ohne Stabilitätsmechanismen verlagert den Engpass nur – vom Warten vor dem Deploy zum Aufräumen danach.\n\nDeshalb gehört Qualität in dieselbe Pipeline wie das Tempo. Wo Services über Systemgrenzen hinweg miteinander sprechen, trägt Consumer-Driven Contract Testing einen großen Teil dieser Last. Die Idee (sie geht auf Ian Robinson und Fowler, 2006, zurück und ist mit Frameworks wie Pact breit etabliert): Der Konsument beschreibt, was er vom Provider erwartet, und diese Erwartung wird auf beiden Seiten unabhängig verifiziert – ohne eine gemeinsame, langsame End-to-End-Umgebung hochziehen zu müssen.\n\n```javascript\n// consumer side: describe the expectation, generate a pact file\nconsumerTest(\"fetches a user by id\", () => {\n  provider\n    .given(\"a user exists\")\n    .uponReceiving(\"a request for user 42\")\n    .withRequest({ method: \"GET\", path: \"/users/42\" })\n    .willRespondWith({\n      status: 200,\n      body: { id: 42, name: like(\"Ada\") }, // matcher, not a fixed value\n    });\n  // -> produces a pact contract, verified in the provider's own pipeline\n});\n```\n\nDer Gewinn ist doppelt. Der Contract-Test läuft in der `acceptance`-Stage in Sekunden statt der End-to-End-Test in Minuten in einer eigens provisionierten Umgebung – die Feedbackschleife an der Service-Grenze wird kürzer. Und er ist präziser: Er sagt nicht nur „irgendwas ist rot“, sondern „der Provider liefert `name` nicht mehr“. Das ist Qualität, die Tempo ermöglicht, statt es zu bremsen.\n\nAuf Architekturebene gehört derselbe Gedanke dazu. Michael Nygard hat in *Release It!* (2007, 2. Auflage 2018) die Stability Patterns beschrieben – Circuit Breaker, Bulkhead und Verwandte –, damit ein Fehler in einem Teil nicht das Ganze mitreißt. Und Neal Ford, Rebecca Parsons und Patrick Kua haben in *Building Evolutionary Architecture* (2017) die Idee der Fitness Functions eingeführt: automatisierte, ausführbare Prüfungen für Architektureigenschaften wie Latenz, Kopplung oder Sicherheit. Beides ist dieselbe Bewegung wie bei den Tests – Qualität wird zu etwas Ausführbarem gemacht, das in der Pipeline schnell Feedback gibt, statt in einem Review-Dokument zu verstauben.\n\n## Wie man kurze Zyklen konkret baut\n\nAus der Praxis ein paar Hebel, die zuverlässig wirken – geordnet nach dem, was die Wartekanten am direktesten trifft.\n\nDer Commit-Build muss schnell sein. Fowlers Faustregel vom „ten-minute build“ ist keine Nostalgie, sondern eine psychologische Grenze: Dauert der Build länger, hört das Team auf, häufig zu integrieren, und die Batches wachsen wieder. Eine schnelle, breite Basis aus Unit-Tests und eine schmale Spitze aus langsamen End-to-End-Tests – die klassische Testpyramide – hält den Build schnell, ohne an Abdeckung zu verlieren.\n\nBranches kurz halten. Trunk-Based Development mit kurzlebigen Feature-Branches und Feature Flags entkoppelt „Code ist gemerged“ von „Feature ist an“. Das ist der Punkt, an dem `production` durch ein Feature-Flag gated wird, nicht durch das Alter eines Branches. Lang lebende Branches sind der klassische Weg, wie sich Integrations-Wartezeit unsichtbar aufstaut, bis der Merge zum Tagesprojekt wird.\n\nUmgebungen on demand. Wenn `provision_env` ein Ticket an ein anderes Team ist, ist Ihre Lead Time keine technische, sondern eine organisatorische Größe. Ephemere, per Skript erzeugte Umgebungen nehmen diese Kante aus der Queue.\n\nUnd der Punkt, der am meisten Konflikt auslöst: Messen Sie das System, nicht die Person. Die vier DORA-Metrics sind Team- und System-Outcome-Metrics. Als individuelles Entwickler-Ranking missbraucht, erzeugen sie sofort Goodhart-Effekte – man optimiert die Zahl statt die Sache. Wer an „Deployments pro Entwickler“ gemessen wird, produziert Micro-Deploys; wer an der Change Failure Rate gemessen wird, deklariert Incidents um. Forsgren und Kollegen haben explizit vor solchen Vanity- und Individual-Metrics gewarnt. Die Metrics zeigen die Gesundheit eines Flusses, nicht die Leistung eines Einzelnen.\n\n## Fazit\n\nProduktivität in der Softwareentwicklung ist nicht sinnvoll über geleistete Stunden allein beschrieben. In vielen Flüssen steckt ein großer Teil der Durchlaufzeit im Warten auf Build, Review oder Umgebung; ob das hier der Engpass ist, muss die Messung zeigen. DORA-Metrics beschreiben die Lieferfähigkeit des Systems. Contract-Tests, Stability Patterns und Fitness Functions können ausgewählte Qualitätsrisiken früher sichtbar machen, während die Discovery-Schleife prüft, ob das Team überhaupt am richtigen Problem arbeitet.\n\nWenn Sie morgen anfangen wollen: Zeichnen Sie Ihre innere Schleife auf und schreiben Sie an jede Kante die reale Wartezeit. Die längste davon ist ein guter Kandidat für die nächste Verbesserung. Danach messen Sie erneut. Kurze Zyklen und verlässliche Qualität bleiben dabei zwei getrennte Größen; keine darf die andere verdecken.\n\n## Weiterführende Quellen\n\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate* (2018) – der Befund, dass Speed und Stability kein Trade-off sind: <https://itrevolution.com/product/accelerate/>\n- Four Keys / DORA-Metrics erklärt: <https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance>\n- DORA-Metrics und die Cluster-Einordnung: <https://dora.dev/guides/dora-metrics-four-keys/>\n- Martin Fowler: *Deployment Pipeline*: <https://www.martinfowler.com/bliki/DeploymentPipeline.html>\n- Martin Fowler: *Continuous Delivery*: <https://martinfowler.com/bliki/ContinuousDelivery.html>\n- Teresa Torres: *Continuous Discovery Habits* (2021): <https://businessofsoftware.org/talks/continuous-discovery/>"},{"locale":"de","translation_key":"svelte-slots-context-und-web-components","slug":"svelte-slots-context-und-web-components","title":"Slots, Context und Web Components in Svelte","summary":"Drei Kompositions-Werkzeuge in Svelte 3: Slots reichen Inhalt von außen hinein, die Context-API vermeidet Prop-Drilling, und Custom Elements machen eine Komponente framework-neutral wiederverwendbar.","tags":["Software","Frontend","Svelte"],"published_at":"2022-11-22T10:00:00+00:00","updated_at":"2026-07-13T07:59:51.626923+00:00","url":"https://www.mikebild.dev/de/blog/svelte-slots-context-und-web-components/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/4b87296fcc1edbc520cd0889db5380746903c20eb4eaf4037294e16a0f16fb2f/svelte-slots-context-und-web-components-vorlesen.mp3","audio_duration_secs":711,"text":"Eine wiederverwendbare Card, in die jedes Team seinen eigenen Header und seinen eigenen Inhalt stecken kann: Die Anforderung klingt harmlos, und mit Props allein bekommt man sie trotzdem nicht sauber gelöst. Im Review tauchen dann die Ausweichmanöver auf – ein Store, wo ein Slot gereicht hätte; ein Prop, das durch sieben Komponenten gefädelt wird, obwohl die Context-API der kürzere Weg gewesen wäre; eine Komponentenbibliothek, die nur unter Svelte läuft, obwohl framework-neutrale Wiederverwendung das eigentliche Ziel war.\n\nSlots, die Context-API und Custom Elements tauchen in denselben Komponenten nebeneinander auf und werden deshalb gern verwechselt. Auseinander hält sie die Richtung, in die etwas fließt: Markup von außen in eine Komponente hinein, Daten von innen an dieses Markup zurück, Werte nach unten durch beliebig viele Ebenen des Komponentenbaums. Wer vor der Werkzeugwahl kurz klärt, welche dieser Richtungen er gerade braucht, hat die Entscheidung meist schon getroffen.\n\n**Redaktionelle Einordnung (Juli 2026):** Der Titel meint ausdrücklich Svelte 3. In Svelte 5 sind Snippets und `{@render ...}` die bevorzugte Komposition anstelle von Slots; Callback-Props ersetzen für neuen Code viele Component Events. Context und Custom Elements bestehen weiter. Die historische Syntax bleibt hier stehen, die Quellen zeigen zusätzlich die heutigen Gegenstücke.\n\n## Slots: Inhalt von außen hineinreichen\n\nEin Slot ist ein Platzhalter in einer Komponente, den der Aufrufer von außen füllt. Die Card-Komponente entscheidet über Rahmen, Abstände und Layout – was innen steht, bestimmt der Aufrufer. Der einfachste Fall ist der Default-Slot:\n\n```svelte\n<!-- Card.svelte -->\n<div class=\"card\">\n  <slot>Nothing here yet</slot>\n</div>\n\n<style>\n  .card {\n    border: 1px solid #ddd;\n    border-radius: 8px;\n    padding: 1rem;\n  }\n</style>\n```\n\nDer Inhalt zwischen den `<slot>`-Tags ist der Fallback: Er erscheint nur, wenn der Aufrufer nichts übergibt. Genutzt wird die Card dann so:\n\n```svelte\n<Card>\n  <p>This paragraph lands inside the card.</p>\n</Card>\n```\n\nInteressant wird es mit benannten Slots. Eine Card hat oft mehr als eine Zone – einen Header und einen Body etwa. In der Kind-Komponente vergibt man dafür Namen, im Aufruf ordnet man Markup diesen Namen zu:\n\n```svelte\n<!-- Card.svelte -->\n<div class=\"card\">\n  {#if $$slots.header}\n    <header class=\"card-header\">\n      <slot name=\"header\"></slot>\n    </header>\n  {/if}\n  <div class=\"card-body\">\n    <slot></slot>\n  </div>\n</div>\n```\n\n```svelte\n<Card>\n  <h2 slot=\"header\">Release notes</h2>\n  <p>Everything else fills the default slot.</p>\n</Card>\n```\n\nDas Objekt `$$slots` verdient einen kurzen Blick. Seine Schlüssel sind die tatsächlich übergebenen Slot-Namen, und damit lässt sich die Struktur bedingt rendern. Der `<header>`-Rahmen erscheint nur, wenn der Aufrufer wirklich einen Header übergeben hat – sonst hätte man einen leeren, umrandeten Kasten. Das ist der Unterschied zwischen einer Komponente, die man gerne benutzt, und einer, die man umständlich findet.\n\nWichtig ist dabei, dass `$$slots` nur die Anwesenheit eines Slots meldet, nicht dessen Inhalt zur Laufzeit. Ob ein benannter Slot befüllt ist, entscheidet sich beim Kompilieren anhand des Aufrufs, nicht durch das, was der Aufrufer später hineinrendert. Für die typische Aufgabe – Rahmen weglassen, wenn niemand einen Header liefert – reicht das genau aus, und man sollte `$$slots` nicht mit einer reaktiven Prüfung auf leeren Inhalt verwechseln. Ein zweiter Punkt, der in Reviews regelmäßig auffällt: Ein benannter Slot lässt sich nur an einer Stelle einer Komponente ausgeben. Wer denselben benannten Slot zweimal rendert, bekommt keinen doppelten Inhalt, sondern ein Verhalten, auf das man sich nicht verlassen sollte. Braucht man denselben übergebenen Inhalt an mehreren Stellen, führt der Weg über slot props oder über eine Umstrukturierung der Komponente, nicht über ein zweites `<slot name=\"…\">`.\n\n### Slot props: Daten von innen nach außen\n\nBis hierher fließt Inhalt nur in eine Richtung: von außen nach innen. Der zweite Teil dreht diese Richtung um, und genau das wird am häufigsten verwechselt. Slot props erlauben es der Kind-Komponente, Daten nach außen an das eingesetzte Markup zu geben. Der klassische Fall ist eine Liste, die das Iterieren übernimmt, aber die Darstellung jedes Eintrags dem Aufrufer überlässt:\n\n```svelte\n<!-- List.svelte -->\n<script>\n  export let items = [];\n</script>\n\n<ul>\n  {#each items as item, index}\n    <li>\n      <slot name=\"item\" {item} {index}>\n        {item}\n      </slot>\n    </li>\n  {/each}\n</ul>\n```\n\nDie Kind-Komponente gibt `item` und `index` über den Slot nach außen. Der Aufrufer empfängt diese Werte mit der `let:`-Directive und darf frei entscheiden, wie ein Eintrag aussieht:\n\n```svelte\n<List items={users}>\n  <span slot=\"item\" let:item let:index>\n    {index + 1}. {item.name} – {item.role}\n  </span>\n</List>\n```\n\nDie Liste kümmert sich um Schleife, Schlüssel und Struktur; der Aufrufer bringt die konkrete Darstellung mit und bekommt dafür genau die Daten, die er braucht. Diese beiden Richtungen sauber auseinanderzuhalten ist der Kern des Slot-Verständnisses: Markup fließt von außen hinein, Daten fließen über slot props von innen nach außen. Das folgende Diagramm hält beide Wege nebeneinander fest.\n\n```mermaid\nflowchart LR\n  Parent[\"Parent<br/>&lt;List let:item&gt;\"]\n  Child[\"List.svelte<br/>&lt;slot name='item' {item}&gt;\"]\n  Render[\"Rendered &lt;li&gt;\"]\n\n  Parent -- \"markup (outside in)\" --> Child\n  Child -- \"slot props: item, index (inside out)\" --> Parent\n  Child --> Render\n```\n\n## Context: durch den Baum reichen ohne Prop-Drilling\n\nSlots lösen die Frage, wie man Inhalt an eine direkte Kind-Komponente gibt. Sie helfen nicht, wenn ein Wert mehrere Ebenen tief benötigt wird. Stellen wir uns eine Toolbar vor, deren einzelne Buttons sich bei ihr registrieren wollen. Zwischen Toolbar und Button liegen vielleicht noch Gruppen, Trenner, Wrapper. Den Registrierungs-Callback durch jede dieser Ebenen als Prop zu reichen, ist mühsam und macht Zwischenkomponenten von Details abhängig, die sie gar nichts angehen. Dieses Weiterreichen nennt man Prop-Drilling, und die Context-API ist die direkte Antwort darauf.\n\nDie Provider-Komponente legt einen Wert unter einem Schlüssel ab, jede Nachfahr-Komponente kann ihn unter demselben Schlüssel wieder abrufen:\n\n```svelte\n<!-- Toolbar.svelte -->\n<script>\n  import { setContext } from 'svelte';\n\n  const buttons = [];\n  function registerButton(id) {\n    buttons.push(id);\n  }\n\n  setContext('toolbar', { registerButton });\n</script>\n\n<div class=\"toolbar\">\n  <slot></slot>\n</div>\n```\n\n```svelte\n<!-- ToolbarButton.svelte -->\n<script>\n  import { getContext } from 'svelte';\n\n  export let id;\n  const toolbar = getContext('toolbar');\n  toolbar.registerButton(id);\n</script>\n\n<button on:click>\n  <slot></slot>\n</button>\n```\n\nDer Button findet seine Toolbar, egal wie viele Ebenen dazwischenliegen. Kein Prop wandert durch die Zwischenkomponenten. Der Schlüssel darf übrigens ein beliebiger Wert sein – ein String wie hier, ein Symbol oder ein Objekt; ein Symbol schützt zuverlässig vor Namenskollisionen in größeren Repositories.\n\nDer Geltungsbereich von Context ist dabei streng auf den Teilbaum unterhalb des Providers beschränkt. Eine Nachbarkomponente, die nicht unter derselben `setContext`-Komponente hängt, sieht den Wert nicht – Context fließt ausschließlich nach unten, nie zur Seite und nie nach oben. Ruft eine Kind-Komponente ihrerseits `setContext` mit demselben Schlüssel auf, überschattet sie den Wert für ihren eigenen Teilbaum, ohne den Wert weiter oben zu verändern; die Auflösung folgt also der Instanzhierarchie, nicht der Reihenfolge im Quelltext. Wer sich nicht sicher ist, ob ein Schlüssel überhaupt gesetzt wurde, kann das mit `hasContext` prüfen, statt sich auf ein `undefined` von `getContext` zu verlassen – das macht den Fehlerfall explizit statt still.\n\nZwei Fallstricke tauchen dabei mit schöner Regelmäßigkeit auf. Der erste: `setContext` muss synchron während der Initialisierung der Komponente aufgerufen werden. Wer den Aufruf in `onMount`, einen Event-Handler oder eine `async`-Funktion verschiebt, bekommt keinen Fehler, sondern etwas Schlimmeres – die Kinder erhalten beim späteren `getContext` schlicht `undefined`, und die Ursache ist schwer zu finden. Der zweite Fallstrick betrifft Reaktivität.\n\n```mermaid\ngraph TD\n  Provider[\"Toolbar<br/>setContext('toolbar', …)\"]\n  Group[\"ButtonGroup<br/>(keine Props)\"]\n  Divider[\"Divider<br/>(keine Props)\"]\n  Consumer[\"ToolbarButton<br/>getContext('toolbar')\"]\n\n  Provider --> Group --> Divider --> Consumer\n```\n\n### Context ist nicht dasselbe wie ein Store\n\nContext ist an die Komponenteninstanz gebunden und für sich genommen nicht reaktiv. Lege ich einen einfachen Zahlenwert in den Context und ändere ihn später, aktualisieren sich die Kinder nicht – sie haben ihre Kopie beim Init gelesen, und dabei bleibt es. Ein Store dagegen ist global teilbar und reaktiv; mit `$store` abonniert man Änderungen und rendert bei jeder Aktualisierung neu. Über den State außerhalb der Komponente und die Store-Mechanik habe ich in [Svelte Stores](https://www.mikebild.dev/de/blog/svelte-stores-zustand-ausserhalb-der-komponente/) ausführlicher geschrieben, und die zugrundeliegende Reaktivität ist Thema von [Svelte-Reaktivität](https://www.mikebild.dev/de/blog/svelte-reaktivitaet-compiler-ohne-virtual-dom/).\n\nDie beiden schließen sich nicht aus, im Gegenteil. Die in der Praxis nützlichste Kombination legt einen Store *in* den Context. Damit bekommt man beides: die implizite Verteilung durch den Baum von Context und die Reaktivität eines Stores.\n\n```svelte\n<!-- ThemeProvider.svelte -->\n<script>\n  import { setContext } from 'svelte';\n  import { writable } from 'svelte/store';\n\n  const theme = writable('light');\n  setContext('theme', theme);\n</script>\n\n<slot></slot>\n```\n\n```svelte\n<!-- ThemeToggle.svelte -->\n<script>\n  import { getContext } from 'svelte';\n\n  const theme = getContext('theme');\n</script>\n\n<button on:click={() => theme.update((t) => (t === 'light' ? 'dark' : 'light'))}>\n  Current theme: {$theme}\n</button>\n```\n\nJetzt reicht Context den Store an jede Nachfahr-Komponente, und weil es ein Store ist, reagiert `{$theme}` auf jede Änderung – ohne ein einziges Prop durch den Baum zu fädeln.\n\n## Web Components: framework-neutrale Wiederverwendung\n\nSlots und Context lösen Kompositionsprobleme innerhalb einer Svelte-Anwendung. Das dritte Werkzeug zielt nach außen. Manchmal soll eine Komponente auch dort funktionieren, wo kein Svelte läuft – in einer bestehenden Seite, in einem anderen Framework, in reinem HTML. Svelte kann eine Komponente als Custom Element kompilieren, also als echtes Web Component nach Browser-Standard.\n\nZwei Dinge braucht es dafür. In der Komponente vergibt man über `<svelte:options>` einen Tag-Namen, und beim Kompilieren aktiviert man die Option `customElement`:\n\n```svelte\n<!-- UserBadge.svelte -->\n<svelte:options tag=\"user-badge\" />\n\n<script>\n  export let name = 'Unknown';\n  export let status = 'offline';\n</script>\n\n<span class=\"badge\" data-status={status}>\n  {name}\n</span>\n\n<style>\n  .badge {\n    display: inline-flex;\n    padding: 0.25rem 0.5rem;\n    border-radius: 999px;\n  }\n  .badge[data-status='online'] {\n    background: #d1fae5;\n  }\n</style>\n```\n\nBeim Bundling schaltet man den Compiler auf Custom-Element-Ausgabe. Mit Rollup und dem offiziellen Plugin sieht der relevante Teil so aus:\n\n```js\n// rollup.config.js\nimport svelte from 'rollup-plugin-svelte';\n\nexport default {\n  // ...\n  plugins: [\n    svelte({\n      compilerOptions: {\n        customElement: true,\n      },\n    }),\n  ],\n};\n```\n\nDanach ist `<user-badge>` ein ganz normales HTML-Element. Es lässt sich in jeder Seite verwenden, ganz ohne Svelte-Laufzeit im Aufrufer:\n\n```html\n<script src=\"./user-badge.js\"></script>\n\n<user-badge name=\"Ada\" status=\"online\"></user-badge>\n```\n\nDie exportierten Props werden zu Element-Properties und -Attributen, sodass man das Element wie jedes andere DOM-Element ansprechen kann. Svelte kapselt die Styles per Shadow DOM – die Badge-Styles greifen nicht auf die umgebende Seite über, und Seiten-Styles dringen nicht unkontrolliert hinein. Das ist meist erwünscht, überrascht aber, wenn man globale Styles erwartet; `:global`-Regeln verhalten sich hier anders.\n\nAn dieser Stelle lohnt ein ehrlicher Blick auf die rauen Kanten, denn Ende 2022 ist der Custom-Element-Modus von Svelte funktional, aber nicht spannungsfrei. Der wichtigste Punkt betrifft die Datenübergabe: HTML-Attribute sind immer Strings. Ein `name=\"Ada\"` im Markup kommt sauber an, aber ein Objekt oder ein Array lässt sich nicht als Attribut übergeben. Solche Werte muss man als JavaScript-Property auf dem Element setzen, etwa `el.items = [...]` – ein Detail, das man leicht übersieht, wenn man das Element nur deklarativ im HTML verwendet. Zweitens sind Custom Elements nach dem Definieren global registriert; derselbe Tag-Name lässt sich im selben Dokument nicht zweimal belegen, was beim Einbinden mehrerer Bundles zu Konflikten führen kann. Und drittens ist die Shadow-DOM-Kapselung zwar ein Gewinn für die Isolation, nimmt einem aber den bequemen Durchgriff von außen: Wer das Element von der Seite aus gestalten will, muss die dafür vorgesehenen Stellen selbst öffnen und CSS Custom Properties bewusst hineinreichen. Nichts davon ist ein Ausschlusskriterium, aber es sind die Stellen, an denen die Praxis von der ersten glatten Demo abweicht.\n\nEin praktischer Hinweis aus Projekten: `customElement: true` gehört nur auf die Komponenten, die man tatsächlich exportieren will, nicht projektweit. Sonst kompiliert man die ganze App zu Custom Elements und verliert den regulären Svelte-Komponentenmodus mit seinen Vorteilen. In der Praxis pflege ich dafür einen separaten Build-Eintrag, der genau die zu exportierenden Komponenten bündelt.\n\n## Wann welches Werkzeug\n\nDie drei Mechanismen lassen sich klar nach ihrem Zweck sortieren:\n\n- Slots wählt man, wenn eine Komponente ihr Layout vorgibt, den Inhalt aber vom Aufrufer bekommen soll – mit slot props auch dann, wenn der Aufrufer für die Darstellung Daten aus dem Inneren braucht.\n- Context wählt man, wenn ein Wert oder eine Funktion mehreren Ebenen tiefer benötigt wird und Prop-Drilling die Zwischenkomponenten unnötig belasten würde; für reaktive Werte legt man einen Store in den Context.\n- Web Components wählt man, wenn eine Komponente außerhalb der Svelte-Welt laufen soll – in fremden Frameworks oder in reinem HTML.\n\nEin kurzer Hinweis zur Einordnung Ende 2022: Ich beziehe mich hier durchgehend auf Svelte 3, die aktuelle Version dieser Tage. Die gezeigte Syntax `tag=\"user-badge\"` ist der Stand von Svelte 3; spätere Versionen haben an dieser Stelle Änderungen gebracht, die hier bewusst außen vor bleiben. Wer das Repository, an dem er arbeitet, auf Svelte 3 hält, ist mit allem hier Gezeigten auf sicherem Boden.\n\n## Fazit\n\nSlots, Context und Web Components wirken zunächst wie drei zusammenhanglose Features, sind aber ein zusammengehöriges Set von Kompositions-Werkzeugen, jedes mit einer eigenen Richtung. Slots reichen Markup von außen hinein und über slot props Daten von innen wieder heraus. Context verteilt Werte implizit durch den Komponentenbaum und erspart das Prop-Drilling – reaktiv wird es erst mit einem Store darin. Und Custom Elements lösen eine Komponente aus der Svelte-Welt heraus, sodass sie überall dort läuft, wo Standard-HTML läuft. Wer sich bei jedem Kompositionsproblem kurz fragt, in welche Richtung Inhalt oder Daten fließen sollen und wie weit sie reichen müssen, greift fast von selbst zum passenden der drei Werkzeuge. Diese eine Frage erspart im Projekt die meisten Umwege.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-svelte.html\n- [Svelte 5: Snippets](https://svelte.dev/docs/svelte/snippet)\n- [Svelte: Slots im Legacy-Modus](https://svelte.dev/docs/svelte/legacy-slots)\n- [Svelte: Context-API](https://svelte.dev/docs/svelte/context)\n- [Svelte: Custom Elements](https://svelte.dev/docs/svelte/custom-elements)\n- [Svelte: `<svelte:options>`](https://svelte.dev/docs/svelte/svelte-options)"},{"locale":"de","translation_key":"build-vs-runtime-webprojekte","slug":"build-vs-runtime-webprojekte","title":"Build vs. Runtime in Webprojekten","summary":"Der Rendering-Zeitpunkt wird pro Route entschieden. Statische, dynamische und inkrementelle Modelle lassen sich nach Datenfrist, Kosten und Fehlerverhalten kombinieren.","tags":["Software","Frontend"],"published_at":"2022-11-12T10:00:00+00:00","updated_at":"2026-07-13T08:48:49.883691+00:00","url":"https://www.mikebild.dev/de/blog/build-vs-runtime-webprojekte/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/93ecafc070d67f1f8cef9a2686991c749fc38612bea19c244d13328b73a59e06/build-vs-runtime-webprojekte-vorlesen.mp3","audio_duration_secs":651,"text":"# Build vs. Runtime in Webprojekten\n\nBeim Aufsetzen eines Projekts fällt diese Entscheidung in einer Sekunde: Man wählt ein Framework, übernimmt den Default und rendert ab da alles serverseitig. Bemerkbar macht sich diese Sekunde erst Monate später – wenn der Build zwanzig Minuten braucht oder die Server bei der ersten Lastspitze volllaufen.\n\nDer Rendering-Zeitpunkt einer Seite ist eine Architekturgrenze und keine Einstellung, die man im Build-Setup wegkonfiguriert. Er legt fest, wann eine Seite entsteht, wie frisch ihre Daten sind, was ein Fehler kostet und wie schnell ein Team liefern kann. Beantwortet wird die Frage – rendern wir zur Build-Zeit oder zur Laufzeit? – trotzdem meist implizit. Wer die Grenze bewusst zieht, verkürzt Zyklen, senkt Kosten und nimmt Reibung zwischen Content, Entwicklung und Betrieb heraus.\n\n## Die zwei Zeitpunkte\n\nJede Ausgabe im Web entsteht zu einem von zwei Zeitpunkten. Zur **Build-Zeit** läuft Arbeit einmal, bevor irgendein Nutzer ankommt: Templates werden zu HTML, Daten werden eingefroren, Assets werden gebündelt und optimiert. Zur **Laufzeit** läuft Arbeit pro Anfrage oder im Browser, während ein Nutzer wartet: Daten werden geholt, Rechte geprüft, HTML zusammengesetzt, State hydriert.\n\nDer entscheidende Unterschied ist nicht „schnell vs. langsam“, sondern **wer wartet und wie oft die Arbeit passiert**. Build-Arbeit passiert einmal und wird beliebig oft ausgeliefert – der Nutzer wartet nie darauf. Runtime-Arbeit passiert bei jeder Anfrage erneut – dafür kennt sie den aktuellen Moment, den eingeloggten Nutzer und den letzten Datenstand.\n\n```mermaid\nflowchart LR\n  subgraph Build[\"Build-Zeit (einmal)\"]\n    Content --> Prerender\n    Prerender --> StaticHTML[\"Static HTML + Assets\"]\n  end\n  subgraph Runtime[\"Laufzeit (pro Request)\"]\n    Request --> Fetch[\"Fetch data + auth\"]\n    Fetch --> Render[\"Render + hydrate\"]\n  end\n  StaticHTML --> CDN\n  CDN --> User\n  Render --> User\n```\n\nZwischen diesen Polen liegt ein Spektrum, kein Entweder-oder: Static Site Generation friert alles zur Build-Zeit ein. Server-Side Rendering baut pro Request neu. Client-Side Rendering schiebt die Arbeit in den Browser. Und Zwischenformen – prerender plus clientseitiges Nachladen, oder statisches HTML mit inkrementeller Revalidierung – mischen beide Zeitpunkte pro Route. Die Kunst besteht darin, die Grenze pro Seite an der richtigen Stelle zu ziehen, statt ein Verfahren für alles auszurufen.\n\n## Der Trade-off, konkret\n\nIch mache den Trade-off an drei Größen fest, weil genau diese drei ein Produkt tragen oder bremsen: Frische der Daten, Kosten pro Anfrage und Time-to-Feedback im Team.\n\nEine Marketing- oder Doku-Seite ändert sich selten und ist für alle gleich. Sie zur Build-Zeit einzufrieren ist fast immer richtig: Sie liegt danach als statische Datei im CDN, kostet pro Aufruf praktisch nichts, hat keine Server-Latenz und keinen Server, der ausfallen kann.\n\n```js\n// Build-time: runs once, per deploy\nexport async function getStaticProps() {\n  const posts = await cms.getPublishedPosts();\n  return { props: { posts } };\n}\n```\n\nEin Kontostand, ein personalisiertes Dashboard oder eine Preisliste, die sich stündlich ändert, verträgt kein Einfrieren. Diese Daten gehören an die Laufzeit – entweder pro Request auf dem Server oder als clientseitiger Fetch nach dem ersten Paint.\n\n```js\n// Runtime: runs on every request, knows \"now\" and the user\nexport async function getServerSideProps(ctx) {\n  const user = await auth(ctx.req);\n  const balance = await ledger.getBalance(user.id);\n  return { props: { balance } };\n}\n```\n\nDie eigentliche Frage lautet nicht „SSG oder SSR?“, sondern: **Wie lange darf diese Ausgabe alt sein, ohne falsch zu werden?** Ich nenne das die Datenfrist. Ist die Frist praktisch unendlich (ein Blogpost von 2019), gehört die Seite in den Build. Ist die Frist null (der aktuelle Kontostand), gehört sie an die Laufzeit. Und dazwischen – die Frist beträgt Minuten oder Stunden – wird es interessant: Dann will ich die Auslieferungskosten eines statischen Assets, aber eine kontrollierte Auffrischung. Genau dafür existieren Caching mit Revalidierung und inkrementelle Regeneration. Sie sind die technische Antwort auf eine endliche Datenfrist, kein Framework-Gimmick.\n\n## Was das messbar bewirkt\n\nDer Grund, warum ich diese Grenze so ernst nehme, ist ihre Wirkung auf harte Zahlen.\n\nEine statisch ausgelieferte Seite antwortet mit der Latenz des nächsten CDN-Knotens – zweistellige Millisekunden, unabhängig von der Last. Dieselbe Seite pro Request serverseitig zu rendern bedeutet Datenbank-Roundtrips, Template-Rendering und einen Server, der mit dem Traffic skalieren muss. Bei einem Lastspitzen-Event ist das der Unterschied zwischen „das CDN liefert eine Datei“ und „unsere Instanzen laufen voll und die Autoscaling-Rechnung explodiert“. Für Seiten ohne echte Datenfrist ist Runtime-Rendering also nicht nur teurer, sondern auch fragiler – man kauft Komplexität, ohne einen Gegenwert zu bekommen.\n\nUmgekehrt kostet zu viel Build-Arbeit Feedback. Wenn jede Änderung an einem Beitrag einen Full-Rebuild von zehntausend Seiten auslöst, wird der Build zum Nadelöhr: Ein Redaktions-Typo braucht 20 Minuten bis zur Sichtbarkeit, und niemand traut sich mehr, kurz vor Feierabend zu deployen. Das ist kein reines Performance-, sondern ein Produktivitätsproblem. Die Konsequenz daraus heißt nicht „mehr Runtime“, sie heißt feinere Grenze: nur die betroffenen Seiten neu erzeugen, statt alles. Kürzere Feedback-Schleifen sind hier der eigentliche Gewinn – sie entscheiden, wie oft ein Team liefert und wie ruhig es das tut.\n\nEin Fall, der mir in Projekten begegnet ist: Ein Content-lastiges Portal rendert historisch alles serverseitig, weil das mal der Framework-Default war. Unter normaler Last läuft es, aber die Server-Rechnung wächst linear mit dem Traffic, und jede Pressemeldung, die das Portal kurz viral gehen lässt, wird zum Incident. Verschiebt man die zwei Handvoll wirklich statischer Seitentypen – Artikel, Kategorien, Landingpages – in den Build und lässt nur Suche und personalisierte Bereiche an der Laufzeit, verändert sich die Kurve grundlegend. Der Löwenanteil des Traffics wird zur CDN-Datei, die Server tragen nur noch den kleinen dynamischen Rest, und die Lastspitze ist plötzlich ein Nicht-Event. Es wurde keine Zeile Fachlogik umgeschrieben – nur die Grenze zwischen Build und Runtime an die tatsächliche Datenfrist angepasst.\n\nIch fasse die Entscheidung deshalb gern in einer kleinen Tabelle zusammen, bevor ich ein Tool anfasse:\n\n| Seite | Datenfrist | Zeitpunkt |\n| --- | --- | --- |\n| Landingpage, Docs | quasi unendlich | Build |\n| Produktkatalog | Stunden | Build + Revalidierung |\n| Suchergebnis, Feed | Sekunden | Runtime (Server) |\n| Dashboard, Kontostand | null, personalisiert | Runtime (Server/Client) |\n\nDie Tabelle ist bewusst schlicht. Sie erzwingt genau die eine Frage, die man sonst überspringt: Wie alt darf das hier sein?\n\n## Wie ich die Grenze ziehe\n\nVor der Tool-Frage kläre ich pro Route: Ist die Ausgabe für alle Nutzer gleich oder personalisiert? Wie lange darf sie alt sein? Was passiert, wenn die Datenquelle beim Rendern nicht antwortet? Und lässt sich der Zeitpunkt später ändern, ohne die halbe Anwendung umzubauen? Wenn ich eine Seite so schneide, dass ich ihren Rendering-Zeitpunkt isoliert verschieben kann – von Build zu Runtime, inkrementell oder zurück –, ohne Nachbarrouten anzufassen, dann ist die Grenze brauchbar.\n\nEin häufig unterschätzter Teil davon ist die Lebensdauer von State. Im Frontend ist die schwierigste Entscheidung selten der Komponentenbaum, sondern die Frage, wo State gehalten wird: in einer Komponente, in der URL, in einem Cache, auf dem Server oder in einem lokalen Modell. Diese Frage ist die Build-vs-Runtime-Frage im Kleinen. State, der in die URL gehört, kann serverseitig gerendert und geteilt werden. State, der nur clientseitig existiert, verlangt Laufzeit im Browser und ist im statischen HTML schlicht nicht vorhanden. Wer diese Zuordnung sauber trifft, bekommt teilbare, indexierbare, testbare Seiten fast geschenkt.\n\n## Progressive Enhancement als dieselbe Grenze\n\nDiese Denkweise ist nicht neu, sie ist nur alt geworden. Progressive Enhancement fragt seit jeher: Was liefere ich als robuste Basis, und was reichere ich zur Laufzeit an, wenn der Client es kann? Schon ein Canvas-Element trägt die Haltung in sich – erst prüfen, ob eine Fähigkeit da ist, dann ein Verhalten aktivieren, sonst einen Fallback anbieten.\n\n```html\n<canvas id=\"clock\" width=\"150\" height=\"150\">\n  <img src=\"clock.png\" alt=\"Clock fallback\" />\n</canvas>\n```\n\n```js\nconst canvas = document.getElementById(\"clock\");\nif (canvas.getContext) {\n  const ctx = canvas.getContext(\"2d\");\n  // enhance at runtime, only when supported\n}\n```\n\nGenau dieselbe Reihenfolge – Fähigkeit, Grenze, Verhalten – gilt für serverseitig geliefertes HTML plus clientseitige Hydration. Die statische Basis ist die Build-Ausgabe. Die Anreicherung ist die Laufzeit. Wenn beide Ebenen sauber getrennt sind, funktioniert die Seite auch dann, wenn die Laufzeit-Schicht langsam ist oder ausfällt. Das ist kein Legacy-Wissen, sondern die konzeptionelle Wurzel der ganzen Rendering-Diskussion.\n\n## Der Fehlerpfad entscheidet\n\nEine Rendering-Entscheidung ist erst belastbar, wenn ihr Fehlerpfad beschrieben ist. Was passiert, wenn das CMS beim Build nicht antwortet – bricht der Deploy ab oder geht die Seite mit Lücke live? Was passiert, wenn eine API beim serverseitigen Rendern hängt – blockiert die ganze Antwort, oder rendert die Seite ohne den Teil und lädt ihn clientseitig nach? Diese Fragen wirken trocken, sind aber der Unterschied zwischen Demo und Betrieb.\n\nBuild-Rendering verlagert das Ausfallrisiko in die Deploy-Pipeline: Fehler passieren einmal, sichtbar, vor dem Nutzer. Runtime-Rendering verteilt das Risiko auf jede einzelne Anfrage: Fehler passieren live, unter Last, im schlechtesten Moment. Beides ist legitim – aber man sollte wissen, welches Risiko man kauft. Ich prüfe deshalb immer, ob die Entscheidung rückbaubar ist: Kann ich eine Route von Runtime auf Build umstellen, wenn die Last steigt? Kann ich einen Cache gezielt invalidieren, ohne alles neu zu bauen? Wenn die Antwort nein ist, fehlt noch ein Teil der Architektur.\n\n## Typische Fehler\n\nDer erste Fehler ist, das Werkzeug mit der Entscheidung zu verwechseln. Ein SSG-Framework ist keine Architektur, SSR ist kein Datenmodell, ein CDN ist keine Frische-Strategie. Diese Werkzeuge können die Grenze zwischen Build und Runtime sauber ausdrücken, aber sie ziehen sie nicht für dich. Wer den Default eines Frameworks übernimmt, hat keine Entscheidung getroffen, sondern eine ausgelassen.\n\nDer zweite Fehler ist, sich am Gutfall zu orientieren. Im Demo-Modus sieht jede Variante schnell aus – ein Datensatz, ein Nutzer, keine Last. Interessant wird es bei zehntausend Seiten, bei Traffic-Spitzen, bei einer langsamen Upstream-API, bei einem Redakteur, der eine Korrektur sofort sehen will. Genau dort zeigt sich, ob die Grenze zwischen Build und Runtime an der richtigen Stelle liegt.\n\n## Validierung\n\nDrei Checks reichen mir meistens. Erstens: Für jede Route ist benannt, ob sie zur Build- oder zur Laufzeit entsteht – und warum, ausgedrückt als Datenfrist. Zweitens: Für jede Runtime-Route ist der Fehlerpfad beschrieben, inklusive des Verhaltens bei ausgefallener Datenquelle. Drittens: Die Entscheidung ist pro Route umstellbar, ohne Nachbarrouten anzufassen. Wenn diese drei Punkte stehen, ist die Architektur robust gegen genau die Überraschungen, die solche Projekte sonst spät und teuer einholen.\n\n## Weiterführende Quellen\n\n- React: Thinking in React: https://react.dev/learn/thinking-in-react\n- React: Managing State: https://react.dev/learn/managing-state\n\nDie Quellen helfen beim Gegenprüfen von Standards und Plattformverhalten. Die eigentliche Aussage bleibt die Architekturentscheidung im konkreten Projekt.\n\n## Schluss\n\nBuild vs. Runtime ist am Ende eine Frage nach der Datenfrist jeder einzelnen Seite. Ein immutable Beitrag kann als Datei ins CDN, ein Kontostand braucht aktuelle Daten, und viele Routen liegen mit Revalidierung dazwischen. Wenn diese Entscheidung pro Route verschiebbar bleibt, muss ein neuer Frischebedarf nicht das Rendering der gesamten Anwendung umwerfen."},{"locale":"de","translation_key":"nodejs-streams-im-objektmodus","slug":"nodejs-streams-im-objektmodus","title":"Streams im Objektmodus: Datenpipelines jenseits von Bytes","summary":"Node.js-Streams transportieren nicht nur Bytes: Mit objectMode:true werden sie zu komponierbaren Datenpipelines aus parsen, filtern und aggregieren – inklusive der Brücke zu Async-Iteratoren.","tags":["Software","Node.js","Backend"],"published_at":"2022-11-08T10:00:00+00:00","updated_at":"2026-07-13T07:59:30.815444+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-streams-im-objektmodus/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0f8df286685c4924529ab1db8a021aa0c9421e3b7ec391b507d3df9124612b21/nodejs-streams-im-objektmodus-vorlesen.mp3","audio_duration_secs":766,"text":"Wer einen Stream auf `objectMode: true` umstellt und dabei sein gewohntes `highWaterMark: 16384` mitnimmt, puffert keine 16 KiB mehr, sondern 16384 Datensätze. Gleiche Zahl, andere Einheit, ein Speicherbedarf um Größenordnungen daneben. Der Objektmodus sieht aus wie eine beiläufige Konstruktoroption, aber er ändert, was ein Stream überhaupt durch die Pipeline schiebt – und damit auch, wann gedrosselt wird.\n\nIm [früheren Beitrag zu Node.js-Streams und Backpressure](https://www.mikebild.dev/de/blog/nodejs-streams-und-backpressure/) drehte sich alles um Bytes: Buffer, die durch eine Pipe fließen, und die Kunst, den Fluss zu drosseln, bevor der Speicher überläuft. Das ist der Standardfall für Datei- und Netzwerk-I/O. Sobald aber keine Dateien kopiert, sondern Datensätze verarbeitet werden – CSV-Zeilen, JSON-Objekte, Log-Einträge –, reicht dieses Bild nicht mehr weit genug.\n\nArbeitet ein Stream im Objektmodus, transportiert er keine Buffer und keine Strings mehr, sondern beliebige JavaScript-Werte – ganze Objekte, Arrays, Zahlen. Damit wird aus dem Werkzeug für rohe Byteströme ein Werkzeug für Datenverarbeitung. Und das Schöne daran: Die Mechanik bleibt dieselbe. Man verkettet Stufen, jede Stufe macht eine Sache, und am Ende steht eine Pipeline, die einen Datensatz nach dem anderen durchreicht, ohne alles auf einmal in den Speicher zu laden.\n\n## Was der Objektmodus wirklich ändert\n\nEin Stream im Standardmodus kennt genau zwei Datentypen: `Buffer` und `String`. Alles, was man hineinschiebt, muss eines von beiden sein. Der Objektmodus hebt diese Einschränkung auf. Ein `new stream.Transform({ objectMode: true })` akzeptiert und liefert beliebige JS-Werte. Die einzige Ausnahme ist `null` – dieser Wert ist reserviert und signalisiert das Ende des Streams. Dazu später mehr, denn genau hier lauert ein Fallstrick.\n\nDer Objektmodus wird pro Stream über die Konstruktoroption gesetzt, und der Standardwert ist `false`. Man aktiviert ihn also bewusst. In den Beispielen aus meinem [Node.js-Repository](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) taucht das Muster bereits durchgehend auf – dort allerdings noch in der ES5-Schreibweise mit `util.inherits` und `Readable.call(this, { objectMode: true })`. Ein `Readable`, der zwei kleine Objekte durchreicht, sieht dort so aus:\n\n```javascript\nconst { Readable } = require('stream');\nconst util = require('util');\n\n// ES5 pattern from the training repo\nconst ReadStream = function () {\n  Readable.call(this, { objectMode: true });\n  this.data = [\n    { id: 0, value: 1 },\n    { id: 1, value: 2 },\n  ];\n  this.curIndex = 0;\n};\nutil.inherits(ReadStream, Readable);\n\nReadStream.prototype._read = function () {\n  if (this.curIndex === this.data.length) {\n    return this.push(null); // signals end of stream\n  }\n  this.push(this.data[this.curIndex++]);\n};\n```\n\nDas funktioniert und ist historisch gewachsen. Ich zeige es trotzdem lieber in der modernen Klassensyntax, weil sie näher an dem liegt, was man heute in Codebasen antrifft. Mit `class ... extends Transform` wird aus dem Konstruktor-Ritual ein `super({ objectMode: true })`, und die Verarbeitungslogik steht in einer klar benannten Methode.\n\n## Die eine Kernmethode: `_transform`\n\nEin Transform-Stream hat im Kern eine einzige Methode, die man selbst schreibt: `_transform(chunk, encoding, callback)`. Für jeden eintreffenden Wert wird sie einmal aufgerufen. Man gibt Ergebnisse mit `this.push(value)` aus und meldet mit `callback()`, dass dieser Wert fertig verarbeitet ist. Im Objektmodus ist `chunk` der rohe JS-Wert – das Argument `encoding` wird ignoriert, weil es hier nichts zu dekodieren gibt.\n\nDer entscheidende Punkt: `push` und `callback` sind zwei getrennte Dinge. `push` schiebt Ausgaben in die nächste Stufe, `callback` signalisiert „ich bin mit diesem Eingabewert durch“. Man kann pro Eingabe null-, ein- oder mehrmals `push`en und ruft am Ende genau einmal `callback` auf. Ruft man nur `callback()` ohne `push`, verschwindet der Wert – das ist die natürliche Art, in einem Filter etwas wegzulassen.\n\nHier eine Verarbeitungsstufe, die rohe CSV-Zeilen zu Objekten parst:\n\n```javascript\nconst { Transform } = require('stream');\n\nclass ParseRow extends Transform {\n  constructor() {\n    super({ objectMode: true });\n  }\n\n  _transform(line, _encoding, callback) {\n    const [id, name, status] = String(line).split(',');\n    this.push({ id: Number(id), name, status });\n    callback();\n  }\n}\n```\n\nUnd eine Filterstufe, die nur aktive Datensätze durchlässt. Hier zeigt sich das Weglassen: Ist die Bedingung nicht erfüllt, wird nichts gepusht, sondern nur `callback()` aufgerufen.\n\n```javascript\nconst { Transform } = require('stream');\n\nclass FilterActive extends Transform {\n  constructor() {\n    super({ objectMode: true });\n  }\n\n  _transform(record, _encoding, callback) {\n    if (record.status === 'active') {\n      this.push(record);\n    }\n    // no push means the record is dropped\n    callback();\n  }\n}\n```\n\nEine Formatierungsstufe rundet das Bild ab. Sie nimmt das Objekt und formt eine Ausgabezeile daraus:\n\n```javascript\nconst { Transform } = require('stream');\n\nclass FormatOutput extends Transform {\n  constructor() {\n    super({ objectMode: true });\n  }\n\n  _transform(record, _encoding, callback) {\n    this.push(`#${record.id} ${record.name}\\n`);\n    callback();\n  }\n}\n```\n\nDrei kleine Stufen, jede mit einer einzigen Verantwortung. Genau so entsteht Komponierbarkeit.\n\n## Stufen verketten: parsen, filtern, formatieren\n\nDie eigentliche Pipeline ist dann fast unspektakulär – und das ist ein gutes Zeichen. Ich verkette die Stufen mit `pipeline()` aus dem `stream`-Modul, nicht mit einer Kette aus `pipe()`. Der Grund: `pipeline()` propagiert Fehler und räumt die beteiligten Streams auf, wenn einer scheitert. Eine reine `pipe()`-Kette tut das nicht – dort muss man Fehler und Cleanup an jeder Naht selbst behandeln, und genau das wird in der Praxis vergessen.\n\n```javascript\nconst { Readable, pipeline } = require('stream');\n\nconst csvLines = ['0,Ada,active', '1,Linus,inactive', '2,Grace,active'];\n\npipeline(\n  Readable.from(csvLines),\n  new ParseRow(),\n  new FilterActive(),\n  new FormatOutput(),\n  process.stdout,\n  (err) => {\n    if (err) {\n      console.error('pipeline failed:', err);\n    } else {\n      console.log('pipeline finished');\n    }\n  }\n);\n```\n\nDie Quelle ist hier `Readable.from(csvLines)` – dazu gleich mehr. Die Senke ist `process.stdout`, ein ganz normaler Writable-Stream. Dazwischen fließt ein Datensatz nach dem anderen: erst als String, nach `ParseRow` als Objekt, durch `FilterActive` gefiltert, in `FormatOutput` wieder zu einer Zeile geformt. Zu keinem Zeitpunkt liegt die gesamte Datenmenge im Speicher – es ist immer nur ein kleiner Vorrat gepufferter Werte unterwegs.\n\nAls Diagramm sieht dieser Datenfluss so aus:\n\n```mermaid\nflowchart LR\n  A[\"Source<br/>Readable.from\"] -->|\"CSV line (string)\"| B[\"Parse<br/>_transform\"]\n  B -->|\"JS object\"| C[\"Filter<br/>_transform\"]\n  C -->|\"JS object\"| D[\"Format<br/>_transform\"]\n  D -->|\"output line\"| E[\"Sink<br/>Writable\"]\n```\n\nAn den Kanten steht, was tatsächlich fließt: erst eine Zeile als String, dann JS-Objekte durch die mittleren Stufen, am Ende wieder Text. Jede Stufe kümmert sich nur um ihre eigene Umwandlung und weiß nichts von den Nachbarn.\n\n## Aggregieren mit `_flush`\n\nFiltern und Umformen arbeiten Datensatz für Datensatz. Für Aggregationen – Summen, Zählungen, Gruppierungen – braucht man einen anderen Rhythmus: sammeln, während die Werte eintreffen, und das Ergebnis erst ausgeben, wenn die Quelle erschöpft ist. Dafür gibt es `_flush(callback)`. Diese Methode wird genau einmal aufgerufen, kurz bevor der Stream endet. In `_transform` sammelt man, in `_flush` gibt man aus.\n\n```javascript\nconst { Transform } = require('stream');\n\nclass CountByStatus extends Transform {\n  constructor() {\n    super({ objectMode: true });\n    this.counts = {};\n  }\n\n  _transform(record, _encoding, callback) {\n    this.counts[record.status] = (this.counts[record.status] || 0) + 1;\n    callback(); // nothing pushed yet, just accumulate\n  }\n\n  _flush(callback) {\n    this.push(this.counts); // emit the aggregate once at the end\n    callback();\n  }\n}\n```\n\nDiese Stufe schluckt viele Objekte und gibt am Ende ein einziges aus – das Aggregat. Sie zeigt gut, dass eine Stream-Stufe ihre Ein- und Ausgabemenge nicht eins zu eins halten muss.\n\n## Backpressure zählt jetzt Objekte\n\n`highWaterMark` bedeutet im Objektmodus etwas anderes als im Bytemodus – das wird regelmäßig überlesen, mit spürbaren Folgen. `highWaterMark` ist die Schwelle, ab der ein Stream als „voll genug“ gilt und Backpressure auslöst. Im Bytemodus wird diese Schwelle in Bytes gemessen; 2022 waren allgemein 16 KiB der Default, seit Node 22 sind es 64 KiB. Im Objektmodus wird sie in Objekten gemessen, weiterhin mit einem Standardwert von 16 Objekten.\n\nDas ist keine Kleinigkeit. Wer aus dem Bytemodus kommt und `highWaterMark: 16` liest, denkt reflexartig an 16 Bytes und hält das für absurd klein. Im Objektmodus sind es aber 16 gepufferte Objekte – ein völlig sinnvoller Vorrat. Umgekehrt kann ein aus Byte-Gewohnheit gesetztes `highWaterMark: 16384` im Objektmodus bedeuten, dass man 16384 Objekte puffert, bevor Backpressure greift. Das ist selten gewollt.\n\nWichtig ist auch: `highWaterMark` ist eine Schwelle, kein harter Riegel. Der Puffer darf sie überschreiten – die Schwelle ist das Signal, ab dem `push()` den Wert `false` zurückgibt und nachgelagerte Stufen zum Drosseln auffordert. Bei `pipeline()` und `pipe()` geschieht dieses Pausieren und Fortsetzen automatisch. Man verlässt sich also im Normalfall auf dieses automatische Zusammenspiel und muss den Rückgabewert von `push` nur dann selbst auswerten, wenn man eine Quelle von Hand steuert. Backpressure funktioniert im Objektmodus genauso zuverlässig wie im Bytemodus, nur ist die Einheit eine andere.\n\nZur Abgrenzung die beiden Modi nebeneinander:\n\n- Der Bytemodus (Standard) transportiert `Buffer` oder `String`; `highWaterMark` zählt hier Bytes. Der allgemeine Default hängt von der Node-Version ab und liegt seit Node 22 bei 64 KiB.\n- Der Objektmodus (`objectMode: true`) transportiert beliebige JS-Werte außer `null`, `highWaterMark` zählt hier Objekte mit Standardwert 16, und die typischen Einsätze sind Datenpipelines aus parsen, filtern, transformieren und aggregieren.\n\n## Die Brücke zu Async-Iteratoren\n\nBis hierhin habe ich Streams als Klassen gebaut. Das ist nicht immer nötig, und oft ist es sogar umständlich. Node bietet zwei moderne Verbindungsstücke, die den Objektmodus mit der Welt der Async-Iteratoren zusammenbringen: `Readable.from(iterable)` und `for await ... of`.\n\n`stream.Readable.from(iterable)` nimmt ein beliebiges Iterable oder Async-Iterable – ein Array, einen Generator, einen Async-Generator – und macht daraus einen Readable-Stream. Standardmäßig arbeitet dieser Stream im Objektmodus. Das ist die eleganteste Art, eine Datenquelle in eine Pipeline einzuspeisen, ohne eine eigene `Readable`-Klasse zu schreiben. Genau das habe ich oben mit `Readable.from(csvLines)` bereits genutzt.\n\nDie Gegenrichtung ist mindestens so praktisch: Ein Readable-Stream ist selbst ein Async-Iterable. Man kann ihn also direkt mit `for await ... of` konsumieren, und das Sprachkonstrukt kümmert sich um Pausieren, Fortsetzen, Backpressure und das Ende – alles automatisch.\n\n```javascript\nconst { Readable } = require('stream');\n\nasync function* generateRecords() {\n  yield { id: 0, value: 1 };\n  yield { id: 1, value: 2 };\n  yield { id: 2, value: 3 };\n}\n\nasync function main() {\n  const source = Readable.from(generateRecords());\n\n  for await (const record of source) {\n    console.log('received:', record);\n  }\n}\n\nmain();\n```\n\nMan kann Async-Generatoren sogar als Pipeline-Stufe einsetzen. Ein Generator, der eine Quelle konsumiert und gefilterte Werte weiterreicht, ersetzt eine ganze Transform-Klasse durch wenige Zeilen:\n\n```javascript\nasync function* filterEven(source) {\n  for await (const n of source) {\n    if (n % 2 === 0) {\n      yield n;\n    }\n  }\n}\n```\n\nOb man eine Transform-Klasse schreibt oder einen Async-Generator, ist zu einem guten Teil Geschmackssache. Ich greife zur Klasse, wenn ich internen Zustand über viele Werte halten muss, etwa bei einer Aggregation mit `_flush`. Für reine Filter und Umformungen sind Async-Generatoren oft der kürzere, besser lesbare Weg.\n\n## Zwei Fallstricke, die immer wieder zuschlagen\n\nDer erste Fallstrick ist das Mischen von Byte- und Objektmodus in einer Pipeline. Man beginnt mit `fs.createReadStream(...)`, das ist ein Byte-Stream und liefert Buffer. Direkt danach hängt man eine Objektmodus-Stufe, die mit `record.status` arbeiten will – und bekommt einen Buffer statt eines Objekts. Zwischen einem Byte-Readable und der ersten Objektstufe muss immer eine Parse-Schicht liegen, die Buffer zu Werten dekodiert. Die umgekehrte Naht ist genauso heikel: Schiebt man ein Objekt in einen Nicht-Objektmodus-Writable, quittiert Node das mit einem Typfehler (`ERR_INVALID_ARG_TYPE`), der einen String, Buffer oder ein Uint8Array verlangt. Man sollte sich an jeder Nahtstelle bewusst machen, was für ein Datentyp gerade fließt.\n\nDer zweite betrifft `null` als legitimen Nutzwert. Weil `push(null)` das Ende des Streams bedeutet, kann man einen echten `null`-Wert nicht durch einen Objektmodus-Stream schicken – er würde als Schlusssignal missverstanden und die restlichen Daten abschneiden. Wenn `null` in den Nutzdaten eine echte Bedeutung hat, braucht es ein Ersatzobjekt, einen sogenannten Sentinel, etwa `{ value: null }` statt eines nackten `null`.\n\nEin dritter Punkt gehört zur Sorgfalt: Fehler in `_transform` gibt man an `callback(err)` weiter, statt sie zu werfen. Nur so landen sie im Fehlerkanal des Streams und werden von `pipeline()` sauber propagiert. Ein geworfener Fehler mitten in der asynchronen Verarbeitung ist deutlich schwerer einzufangen – auch das ist ein Argument für `pipeline()` gegenüber einer nackten `pipe()`-Kette.\n\n## Fazit\n\nDer Objektmodus verwandelt Node.js-Streams von einem I/O-Werkzeug für Bytes in ein Werkzeug für Datenverarbeitung. Die Mechanik bleibt vertraut – `_transform` mit `push` und `callback`, `_flush` fürs Aggregieren, Verkettung über `pipeline()` –, aber der Inhalt sind jetzt ganze JS-Werte. Damit lassen sich Pipelines aus parsen, filtern, transformieren und aggregieren als getrennte, komponierbare Stufen bauen, die immer nur einen kleinen Vorrat an Datensätzen im Speicher halten.\n\nZwei Dinge nehme ich als Kernbotschaft mit. Erstens: `highWaterMark` zählt im Objektmodus Objekte, nicht Bytes – wer das verwechselt, dimensioniert seinen Puffer um Größenordnungen falsch. Zweitens: `Readable.from` und `for await ... of` sind die moderne Brücke zwischen Streams und Async-Iteratoren und ersparen einem in vielen Fällen die eigene Stream-Klasse. Wer den byteorientierten Teil aus dem Beitrag zu [Buffers und Binärdaten](https://www.mikebild.dev/de/blog/nodejs-buffers-und-binaerdaten/) verstanden hat und den Objektmodus dazunimmt, hat beide Hälften der Stream-Welt beisammen – die rohe und die strukturierte.\n\n## Weiterführende Quellen\n\n- [Node.js Stream API – Object mode](https://nodejs.org/api/stream.html#object-mode)\n- [Node.js Stream API – Buffering](https://nodejs.org/api/stream.html#buffering)\n- [Node.js Stream API – stream.Readable.from](https://nodejs.org/api/stream.html#streamreadablefromiterable-options)\n- [Node.js Stream API – readable[Symbol.asyncIterator]](https://nodejs.org/api/stream.html#readablesymbolasynciterator)\n- [Node.js Stream API – Class: stream.Transform](https://nodejs.org/api/stream.html#class-streamtransform)"},{"locale":"de","translation_key":"reproduzierbare-testpipelines-kein-flaky","slug":"reproduzierbare-testpipelines-kein-flaky","title":"Reproduzierbare Testpipelines: kein Flaky, kein Zufall","summary":"Flakiness weist auf unkontrollierte Eingaben oder Abhängigkeiten hin. Wer Zeit, Daten und Isolation sichtbar macht, kann die Ursache eingrenzen und das Merge-Gate wieder belastbar machen.","tags":["Software","Delivery"],"published_at":"2022-10-26T10:00:00+00:00","updated_at":"2026-07-13T13:23:46.335954+00:00","url":"https://www.mikebild.dev/de/blog/reproduzierbare-testpipelines-kein-flaky/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/2714517852c87864d04f2c7f2ab983776d9a61f1e064a8a1c43dfdf1276d1b66/reproduzierbare-testpipelines-kein-flaky-vorlesen.mp3","audio_duration_secs":672,"text":"```text\n$ git rev-parse HEAD\n9f2c1ab\n\nLauf 412   FAIL  checkout.spec.ts › Rabatt gilt bis Monatsende   (2.1s)\nLauf 413   PASS  checkout.spec.ts › Rabatt gilt bis Monatsende   (2.0s)\n```\n\nDerselbe Commit, zwei Läufe, zwei Ergebnisse. Wenn sich am Code nichts geändert hat und das Ergebnis trotzdem kippt, dann liest der Test eine weitere Eingabe, die nicht im Repository steht. „Lass den Build noch einmal laufen, der ist manchmal einfach rot“ ist deshalb keine Diagnose. Es ist das Eingeständnis, dass niemand weiß, welche Eingabe das ist.\n\nEin Test, der ohne Codeänderung sein Ergebnis wechselt, reagiert auf eine weitere Eingabe. Häufig steckt sie in Zeit, Daten oder fehlender Isolation. Bei Integrationstests können auch Netz, Cloud-Dienste oder andere externe Systeme real schwanken. Nicht jede Abhängigkeit lässt sich einfrieren; sichtbar machen, begrenzen und im Testtyp benennen muss ich sie trotzdem. Sonst gewöhnt sich das Team daran, dass die eigene Testsuite mal grün und mal rot meldet, und verliert das Vertrauen in sein Merge-Gate.\n\n## Warum das ein Business-Problem ist, kein Test-Detail\n\nBevor es zur Mechanik geht, der Grund, warum das Thema nicht im Testverzeichnis endet: Eine flaky Suite bleibt kein Ärgernis der Entwickler. Sie bremst die gesamte Lieferfähigkeit.\n\nMartin Fowler hat das schon 2011 auf den Punkt gebracht. Ein nicht-deterministischer Test ist nicht nur nutzlos – er ist eine „virulente Infektion“. Sobald ein einziger Test gelegentlich grundlos rot wird, gewöhnen sich alle daran, rote Builds zu ignorieren. Genau in diesem Moment schützt die Suite nichts mehr, denn ein echter Fehler sieht jetzt aus wie das übliche Rauschen. Der Schaden ist nicht der eine flaky Test, sondern der Vertrauensverlust, der sich auf die ganze Suite ausbreitet.\n\nDas ist kein akademisches Argument. Google hat 2016 im Testing Blog Zahlen genannt: rund 1,5 Prozent aller Testläufe sind flaky. Das klingt nach wenig, bis man es hochrechnet. Flaky Tests verstopfen die Pipeline, sperren Branches, erzeugen Duplikate von Bug-Tickets und verbrennen Entwicklerzeit im großen Stil – Zeit, die in Diagnose von Fehlern fließt, die gar keine sind.\n\nUnd genau hier schließt sich der Kreis zur Delivery-Performance. Accelerate (Forsgren, Humble, Kim, 2018) verbindet die vier bekannten Metrics – Deployment Frequency, Lead Time for Changes, Change Failure Rate und Time to Restore – mit gelebter Continuous Integration und *zuverlässiger* Testautomatisierung. Wichtig ist das Wort \"zuverlässig\". Ein Elite-Team, das on-demand deployt, kann das nur, weil die Suite ein vertrauenswürdiges Gate ist. Eine flaky Suite ist kein Gate, sondern eine Ampel, die zufällig schaltet – und niemand deployt auf Basis einer zufälligen Ampel. Ich lese die vier Metrics übrigens bewusst immer gemeinsam: eine hohe Deploy-Frequenz bei gleichzeitig hoher Change Failure Rate ist wertlos. Determinismus in der Suite ist eine der Bedingungen, unter denen diese Metrics überhaupt ehrlich werden.\n\nDer Gewinn liegt also nicht in \"schöneren Tests\". Er liegt in verkürzten Zyklen, weniger Reibung im Team und einer höheren Auslieferungsqualität. Determinismus gehört deshalb in die Architekturdiskussion und nicht auf die QA-Checkliste.\n\n## Die drei Achsen als Gate\n\nDie Diskussion lässt sich auf ein einfaches Bild reduzieren. Eine Pipeline läuft von links nach rechts: commit, build, test, merge. Über der Test-Stufe stehen drei Regler. Nur wenn alle drei auf \"kontrolliert\" stehen, wird das Gate grün und der Merge frei. Kippt einer in \"unkontrolliert\", entsteht flaky Rot.\n\n```mermaid\nflowchart LR\n  C[commit] --> B[build] --> T[test gate] --> M[merge]\n  A1[TIME<br/>frozen clock] --> T\n  A2[DATA<br/>seeded fixtures] --> T\n  A3[ISOLATION<br/>hermetic sandbox] --> T\n  T -->|all three controlled| M\n  T -->|any axis uncontrolled| F[flaky red]\n```\n\nDer Wert dieses Bildes liegt in der Diagnose. Wenn ein Build flaky ist, frage ich nicht \"welcher Test spinnt\", sondern \"welche der drei Achsen ist unkontrolliert\". Das führt fast immer schneller zur Ursache, weil es die Suche strukturiert. Gehen wir die Achsen einzeln durch.\n\n## Achse 1: Zeit\n\nDie häufigste versteckte Ursache. Sobald Domänencode direkt `new Date()` oder `Instant.now()` aufruft, ist er an die Wall-Clock gekoppelt – und die Wall-Clock ändert sich zwischen zwei Testläufen garantiert. Ein Test, der \"der Rabatt gilt bis Monatsende\" prüft, wird am 31. anders reagieren als am 1., ein Test mit `expiresAt` in genau 24 Stunden kippt an Zeitzonen- und DST-Grenzen.\n\nDie Lösung ist keine Bibliothek, sondern eine Entwurfsentscheidung: Die Uhr wird ein injizierter Dienst. Der Domänencode fragt nie das Betriebssystem, sondern immer die Abstraktion.\n\n```typescript\ninterface Clock {\n  now(): Date;\n}\n\nclass SystemClock implements Clock {\n  now(): Date {\n    return new Date();\n  }\n}\n\nclass FixedClock implements Clock {\n  constructor(private readonly instant: Date) {}\n  now(): Date {\n    return this.instant;\n  }\n}\n\n// domain code never calls `new Date()` directly:\nfunction isExpired(subscription: Subscription, clock: Clock): boolean {\n  return subscription.expiresAt.getTime() <= clock.now().getTime();\n}\n```\n\nIn Produktion läuft die `SystemClock`, im Test ein `FixedClock(new Date(\"2022-01-01T00:00:00Z\"))`. Das ist keine exotische Idee: Java hat mit `java.time.Clock` seit Version 8 genau diese Abstraktion eingebaut, in Ruby macht Timecop das seit 2011, in JavaScript liefern Sinons Fake Timers dasselbe. Ich bevorzuge die injizierte Uhr gegenüber globalem Time-Freezing, weil sie ehrlicher ist: Sie macht die Zeitabhängigkeit im Code sichtbar, statt sie global zu überschreiben.\n\nDamit es nicht zu einfach klingt: Zeit-Determinismus ist mehr als die Uhr einzufrieren. Zeitzonen, DST-Übergänge, Locale-abhängige Formatierung und die Sortierreihenfolge von Maps oder Sets sind eigene Nicht-Determinismus-Quellen. Die eingefrorene Uhr löst den großen Brocken, nicht alles.\n\n## Achse 2: Daten\n\nDie zweite Achse ist unscheinbar und richtet stillen Schaden an: Zufallsdaten. Ein `faker.name()` oder eine ungeseedete Zufallszahl macht jeden Testlauf einzigartig. Meistens geht das gut – bis der eine Datensatz auftaucht, der die Sortierung, eine Längenbegrenzung oder einen Unicode-Sonderfall kippt. Dann ist der Build rot, beim nächsten Lauf grün, und niemand kann es reproduzieren.\n\nDie Regel ist simpel: deterministische Daten. Entweder feste Fixtures oder ein geseedeter Zufallsgenerator. Der geseedete Weg ist oft der bessere, weil er Streuung behält und trotzdem reproduzierbar bleibt.\n\n```typescript\nimport seedrandom from \"seedrandom\";\n\nfunction makeRng(seed = \"1337\") {\n  return seedrandom(seed);\n}\n\n// same seed -> same sequence -> reproducible failures\nfunction buildUser(rng: () => number): User {\n  return {\n    id: Math.floor(rng() * 1_000_000),\n    tier: rng() > 0.5 ? \"premium\" : \"free\",\n  };\n}\n```\n\nInteressant ist, dass genau diese Regel im Contract Testing explizit festgeschrieben ist. Pact – seit 2013 im Einsatz für consumer-driven contracts – formuliert die Vorgabe \"use deterministic data, avoid random data\" ohne Wenn und Aber. Der Grund ist aufschlussreich: Wenn ein Kontrakt zufällige Daten enthält, wird er bei jedem Lauf als \"verändert\" markiert, obwohl sich fachlich nichts geändert hat. Nicht-deterministische Daten erzeugen also nicht nur flaky Tests, sondern flaky Verträge.\n\nContract Testing verdient hier eine kurze Würdigung, weil es die Datenachse mit der Isolationsachse verbindet. Statt dass ein Service den anderen startet, um \"echt\" zu testen, prüft jedes Consumer-Provider-Paar in Isolation gegen einen geteilten, deterministischen Kontrakt. Kein Netz, keine fremde Laufzeit, kein Timing – die klassischen Flaky-Quellen sind per Konstruktion ausgeschlossen.\n\n## Achse 3: Isolation\n\nDie dritte Achse ist die grundlegendste und trägt den treffenden Namen Hermetik. Die Bazel-Dokumentation verwendet „hermeticity“ für Builds und Tests, deren Werkzeuge und Eingaben bekannt und kontrolliert sind. Diese Abschottung von Netz, geteilter Datenbank und Host-Zustand entfernt wichtige versteckte Einflüsse; sie garantiert allein noch keinen Determinismus, wenn etwa Rennen, Zufall oder Zeit im Test unkontrolliert bleiben. Ein nicht hermetischer Test kann reproduzierbar sein, ist aber stärker von seiner Umgebung abhängig.\n\nDie zwei praktischen Feinde der Isolation sind geteilter Zustand und Test-Reihenfolge-Abhängigkeit. Wenn Test B nur grün ist, weil Test A vorher eine Zeile in die Datenbank geschrieben hat, dann ist die Suite eine Kette, die bei jeder Umsortierung reißt. Das Gegenmittel heißt shared-nothing: Jeder Test baut seinen Zustand auf und räumt ihn wieder ab.\n\nFür echte Abhängigkeiten wie Datenbank oder Message-Broker haben sich seit 2015 Testcontainers durchgesetzt: eine ephemere, weggeworfene Instanz pro Test statt einer geteilten, langlebigen Umgebung. Das folgende Skelett zeigt die Isolationsdisziplin kompakt – und es kombiniert bewusst alle drei Achsen:\n\n```typescript\nlet db: EphemeralDatabase;\nlet clock: Clock;\nlet rng: () => number;\n\nbeforeEach(async () => {\n  rng = makeRng(\"1337\");                       // DATA: seeded\n  clock = new FixedClock(FIXED_INSTANT);       // TIME: frozen\n  db = await startEphemeralContainer();         // ISOLATION: hermetic\n  await db.beginTransaction();\n});\n\nafterEach(async () => {\n  await db.rollbackTransaction();               // state reset, shared-nothing\n  await db.stop();\n});\n```\n\nDer Transaktions-Rollback pro Test ist mein bevorzugter Reset-Mechanismus, wo er geht: schnell und vollständig. Wo Transaktionen nicht reichen, tut es Truncation zwischen den Tests. Entscheidend ist nur das Prinzip: Kein Test darf davon abhängen, was ein anderer hinterlassen hat.\n\nFowlers Ursachenliste fällt übrigens exakt auf diese drei Achsen zurück. Er nennt lack of isolation, time, asynchrony beziehungsweise remote services und resource leaks. Als Fishbone gezeichnet:\n\n```mermaid\nflowchart LR\n  ISO[lack of isolation] --> S[flaky build]\n  TIME[time / clock] --> S\n  ASYNC[async / remote services] --> S\n  LEAK[resource leaks] --> S\n```\n\nDie Asynchronität verdient einen eigenen Satz, weil sie der klassische Flaky-Generator ist. Der häufigste Fehler ist ein `sleep(500)`, in der Hoffnung, dass eine asynchrone Operation \"wohl fertig\" ist. Auf einem langsamen CI-Runner ist sie es manchmal nicht. Der Fix ist nie eine längere Wartezeit, sondern Polling gegen eine echte Bedingung – warten, bis der Zustand tatsächlich eingetreten ist, mit einem Timeout als Obergrenze. \"Warte, bis\" statt \"warte, wie lange\".\n\n## Der ehrliche Umgang mit Retries\n\nBleibt das Thema, um das in solchen Diskussionen alle herumreden: der automatische Retry. Fast jedes CI-System bietet an, fehlgeschlagene Tests einfach nochmal laufen zu lassen, und wenn der zweite Lauf grün ist, gilt der Build als grün. Das ist verführerisch, weil es die roten Builds sofort verschwinden lässt.\n\nDie Einordnung ist eindeutig: Retries verstecken Nicht-Determinismus, sie beseitigen ihn nicht. Als kurzfristiges Notpflaster, um ein Team nicht komplett auszubremsen, kann ein begrenzter Retry vertretbar sein. Als Dauerlösung schaltet er genau das Signal aus, das man zur Ursachenanalyse braucht. Eine zeitlich begrenzte Quarantäne kann ehrlicher sein: Der Test läuft in einem separaten Job weiter, bekommt einen benannten Verantwortlichen und eine Frist. Der Haupt-Build wird davon nicht rot; die fehlende Abdeckung im Merge-Gate bleibt bis zur Reparatur jedoch ein bewusst eingegangenes Risiko.\n\n```yaml\n# conceptual pipeline stages\nstages:\n  - name: test\n    fail_on_red: true          # the trustworthy merge gate\n  - name: contract-verify\n    run: pact can-i-deploy --to prod\n  - name: quarantine\n    tests: tagged(\"flaky\")\n    fail_on_red: false         # does not block merge\n    on_red: open_bug_ticket    # but never silently ignored\n```\n\nDer Unterschied zwischen Retry und Quarantäne ist eine Haltungsfrage. Retry sagt: „Ich hoffe, es war Zufall.“ Quarantäne sagt: „Ich kenne die Lücke, ihren Besitzer und ihre Frist.“ Ohne diese drei Angaben wird auch die Quarantäne nur zum dauerhaften Ignorieren.\n\n## Fazit\n\nDer rote Faden ist einfacher, als die Menge der Bibliotheken vermuten lässt. Flakiness hat eine Ursache, aber nicht jede Ursache liegt vollständig in der Testfunktion. Zeit einfrieren, Daten festlegen und Isolation herstellen räumt die häufigsten hausgemachten Quellen aus. Externe Abhängigkeiten werden simuliert, gezielt beobachtet oder in einen eigenen Integrationstest verschoben, dessen Schwankungsbreite bekannt ist.\n\nUnd der Ertrag ist eben nicht \"grünere Dashboards\". Der Ertrag ist ein Merge-Gate, dessen Aussage das Team einschätzen kann. Wer flaky Tests als \"Pech\" abtut, gibt seine Qualitätskontrolle an den Zufall ab. Wer die verborgene Eingabe sucht und verbleibende Unsicherheit offen ausweist, kann auf einen roten Build wieder sinnvoll reagieren.\n\n## Weiterführende Quellen\n\n- Martin Fowler: \"Eradicating Non-Determinism in Tests\" (2011) – https://martinfowler.com/articles/nonDeterminism.html\n- Google Testing Blog: \"Flaky Tests at Google and How We Mitigate Them\" (2016) – https://testing.googleblog.com/2016/05/flaky-tests-at-google-and-how-we.html\n- Google Testing Blog: \"Where do our flaky tests come from?\" (2017) – https://testing.googleblog.com/2017/04/where-do-our-flaky-tests-come-from.html\n- Bazel: Hermeticity – https://bazel.build/basics/hermeticity und Test Encyclopedia – https://bazel.build/reference/test-encyclopedia\n- Pact: Consumer-driven contracts, deterministic data – https://docs.pact.io/\n- Forsgren, Humble, Kim: \"Accelerate\" (2018), DORA-Metrics – https://www.atlassian.com/devops/frameworks/dora-metrics\n- Ford, Parsons, Kua: \"Building Evolutionary Architectures\" (1. Auflage, 2017) – https://nealford.com/books/buildingevolutionaryarchitectures.html\n- Trunk-Based Development – https://trunkbaseddevelopment.com"},{"locale":"de","translation_key":"adapter-design-framework-grenzen","slug":"adapter-design-framework-grenzen","title":"Adapter-Design: wo Frameworks enden","summary":"Was ein Framework-Adapter wirklich leistet: der Vertrag über den Build-Output, die Übersetzung von Request und Response und die stillen Umgebungsannahmen an der Grenze zwischen SvelteKit und AWS.","tags":["Software","AWS","Cloud"],"published_at":"2022-10-12T10:00:00+00:00","updated_at":"2026-07-14T17:20:29.175417+00:00","url":"https://www.mikebild.dev/de/blog/adapter-design-framework-grenzen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/48b44a6738d412b8fa945afc676e4106aebe361bd7c552284962604ccdc680f9/adapter-design-framework-grenzen-vorlesen.mp3","audio_duration_secs":664,"text":"# Adapter-Design: wo Frameworks enden\n\nEin Adapter im SvelteKit-Sinn ist kein Entwurfsmuster aus dem Lehrbuch und auch kein Deployment-Werkzeug. Er ist ein Stück Code, das nach dem Build läuft, den Output des Frameworks entgegennimmt und daraus etwas erzeugt, das eine konkrete Plattform ausführen kann: ein Node-Server, eine Lambda-Function, ein Worker am Netzwerkrand. Er startet keine Prozesse, er bedient keine Requests, er provisioniert im Kern keine Infrastruktur. Er übersetzt.\n\nDie Definition klingt harmlos. Interessant ist, was sie impliziert: Ein Adapter ist genau die Stelle, an der ein Framework aufhört, Verantwortung zu übernehmen – und die Plattform anfängt. Alles vor dieser Stelle gehört dem Framework: Routing, Rendering, Datenladen, die Semantik einer Seite. Alles danach gehört der Plattform: Prozessmodell, Netzwerk, Dateisystem, Limits, Preisschild. Wer einen Adapter schreibt, zieht diese Grenze nicht selbst, aber er muss sie präzise nachzeichnen. Und dabei fällt auf, wie viele Entscheidungen auf beiden Seiten stillschweigend getroffen wurden.\n\nSeit Anfang des Jahres pflege ich einen solchen Adapter: `sveltekit-adapter-aws` bringt SvelteKit-Anwendungen per CDK auf Lambda, S3 und CloudFront. [Das Projekt selbst habe ich bereits vorgestellt](https://www.mikebild.dev/de/blog/sveltekit-adapter-aws/) – hier geht es um das, was ich beim Bauen über die Schnittstelle gelernt habe. Denn die eigentliche Erkenntnis steckt nicht im AWS-Teil, sondern in der Frage, die jeder Adapter beantworten muss: Was gehört auf welche Seite?\n\n## Der Vertrag über den Build-Output\n\nSvelteKit gibt einem Adapter erstaunlich wenig – und genau das ist gut. Die Schnittstelle besteht aus einem Objekt mit einem Namen und einer `adapt`-Funktion, die ein `builder`-Objekt bekommt. Der Builder ist der komplette Vertrag: Er liefert die Client-Assets, die prerenderten Seiten und den Server-Code, dazu ein Manifest mit den Routen-Metadaten. Mehr nicht.\n\n```js\nimport { writeFileSync } from 'node:fs';\n\nexport function adapter(options = {}) {\n  return {\n    name: 'sveltekit-adapter-aws',\n    async adapt(builder) {\n      const out = 'build';\n      builder.rimraf(out);\n\n      builder.writeClient(`${out}/assets`);        // static files for the CDN\n      builder.writePrerendered(`${out}/prerendered`);\n      builder.writeServer(`${out}/server`);        // the SSR part\n\n      const manifest = builder.generateManifest({ relativePath: './' });\n      writeFileSync(\n        `${out}/server/manifest.js`,\n        `export const manifest = ${manifest};`\n      );\n    }\n  };\n}\n```\n\nDas Framework sagt damit: Es gibt drei Sorten von Artefakten, und ich schreibe sie dir dorthin, wo du sie haben willst. Wohin sie am Ende gehören, wie sie ausgeliefert werden, was ein „Server\" auf deiner Plattform überhaupt ist – dein Problem. Für AWS heißt das konkret: Client-Assets und prerenderte Seiten wandern in einen S3-Bucket hinter CloudFront, der Server-Code wird mit esbuild zu einem Lambda-Bundle gebaut, und die Routing-Regeln der CDN-Verteilung müssen entscheiden, welcher Request an S3 geht und welcher an die Funktion.\n\n```mermaid\nflowchart LR\n  subgraph FW[Framework-Seite]\n    SRC[Quellcode] --> VITE[Vite-Build]\n    VITE --> CL[Client-Assets]\n    VITE --> PR[Prerenderte<br/>Seiten]\n    VITE --> SV[Server-Code +<br/>Manifest]\n  end\n  subgraph AD[Adapter]\n    CL --> MAP[Zuordnung,<br/>Bundling]\n    PR --> MAP\n    SV --> MAP\n  end\n  subgraph PF[Plattform-Seite]\n    MAP --> S3[S3-Bucket]\n    MAP --> LB[Lambda-Bundle]\n    S3 --> CF[CloudFront]\n    LB --> CF\n  end\n```\n\nDie Zuordnung im mittleren Kasten ist der Teil, den niemand sieht und in dem die meiste Arbeit steckt. Welche Pfade sind statisch, welche dynamisch? Was passiert mit einer prerenderten Seite, die auch eine Server-Route hat? Wer setzt die Cache-Header? Das Framework hat dazu eine Meinung, aber es erzwingt sie nicht – es kann sie gar nicht erzwingen, weil es die Plattform nicht kennt. Der Adapter muss die Meinung des Frameworks in die Mechanik der Plattform übersetzen, ohne dabei eine eigene, dritte Meinung zu erfinden.\n\n## Request und Response als gemeinsame Sprache\n\nZur Laufzeit ist der Vertrag noch schmaler. Der SvelteKit-Server spricht die Web-Standards: Er nimmt ein `Request`-Objekt aus der Fetch-API entgegen und gibt ein `Response`-Objekt zurück. Das ist eine bewusste und, wie ich finde, kluge Entscheidung – dieselben Typen, die im Browser seit Jahren existieren und die Deno Deploy und Cloudflare Workers ohnehin als natives Format verwenden. Die frisch gegründete WinterCG versucht gerade, genau diesen Kern serverseitiger Web-APIs über Runtimes hinweg zu vereinheitlichen. SvelteKit hat sich schon vorher darauf festgelegt.\n\nFür den Adapter bedeutet das: Seine Laufzeit-Aufgabe ist eine Hin- und eine Rückübersetzung. AWS spricht nicht Fetch, AWS spricht API-Gateway-Events. Der Handler in meinem Lambda-Bundle tut deshalb im Kern nur das hier:\n\n```js\nimport { Server } from './index.js';\nimport { manifest } from './manifest.js';\n\nconst server = new Server(manifest);\nawait server.init({ env: process.env });\n\nexport async function handler(event) {\n  const request = toRequest(event); // API Gateway event -> fetch Request\n  const response = await server.respond(request, {\n    getClientAddress: () => event.requestContext.http.sourceIp\n  });\n  return toLambdaResult(response); // fetch Response -> Lambda result\n}\n```\n\nDie beiden unscheinbaren Funktionen `toRequest` und `toLambdaResult` sind der Ort, an dem die Plattform ihre Eigenheiten zeigt. Ein API-Gateway-Event trägt Query-Parameter bereits zerlegt, der `Request` will eine vollständige URL. Binäre Antworten müssen Base64-kodiert werden, und ob etwas „binär\" ist, entscheidet der Adapter anhand des Content-Types – eine Heuristik, die man irgendwann zum ersten Mal falsch hat. Und `Set-Cookie` ist der Klassiker: Mehrere Cookies in einer Antwort werden von der `Headers`-Implementierung zu einer Zeile zusammengezogen, während API Gateway sie als separates Array erwartet.\n\n```js\nasync function toLambdaResult(response) {\n  const contentType = response.headers.get('content-type') || '';\n  const isBinary = !/^(text\\/|application\\/(json|javascript))/.test(contentType);\n\n  return {\n    statusCode: response.status,\n    headers: Object.fromEntries(response.headers.entries()),\n    // API Gateway expects cookies as a separate array\n    cookies: splitSetCookie(response.headers.get('set-cookie')),\n    body: isBinary\n      ? Buffer.from(await response.arrayBuffer()).toString('base64')\n      : await response.text(),\n    isBase64Encoded: isBinary\n  };\n}\n```\n\nNichts davon ist schwierig. Aber alles davon ist Verantwortung, die das Framework ausdrücklich nicht übernimmt – und auch nicht übernehmen sollte. Würde SvelteKit anfangen, API-Gateway-Eigenheiten zu kennen, müsste es morgen auch die von Azure, Google und jedem Hoster kennen, der eine eigene Event-Struktur erfindet. Die schmale Fetch-API ist die Grenze, die beide Seiten unabhängig hält.\n\n```mermaid\nsequenceDiagram\n  participant C as Client\n  participant CF as CloudFront\n  participant L as Lambda-Handler\n  participant K as SvelteKit-Server\n  C->>CF: HTTP-Request\n  CF->>L: API-Gateway-Event\n  L->>K: fetch Request\n  K-->>L: fetch Response\n  L-->>CF: statusCode, headers,<br/>cookies, body\n  CF-->>C: HTTP-Response\n```\n\n## Die stillen Annahmen der Umgebung\n\nDer dritte Teil der Grenze ist der unangenehmste, weil er in keiner Schnittstellen-Signatur steht: die Annahmen über die Umgebung. Eine SvelteKit-Anwendung darf in ihren Server-Routen fast beliebigen Node-Code ausführen. Was davon auf der Zielplattform funktioniert, weiß nur der Adapter – und oft erst der Betrieb.\n\nAuf Lambda sind mir drei Punkte immer wieder begegnet:\n\n- Das Dateisystem ist schreibgeschützt, bis auf `/tmp`. Wer im Server-Code Dateien ablegt, Caches auf Platte schreibt oder eine SQLite-Datei neben dem Code erwartet, fällt beim ersten echten Request auf die Nase – lokal mit `vite dev` funktioniert alles.\n- Umgebungsvariablen kommen aus der Funktionskonfiguration, nicht aus einer `.env`-Datei. SvelteKit hat dafür inzwischen den Hook `server.init({ env })`, über den der Adapter die Variablen explizit hineinreicht. Genau solche kleinen Übergabepunkte machen die Grenze ehrlich: Die Umgebung ist ein Parameter, kein globaler Zustand.\n- Streaming gibt es nicht. Lambda hinter API Gateway puffert die komplette Antwort und liefert sie am Stück aus, mit harten Größenlimits. Eine `Response` mit einem langsamen Stream als Body ist auf dieser Plattform schlicht nicht abbildbar – der Adapter muss den Stream einsammeln und materialisieren.\n\nDer letzte Punkt zeigt, warum Adapter-Design mehr ist als Format-Konvertierung. Das Framework verspricht mit dem `Response`-Typ eine Fähigkeit – streamende Bodies –, die die Plattform nicht einlösen kann. Der Adapter kann das nicht reparieren, er kann es nur sichtbar machen: dokumentieren, im Zweifel beim Build warnen, und die Antwort korrekt puffern statt sie abzuschneiden. Wo Framework-Versprechen und Plattform-Fähigkeit auseinanderlaufen, ist der Adapter derjenige, der die Differenz erklären muss.\n\n## Wenn sich die Framework-Seite bewegt\n\nSvelteKit ist im Oktober 2022 immer noch pre-1.0, und das merkt man als Adapter-Autor deutlicher als als Anwendungsentwickler. Seit Anfang des Jahres habe ich die Adapter-Integration mehrfach anfassen müssen: Aus `app.render(request)` wurde `server.respond(request, options)`, das Manifest-Format und die Builder-Methoden haben sich verschoben, und die große Routing-Umstellung im Spätsommer hat verändert, was überhaupt im Server-Output landet. Mit dem Wechsel auf Vite 3 kam noch die Werkzeug-Ebene dazu.\n\nIch will das nicht als Klage verstanden wissen – ein Framework vor 1.0 darf seine Schnittstellen ändern, dafür ist die Phase da. Aufschlussreich war etwas anderes: Jede dieser Änderungen hat mir gezeigt, welche meiner Annahmen zum Vertrag gehörten und welche ich mir nur eingebildet hatte. Wer eine Schnittstelle dreimal nachziehen muss, versteht sie danach besser als jemand, der sie einmal gelesen hat.\n\nPraktisch habe ich daraus zwei Konsequenzen gezogen. Erstens: Die SvelteKit-Version wird im Adapter-Projekt exakt gepinnt, und jede Aktualisierung ist ein bewusster Schritt mit eigenem Commit statt eines beiläufigen `npm update`. Zweitens: Der wichtigste Test ist kein Unit-Test der Konvertierungsfunktionen, sondern ein Beispielprojekt, das bei jeder Änderung wirklich gebaut und deployt wird. Ein Adapter ist Konsument einer instabilen API; die einzige belastbare Prüfung ist die, die den ganzen Weg geht – vom `vite build` bis zur HTTP-Antwort aus CloudFront. Alles andere testet nur die eigene Vorstellung vom Vertrag, nicht den Vertrag.\n\n## Dieselbe Grenze, andere Frameworks\n\nDie Frage „was gehört auf welche Seite\" stellt sich überall, nur beantworten die Frameworks sie unterschiedlich – und die Antworten sind aufschlussreich.\n\nNext.js hat keine Adapter-Schnittstelle. Die Plattform ist implizit Vercel, und wer woanders deployt, arbeitet sich an einem Output ab, der dafür nie gedacht war. Bemerkenswert finde ich, dass Vercel dieses Jahr mit der Build-Output-API den Spieß umgedreht hat: Dort definiert die Plattform ein dokumentiertes Verzeichnisformat, und beliebige Frameworks können sich darauf hinbauen. Das ist dieselbe Grenze, nur von der anderen Seite gezeichnet – statt „Framework definiert, Adapter übersetzt\" gilt „Plattform definiert, Framework liefert an\". Wer den Vertrag besitzt, hat die Macht über die Grenze.\n\nRemix wiederum hat die Übersetzung von Anfang an eingebaut: `createRequestHandler` nimmt plattformspezifische Requests entgegen, und offizielle Adapter existieren für Express, Architect und Cloudflare Workers. Auch dort ist der Kern identisch mit dem, was SvelteKit macht – Web-Standard-`Request` rein, Web-Standard-`Response` raus, und drumherum eine dünne Schicht Plattform-Dialekt. Je konsequenter sich Frameworks auf diese Standards festlegen, desto dünner werden die Adapter. Im besten Fall schrumpft die Laufzeit-Übersetzung auf null, wie bei Deno Deploy und den Workers, die Fetch nativ sprechen, und es bleibt nur noch der Build-Output-Teil übrig.\n\n## Was ich daraus mitnehme\n\nEin Adapter ist die ehrlichste Stelle einer Framework-Architektur, weil sich dort nichts wegabstrahieren lässt. Auf der einen Seite steht, was das Framework wirklich garantiert: drei Sorten Artefakte, ein Manifest, eine Fetch-API. Auf der anderen Seite steht, was die Plattform wirklich verlangt: ihr Event-Format, ihr Dateisystem, ihre Limits. Der Adapter dazwischen sollte langweilig und dünn sein. Wird er dick, ist das ein Befund – dann garantiert das Framework zu wenig, oder die Plattform verlangt zu viel, und beides sollte man wissen, bevor man eine Anwendung darauf baut.\n\nDeshalb lohnt sich der Blick in den Adapter auch für alle, die nie einen schreiben werden. Wer versteht, was `adapter-node` oder ein AWS-Adapter im Detail tun, weiß genau, welche Annahmen die eigene Anwendung an ihre Umgebung stellt – und welche davon beim nächsten Plattformwechsel brechen. Die Grenze zwischen Framework und Plattform verschwindet nicht dadurch, dass man sie ignoriert. Sie wird nur unsichtbar. Ein guter Adapter macht sie wieder sichtbar, und das ist mehr wert als jedes Feature, das er sonst noch mitbringt.\n\n## Weiterführende Quellen\n\n- Mein Adapter-Projekt: https://github.com/MikeBild/sveltekit-adapter-aws\n- SvelteKit-Doku zu Adaptern: https://svelte.dev/docs/kit/adapters\n- SvelteKit-Doku „Writing adapters\": https://svelte.dev/docs/kit/writing-adapters\n- Remix Server Adapters: https://v2.remix.run/docs/other-api/adapter"},{"locale":"de","translation_key":"rxjs-in-react-datenfluss","slug":"rxjs-in-react-datenfluss","title":"RxJS in React: Observables im Datenfluss der Oberfläche","summary":"RxJS glänzt in React nicht überall, sondern genau dort, wo asynchrone Events koordiniert werden müssen – entprellte Eingaben, abgebrochene Autocomplete-Requests, kontinuierliche Ströme. Der Beitrag zeigt die wenigen Stellen, an denen sich Observables wirklich lohnen, und wo useState völlig genügt.","tags":["Software","Frontend","React"],"published_at":"2022-10-05T10:00:00+00:00","updated_at":"2026-07-13T10:04:28.27524+00:00","url":"https://www.mikebild.dev/de/blog/rxjs-in-react-datenfluss/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/43d132efa1f894e5eabdffa63e9f074587a13970fae4002aeebe61d73aaa2a44/rxjs-in-react-datenfluss-vorlesen.mp3","audio_duration_secs":618,"text":"Ein Observable ist kein Zustandsspeicher. Es hält keinen Wert bereit, den eine Komponente auslesen könnte, und es ersetzt kein `useState`. Es beschreibt eine Ausführung, die Werte über die Zeit an ihre Abonnenten schiebt und die sich jederzeit abbrechen lässt. Wer diese Definition ernst nimmt, hat die Frage nach RxJS in React halb beantwortet: Wo es nur um den aktuellen Wert eines Feldes geht, trägt ein Observable nichts bei. Es zahlt sich erst aus, wo die Zeitachse selbst zum Problem wird.\n\n**Redaktionelle Einordnung (Juli 2026):** Die gezeigten component-lokalen Subscriptions mit `useEffect` und Cleanup bleiben sinnvoll. Wird ein RxJS-basierter State dagegen als externer Store von mehreren Komponenten gelesen, braucht React einen stabilen Snapshot-Vertrag, typischerweise über `useSyncExternalStore` oder eine darauf aufbauende Adapter-Bibliothek. Der Beitrag bleibt bewusst bei der Koordination von Events und macht RxJS nicht zur allgemeinen State-Lösung.\n\nAn dieser Unterscheidung hängt die ganze Diskussion, die in React-Teams meist verhakt läuft. Wer RxJS aus dem Angular-Umfeld kennt, verbindet damit oft Pipelines, die quer durch die Anwendung liefen und niemand mehr überblickte. Wer Streams nur von außen kennt, findet sie elegant und würde den kompletten Komponentenzustand in Observables gießen. Beide Positionen verfehlen den schmalen Bereich, um den es tatsächlich geht: Tastenanschläge, die schneller kommen, als eine API antwortet. Antworten, die in der falschen Reihenfolge eintreffen. Verbindungen, die einfach weitersenden. Diese drei Fälle nehme ich hier auseinander – und danach die Stellen, an denen die React-Bordmittel die bessere Wahl bleiben.\n\n## Kurz eingeordnet: Was ein Observable in diesem Kontext ist\n\nIch setze die Grundlagen aus [RxJS: Push und Pull](https://www.mikebild.dev/de/blog/rxjs-push-und-pull/) hier voraus – der Beitrag erklärt, warum ein Observable ein Push-Producer ist und wie er sich von Promises und Iteratoren unterscheidet. Für den React-Kontext sind drei Eigenschaften entscheidend.\n\nEin Observable ist erstens *lazy*: Der Code im `subscribe`-Callback läuft erst, wenn tatsächlich jemand `subscribe()` aufruft. Ein Observable, das niemand abonniert, tut nichts. Zweitens ist ein normales Observable per Default *cold* und *unicast* – jede Subscription startet ihre eigene Ausführung. Drittens gibt `subscribe()` eine `Subscription` zurück, und über deren `unsubscribe()` wird die Ausführung wieder beendet.\n\nDiese drei Punkte zusammengenommen erklären, warum RxJS und der `useEffect`-Lifecycle so gut zusammenpassen: Ein Effect hat genau die Struktur „aufsetzen beim Mount, aufräumen beim Unmount“, die ein Observable braucht.\n\n```ts\nimport { Observable } from 'rxjs';\n\n// A cold observable: the callback runs once per subscriber\nconst ticker$ = new Observable<number>((subscriber) => {\n  let count = 0;\n  const id = setInterval(() => subscriber.next(count++), 1000);\n\n  // teardown logic runs on unsubscribe\n  return () => clearInterval(id);\n});\n\nconst subscription = ticker$.subscribe((value) => console.log(value));\n// later, to stop and clean up:\nsubscription.unsubscribe();\n```\n\nWer den Aufbau dieses `subscribe`/`unsubscribe`-Musters verinnerlicht hat, erkennt sofort die Parallele zur Cleanup-Function von `useEffect`. Das ist kein Zufall, sondern der eigentliche Grund, warum die Integration so geradlinig ist.\n\n## Der erste sinnvolle Fall: Eingaben entprellen\n\nDas klassische Beispiel ist ein Suchfeld. Bei jedem Tastenanschlag einen HTTP-Request abzufeuern ist verschwenderisch – der Nutzer tippt „React“, und schon sind sechs Requests unterwegs, von denen fünf sofort veraltet sind. Die naive React-Lösung baut hier einen `setTimeout` mit `clearTimeout` im Effect zusammen. Das funktioniert, wird aber schnell unübersichtlich, sobald mehr als nur Entprellung dazukommt.\n\nMit RxJS wird die Entprellung zu einem einzigen deklarativen Operator. `debounceTime(300)` emittiert einen Wert erst, wenn 300 Millisekunden lang kein neuer Wert nachgekommen ist. Ich speise die Eingaben über ein `Subject` ein – ein Subject ist zugleich Observable und Observer, ich kann also im `onChange`-Handler `next()` aufrufen und am anderen Ende die Pipeline abonnieren.\n\n```tsx\nimport { useEffect, useRef, useState } from 'react';\nimport { Subject } from 'rxjs';\nimport { debounceTime, distinctUntilChanged } from 'rxjs/operators';\n\nfunction SearchField() {\n  const query$ = useRef(new Subject<string>()).current;\n  const [debounced, setDebounced] = useState('');\n\n  useEffect(() => {\n    const subscription = query$\n      .pipe(debounceTime(300), distinctUntilChanged())\n      .subscribe(setDebounced);\n\n    return () => subscription.unsubscribe();\n  }, [query$]);\n\n  return (\n    <input\n      type=\"search\"\n      onChange={(event) => query$.next(event.target.value)}\n      placeholder=\"Enter search term\"\n    />\n  );\n}\n```\n\nZwei Details gehen in Code-Reviews regelmäßig unter. Das `Subject` lege ich mit `useRef` an, damit es über Re-Renders hinweg stabil bleibt – würde ich es im Render-Body neu erzeugen, hätte jeder Render sein eigenes Subject, und die Verbindung zwischen Handler und Pipeline bräche. Und `distinctUntilChanged()` filtert identische aufeinanderfolgende Werte heraus, damit ein Fokuswechsel ohne Textänderung keinen neuen Durchlauf auslöst.\n\n## Der Fall, in dem RxJS wirklich glänzt: Autocomplete mit switchMap\n\nEntprellen alleine rechtfertigt RxJS noch nicht – das bekommt man auch mit einem Timeout hin. Was RxJS trägt, ist das Verwerfen veralteter Requests. Genau hier liegt das eigentliche Race-Condition-Problem eines Autocomplete: Ich tippe „re“, ein Request geht raus. Ich tippe „rea“, ein zweiter Request geht raus. Wenn nun die Antwort auf „re“ *nach* der Antwort auf „rea“ eintrifft, überschreibt das veraltete Ergebnis das aktuelle. Die Oberfläche zeigt Treffer zu einem Suchbegriff an, der gar nicht mehr im Feld steht.\n\n`switchMap` löst das per Konstruktion. Der Operator abonniert das innere Observable – hier den HTTP-Request – und cancelt die vorherige innere Subscription, sobald ein neuer Wert von außen kommt. Kombiniert mit `fromFetch` und dessen `AbortController` wird der veraltete Request nicht nur ignoriert, sondern real abgebrochen.\n\n```tsx\nimport { useEffect, useRef, useState } from 'react';\nimport { Subject } from 'rxjs';\nimport { fromFetch } from 'rxjs/fetch';\nimport {\n  debounceTime,\n  distinctUntilChanged,\n  filter,\n  switchMap,\n} from 'rxjs/operators';\n\ntype Hit = { id: string; label: string };\n\nfunction Autocomplete() {\n  const query$ = useRef(new Subject<string>()).current;\n  const [results, setResults] = useState<Hit[]>([]);\n\n  useEffect(() => {\n    const subscription = query$\n      .pipe(\n        debounceTime(300),\n        distinctUntilChanged(),\n        filter((term) => term.length > 1),\n        switchMap((term) =>\n          fromFetch(`/api/search?q=${encodeURIComponent(term)}`).pipe(\n            switchMap((response) => response.json() as Promise<Hit[]>),\n          ),\n        ),\n      )\n      .subscribe(setResults);\n\n    return () => subscription.unsubscribe();\n  }, [query$]);\n\n  return (\n    <div>\n      <input onChange={(event) => query$.next(event.target.value)} />\n      <ul>\n        {results.map((hit) => (\n          <li key={hit.id}>{hit.label}</li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n```\n\nDer entscheidende Unterschied hängt an einem einzigen Operatornamen. Wer hier aus Gewohnheit `mergeMap` schreibt, lässt alle Requests parallel weiterlaufen, und das oben beschriebene Race-Condition-Problem ist wieder da. Für „nur die letzte Eingabe zählt“ ist `switchMap` die richtige Wahl. Der Unterschied wird greifbar, wenn man die Pipeline einmal bewusst mit `mergeMap` baut und gegen eine künstlich verlangsamte API laufen lässt: Die veralteten Treffer blitzen dann sichtbar in der Liste auf, bevor das aktuelle Ergebnis sie ersetzt.\n\nDas folgende Diagramm zeigt den Datenfluss der Pipeline von der Eingabe bis zum Re-Render.\n\n```mermaid\nflowchart LR\n  A[\"Input-Event<br/>onChange\"] --> B[\"Subject.next(term)\"]\n  B --> C[\"debounceTime(300)<br/>Ruhephase abwarten\"]\n  C --> D[\"distinctUntilChanged<br/>Duplikate filtern\"]\n  D --> E[\"switchMap<br/>alten Request verwerfen\"]\n  E --> F[\"subscribe<br/>setResults\"]\n  F --> G[\"React Re-Render\"]\n```\n\nWichtig ist die Cancellation-Semantik von `switchMap`, weil sie der Kern des Ganzen ist. Das zweite Diagramm stellt sie als Sequenz dar: Die Eingabe „rea“ bricht den noch offenen inneren Stream von „re“ ab, sodass nur die Antwort zur letzten Eingabe im State landet.\n\n```mermaid\nsequenceDiagram\n  participant U as Nutzer\n  participant P as Pipeline (switchMap)\n  participant A as API\n  U->>P: Eingabe \"re\"\n  P->>A: Request \"re\"\n  U->>P: Eingabe \"rea\"\n  Note over P: switchMap cancelt<br/>inneren Stream \"re\"\n  P--xA: Request \"re\" abgebrochen\n  P->>A: Request \"rea\"\n  A-->>P: Antwort \"rea\"\n  P->>U: setResults (nur letzte Antwort)\n```\n\n## Kontinuierliche Ströme: WebSockets und Events\n\nDer dritte Fall, in dem sich RxJS auszahlt, sind Quellen, die nicht ein einzelnes Ergebnis liefern, sondern über die Zeit immer weiter emittieren. WebSockets sind das offensichtliche Beispiel. RxJS bringt mit `webSocket` aus `rxjs/webSocket` einen bidirektionalen Wrapper mit, der zugleich Observable und Observer ist – ich kann eintreffende Nachrichten abonnieren und über `next()` selbst welche senden. Das Detail, das hier Gold wert ist: `unsubscribe()` schließt die Verbindung sauber.\n\n```tsx\nimport { useEffect, useState } from 'react';\nimport { webSocket } from 'rxjs/webSocket';\n\ntype Message = { id: string; text: string };\n\nfunction LiveFeed() {\n  const [messages, setMessages] = useState<Message[]>([]);\n\n  useEffect(() => {\n    const socket$ = webSocket<Message>('wss://example.com/feed');\n\n    const subscription = socket$.subscribe((message) =>\n      setMessages((prev) => [...prev, message]),\n    );\n\n    // unsubscribe closes the underlying socket\n    return () => subscription.unsubscribe();\n  }, []);\n\n  return (\n    <ul>\n      {messages.map((message) => (\n        <li key={message.id}>{message.text}</li>\n      ))}\n    </ul>\n  );\n}\n```\n\nDie Grundlagen hinter solchen Message-Strömen beschreibe ich in [RxJS: Push und Pull](https://www.mikebild.dev/de/blog/rxjs-push-und-pull/). Bidirektionale Kanäle ändern an diesem Modell nichts: Senden und Empfangen bleiben zwei getrennte Ströme.\n\nEine Variante zu `fromEvent` gehört noch dazu, weil sie eine Stolperstelle offenlegt. `fromEvent` hängt sich an einen echten DOM-Knoten, nicht an Reacts synthetisches Event-System. Man braucht also eine `ref`, und die ist erst nach dem Mount gesetzt:\n\n```tsx\nimport { useEffect, useRef, useState } from 'react';\nimport { fromEvent } from 'rxjs';\nimport { map, debounceTime } from 'rxjs/operators';\n\nfunction ScrollTracker() {\n  const boxRef = useRef<HTMLDivElement>(null);\n  const [position, setPosition] = useState(0);\n\n  useEffect(() => {\n    const node = boxRef.current;\n    if (!node) return;\n\n    const subscription = fromEvent(node, 'scroll')\n      .pipe(\n        map((event) => (event.target as HTMLElement).scrollTop),\n        debounceTime(50),\n      )\n      .subscribe(setPosition);\n\n    return () => subscription.unsubscribe();\n  }, []);\n\n  return <div ref={boxRef}>{/* scrollable content */}</div>;\n}\n```\n\n## Der Fallstrick, der jeden einmal erwischt: fehlendes unsubscribe\n\nWenn eine RxJS-React-Komponente unerklärlich Speicher frisst oder eine Warnung „setState on an unmounted component“ wirft, ist die Ursache fast immer dieselbe: Die Cleanup-Function fehlt oder gibt die Subscription nicht frei. Ohne `unsubscribe()` läuft der Stream nach dem Unmount weiter. Der Event-Listener bleibt hängen, der Timer tickt weiter, der WebSocket bleibt offen – und jeder emittierte Wert ruft ein `setState` auf einer Komponente auf, die es nicht mehr gibt.\n\n```tsx\n// Wrong: no cleanup, the stream keeps running after unmount\nuseEffect(() => {\n  interval(1000).subscribe((n) => setTick(n)); // memory leak\n}, []);\n\n// Right: keep the subscription and release it in cleanup\nuseEffect(() => {\n  const subscription = interval(1000).subscribe((n) => setTick(n));\n  return () => subscription.unsubscribe();\n}, []);\n```\n\nDer zweite verwandte Fehler ist subtiler: die Pipeline im Render-Body statt im Effect aufzubauen. Ein `fromEvent(...).pipe(...)`, das bei jedem Render neu entsteht, produziert doppelte Listener und doppelte Subscriptions. Die Reihenfolge, die zuverlässig funktioniert: Die Quelle stabil halten (per `useRef` oder außerhalb der Komponente), die Subscription im Effect aufsetzen, im Cleanup abbauen, und das Dependency-Array sauber pflegen.\n\nAls Randnotiz für 2022: React 18 bringt mit `useSyncExternalStore` einen Mechanismus, um sich sauber an externe Stores – auch RxJS-basierte – zu binden. Für die hier gezeigten Fälle ist der `useEffect`-Weg aber völlig ausreichend, und ich würde `useSyncExternalStore` erst dann heranziehen, wenn ein Store wirklich außerhalb der Komponente liegt und von mehreren Stellen aus genutzt wird.\n\n## Wann RxJS sich lohnt – und wann nicht\n\nDie häufigste Fehlentscheidung ist, RxJS überall hineinzuziehen. Verhindern lässt sie sich mit zwei kurzen Listen.\n\nRxJS lohnt sich, wenn:\n\n- Eingaben zeitbasiert entprellt oder gedrosselt werden müssen, bevor ein teurer Effect läuft.\n- veraltete asynchrone Ergebnisse aktiv verworfen werden sollen (Autocomplete, konkurrierende Requests) – der Kernfall für `switchMap`.\n- kontinuierliche Ströme wie WebSockets, Server-Sent-Events oder Timer verarbeitet werden.\n- mehrere Event- und Zeitquellen kombiniert, gemischt oder zeitlich koordiniert werden müssen.\n\nRxJS lohnt sich nicht, wenn:\n\n- es um einfachen lokalen Komponentenzustand geht – dafür sind `useState` und `useReducer` da.\n- ein einzelner Request beim Mount geladen wird; ein `fetch` mit `AbortController` im Effect reicht, oder man greift zu einer Data-Fetching-Bibliothek.\n- das Team RxJS nicht beherrscht und die Anforderung keine echte asynchrone Koordination enthält – die Lernkurve zahlt sich dann nicht aus.\n\nDiese Trennung ist der eigentliche Kern des Beitrags. RxJS ist kein Ersatz für Reacts Zustandsmodell, sondern eine Ergänzung für einen schmalen, aber wichtigen Ausschnitt: die Koordination asynchroner Events über die Zeit. Wer Observables gezielt an diesen wenigen Stellen einsetzt und überall sonst bei den React-Bordmitteln bleibt, bekommt beides: deklarative Streams dort, wo sie echte Probleme lösen, und schlanke Komponenten im Rest der Anwendung. Und wer konsequent im Cleanup `unsubscribe()` aufruft, umgeht den einen Fehler, der sonst zuverlässig zurückkommt.\n\n## Weiterführende Quellen\n\n- [RxJS: Push und Pull](https://www.mikebild.dev/de/blog/rxjs-push-und-pull/) – die Grundlagen zu Observables als Push-Producer.\n- [Observable-Guide (rxjs.dev)](https://rxjs.dev/guide/observable)\n- [Operators-Guide / pipe (rxjs.dev)](https://rxjs.dev/guide/operators)\n- [Subject (rxjs.dev)](https://rxjs.dev/guide/subject)\n- [switchMap (rxjs.dev)](https://rxjs.dev/api/operators/switchMap)\n- [debounceTime (rxjs.dev)](https://rxjs.dev/api/operators/debounceTime)\n- [fromEvent (rxjs.dev)](https://rxjs.dev/api/index/function/fromEvent)\n- [Subscription / unsubscribe (rxjs.dev)](https://rxjs.dev/guide/subscription)\n- [React: Using the Effect Hook (reactjs.org)](https://reactjs.org/docs/hooks-effect.html)"},{"locale":"de","translation_key":"svelte-motion-transitions-animationen","slug":"svelte-motion-transitions-animationen","title":"Motion, Transitions und Animationen in Svelte","summary":"Wie Svelte Bewegung deklarativ und ohne Extra-Bibliothek mitbringt: transition-Direktiven fürs Ein- und Ausblenden, svelte/motion für sanft interpolierte Werte und animate:flip fürs Umsortieren von Listen.","tags":["Software","Frontend","Svelte"],"published_at":"2022-09-27T10:00:00+00:00","updated_at":"2026-07-13T07:58:57.049025+00:00","url":"https://www.mikebild.dev/de/blog/svelte-motion-transitions-animationen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/bd1ee46132158debdb3578dfd1f55510154a8638e740677e443ad9fd1b88d297/svelte-motion-transitions-animationen-vorlesen.mp3","audio_duration_secs":647,"text":"Ein Hinweis über der Liste taucht auf, und er ist einfach da – hart, ohne Übergang. Ein Eintrag wird gelöscht, und alles darunter rutscht schlagartig eine Zeile nach oben. In React-Projekten landet spätestens an dieser Stelle `react-transition-group` oder eine Animations-Runtime im `package.json`. In Svelte sind es drei Importe aus der Standardausstattung, und die Abhängigkeitsliste bleibt, wie sie war.\n\nDie drei Module sind aufeinander abgestimmt und decken zusammen fast alles ab, was im Alltag anfällt. Wer schon einmal verstanden hat, warum [Svelte ohne Virtual DOM auskommt und stattdessen zur Compile-Zeit Code erzeugt](https://www.mikebild.dev/de/blog/svelte-reaktivitaet-compiler-ohne-virtual-dom/), ahnt bereits, worauf das hinausläuft: Auch die Bewegung ist eng mit dem Compiler verwoben – er übersetzt die Direktiven in Code, der die Animation nach Möglichkeit über CSS-Keyframes statt über JavaScript pro Frame laufen lässt.\n\n**Redaktionelle Einordnung (Juli 2026):** Die Beispiele sind im Svelte-3-Stil geschrieben. `svelte/transition`, `svelte/animate` und `svelte/motion` gibt es auch in Svelte 5; geändert hat sich vor allem das umgebende Reaktivitätsmodell. Die alten Tutorial-URLs wurden durch die heutigen API-Seiten ersetzt.\n\n## Drei Werkzeuge, drei Aufgaben\n\nBevor wir Code schreiben, lohnt sich eine saubere Trennung im Kopf. Die drei Module haben unterschiedliche Zuständigkeiten, und die meisten Missverständnisse, die mir begegnet sind, entstehen daraus, dass jemand das falsche Werkzeug für die falsche Aufgabe greift.\n\n- `transition:` (aus `svelte/transition`) beschreibt, wie ein einzelnes Element in den DOM hinein- und wieder herauskommt. Es geht um Erscheinen und Verschwinden.\n- `animate:` (aus `svelte/animate`) beschreibt, wie sich Elemente bewegen, die im DOM bleiben, aber ihre Position ändern – also beim Umsortieren einer Liste.\n- `svelte/motion` (mit `tweened` und `spring`) hat mit dem DOM erst einmal gar nichts zu tun. Hier geht es um Werte, die sich weich von einem State zum nächsten interpolieren – eine Zahl, eine Farbe, eine Koordinate.\n\nDiese Dreiteilung ist der rote Faden für alles Weitere. Sobald klar ist, ob man ein Element auftauchen lässt, es innerhalb einer Liste verschiebt oder einen Wert gleiten lässt, ergibt sich das passende Modul fast von selbst.\n\n## Transitions: Ein- und Ausblenden\n\nEine Transition hängt man in Svelte als Direktive an ein Element. Sie wird ausgelöst, sobald das Element durch einen Kontrollfluss – ein `{#if}`, ein `{#each}` – in den DOM eintritt oder ihn verlässt. Das ist der entscheidende Punkt: Nicht ich rufe eine Animation auf, sondern die State-Änderung tut es. Ich beschreibe nur, wie sie aussieht.\n\n```svelte\n<script>\n  import { fade, fly } from 'svelte/transition';\n  let visible = true;\n</script>\n\n<label>\n  <input type=\"checkbox\" bind:checked={visible} />\n  toggle\n</label>\n\n{#if visible}\n  <p transition:fade={{ duration: 300 }}>\n    fades in and out\n  </p>\n\n  <div transition:fly={{ y: 20, duration: 300 }}>\n    flies in from below, flies back down on exit\n  </div>\n{/if}\n```\n\n`transition:` gilt bidirektional – dieselbe Bewegung läuft beim Einblenden vorwärts und beim Ausblenden rückwärts. Das ist häufig genau richtig. Manchmal aber möchte man asymmetrisch sein: hereinfliegen, aber verblassend verschwinden. Dafür gibt es die getrennten Direktiven `in:` und `out:`.\n\n```svelte\n<script>\n  import { fly, fade } from 'svelte/transition';\n  let visible = true;\n</script>\n\n{#if visible}\n  <div in:fly={{ y: 20, duration: 300 }} out:fade={{ duration: 200 }}>\n    enters flying, leaves fading\n  </div>\n{/if}\n```\n\nDas eingebaute Sortiment ist überschaubar und gut aufeinander abgestimmt: `fade`, `blur`, `fly`, `slide`, `scale`, `draw` und `crossfade`. Für den Alltag reichen die ersten fünf fast immer. `fly` nimmt `x` und `y` als Zahlen in Pixeln entgegen, `slide` blendet vertikal auf und zu, `scale` skaliert von einem Startwert her.\n\nEin Detail, das mir selbst erst beim genauen Hinsehen klar geworden ist: Eine Out-Transition braucht Zeit, und das Element bleibt für diese Dauer im DOM. Svelte entfernt es erst, wenn die Bewegung abgeschlossen ist. Wer also glaubt, ein Element sei schon weg, während es noch ausblendet, wundert sich über kurzzeitig doppelte Einträge. Das ist kein Fehler, sondern die Voraussetzung dafür, dass man das Verschwinden überhaupt sehen kann.\n\n## Was der Compiler intern daraus macht\n\nDer Grund, warum diese Transitions ohne Performance-Sorgen laufen, liegt darin, wie sie erzeugt werden. Eine Transition-Function liefert im Kern eine `css`-Funktion zurück, die für einen Fortschrittswert `t` (von 0 bis 1) einen CSS-String erzeugt. Aus dieser Funktion baut Svelte echte CSS-Keyframes. Die Animation läuft damit über die CSS-Engine des Browsers und blockiert nicht den Main-Thread mit JavaScript pro Frame.\n\n```mermaid\nflowchart LR\n  A[\"State change<br/>{#if} / {#each}\"] --> B[\"Svelte compiler\"]\n  B --> C[\"transition: / animate:<br/>directive\"]\n  C --> D{\"css function<br/>available?\"}\n  D -->|yes| E[\"CSS keyframes<br/>off main thread\"]\n  D -->|no| F[\"tick per frame<br/>JS on main thread\"]\n  E --> G[\"DOM update\"]\n  F --> G\n```\n\nNur wenn eine Bewegung sich nicht rein über CSS ausdrücken lässt – etwa weil man pro Frame einen Textinhalt ändern will –, greift der zweite Weg über eine `tick`-Funktion, die tatsächlich pro Frame in JavaScript läuft. Der Standardfall aber ist der performante CSS-Pfad, und man bekommt ihn geschenkt, ohne selbst Keyframes zu schreiben.\n\n## animate:flip für Listen\n\nKommen wir zum zweiten Werkzeug. `transition:` kümmert sich um Elemente, die kommen und gehen. Aber was ist mit Elementen, die bleiben und nur ihren Platz tauschen? Wenn ich eine Liste sortiere oder mische, springen die Einträge ohne Zutun hart an ihre neue Position. Genau hier setzt `animate:flip` an.\n\nDer Name FLIP steht für „First, Last, Invert, Play“ – eine bekannte Technik, bei der die alte und die neue Position eines Elements verglichen und die Differenz weganimiert wird. Svelte erledigt diese Rechnung für uns. Wichtig ist nur eine Bedingung: `animate:` funktioniert ausschließlich in einem keyed `{#each}`-Block, also einem `{#each}` mit einem stabilen Schlüssel. Ohne diesen Schlüssel kann Svelte gar nicht wissen, welches Element vorher wo war.\n\nDas folgende Beispiel bringt beide Werkzeuge zusammen – `transition:fly` fürs Ein- und Ausblenden neuer beziehungsweise entfallender Einträge und `animate:flip` fürs weiche Umsortieren der bleibenden:\n\n```svelte\n<script>\n  import { fly } from 'svelte/transition';\n  import { flip } from 'svelte/animate';\n\n  let items = [\n    { id: 1, label: 'apples' },\n    { id: 2, label: 'oranges' },\n    { id: 3, label: 'bananas' },\n    { id: 4, label: 'pears' }\n  ];\n\n  function shuffle() {\n    items = items\n      .map((item) => ({ item, sort: Math.random() }))\n      .sort((a, b) => a.sort - b.sort)\n      .map(({ item }) => item);\n  }\n\n  function remove(id) {\n    items = items.filter((item) => item.id !== id);\n  }\n</script>\n\n<button on:click={shuffle}>shuffle</button>\n\n<ul>\n  {#each items as item (item.id)}\n    <li\n      transition:fly={{ y: 20, duration: 300 }}\n      animate:flip={{ duration: 300 }}\n    >\n      {item.label}\n      <button on:click={() => remove(item.id)}>x</button>\n    </li>\n  {/each}\n</ul>\n```\n\nDer Schlüssel `(item.id)` ist hier nicht dekorativ, sondern trägt die ganze Mechanik. Er erlaubt es Svelte, dieselbe DOM-`<li>` über das Umsortieren hinweg als dasselbe Element zu erkennen und die Positionsdifferenz zu animieren. Das animierte Element muss außerdem direktes Kind des `{#each}`-Blocks sein. Wer stattdessen einen Wrapper dazwischenschiebt und `animate:flip` an das falsche Element hängt, sieht schlicht keine Bewegung – ein Klassiker, über den ich in Reviews immer wieder stolpere.\n\nDas Zusammenspiel von `transition` und `animate` in derselben Liste ist übrigens Absicht und gut abgestimmt: Neue Einträge fliegen herein, entfernte fliegen heraus und bleiben dafür kurz im DOM, und alle übrigen rutschen sanft auf ihre neuen Plätze. Drei Bewegungen, ein deklarativer Block.\n\n## svelte/motion: Werte, die gleiten\n\nDas dritte Werkzeug lässt den DOM zunächst außen vor. `tweened` und `spring` sind Stores – schreibbare Stores, wie ich sie im Artikel über [State außerhalb der Komponente mit Svelte Stores](https://www.mikebild.dev/de/blog/svelte-stores-zustand-ausserhalb-der-komponente/) beschrieben habe, nur mit einer Besonderheit: Wenn man ihren Wert setzt, springen sie nicht sofort auf das Ziel, sondern interpolieren dorthin. Man liest sie im Markup wie jeden Store mit dem `$`-Präfix.\n\n`tweened` interpoliert über eine feste Dauer und eine Easing-Funktion – gut für alles, was einem klaren zeitlichen Verlauf folgen soll, etwa ein Fortschrittsbalken.\n\n```svelte\n<script>\n  import { tweened } from 'svelte/motion';\n  import { cubicOut } from 'svelte/easing';\n\n  const progress = tweened(0, {\n    duration: 400,\n    easing: cubicOut\n  });\n</script>\n\n<progress value={$progress}></progress>\n\n<button on:click={() => progress.set(0)}>0%</button>\n<button on:click={() => progress.set(0.5)}>50%</button>\n<button on:click={() => progress.set(1)}>100%</button>\n```\n\n`spring` dagegen interpoliert nicht über eine Dauer, sondern über eine Physik – Steifigkeit und Dämpfung. Das Ergebnis wirkt lebendiger, weil es leicht nachfedert, statt exakt zu einem Zeitpunkt anzukommen. Für Dinge, die sich „natürlich“ anfühlen sollen, etwa ein Element, das der Maus folgt oder auf Eingaben reagiert, ist `spring` meist die schönere Wahl.\n\n```svelte\n<script>\n  import { spring } from 'svelte/motion';\n\n  const size = spring(1, {\n    stiffness: 0.1,\n    damping: 0.4\n  });\n</script>\n\n<div class=\"box\" style=\"transform: scale({$size})\">\n  {$size.toFixed(2)}\n</div>\n\n<button on:click={() => size.set(0.5)}>small</button>\n<button on:click={() => size.set(1)}>normal</button>\n<button on:click={() => size.set(2)}>large</button>\n\n<style>\n  .box {\n    width: 80px;\n    height: 80px;\n    background: #ff3e00;\n    display: grid;\n    place-items: center;\n    color: white;\n  }\n</style>\n```\n\nZwei Details fallen erst beim Arbeiten damit auf. Erstens geben `.set()` und `.update()` ein Promise zurück, das erst auflöst, wenn die Interpolation abgeschlossen ist – wer also darauf warten will, dass ein Wert „angekommen“ ist, kann das `await`en. Zweitens interpoliert Svelte Zahlen, Arrays und Objekte aus Zahlen automatisch; für andere Werttypen, etwa Farben in einer bestimmten Notation, gibt man `tweened` über die Option `interpolate` eine eigene Interpolationsfunktion mit.\n\nDie Parameter `stiffness` und `damping` lassen sich sogar zur Laufzeit anpassen. Man kann sie an Slider binden und live erleben, wie sich das Verhalten der Feder ändert. Das ist der schnellste Weg, ein Gefühl dafür zu bekommen, was die beiden Zahlen tatsächlich bewirken – schneller jedenfalls, als die Werte im Code zu raten und neu zu laden.\n\n## Eigene Transitions schreiben\n\nDer vielleicht schönste Beweis dafür, dass hier keine Blackbox arbeitet: Eine Transition ist nichts weiter als eine Funktion. Sie bekommt den DOM-Knoten und ihre Parameter und gibt ein Objekt zurück, das unter anderem eine `css`-Funktion enthält. Diese Funktion erhält den Fortschritt `t` von 0 bis 1 sowie den Gegenwert `u`, der `1 - t` entspricht, und liefert einen CSS-String.\n\n```js\nfunction spin(node, { duration = 400 }) {\n  return {\n    duration,\n    css: (t, u) => `\n      transform: rotate(${u * 360}deg) scale(${t});\n      opacity: ${t};\n    `\n  };\n}\n```\n\nVerwenden lässt sich diese eigene Transition exakt wie die eingebauten:\n\n```svelte\n<script>\n  import { spin } from './spin.js';\n  let visible = true;\n</script>\n\n{#if visible}\n  <div in:spin={{ duration: 600 }}>\n    spins into view\n  </div>\n{/if}\n```\n\nWenn man das einmal geschrieben hat, entzaubert sich der Rest von selbst. `fade`, `fly` und `scale` sind genau solche Funktionen – nur eben in der Bibliothek. Es gibt keinen zweiten, verborgenen Mechanismus. Genau diese Durchgängigkeit ist es, die ich an Sveltes Bewegungsmodell so schätze: Vom fertigen Einzeiler bis zur eigenen Funktion ist es ein durchgehendes Konzept, kein Bruch.\n\nZur Einordnung noch einmal die drei Werkzeuge im direkten Vergleich, damit die Zuordnung dauerhaft sitzt:\n\n- `transition:` / `in:` / `out:` – für das Erscheinen und Verschwinden einzelner Elemente, ausgelöst durch `{#if}` oder `{#each}`.\n- `animate:flip` – für Elemente, die im DOM bleiben und in einem keyed `{#each}` nur ihre Position tauschen.\n- `tweened` / `spring` aus `svelte/motion` – für interpolierte Werte, die man als Store mit `$` liest und ins Markup einbindet.\n\n## Fazit\n\nBewegung ist in Svelte keine Zusatzentscheidung, die man später mit einer Bibliothek nachrüstet, sondern ein Teil der Sprache. Das verändert die Art, wie man an das Thema herangeht. Statt zu fragen „Welches Paket nehme ich?“, fragt man „Erscheint hier etwas, verschiebt sich etwas, oder gleitet ein Wert?“ – und die Antwort führt direkt zu `transition:`, `animate:flip` oder `svelte/motion`.\n\nDer gemeinsame Nenner ist der deklarative Ansatz: Ich beschreibe, wie eine Bewegung aussieht, und der Compiler kümmert sich darum, dass sie ausgelöst wird, wenn sich der State ändert, und dass sie möglichst über CSS-Keyframes performant läuft. Dass eigene Transitions dieselben schlichten Funktionen sind wie die eingebauten, macht das Ganze lernbar bis auf den Grund. Für den Projektalltag heißt das: weniger Abhängigkeiten, weniger Boilerplate und mehr Zeit für die Frage, welche Bewegung eine Oberfläche wirklich verständlicher macht – statt für die Frage, welches Framework sie überhaupt ermöglicht.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-svelte.html\n- Repository zur Artikelreihe mit den lauffähigen Svelte-Beispielen\n- [`svelte/transition` – offizielle Dokumentation](https://svelte.dev/docs/svelte/svelte-transition)\n- [`svelte/animate` – offizielle Dokumentation](https://svelte.dev/docs/svelte/svelte-animate)\n- [`svelte/motion` – offizielle Dokumentation](https://svelte.dev/docs/svelte/svelte-motion)"},{"locale":"de","translation_key":"nodejs-buffers-und-binaerdaten","slug":"nodejs-buffers-und-binaerdaten","title":"Buffers in Node.js: mit Binärdaten arbeiten","summary":"Warum JS-Strings für rohe Bytes nicht taugen und Buffer Nodes Werkzeug dafür ist: alloc gegen allocUnsafe, Encodings sauber lesen und schreiben, und die Speicherfalle hinter slice und subarray.","tags":["Software","Node.js","Backend"],"published_at":"2022-08-09T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-buffers-und-binaerdaten/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/f79ce3a3f7b7ae540531c3cc02d79483ea907f28698d77a4b751c67810c56712/nodejs-buffers-und-binaerdaten-vorlesen.mp3","audio_duration_secs":667,"text":"Ein `Buffer` ist kein kaputter String. Wenn nach dem Einlesen einer Datei `<Buffer 89 50 4e 47 0d 0a 1a 0a ...>` in der Konsole steht, ist nichts schiefgegangen: Node zeigt genau das, was in der Datei liegt – eine Folge von Bytes, die keine Textbedeutung hat und auch keine bekommen soll.\n\nSolche Bytes kommen in Node aus vielen Richtungen: aus `fs`, aus offenen Netzwerkverbindungen, aus `crypto`. Der `Buffer` ist der Typ, in dem Node sie hält. Interessant an ihm sind vor allem die Stellen, an denen er sich anders verhält, als man es von Strings und Arrays gewohnt ist – beim Anlegen und beim Zerteilen.\n\n## Warum Strings hier nicht reichen\n\nEin JavaScript-String ist eine Folge von Unicode-Zeichen, keine Folge von Bytes. Das klingt nach Haarspalterei, ist aber der Kern des Problems. Sobald ich einen String habe, hat die Laufzeit bereits eine Interpretation vorgenommen: Diese Bytes sind Text, und zwar in einer bestimmten Kodierung. Rohe Binärdaten – ein PNG-Header, ein komprimierter Block, ein kryptografischer Schlüssel – haben aber gar keine Textbedeutung. Zwinge ich sie durch einen String, verliere oder verfälsche ich Bytes, weil ungültige Byte-Folgen durch Ersatzzeichen ausgetauscht werden. Das fällt oft erst spät auf, etwa wenn eine hochgeladene Datei am anderen Ende beschädigt ankommt.\n\nNode löst das mit `Buffer`: einem Bereich fester Byte-Länge, der genau die Bytes enthält, die man hineingelegt hat, ohne jede Umdeutung. Entscheidend ist dabei ein Detail, das vieles erklärt: Ein `Buffer` ist eine Unterklasse von `Uint8Array`, also selbst ein TypedArray. Alles, was man von `Uint8Array` kennt – Indexzugriff, `length`, `for`-Schleifen, die TypedArray-Methoden – funktioniert damit auch auf einem Buffer. `Buffer` fügt lediglich die für Node praktischen Extras hinzu, allen voran die Encodings.\n\n```js\nconst fs = require('node:fs');\n\nconst data = fs.readFileSync('image.png');\n\nconsole.log(Buffer.isBuffer(data));        // true\nconsole.log(data instanceof Uint8Array);   // true\nconsole.log(data.length);                  // number of bytes\nconsole.log(data.subarray(0, 8));          // <Buffer 89 50 4e 47 0d 0a 1a 0a>\n```\n\nDie ersten acht Bytes sind übrigens die feste Signatur einer PNG-Datei. Genau solche Header liest man in der Praxis, um Dateitypen zu erkennen, ohne sich auf die Endung zu verlassen.\n\n## Einen Buffer anlegen: alloc, allocUnsafe, from\n\nEs gibt drei Wege, an einen Buffer zu kommen, und die Unterschiede sind wichtig – auch aus Sicherheitsgründen.\n\n- `Buffer.alloc(size)` reserviert `size` Bytes und setzt sie alle auf `0`. Optional gibt man ein Füllbyte und ein Encoding mit. Das ist der sichere Standardweg, wenn man einen leeren Buffer bestimmter Größe braucht.\n- `Buffer.allocUnsafe(size)` reserviert ebenfalls `size` Bytes, initialisiert sie aber nicht. Der Inhalt ist alter Speicher – was vorher dort stand, steht weiter dort. Dafür ist das Anlegen messbar schneller, weil das Nullen entfällt und der Speicher gegebenenfalls aus einem internen Pool stammt.\n- `Buffer.from(...)` erzeugt einen Buffer aus vorhandenen Daten: aus einem String (mit Encoding), aus einem Array von Byte-Werten, aus einem anderen Buffer (kopiert) oder aus einem `ArrayBuffer`.\n\nDer Unterschied zwischen den ersten beiden ist kein Detail. `allocUnsafe` gibt Speicher zurück, der Reste früherer Allokationen enthalten kann – möglicherweise Daten aus ganz anderen Teilen des Programms.\n\n```js\nconst zeroed = Buffer.alloc(8);\nconsole.log(zeroed);        // <Buffer 00 00 00 00 00 00 00 00>\n\nconst uninitialized = Buffer.allocUnsafe(8);\nconsole.log(uninitialized); // <Buffer ?? ?? ?? ?? ?? ?? ?? ??> old memory\n```\n\n`alloc` ist deshalb die Voreinstellung; `allocUnsafe` lohnt sich nur dort, wo der Buffer unmittelbar danach ohnehin vollständig überschrieben wird. Wer `allocUnsafe` nutzt und den Speicher nur teilweise füllt, darf den Rest niemals ausgeben oder versenden, denn dort können sensible Daten stehen. Das ist die erste der beiden klassischen Fallen, und sie ist tückisch, weil sie im lokalen Test nie auffällt – auf einem frisch gestarteten Prozess ist der Speicher oft zufällig genullt. Erst unter Last, wenn der Pool wiederverwendet wird, tauchen die Datenreste auf.\n\nAm Rande, weil es in altem Code noch herumgeistert: Der frühere Aufruf `new Buffer(...)` ist seit Node 10 zur Laufzeit abgekündigt (DEP0005) und sollte nicht mehr verwendet werden. Und `Buffer.from(10)` erzeugt keinen Buffer der Größe 10, sondern wirft einen `TypeError` – eine Zahl ist für `Buffer.from` kein gültiges Argument. Wer eine Größe meint, nimmt `alloc` oder `allocUnsafe`.\n\n## Encodings: dieselben Bytes, andere Brille\n\nDer zweite große Nutzen von `Buffer` gegenüber einem nackten `Uint8Array` sind die Encodings. Ein Encoding ist keine Umwandlung der Bytes, sondern eine Vorschrift, wie man dieselben Bytes als Text liest oder wie man Text in Bytes zerlegt. Der Kreislauf zwischen beiden Seiten sieht so aus:\n\n```mermaid\ngraph LR\n  S[\"String<br/>(Unicode-Text)\"] -->|\"Buffer.from(str, enc)\"| B[\"Buffer<br/>(rohe Bytes)\"]\n  B -->|\"buf.toString(enc)\"| S\n  B -->|\"buf.toString('hex')\"| H[\"Hex-Text\"]\n  B -->|\"buf.toString('base64')\"| B64[\"Base64-Text\"]\n```\n\nBeim Hineinschreiben mit `Buffer.from(str, enc)` sage ich: Zerlege diesen Text nach dieser Regel in Bytes. Beim Herauslesen mit `buf.toString(enc)` sage ich: Deute diese Bytes nach dieser Regel als Text. Wichtig ist, dass beide Seiten dasselbe Encoding meinen, sonst kommt Unsinn heraus.\n\nDie gebräuchlichen Encodings lassen sich in zwei Gruppen teilen. Die einen beschreiben Text-zu-Bytes: `utf8` (der Standard), `utf16le`, `latin1` (auch `binary` genannt) und `ascii`. Die anderen sind Byte-zu-Text-Darstellungen, die beliebige Binärdaten druckbar machen: `hex`, `base64` und `base64url`. Gerade `hex` und `base64` braucht man ständig, etwa um einen Hash lesbar zu machen oder Binärdaten in JSON zu transportieren.\n\n```js\nconst buf = Buffer.from('Grüße', 'utf8');\n\nconsole.log(buf.length);            // 7 bytes, not 5\nconsole.log('Grüße'.length);        // 5 characters\n\nconsole.log(buf.toString('hex'));     // 4772c3bcc39f65 byte view as hex\nconsole.log(buf.toString('base64'));  // R3LDvMOfZQ== byte view as base64\n\nconst b64 = buf.toString('base64');\nconst back = Buffer.from(b64, 'base64').toString('utf8');\nconsole.log(back);                    // 'Grüße' again\n```\n\nDer interessante Punkt steht in den ersten beiden Zeilen: Der String hat fünf Zeichen, der Buffer aber sieben Bytes. Das ü und das ß belegen in UTF-8 jeweils zwei Bytes. Bytes und Zeichen sind eben nicht dasselbe, und wer `length` verwechselt, berechnet Offsets falsch. Genau daraus entsteht in der Praxis ein verwandtes Problem: Bei Streams kann ein Multibyte-Zeichen an der Stelle zerschnitten werden, an der ein Datenblock endet und der nächste beginnt. Für sauberes Dekodieren über solche Blockgrenzen hinweg gibt es den `string_decoder`, der halbe Zeichen zwischenpuffert – aber das ist ein Thema für sich, das der Beitrag [Node.js-Streams und Backpressure](https://www.mikebild.dev/de/blog/nodejs-streams-und-backpressure/) genauer ausführt.\n\n## Zahlen als Bytes: die Byte-Reihenfolge\n\nEncodings kümmern sich um Text. Sobald man aber ein Binärformat auseinandernimmt – einen Dateikopf, ein Netzwerkprotokoll, einen Frame – geht es um Zahlen, die über mehrere Bytes verteilt sind. Dafür bringt `Buffer` eine Reihe von Lese- und Schreibmethoden mit, die eine feste Anzahl Bytes an einem Offset als Ganzzahl deuten: `readUInt8`, `readUInt16BE`, `readUInt32LE`, dazu die vorzeichenbehafteten Varianten und für 64 Bit die `BigInt`-Fassungen wie `readBigUInt64BE`. Das Gegenstück zum Schreiben heißt `writeUInt32BE` und so fort.\n\nDas Kürzel am Ende ist der Punkt, an dem viele stolpern: `BE` steht für Big-Endian, `LE` für Little-Endian – also für die Frage, ob das höchstwertige Byte zuerst oder zuletzt steht. Wählt man beim Lesen die andere Reihenfolge als der Schreiber, bekommt man eine völlig andere Zahl heraus, ohne dass ein Fehler geworfen wird. Netzwerkprotokolle sind traditionell Big-Endian, viele Dateiformate legen ihre Reihenfolge selbst fest; man muss also im jeweiligen Format nachsehen und darf nicht raten.\n\n```js\nconst buf = Buffer.alloc(4);\n\nbuf.writeUInt32BE(0x89504e47, 0); // PNG signature bytes as one number\nconsole.log(buf);                 // <Buffer 89 50 4e 47>\n\nconsole.log(buf.readUInt32BE(0).toString(16)); // 89504e47\nconsole.log(buf.readUInt32LE(0).toString(16)); // 474e5089, reversed bytes\n```\n\nDieselben vier Bytes ergeben je nach gewählter Reihenfolge zwei verschiedene Zahlen. Der Buffer selbst weiß nicht, was richtig ist – die Bedeutung steckt im Format, nicht in den Bytes.\n\n## Die Speicherfalle: slice und subarray teilen den Speicher\n\nJetzt zur zweiten großen Falle, und die schnappt besonders oft zu, weil das Verhalten von Arrays ein anderes ist. Wenn man von einem gewöhnlichen JavaScript-Array `slice` aufruft, bekommt man eine Kopie. Bei einem Buffer ist das anders: `buf.subarray(start, end)` und das ältere `buf.slice(start, end)` erzeugen beide keine Kopie, sondern eine Sicht auf denselben zugrunde liegenden Speicher. Wer in die Sicht schreibt, verändert das Original mit.\n\n```mermaid\ngraph TD\n  M[\"Byte-Block im Speicher<br/>[1, 2, 3, 4, 5]\"]\n  O[\"original<br/>(ganzer Block)\"] --> M\n  V[\"view = original.subarray(1, 3)<br/>(Bytes 1 und 2)\"] --> M\n```\n\nBeide Namen, `original` und `view`, zeigen auf denselben Speicher. Ein Schreibzugriff über den einen ist über den anderen sichtbar.\n\n```js\nconst original = Buffer.from([1, 2, 3, 4, 5]);\n\nconst view = original.subarray(1, 3); // shares memory, no copy\nview[0] = 99;\n\nconsole.log(view);      // <Buffer 63 03>\nconsole.log(original);  // <Buffer 01 63 03 04 05> byte 1 changed too!\n```\n\nDas Byte an Position 1 im Original hat sich geändert, obwohl ich scheinbar nur in `view` geschrieben habe. In einer Funktion, die einen Teil-Buffer zurückgibt und der Aufrufer diesen dann verändert, führt das zu Fehlern, die schwer zu finden sind, weil die Ursache und die Wirkung an ganz verschiedenen Stellen des Codes stehen.\n\nWer eine unabhängige Kopie braucht, muss sie explizit anlegen – etwa mit `Buffer.from` über die Sicht oder mit `buf.copy` in einen frisch reservierten Ziel-Buffer.\n\n```js\nconst original = Buffer.from([1, 2, 3, 4, 5]);\n\nconst copy = Buffer.from(original.subarray(1, 3)); // independent copy\ncopy[0] = 99;\n\nconsole.log(copy);      // <Buffer 63 03>\nconsole.log(original);  // <Buffer 01 02 03 04 05> untouched\n```\n\nZur Namensfrage, weil sie oft aufkommt: Die Node-Dokumentation empfiehlt inzwischen `subarray`. Der Name `slice` existiert bei Buffern nur noch aus Kompatibilitätsgründen und weicht bewusst vom Verhalten von `TypedArray.prototype.slice` ab, das eine Kopie liefert. Diese Inkonsistenz ist historisch gewachsen und eine häufige Verwechslungsquelle. Ich rate dazu, bei Buffern konsequent `subarray` zu schreiben – dann weiß man beim Lesen sofort, dass hier Speicher geteilt wird und keine Kopie entsteht.\n\n## Wo Buffer im Alltag auftauchen\n\nMan legt Buffer selten von Hand an; meist bekommt man sie von der Plattform gereicht. Das Modul `fs` gibt beim Lesen ohne Encoding-Angabe einen Buffer zurück. Streams liefern ihre Daten in Buffer-Blöcken, wenn man sie nicht als Text konfiguriert. Das Netzwerkmodul `net` reicht empfangene Pakete als Buffer weiter. Und `crypto` arbeitet fast durchgängig mit Buffern – ein Hash etwa entsteht als Buffer, den man anschließend mit `toString('hex')` lesbar macht.\n\n```js\nconst crypto = require('node:crypto');\n\nconst hash = crypto.createHash('sha256')\n  .update('hello world')   // accepts string or Buffer\n  .digest();               // returns a Buffer\n\nconsole.log(Buffer.isBuffer(hash)); // true\nconsole.log(hash.toString('hex'));  // b94d27b9934d3e08a52e52d7da7dabfa...\n```\n\nHier sieht man die zwei Rollen des Buffers schön zusammen: `update` nimmt Text oder Bytes entgegen, `digest` gibt rohe Bytes zurück, und `toString('hex')` macht diese Bytes für Logs und Vergleiche lesbar. Wer verstehen will, in welchem Ausführungsmodell diese Ein- und Ausgaben laufen und warum das nicht blockiert, findet den Hintergrund im Beitrag [Node.js-Training](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) zur Event-Loop-Architektur.\n\n## Was hängen bleibt\n\nDrei Dinge tragen weit. Erstens: Ein Buffer ist ein `Uint8Array` mit Node-Extras – wer das im Kopf hat, versteht den Indexzugriff und die Länge sofort und erwartet keine String-Magie. Zweitens: `alloc` ist der sichere Standard, `allocUnsafe` ein bewusster Kompromiss für Fälle, in denen man den Speicher ohnehin komplett überschreibt; alles andere riskiert, alte Daten preiszugeben. Drittens: `subarray` und `slice` teilen den Speicher, kopieren nicht – wer eine unabhängige Fassung braucht, kopiert von Hand.\n\nDie beiden Fallen – uninitialisierter Speicher aus `allocUnsafe` und die geteilte Sicht aus `subarray` – haben eines gemeinsam: Sie fallen im schnellen Test nicht auf und schlagen erst später oder unter Last zu. Genau deshalb lohnt es sich, das Verhalten einmal bewusst durchzuspielen, statt es dem Zufall zu überlassen. Dateizugriff, Netzwerk und Kryptografie laufen in Node über rohe Bytes; wer den Buffer verstanden hat, liest ihre Ausgabe in der Konsole als das, was sie ist: eine Darstellung der Daten ohne jede Umdeutung.\n\n## Weiterführende Quellen\n\n- [Node.js-Training: Event-Loop-Architektur](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/)\n- [Node.js-Streams und Backpressure](https://www.mikebild.dev/de/blog/nodejs-streams-und-backpressure/)\n- [Node.js-Dokumentation: Buffer](https://nodejs.org/api/buffer.html)\n- [Buffer.alloc(size, fill, encoding)](https://nodejs.org/api/buffer.html#static-method-bufferallocsize-fill-encoding)\n- [Buffer.allocUnsafe(size)](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize)\n- [Buffers and character encodings](https://nodejs.org/api/buffer.html#buffers-and-character-encodings)\n- [buf.slice() – Legacy-Hinweis, subarray bevorzugen](https://nodejs.org/api/buffer.html#bufslicestart-end)\n- [MDN: Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)"},{"locale":"de","translation_key":"svelte-stores-zustand-ausserhalb-der-komponente","slug":"svelte-stores-zustand-ausserhalb-der-komponente","title":"Svelte Stores: State außerhalb der Komponente","summary":"Svelte Stores sind ein minimales Modell für State, der nicht in eine einzelne Komponente passt: writable, readable, derived – plus die $-Kurzschreibweise, die abonniert und beim Unmount aufräumt.","tags":["Software","Frontend","Svelte"],"published_at":"2022-07-19T10:00:00+00:00","updated_at":"2026-07-13T13:25:28.073895+00:00","url":"https://www.mikebild.dev/de/blog/svelte-stores-zustand-ausserhalb-der-komponente/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/5778b78c43791f059972fe0f796b916d21e93dfa08bc5ec98d43e0cab5248f93/svelte-stores-zustand-ausserhalb-der-komponente-vorlesen.mp3","audio_duration_secs":831,"text":"Wer eine State-Management-Bibliothek installiert, bevor die Besitzfrage geklärt ist, hat den Preis schon bezahlt: eine zusätzliche Abhängigkeit, ein zweites mentales Modell und Boilerplate – für ein Problem, das das Projekt womöglich gar nicht hat. Der Auslöser ist meist harmlos. Zwei Komponenten, die nicht direkt verwandt sind, sollen sich einen Wert teilen; die Reaktivität innerhalb einer Komponente funktioniert wunderbar, aber über die Komponentengrenze hinweg fehlt der Mechanismus. Aus der React-Welt kennt man den Griff zur großen Bibliothek, und er passiert reflexartig, obwohl die eigentliche Frage keine API-Frage ist: Wem gehört dieser State, und wie viel Maschinerie darf er kosten?\n\nSvelte hat für diesen Fall bereits ein Werkzeug an Bord, das kaum eine Handvoll Funktionen umfasst – Stores. Sie beantworten die Besitzfrage mit dem kleinstmöglichen Mittel und lassen die Kosten erst dann steigen, wenn ein konkretes Problem es erzwingt. Der eigentliche Gewinn liegt dabei weniger in den Funktionen selbst als in der Disziplin, die sie erlauben: klein anfangen und die Grenze zu „mehr“ bewusst ziehen statt sie reflexartig zu überschreiten.\n\nEin Store ist State, der außerhalb der Komponente steht. Er gehört keiner einzelnen `.svelte`-Datei, sondern liegt in einem separaten Modul und kann von überall aus abonniert werden. Damit löst er ein Problem, das in Komponentenbäumen schnell lästig wird: das Durchreichen von Werten durch mehrere Ebenen, nur damit ein tief verschachteltes Kind an eine Information kommt. Wer meinen Artikel zur [Svelte-Reaktivität](https://www.mikebild.dev/de/blog/svelte-reaktivitaet-compiler-ohne-virtual-dom/) gelesen hat, kennt bereits das Fundament: Der Compiler baut die Reaktivität zur Bauzeit ein, ohne Virtual DOM. Stores sind die logische Fortsetzung dieses Gedankens für State, der die Komponentengrenze überschreiten muss.\n\n**Redaktionelle Einordnung (Juli 2026):** Der Text verwendet das Store-Modell von Svelte 3/4. Stores sind in Svelte 5 weiterhin unterstützt und besonders für asynchrone Streams oder manuell kontrollierte Subscriptions nützlich. Für geteilten State kann heute aber auch eine `.svelte.js`- oder `.svelte.ts`-Datei mit Runes genügen; Stores sind nicht mehr die einzige eingebaute Antwort außerhalb einer Komponente.\n\n## Die Besitzfrage steht vor der Werkzeugfrage\n\nBevor ich zu den konkreten Svelte-Funktionen komme, ein Prinzip, das mit Svelte selbst nichts zu tun hat und in jedem komponentenbasierten Frontend gilt – ob React, Vue oder Svelte. Ich habe es an anderer Stelle für React ausführlich hergeleitet, im [State-Management-Vergleich](https://www.mikebild.dev/de/blog/state-management-vergleich/), und der Kern trägt eins zu eins hierher: Die entscheidende Frage lautet nicht „welche State-Bibliothek“, sondern „wem gehört dieser State?“. Ein State gehört an die tiefste Stelle, an der ihn alle Beteiligten noch erreichen. Solange das eine einzelne Komponente ist, bleibt er dort – lokal, ohne jede Zeremonie. Erst wenn sich mehrere, nicht verwandte Komponenten denselben Wert teilen oder er von außerhalb des Baums kommt, verlässt er die Komponente. Ein globaler oder modulweiter Store ist damit die Ausnahme, die man begründet, nicht der Normalfall, in den man hineinfällt.\n\nWarum ich das so betone, ist ein Kostenargument. Jede Ebene, auf die ich State hebe, macht ihn teurer: mehr Stellen, die schreiben dürfen, schwerer nachvollziehbare Änderungen, eine größere Fläche für Fehler. In Projekten habe ich den umgekehrten Weg oft genug mitgemacht – erst wird die große Bibliothek gewählt, dann wird State hineingeschoben, bis alles global ist. Die Gegenprobe geht andersherum: Braucht dieser Wert wirklich mehrere Komponenten, und sind sie so entkoppelt, dass eine gemeinsame Elternkomponente sie nicht ohnehin verbinden würde? In meiner Erfahrung bleibt nach dieser Frage deutlich weniger globaler State übrig als anfangs vermutet.\n\nFür die Entscheidung, ob ein Wert die Komponente verlassen soll, nutze ich drei Kriterien. Die Reichweite: Teilen ihn mindestens zwei Komponenten, die nicht in einer sauberen Eltern-Kind-Beziehung stehen? Die Herkunft: Wird der Wert von außerhalb des Baums geschrieben – Timer, WebSocket, Sensor? Und die Lebensdauer: Muss er unabhängig davon existieren, ob eine bestimmte Komponente gerade gemountet ist? Trifft keines zu, bleibt der State lokal, und jede darüberliegende Lösung ist bezahlte Komplexität ohne Gegenwert. Trifft eines zu, ist ein schlanker, modulweiter Store die richtige Antwort – in Svelte buchstäblich eine Zeile Code. Die eigentliche Arbeit steckt in der Entscheidung davor, nicht in der API danach.\n\n## Der Contract, nicht die Klasse\n\nEin Store ist in Svelte kein spezieller Typ und keine Klasse, von der man erben muss. Ein Store ist jedes Objekt, das eine `.subscribe`-Methode nach einem festen Vertrag bereitstellt – und optional eine `.set`-Methode, wenn es schreibbar sein soll. `subscribe` muss den aktuellen Wert synchron an den Subscriber liefern und eine Funktion zum Abbestellen zurückgeben. Genau dieser Contract ist es, der zählt. Alles, was ihn erfüllt, funktioniert mit der `$`-Syntax.\n\nIn der Praxis schreibt man diese `.subscribe`-Methode fast nie selbst. Svelte liefert drei Fabrikfunktionen mit, die einem die Arbeit abnehmen. Sie stammen alle aus demselben Modul:\n\n```js\nimport { writable, readable, derived, get } from 'svelte/store';\n```\n\nDie drei Store-Typen decken drei unterschiedliche Rollen ab:\n\n- `writable` – les- und schreibbar. Der Standardfall für geteilten State, den irgendeine Komponente oder Funktion verändern darf. Bietet `.set(value)`, `.update(fn)` und `.subscribe(run)`.\n- `readable` – nur lesbar von außen. Der Wert wird intern über einen Start-Callback gesetzt, ideal für externe Quellen wie eine Uhr, einen WebSocket oder einen Event-Listener.\n- `derived` – abgeleitet. Berechnet seinen Wert reaktiv aus einem oder mehreren anderen Stores und aktualisiert sich automatisch, wenn sich eine seiner Quellen ändert.\n\n## Der writable Store und die $-Kurzschreibweise\n\nFangen wir mit dem häufigsten Fall an – einem gemeinsamen Zähler, den mehrere Komponenten teilen. Der Store liegt in einem eigenen Modul, damit ihn jede Komponente importieren kann:\n\n```js\n// stores.js\nimport { writable } from 'svelte/store';\n\nexport const count = writable(0);\n```\n\nDas ist der komplette Store. Ein Modul, eine Zeile, ein Anfangswert. Jetzt kann eine beliebige Komponente diesen Zähler lesen und schreiben – und hier kommt die eleganteste Idee von Svelte ins Spiel, die `$`-Kurzschreibweise:\n\n```svelte\n<script>\n  import { count } from './stores.js';\n</script>\n\n<button on:click={() => $count++}>\n  Clicked {$count} times\n</button>\n```\n\nDas `$count` im Template ist keine magische globale Variable, sondern eine Anweisung an den Compiler. Er erkennt das Präfix `$` vor einer Store-Referenz und generiert daraus zweierlei: erstens ein `count.subscribe(...)`, das den aktuellen Wert in eine lokale Variable schreibt und das Template bei jeder Änderung neu rendert; zweitens – und das ist der entscheidende Teil – ein automatisches `unsubscribe`, sobald die Komponente zerstört wird. Man muss sich um das Aufräumen also nicht kümmern, der Compiler nimmt es einem ab.\n\nAuch das Schreiben ist über die Kurzschreibweise abgedeckt. `$count++` übersetzt der Compiler in einen `count.set(...)`-Aufruf mit dem inkrementierten Wert. Wer es expliziter mag oder eine komplexere Änderung braucht, greift zu den Methoden direkt:\n\n```svelte\n<script>\n  import { count } from './stores.js';\n\n  function increment() {\n    count.update(n => n + 1);\n  }\n\n  function reset() {\n    count.set(0);\n  }\n</script>\n\n<button on:click={increment}>+1</button>\n<button on:click={reset}>Reset</button>\n<p>Current value: {$count}</p>\n```\n\nDer Unterschied zwischen `set` und `update` ist schnell erklärt. `set` überschreibt den Wert bedingungslos, `update` bekommt den aktuellen Wert als Argument und gibt den neuen zurück – praktisch immer dann, wenn der neue Wert vom alten abhängt.\n\nUnd jetzt der Kern des Ganzen: Sobald eine zweite Komponente denselben Store importiert und `$count` verwendet, teilen sich beide denselben State. Ändert die eine den Wert, sieht ihn die andere sofort. Kein Prop wird durch den Baum gereicht, keine gemeinsame Elternkomponente muss den State halten. Der Store ist die gemeinsame Quelle, an der alle Beteiligten hängen.\n\n```mermaid\ngraph TD\n  S[\"writable count<br/>(stores.js)\"]\n  A[\"Component A<br/>$count lesen + schreiben\"]\n  B[\"Component B<br/>$count anzeigen\"]\n  C[\"Component C<br/>$count anzeigen\"]\n  S --> A\n  S --> B\n  S --> C\n  A -. \"count.set()\" .-> S\n```\n\nMan sieht hier gut, was der Store leistet: Er entkoppelt die Komponenten voneinander. A, B und C müssen weder verwandt sein noch voneinander wissen. Sie kennen nur den Store.\n\n## Abgeleiteter State mit derived\n\nOft braucht man einen Wert, der sich aus einem anderen ergibt. Man könnte ihn in jeder Komponente neu ausrechnen – oder man leitet ihn einmal zentral ab und alle profitieren. Genau dafür ist `derived` da:\n\n```js\n// stores.js\nimport { writable, derived } from 'svelte/store';\n\nexport const count = writable(0);\n\nexport const doubled = derived(count, $count => $count * 2);\n```\n\n`doubled` ist selbst wieder ein Store, aber ein nur lesbarer. Er hat keine `.set`-Methode, denn sein Wert ergibt sich vollständig aus `count`. Ändert sich `count`, berechnet `derived` den Wert neu und benachrichtigt seine Abonnenten. In der Komponente sieht das dann so aus, als wäre es ein ganz normaler Store:\n\n```svelte\n<script>\n  import { count, doubled } from './stores.js';\n</script>\n\n<p>{$count} doubled is {$doubled}</p>\n<button on:click={() => $count++}>+1</button>\n```\n\n`derived` kann auch aus mehreren Quellen ableiten. Dann übergibt man ein Array von Stores und bekommt im Callback ein Array der Werte:\n\n```js\nimport { writable, derived } from 'svelte/store';\n\nexport const price = writable(100);\nexport const quantity = writable(2);\n\nexport const total = derived(\n  [price, quantity],\n  ([$price, $quantity]) => $price * $quantity\n);\n```\n\nNeben dieser synchronen Form gibt es eine zweite, die einen `set`-Callback bekommt. Damit lässt sich der abgeleitete Wert verzögert oder bedingt setzen – etwa nach einem Timeout oder erst, wenn eine bestimmte Bedingung erfüllt ist:\n\n```js\nimport { derived } from 'svelte/store';\n\n// Sets the value one second after each change of 'count'\nexport const delayed = derived(\n  count,\n  ($count, set) => {\n    const id = setTimeout(() => set($count), 1000);\n    return () => clearTimeout(id);\n  }\n);\n```\n\nDer Rückgabewert der Callback-Function ist hier eine Aufräumfunktion, die Svelte vor der nächsten Berechnung und beim letzten Unsubscribe ausführt. So bleibt kein Timeout hängen.\n\n## readable für externe Quellen\n\nNicht jeder State wird von der Anwendung selbst geschrieben. Manchmal kommt er von außen – eine Uhr, die tickt, ein WebSocket, der Nachrichten liefert, ein Sensor. Für solche Fälle gibt es `readable`. Von außen kann man ihn nur lesen; wer ihn füttert, ist ein Start-Callback, der die Quelle aufsetzt:\n\n```js\nimport { readable } from 'svelte/store';\n\nexport const time = readable(null, set => {\n  const id = setInterval(() => set(new Date()), 1000);\n\n  return () => clearInterval(id);\n});\n```\n\nHier lohnt sich ein genauer Blick auf das Timing, weil es ein zentrales Prinzip von Stores offenlegt. Der Start-Callback läuft nicht sofort beim Anlegen des Stores. Er läuft erst, wenn der erste Abonnent hinzukommt – wenn die Zahl der Subscriber von null auf eins springt. Und die zurückgegebene Funktion – der Stop-Teil – läuft, wenn der letzte Abonnent abspringt, also von eins auf null. Solange niemand zuhört, tickt bei diesem `readable` kein Intervall und öffnet sich kein Socket. Bei `writable` bleiben `set` und `update` auch ohne Subscriber wirksam; lazy ist nur eine optionale Start-/Stop-Arbeit. `derived` wiederum berechnet für seine Abonnenten und meldet sich ohne sie von den Quellen ab.\n\nIn der Komponente ist der Umgang wieder trivial, denn `$time` abonniert automatisch und räumt beim Unmount auf:\n\n```svelte\n<script>\n  import { time } from './stores.js';\n</script>\n\n<p>The time is {$time?.toLocaleTimeString()}</p>\n```\n\n## Der Fallstrick: subscribe ohne unsubscribe\n\nBisher lief alles über die `$`-Kurzschreibweise, und dort ist das Aufräumen kein Thema. Aber Stores sind nicht auf Komponenten beschränkt. Man kann sie genauso in einem reinen JavaScript-Modul verwenden – in einer Utility-Function, einem Service, irgendwo außerhalb von Svelte. Und genau da lauert der häufigste Fehler.\n\nAußerhalb einer Komponente gibt es kein `$` und keinen Compiler, der aufräumt. Man ruft `subscribe` von Hand auf, und die Methode gibt eine Unsubscribe-Function zurück. Diese Funktion **muss** man aufheben und aufrufen, sonst hat man ein Leak:\n\n```js\n// utils.js\nimport { count } from './stores.js';\n\n// WRONG: the callback runs forever.\ncount.subscribe(value => {\n  console.log('count is now', value);\n});\n```\n\nDer Rückgabewert von `subscribe` wird hier einfach ignoriert. Solange das Modul beziehungsweise dieser Nutzungskontext lebt, bleibt der Callback registriert. Der Store zählt weiterhin einen Abonnenten, der Stop-Callback von 1→0 wird nicht ausgelöst – bei einem `readable` mit Intervall liefe der Timer entsprechend weiter. Richtig ist es so:\n\n```js\n// utils.js\nimport { count } from './stores.js';\n\nconst unsubscribe = count.subscribe(value => {\n  console.log('count is now', value);\n});\n\n// ... later, when no longer needed:\nunsubscribe();\n```\n\nDieselbe Regel gilt sinngemäß auch innerhalb von Komponenten, falls man dort aus irgendeinem Grund manuell `subscribe` statt `$` verwendet: Dann muss man den Unsubscriber in `onDestroy` aufrufen. Aber ehrlich gesagt ist das fast immer ein Zeichen, dass man einfach die `$`-Syntax hätte nehmen sollen. Genau diese Buchhaltung nimmt sie einem ab.\n\nWenn man den Wert nur ein einziges Mal lesen will – ohne Abonnement, ohne Reaktivität – gibt es einen sauberen Weg, der das Leak-Problem gar nicht erst aufkommen lässt:\n\n```js\nimport { get } from 'svelte/store';\nimport { count } from './stores.js';\n\nconst current = get(count);\n```\n\n`get` abonniert intern kurz, liest den aktuellen Wert und meldet sich sofort wieder ab. Der Wert ist eine Momentaufnahme und aktualisiert sich nicht mehr. Genau deshalb passt `get` gut für einmaliges Auslesen in einem JS-Modul – und gerade nicht in einen heißen Pfad, der ständig durchlaufen wird.\n\n```mermaid\nsequenceDiagram\n  participant C as Erster Subscriber\n  participant S as Store\n  participant Q as Externe Quelle\n  C->>S: subscribe(run)\n  S->>Q: start-Callback (0 -> 1)\n  Q-->>S: Werte fließen\n  S-->>C: run(value)\n  C->>S: unsubscribe()\n  S->>Q: stop-Callback (1 -> 0)\n```\n\n## Wann Store, und wann nicht\n\nDer Store ist das richtige Werkzeug, sobald State nicht mehr sauber in eine einzelne Komponente passt – wenn mehrere, nicht direkt verwandte Komponenten sich denselben Wert teilen, oder wenn ein Wert von außerhalb des Komponentenbaums kommt. Das klassische Symptom, das nach einem Store ruft, ist Prop-Drilling: Man reicht einen Wert durch drei, vier Ebenen, obwohl ihn nur die unterste Komponente wirklich braucht. Ein Store schneidet diesen Durchreiche-Pfad ab. Die betroffenen Komponenten importieren den Store direkt, und die Zwischenebenen müssen von dem Wert gar nichts wissen.\n\nBleibt die Frage, ob es daneben noch eine große State-Management-Bibliothek braucht. Für die allermeisten Svelte-Anwendungen: nein. Die drei Store-Typen decken erstaunlich viel ab. `writable` für den State, den man verändert, `derived` für alles, was sich daraus ergibt, `readable` für externe Quellen. Das ist kein Kompromiss, kein „reicht erstmal“ – es ist für den Großteil realer Anwendungen schlicht ausreichend. Ein zentrales Store-Modul, das die einzelnen Stores exportiert, gibt der Anwendung eine klare, überschaubare Struktur, ohne dass man ein weiteres mentales Modell und eine weitere Abhängigkeit mitschleppen muss.\n\nWo liegt dann der Rand, ab dem man über mehr nachdenkt? Ich würde sagen: Erst wenn der State wirklich komplex wird – viele voneinander abhängige Übergänge, strikte Nachvollziehbarkeit jeder Änderung, ausgefeiltes Time-Travel-Debugging über eine große Domäne hinweg. Solche Anforderungen sind selten, und selbst dann baut man häufig eine dünne Schicht auf Stores auf, statt sie zu ersetzen. Solange die Frage aber nur lautet „Wie teilen sich meine Komponenten einen Wert?“, ist die Antwort ein Store – und mehr braucht es nicht.\n\nWas nach mehreren Projekten mit Svelte bleibt, ist weniger eine API-Empfehlung als eine Reihenfolge: erst den Besitzer des States bestimmen, dann das Werkzeug. Für das 2022 gezeigte Modell sind `writable`, `readable` und `derived` oft genug. Die `$`-Kurzschreibweise erledigt in Komponenten die Subscription-Buchhaltung; außerhalb bleibt die schlichte Regel, jedes manuelle `subscribe` mit einem `unsubscribe` zu paaren.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-svelte.html\n- Repository: [mikebild.dev](https://www.mikebild.dev) – dieser und weitere Artikel zu Svelte und Frontend-Architektur\n- [Svelte-Reaktivität: der Compiler ohne Virtual DOM](https://www.mikebild.dev/de/blog/svelte-reaktivitaet-compiler-ohne-virtual-dom/)\n- [Svelte-Docs – Stores und Runes](https://svelte.dev/docs/svelte/stores)"},{"locale":"de","translation_key":"nodejs-streams-und-backpressure","slug":"nodejs-streams-und-backpressure","title":"Node.js-Streams: Backpressure verstehen und nutzen","summary":"Warum ein schneller Producer einen langsamen Consumer nicht überrennen darf – und wie pipe, pipeline, der Rückgabewert von write() und das drain-Event die Flusskontrolle in Node.js regeln.","tags":["Software","Node.js","Backend"],"published_at":"2022-06-21T10:00:00+00:00","updated_at":"2026-07-13T07:58:20.382471+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-streams-und-backpressure/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/3e382a54f3c092a6f85e773ef76392af44fc3ece61a521d50f1d211acd968fb0/nodejs-streams-und-backpressure-vorlesen.mp3","audio_duration_secs":713,"text":"```\nFATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory\n```\n\nDieser Abbruch kommt nicht davon, dass zu viele Daten verarbeitet wurden. Er kommt davon, dass sie zu schnell hereinkamen. Eine Quelle liest ein Logfile von einer schnellen SSD, jeder Chunk geht per `write()` an ein langsames Ziel – und weil niemand hinsieht, was `write()` zurückgibt, wächst der interne Puffer, bis der Heap voll ist. Die Datenmenge ist dabei egal; entscheidend ist das Tempogefälle zwischen den beiden Enden.\n\nStreams gelten vielen als Dateikram rund um `createReadStream`. Sie sind aber das grundlegende Modell, wie Node.js Daten stückweise durch eine Pipeline schiebt, ohne dass jemals alles gleichzeitig im Speicher liegt. Der Teil davon, der in echten Systemen über \"läuft stabil\" und \"Prozess stirbt nachts um drei\" entscheidet, heißt Backpressure. Die Stream-API sieht harmlos aus, man verkettet ein paar `pipe`-Aufrufe, und es funktioniert – bis zu dem Tag, an dem die Quelle schneller liefert als das Ziel schlucken kann.\n\n## Warum Streams überhaupt\n\nDer klassische Weg, eine Datei zu verarbeiten, ist `fs.readFile`. Die Funktion liest die komplette Datei in einen Buffer und ruft dann den Callback auf. Bei einer 2-MB-Konfigurationsdatei völlig in Ordnung. Bei einem 4-GB-Logfile hat man ein Problem: Node.js versucht, vier Gigabyte in den Heap zu laden, und der Prozess kippt um, lange bevor überhaupt eine Zeile verarbeitet wurde.\n\nEin Stream macht es anders. Er liest die Datei in kleinen Häppchen – Chunks – und reicht jeden Chunk einzeln weiter. Zu jedem Zeitpunkt liegt nur ein kleiner Puffer im Speicher, unabhängig davon, ob die Datei zwei Megabyte oder zwei Terabyte groß ist. Der Speicherverbrauch bleibt konstant. Das ist der Kernnutzen, und er gilt nicht nur für Dateien: HTTP-Requests, TCP-Sockets, Kompression, Verschlüsselung – all das sind in Node.js Streams.\n\n## Die vier Typen\n\nBevor es um Flusskontrolle geht, lohnt sich der Überblick über die vier Stream-Typen. Alle vier erben von `EventEmitter`, kommunizieren also über Events – das ist der rote Faden, der sich durch die ganze asynchrone Seite von Node.js zieht, wie ich sie im [Node.js-Training: Vom Event Loop zur Architekturentscheidung](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/) ausführlicher beschreibe.\n\n- Ein Readable ist eine Quelle, aus der man liest. `fs.createReadStream()` liefert einen Readable, ebenso der eingehende Body eines HTTP-Requests.\n- Ein Writable ist ein Ziel, in das man schreibt. `fs.createWriteStream()` oder die HTTP-Response sind Writables.\n- Ein Duplex ist lesbar und schreibbar zugleich, aber mit getrennten Kanälen. Ein `net.Socket` ist das Paradebeispiel: rein und raus über dieselbe Verbindung.\n- Ein Transform ist ein Duplex, bei dem der Output eine Funktion des Inputs ist. `zlib.createGzip()` nimmt rohe Bytes rein und gibt komprimierte raus. Genau hier setzt man eigene Verarbeitungslogik an.\n\nDiese Typen kombiniert man zu einer Pipeline: eine Quelle, beliebig viele Transforms in der Mitte, ein Ziel am Ende.\n\n```mermaid\nflowchart LR\n    A[\"Readable<br/>fs.createReadStream\"] -->|chunks| B[\"Transform<br/>gzip / uppercase\"]\n    B -->|chunks| C[\"Writable<br/>fs.createWriteStream\"]\n    C -.->|drain-Signal| A\n    style A fill:#2b6cb0,color:#fff\n    style B fill:#2f855a,color:#fff\n    style C fill:#c05621,color:#fff\n```\n\nDie durchgezogenen Pfeile sind der Datenfluss vorwärts. Der gestrichelte Pfeil zurück ist das Entscheidende – er ist Backpressure. Dazu gleich mehr.\n\n## Der naive Ansatz und warum er kippt\n\nNehmen wir an, wir wollen eine große Datei in eine andere kopieren und dabei jeden Chunk verarbeiten. Der intuitive Code sieht so aus:\n\n```js\nconst fs = require('node:fs');\n\nconst source = fs.createReadStream('huge-input.log');\nconst target = fs.createWriteStream('huge-output.log');\n\nsource.on('data', (chunk) => {\n  target.write(chunk);\n});\n```\n\nDas läuft. Meistens. Und dann kommt der Fall, in dem `huge-input.log` von einer schnellen SSD kommt und `huge-output.log` auf ein langsames Netzlaufwerk geschrieben wird. Die Quelle feuert `data`-Events, so schnell sie kann, und `target.write()` nimmt jeden Chunk entgegen. Kann das Ziel nicht schnell genug wegschreiben, puffert Node.js die Chunks intern – und dieser Puffer kennt keine Obergrenze. Der Speicher füllt sich, `RSS` klettert, der Garbage Collector arbeitet gegen eine immer größere Menge, und irgendwann beendet das Betriebssystem den Prozess.\n\nDas ist der Fallstrick in einem Satz: **Wer den Rückgabewert von `write()` ignoriert und einfach weiterschreibt, produziert unbegrenztes Puffern.**\n\n## Was write() eigentlich sagt\n\n`writable.write(chunk)` gibt einen Boolean zurück, und dieser Boolean ist die halbe Miete:\n\n- `true` bedeutet: Der interne Puffer liegt noch unter `highWaterMark`, du darfst weiterschreiben.\n- `false` bedeutet: Der Puffer hat `highWaterMark` erreicht oder überschritten. Hör auf zu schreiben, sonst puffert Node.js ins Blaue.\n\n`highWaterMark` ist die Puffergrenze. Im hier behandelten Node 16/18 lag der allgemeine Default für Byte-Streams bei 16384 Bytes, also 16 KiB; seit Node 22 sind es 64 KiB. Im Object-Mode – dazu später – bleibt der Default bei 16 Objekten. Wichtig zu verstehen: Diese Grenze ist ein **Schwellwert, keine harte Mauer**. Node.js hört nicht auf zu puffern, wenn man `highWaterMark` überschreitet. Es sagt einem nur höflich per `false`-Rückgabe Bescheid, dass es genug ist. Wer die Warnung überhört, puffert trotzdem weiter – auf eigenes Risiko.\n\nWenn `write()` einmal `false` geliefert hat, sollte man pausieren und auf das `'drain'`-Event warten. Das Writable emittiert `'drain'`, sobald sein Puffer wieder geleert ist – das Signal, dass man weiterschreiben darf. Von Hand sieht der korrekte Zyklus so aus:\n\n```js\nsource.on('data', (chunk) => {\n  const ok = target.write(chunk);\n  if (!ok) {\n    source.pause();\n    target.once('drain', () => source.resume());\n  }\n});\n```\n\nWir schreiben, prüfen den Rückgabewert, pausieren die Quelle bei `false` und nehmen sie erst nach `'drain'` wieder auf. Genau das ist Flusskontrolle: Ein schneller Producer wird ausgebremst, damit er einen langsamen Consumer nicht überrennt.\n\nDen Zyklus kann man auch als State Machine zeichnen:\n\n```mermaid\nstateDiagram-v2\n    [*] --> Schreiben\n    Schreiben --> Schreiben: write() liefert true\n    Schreiben --> Pausiert: write() liefert false<br/>source.pause()\n    Pausiert --> Schreiben: 'drain'-Event<br/>source.resume()\n```\n\n## pipe erledigt das automatisch\n\nDie gute Nachricht: Diesen ganzen `pause`/`resume`-Tanz muss man in der Praxis selten von Hand schreiben. `pipe()` macht genau das im Hintergrund.\n\n```js\nconst fs = require('node:fs');\n\nfs.createReadStream('huge-input.log')\n  .pipe(fs.createWriteStream('huge-output.log'));\n```\n\n`pipe()` verbindet Quelle und Ziel miteinander, prüft intern den Rückgabewert von `write()`, pausiert den Readable bei Backpressure und resumt ihn nach `'drain'`. Backpressure ist also gelöst, ohne dass man eine Zeile Flusskontrolle selbst schreibt. `pipe()` gibt außerdem das Ziel zurück, sodass man verketten kann – praktisch, wenn ein Transform dazwischenhängt:\n\n```js\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\nfs.createReadStream('huge-input.log')\n  .pipe(zlib.createGzip())\n  .pipe(fs.createWriteStream('huge-input.log.gz'));\n```\n\nUnd trotzdem rate ich davon ab, produktiv nur `pipe()` zu verketten. Der Grund ist die Error Handling.\n\n## Warum pipeline die bessere Wahl ist\n\n`pipe()` hat eine tückische Schwäche: Es propagiert Fehler nicht. Wirft eine Stage mitten in der Kette einen Fehler – die Netzverbindung bricht weg, die Platte ist voll – dann bekommt das ein `pipe()`-Verbund nicht sauber mit. Die anderen Streams werden nicht zerstört, Dateideskriptoren bleiben offen, der Stream hängt. In einem langlaufenden Serverprozess sammeln sich solche Leaks an, bis irgendwann die Ressourcen ausgehen.\n\n`stream.pipeline()` löst das. Es verkettet die Stages genauso, aber es propagiert Fehler über alle Stufen hinweg und ruft bei Fehler oder regulärem Ende `destroy()` auf jedem beteiligten Stream auf. Nichts leakt. Es gibt die Callback-Variante:\n\n```js\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst { pipeline } = require('node:stream');\n\npipeline(\n  fs.createReadStream('huge-input.log'),\n  zlib.createGzip(),\n  fs.createWriteStream('huge-input.log.gz'),\n  (err) => {\n    if (err) {\n      console.error('pipeline failed', err);\n      return;\n    }\n    console.log('pipeline succeeded');\n  }\n);\n```\n\nSeit Node.js 15 – in den 2022 aktuellen Release-Linien 16 und 18 also fest verankert – gibt es zusätzlich eine Promises-Variante aus `node:stream/promises`. Die liest sich in async-Functions deutlich sauberer, weil man Fehler mit try/catch fängt:\n\n```js\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst { pipeline } = require('node:stream/promises');\n\nasync function compress() {\n  try {\n    await pipeline(\n      fs.createReadStream('huge-input.log'),\n      zlib.createGzip(),\n      fs.createWriteStream('huge-input.log.gz')\n    );\n    console.log('done');\n  } catch (err) {\n    console.error('pipeline failed', err);\n  }\n}\n\ncompress();\n```\n\nDie Promises-Variante nimmt auch Optionen, etwa ein `signal` für ein `AbortSignal`, mit dem man die Pipeline von außen abbrechen kann. Der Punkt, der für mich den Ausschlag gibt: Backpressure regelt `pipeline()` genauso automatisch wie `pipe()` – aber es räumt auch auf. Für Produktionscode ist `pipeline()` die Standardwahl, `pipe()` höchstens für kurze, isolierte Skripte.\n\n## Einen eigenen Transform schreiben\n\nDer Punkt, an dem Streams richtig nützlich werden, ist der eigene Transform in der Mitte. Ein Transform bekommt Chunks rein, verarbeitet sie und schiebt das Ergebnis raus. Das Skelett besteht aus einer `transform`-Funktion, die drei Dinge bekommt: den Chunk, das Encoding und einen Callback, den man am Ende aufrufen muss.\n\n```js\nconst { Transform } = require('node:stream');\n\nconst upperCase = new Transform({\n  transform(chunk, encoding, callback) {\n    const transformed = chunk.toString().toUpperCase();\n    this.push(transformed);\n    callback();\n  }\n});\n```\n\n`this.push()` reicht das Ergebnis an die nächste Stage weiter, `callback()` signalisiert, dass dieser Chunk fertig verarbeitet ist. Ruft man `callback()` mit einem Fehler auf – `callback(err)` –, propagiert `pipeline()` diesen Fehler sauber durch die ganze Kette. Eingebaut in eine Pipeline sieht das so aus:\n\n```js\nconst fs = require('node:fs');\nconst { pipeline } = require('node:stream/promises');\n\nawait pipeline(\n  fs.createReadStream('input.txt'),\n  upperCase,\n  fs.createWriteStream('output.txt')\n);\n```\n\nUnd weil der `upperCase`-Transform wie jeder Stream an der Flusskontrolle teilnimmt, greift Backpressure auch hier: Ist das Ziel langsam, bremst die Pipeline über den Transform hinweg bis zur Quelle zurück. Man muss dafür nichts extra tun.\n\n## Async-Iteration als moderne Alternative\n\nSeit Node.js 10 implementiert jeder Readable `Symbol.asyncIterator`, lässt sich also direkt mit `for await ... of` konsumieren. Das liest sich in async-Functions oft klarer als `on('data')` und behält die Flusskontrolle bei, ohne dass man `pause` und `resume` anfassen muss.\n\n```js\nconst fs = require('node:fs');\n\nasync function countLines(path) {\n  const stream = fs.createReadStream(path, { encoding: 'utf8' });\n  let lines = 0;\n  for await (const chunk of stream) {\n    lines += chunk.split('\\n').length - 1;\n  }\n  return lines;\n}\n```\n\nDer Backpressure entsteht hier implizit: Solange der Schleifenkörper mit einem Chunk beschäftigt ist – und ein `await` darin ihn zusätzlich aufhält –, fordert die Schleife keinen neuen Chunk an, und der Readable liefert von selbst erst dann den nächsten. Man bekommt also dieselbe Bremse wie bei `pipe()`, nur in gewöhnlichem async/await-Code. Wichtig bleibt die Regel, die gleich noch kommt: Wer so iteriert, sollte den Stream nicht parallel auch noch über `on('data')` konsumieren.\n\n## Object-Mode und ein paar Regeln\n\nStandardmäßig arbeiten Streams mit Buffers und Strings. Setzt man `objectMode: true`, dürfen die Chunks beliebige JavaScript-Objekte sein – nützlich, wenn man eine Pipeline aus geparsten Datensätzen baut statt aus rohen Bytes. Zu beachten ist dabei, dass `highWaterMark` im Object-Mode als Anzahl Objekte zählt, nicht als Bytes; der Default sind 16 Objekte. Und ein bestehender Stream lässt sich nicht nachträglich sicher auf Object-Mode umschalten – das entscheidet man bei der Konstruktion.\n\nEine Regel, an der es in Reviews immer wieder hakt: Konsummethoden nicht mischen. Pro Readable wählt man genau eine Art zu lesen – entweder `on('data')`, oder `on('readable')`, oder `pipe()`, oder async-Iteration. Wer zwei davon kombiniert, produziert Race Conditions, verlorene Chunks und schwer reproduzierbare Bugs. Ein Readable, eine Konsummethode.\n\n## Was hängenbleiben soll\n\nStreams sind das Werkzeug, um beliebig große Datenmengen mit konstantem Speicher zu verarbeiten – der Puffer bleibt klein, egal wie groß die Quelle ist. Backpressure ist der Mechanismus, der das trägt: Der Rückgabewert von `write()` und das `'drain'`-Event bilden die Flusskontrolle, die einen schnellen Producer davon abhält, einen langsamen Consumer zu überrennen. `highWaterMark` ist dabei der Schwellwert, an dem `write()` von `true` auf `false` kippt – eine Warnung, kein Zwang.\n\nVon Hand muss man diesen Zyklus selten schreiben, weil `pipe()` und vor allem `pipeline()` ihn automatisch regeln. Der entscheidende Unterschied liegt in der Error Handling: `pipeline()` propagiert Fehler und räumt alle Streams auf, `pipe()` tut das nicht. Mit diesem Unterschied im Hinterkopf entsteht Node.js-Verarbeitungscode, der auch bei vier Gigabyte und einem langsamen Ziel nicht umkippt – sondern einfach ein bisschen langsamer wird, so wie es sein soll.\n\n## Weiterführende Quellen\n\n- Repository zur Node.js-Einführung: [mikebild/introduction-nodejs](https://github.com/mikebild/introduction-nodejs) – Lehrmaterial zu Async-Patterns inklusive `10-streams.md`.\n- [Node.js Stream API (v18)](https://nodejs.org/docs/latest-v18.x/api/stream.html) – Readable, Writable, Duplex, Transform, `pipe`, `pipeline`, `write`, `drain`, `highWaterMark`.\n- [Aktuelle Node.js Stream API – heutige Defaults](https://nodejs.org/api/stream.html)\n- [stream.pipeline in der offiziellen Doku](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-callback)\n- [Guide: Backpressuring in Streams](https://nodejs.org/learn/modules/backpressuring-in-streams)"},{"locale":"de","translation_key":"fitness-functions-messbare-architektur","slug":"fitness-functions-messbare-architektur","title":"Fitness Functions: ausgewählte Architektureigenschaften prüfen","summary":"Fitness Functions machen ausgewählte Eigenschaften wie Kopplung, Abhängigkeiten und Latenz kontinuierlich prüfbar. Fachliche Qualität und Architekturabwägungen ersetzen sie nicht.","tags":["Software","Architektur"],"published_at":"2022-05-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/fitness-functions-messbare-architektur/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/c46ce971e174566c7367923c5edbfdfd366b5bbefe7b3a688f4cf59e34fd7326/fitness-functions-messbare-architektur-vorlesen.mp3","audio_duration_secs":761,"text":"Eine Fitness Function ist kein vollständiges Qualitätsmodell. Sie bewertet gezielt eine operationalisierbare Architektureigenschaft – etwa Zyklenfreiheit, Kopplung, Latenz oder Verträglichkeit zwischen zwei Services. In diesem Beitrag konzentriere ich mich auf automatisierte, möglichst eindeutige Prüfungen, die bei jedem Commit ein eng begrenztes Urteil fällen. Eigenschaften wie Verständlichkeit oder fachliche Angemessenheit brauchen weiterhin menschliche Bewertung.\n\nWie groß der Unterschied zur üblichen Praxis ist, zeigt ein Satz, der in Architektur-Reviews regelmäßig fällt: „Die Domäne darf natürlich nicht auf die Infrastruktur zugreifen.“ Alle nicken. Es wird ein Diagramm gezeichnet, vielleicht ein Confluence-Eintrag angelegt. Drei Sprints später zeigt eine Import-Anweisung von der Domain-Schicht direkt in den Datenbank-Adapter. Niemand hat das böswillig getan. Es war Freitagnachmittag, der Bugfix musste raus, und die Regel stand nun mal nicht im Code, sondern in einem Protokoll, das keiner mehr liest. Wo sich eine Architektureigenschaft eindeutig prüfen lässt, ist ein automatischer Check verlässlicher als die Erinnerung im Review.\n\nEine Fitness Function schließt den Weg von einer gewünschten Eigenschaft bis zu einer wiederholbaren Entscheidung.\n\n:::process{title=\"Von der Architekturaussage zum Gate\" role=\"primary\" preferredPattern=\"connected-process\"}\n1. Eigenschaft · eine fachlich relevante Architekturqualität benennen\n2. Beobachtung · ein reproduzierbares Signal dafür auswählen\n3. Schwelle · den noch akzeptablen Bereich ausdrücklich festlegen\n4. Prüfung · das Signal automatisch und wiederholbar auswerten\n5. Gate · eine Verletzung sichtbar machen oder die Änderung passieren lassen\n6. Anpassung · Eigenschaft und Schwelle bei veränderten Bedingungen erneut prüfen\n:::\n\nDie Reihenfolge bewahrt den fachlichen Grund der Messung. Ein vorhandenes Tool allein definiert noch keine sinnvolle Fitness Function.\n\n## Vom Wunsch zur mechanischen Prüfung\n\nDer Begriff stammt aus *Building Evolutionary Architectures* von Neal Ford, Rebecca Parsons und Patrick Kua (O'Reilly, 2017), entliehen aus dem Evolutionary Computing, wo eine Fitness-Function misst, wie nah eine Lösung am Ziel ist. Übertragen auf Software heißt das: Eine architectural fitness function ist ein objektiver, mechanischer Integritätstest für ein oder mehrere architectural characteristics – also für die Eigenschaften, die man früher etwas sperrig \"-ilities\" nannte: Performance, Skalierbarkeit, Kopplung, Sicherheit.\n\nDer Perspektivwechsel, der in der Praxis den Unterschied macht, ist folgender: Architektur wird nicht länger als Zustand behandelt, den man einmal beschließt, sondern als Eigenschaft, die man kontinuierlich einhält. Das klingt nach einer Nuance, ist aber ein Bruch im Arbeitsmodus. Ein Diagramm beschreibt, wie das System aussehen soll. Eine Fitness Function beschreibt, wie es aussehen muss – und bricht den Build, wenn es das nicht tut.\n\nDamit wandert ein Teil der Governance von der Sitzung in die Pipeline. Die automatisierbaren Regeln laufen bei jedem Commit mit; Reviews bleiben dort nötig, wo Zielkonflikte, Kontext und fachliche Angemessenheit zählen. Der Gewinn ist vor allem das frühe Feedback: Eine explizit vereinbarte Regel hängt nicht davon ab, ob sie im nächsten Review wieder auffällt. Wer schon einmal erlebt hat, wie ein einziger schleichender Kopplungsverstoß über Monate ein Refactoring blockiert, kennt den Preis der nachgelagerten Kontrolle.\n\n## Die erste Fitness Function ist ein Unit-Test\n\nDer Einstieg ist unspektakulär, und das ist die gute Nachricht. Die einfachste Kategorie sind statische, atomare Fitness Functions – Regeln über die Struktur des Codes, die sich als ganz normaler Test ausdrücken lassen. In der Java-Welt hat sich dafür ArchUnit von TNG etabliert, das über Bytecode-Analyse Paket- und Schichtabhängigkeiten prüft. Für .NET gibt es NetArchTest, im JavaScript-Umfeld den Dependency-Cruiser. Das Prinzip ist überall dasselbe.\n\nDie eingangs beschworene Regel – Domäne kennt keine Infrastruktur – sieht als Fitness Function so aus:\n\n```java\n@ArchTest\nstatic final ArchRule domain_must_not_depend_on_infrastructure =\n    noClasses().that().resideInAPackage(\"..domain..\")\n        .should().dependOnClassesThat().resideInAPackage(\"..infrastructure..\");\n\n@ArchTest\nstatic final ArchRule no_cyclic_dependencies =\n    slices().matching(\"..(*)..\").should().beFreeOfCycles();\n```\n\nDas Schöne daran: Diese Regel ist selbst dokumentierend. Sie steht im Repository, sie läuft in der CI, und sie ist nicht verhandelbar, ohne dass jemand sie sichtbar ändert. Der Confluence-Eintrag von oben beschreibt eine Absicht. Der Test macht dieselbe gewählte Regel ausführbar und ihre Verletzung sichtbar.\n\nDer zweite Block – `no_cyclic_dependencies` – adressiert einen Klassiker, der in Reviews notorisch schwer zu erkennen ist. Zyklische Abhängigkeiten entstehen selten in einem großen Schritt. Sie wachsen aus vielen kleinen, je für sich harmlosen Importen. Ein Mensch sieht den Zyklus im Diagramm nicht mehr, wenn er über sieben Module läuft. Die Maschine schon. Genau solche Eigenschaften – afferent/efferent coupling, Instabilität, Zyklenfreiheit – sind der Idealfall für statische Fitness Functions, weil sie deterministisch und billig zu prüfen sind.\n\n## Mehr als eine Werkzeugliste\n\nWer bei Fitness Functions nur an ArchUnit denkt, verkennt die Reichweite des Konzepts. Ford, Parsons und Kua schlagen eine Taxonomie vor, die sich gut als Sortierhilfe eignet, weil sie den richtigen Testtyp für die jeweilige Eigenschaft nahelegt. Zwei Achsen genügen für den Anfang:\n\n```mermaid\nquadrantChart\n    title Einordnung von Fitness Functions\n    x-axis \"atomic (ein Merkmal)\" --> \"holistic (Zusammenspiel)\"\n    y-axis \"triggered (bei Bedarf)\" --> \"continuous (laufend)\"\n    quadrant-1 \"Latenz-/Lasttests in Prod\"\n    quadrant-2 \"Chaos-/Resilienz-Checks\"\n    quadrant-3 \"ArchUnit-Dependency-Rules\"\n    quadrant-4 \"Security-Scan pro Commit\"\n```\n\n*Atomic* misst eine einzelne Eigenschaft isoliert, *holistic* prüft das Zusammenspiel mehrerer – etwa Sicherheit und Latenz gemeinsam unter Last. *Triggered* läuft auf Anstoß, etwa im Build, *continuous* läuft dauerhaft gegen das produktive System. Dazu kommen weitere Dimensionen aus dem Buch: static versus dynamic, automated versus manual, sowie temporal fitness functions, die bewusst nur für eine begrenzte Zeit gelten – etwa eine Erinnerung, eine Bibliotheksmigration bis zu einem Stichtag abzuschließen.\n\nDer praktische Wert dieser Einteilung liegt nicht in der Klassifikation um ihrer selbst willen. Er liegt darin, dass sie eine Frage erzwingt, der man sonst ausweicht: An welches konkrete architectural characteristic ist diese Prüfung eigentlich gekoppelt? Wer das nicht beantworten kann, baut vermutlich gerade eine Vanity-Metric.\n\n## Wenn die Eigenschaft dynamisch ist\n\nNicht alles lässt sich statisch prüfen. Latenz zum Beispiel ist keine Eigenschaft des Quelltexts, sondern des laufenden Systems. Hier kommen dynamische Fitness Functions ins Spiel, die gegen ein Deployment messen. Konzeptionell bleibt es dasselbe – ein Schwellwert, ein Vergleich, ein Urteil:\n\n```python\ndef latency_fitness(service):\n    p95 = measure_p95_ms(service, window=\"5m\")\n    assert p95 < LATENCY_BUDGET_MS, f\"p95 {p95} exceeds budget\"\n```\n\nSo sauber das aussieht, so gefährlich ist es, diesen Assert blind als hartes Gate in die CI zu hängen. Latenzwerte schwanken. Ein p95 über ein Fünf-Minuten-Fenster kann durch einen einzelnen Garbage-Collection-Peak oder einen langsamen Nachbarn im Cluster reißen, ohne dass sich an deiner Software irgendetwas geändert hätte. Wer das ignoriert, produziert flaky builds – und ein flaky gate wird binnen zwei Wochen weggeklickt oder auskommentiert. Dann hast du die Reibung der Prüfung, aber nicht mehr ihren Nutzen.\n\nDie pragmatische Antwort ist eine Trennung: Statische, deterministische Eigenschaften dürfen den Build blockieren. Dynamische, statistisch schwankende Eigenschaften laufen als beobachtende, getriggerte Checks mit statistischen Fenstern und alarmieren, statt hart zu brechen. Dieselbe Idee, zwei Betriebsmodi – je nachdem, wie deterministisch das gemessene Merkmal ist.\n\nFür resilienzbezogene Eigenschaften lohnt der Blick in Michael Nygards *Release It!*. Die dort beschriebenen Stability Patterns – Circuit Breaker, Bulkhead, Timeout – liefern nicht nur Bausteine für robuste Systeme, sondern auch prüfbare Erwartungen: Öffnet der Circuit Breaker unter simulierter Überlast wie vorgesehen? Auch das ist eine Fitness Function, nur eben eine dynamische.\n\n## Kopplung zwischen Services messen\n\nDie interessanteste Kopplung in verteilten Systemen verläuft nicht innerhalb eines Deployables, sondern zwischen ihnen. Zwei Teams, zwei Services, ein Vertrag – und die stille Annahme, dass der andere sein API nicht kaputtmacht. Consumer-Driven Contract Testing macht diese Annahme prüfbar. Mit Pact und einem Pact Broker beschreibt der Konsument seine Erwartung an den Provider, und der Provider verifiziert gegen genau diese Erwartung.\n\nAls Fitness Function landet das direkt als Schritt in der Deployment-Pipeline:\n\n```bash\npact-broker can-i-deploy \\\n    --pacticipant Checkout \\\n    --version \"$GIT_SHA\" \\\n    --to-environment production\n```\n\nDie Frage \"kann ich das deployen, ohne einen Konsumenten zu brechen?\" wird damit von einer Bauchentscheidung zu einer mechanischen Antwort. Aus der Annahme, kompatibel zu bleiben, wird ein Nachweis – Kopplung als Governance-as-Code. In der Praxis ist das oft der Moment, in dem Teams zum ersten Mal wirklich unabhängig deployen können, weil die Angst vor dem unbemerkten Bruch aus dem Prozess genommen ist.\n\n## Der Ort, an dem alles zusammenläuft\n\nEine lose Sammlung von Regeln entfaltet wenig Wirkung. Wirksam werden Fitness Functions erst als Gate in der Auslieferung. Die Deployment-Pipeline – konzeptuell seit Humble und Farley etabliert – ist der natürliche Ort dafür. Zwischen Build und Deploy liegt eine Barriere, die mehrere Kategorien parallel prüft:\n\n```mermaid\nflowchart LR\n    commit[\"commit\"] --> build[\"build\"]\n    build --> gate{\"Fitness<br/>Functions<br/>Gate\"}\n    gate -->|static / atomic| s[\"Dependency &amp; Cycle Rules\"]\n    gate -->|dynamic / holistic| d[\"Latency p95 &amp; Load\"]\n    gate -->|contract| c[\"Pact can-i-deploy\"]\n    s -->|fail = break build| commit\n    d -->|fail = break build| commit\n    c -->|fail = break build| commit\n    gate -->|all green| deploy[\"deploy\"]\n```\n\nDie roten Rückpfeile sind der Kern der Idee: Ein Verstoß führt nicht zu einem Ticket, das irgendwann priorisiert wird, sondern zu einem gebrochenen Build, den derjenige repariert, der ihn verursacht hat – sofort, mit vollem Kontext, bevor der Fehler in die Historie einsintert. Das ist derselbe Mechanismus, der Continuous Integration wirksam macht, angewandt auf Architektureigenschaften.\n\nUnd hier schließt sich der Kreis zur messbaren Auslieferungsqualität. *Accelerate* von Forsgren, Humble und Kim und die DORA Four Key Metrics – Deployment Frequency, Lead Time for Changes, Change Failure Rate, Time to Restore – liefern Metrics für die Delivery-Ebene. Fitness Functions können dazu passende technische Leitplanken prüfen. Eine verletzte Kopplungsregel fällt dann früh auf; ob dadurch Lead Time oder Fehlerrate sinken, muss das Team an den eigenen Daten überprüfen.\n\n## Wo es in der Praxis kippt\n\nSo überzeugend das Konzept ist, so zuverlässig scheitert seine naive Umsetzung an drei Stellen – und die habe ich in Projekten alle gesehen.\n\nErstens die Vanity-Metric. Eine grüne Fitness Function, die eine reine Test-Coverage-Schwelle prüft, fühlt sich nach Sicherheit an und misst doch nichts Architektonisches. Coverage sagt, wie viel Code ausgeführt wird, nicht, ob die Abhängigkeiten stimmen. Jede Function muss an ein konkretes architectural characteristic gekoppelt sein, sonst ist sie Theater.\n\nZweitens die Wartungslast. Fitness Functions sind Code und altern wie Code. Ich habe Codebasen gesehen, in denen jede zweite Regel ein `@ArchIgnore` trug, weil es unter Termindruck schneller ging, die Ausnahme einzutragen, als das Problem zu lösen. Ohne Ownership und regelmäßiges Aufräumen der Ausnahmeliste erodiert die Aussagekraft, bis nur noch grünes Rauschen bleibt. Diese Regeln brauchen dieselbe Pflege wie Produktionscode – sonst sind sie schlimmer als nichts, weil sie falsche Sicherheit erzeugen.\n\nDrittens der zu späte Einstieg. Wer Fitness Functions auf eine gewachsene Legacy-Codebasis loslässt, bekommt beim ersten Lauf Tausende Violations – und garantiert Frust. Der Ausweg ist eine Baseline: Man friert den Ist-Zustand ein, deklariert Fitness von jetzt an und lässt nur noch Verbesserung zu, keine Verschlechterung. \"Declare fitness from now on\" ist kein Betrug an der Reinheit. In gewachsenen Systemen ist es die einzige Art, wie so etwas überhaupt anläuft.\n\n## Fazit\n\nDer rote Faden dieser drei Bausteine – statische Regeln, dynamische Messungen, Vertragsprüfungen – ist ein einziger Gedanke: Architektur ist eine Eigenschaft, die man einhält, keine Entscheidung, die man einmal trifft. Fitness Functions verschieben die Kontrolle vom Review in die Pipeline und damit von der Hoffnung zur Gewissheit.\n\nDer Gewinn ist selten die einzelne Regel. Er liegt im veränderten Arbeitsmodus. Teams, die ihre wichtigsten Architektureigenschaften mechanisch absichern, diskutieren in Reviews nicht mehr über Importrichtungen, sondern über Fachlichkeit. Sie deployen öfter, weil die stille Angst vor dem unbemerkten Bruch aus dem Prozess genommen ist. Und sie refaktorieren mutiger, weil ein Netz aus grünen Checks sofort meldet, wenn eine Umstrukturierung eine Eigenschaft verletzt.\n\nDer Anfang darf klein sein: eine einzige atomare, statische Regel, die eine Eigenschaft absichert, an der dir wirklich etwas liegt. Eine Abhängigkeitsregel, die den Build bricht, ist mehr wert als zwanzig Regeln in einem Dokument, das keiner liest. Der Rest wächst von dort – als schlichter Code, der bei jedem Build mitläuft und niemandem einen zusätzlichen Prozess aufzwingt.\n\n## Weiterführende Quellen\n\n- Neal Ford, Rebecca Parsons, Patrick Kua: *Building Evolutionary Architectures* (O'Reilly, 2017) – [Kapitel zu Fitness Functions](https://www.oreilly.com/library/view/building-evolutionary-architectures/9781491986356/ch02.html)\n- [ArchUnit (TNG)](https://www.archunit.org/) – statische Architekturtests für Java\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate* (2018) und die DORA Four Key Metrics – [martinfowler.com: StateOfDevOpsReport](https://www.martinfowler.com/bliki/StateOfDevOpsReport.html)\n- Michael Nygard: *Release It!* (2. Auflage, 2018) – Stability Patterns für resilienzbezogene Fitness Functions\n- [Pact](https://docs.pact.io/) – Consumer-Driven Contract Testing mit `can-i-deploy`"},{"locale":"de","translation_key":"svelte-reaktivitaet-compiler-ohne-virtual-dom","slug":"svelte-reaktivitaet-compiler-ohne-virtual-dom","title":"Svelte-Reaktivität: der Compiler statt Virtual DOM","summary":"Svelte kompiliert Komponenten zur Build-Zeit in gezielten DOM-Code, statt zur Laufzeit einen Virtual DOM zu diffen. Ich zeige das mentale Modell, die reaktive Zuweisung mit $: und die klassische push-Falle, die mir in Projekten immer wieder begegnet.","tags":["Software","Frontend","Svelte"],"published_at":"2022-04-26T10:00:00+00:00","updated_at":"2026-07-13T13:25:08.920456+00:00","url":"https://www.mikebild.dev/de/blog/svelte-reaktivitaet-compiler-ohne-virtual-dom/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/f0ef6dba8a07d70d3d2da6973b896daf952f6459e64a67c3601a3aa53ca0c987/svelte-reaktivitaet-compiler-ohne-virtual-dom-vorlesen.mp3","audio_duration_secs":727,"text":"Zwei Regeln tragen einen großen Teil des Legacy-Modells von Svelte 3. Erstens: Der Compiler erkennt Zuweisungen wie `count += 1`, `obj.key = value` oder `array[index] = value`; ein bloßer Methodenaufruf wie `array.push(...)` ist keine solche Zuweisung. Zweitens: Eine `$:`-Anweisung hängt an den Variablen, die der Compiler in ihrem Rumpf statisch erkennt. Daraus folgen die direkte Syntax und einige typische Überraschungen.\n\nBeide Regeln stammen aus derselben Quelle. Svelte entscheidet schon beim Übersetzen einer Komponente, welche Variable welchen DOM-Knoten berührt. Was im Browser ankommt, sind fertige Update-Anweisungen; ein Baumvergleich zur Laufzeit findet nicht statt. `count += 1` genügt deshalb tatsächlich – aber nur, solange man weiß, woran der Compiler eine Änderung erkennt.\n\nGrundlage ist der Stand von Svelte 3, im April 2022 die aktuelle Hauptversion. Alles Folgende beruht auf dem assignment-basierten Reaktivitätsmodell und den `$:`-Deklarationen. Vollständig ist das nicht; es ist der Ausschnitt, an dem sich das mentale Modell am schnellsten begreifen lässt.\n\n**Redaktionelle Einordnung (Juli 2026):** Svelte 5 arbeitet für neuen Code bevorzugt mit Runes wie `$state`, `$derived` und `$effect`. Das hier erklärte `$:`- und Zuweisungsmodell gehört zum weiterhin unterstützten Legacy-Modus. „Ohne Virtual DOM“ stimmt nach wie vor, beschreibt allein aber nicht mehr die heutige Reaktivitäts-API.\n\n## Der Denkfehler, den fast alle mitbringen\n\nWer aus React kommt, trägt ein bestimmtes Bild im Kopf: Eine Komponente ist eine Funktion, die bei jeder State-Änderung neu läuft und eine Beschreibung des gewünschten UI States zurückgibt – einen Virtual-DOM-Baum. Das Framework vergleicht diesen neuen Baum mit dem alten, findet die Unterschiede und überträgt nur die auf das echte DOM. Dieses Diffing ist clever, aber es ist Arbeit, die bei jedem Update im Browser des Nutzers stattfindet. Rich Harris hat das in seinem oft zitierten Text „Virtual DOM is pure overhead“ scharf formuliert: Der Virtual DOM ist kein Feature, für das man dankbar sein sollte, sondern ein Mittel zum Zweck – und ein Mittel mit Preis.\n\nSvelte stellt die Frage anders. Wenn schon zur Build-Zeit feststeht, welche Teile des Markups von welchen Variablen abhängen, warum sollte man diese Zuordnung dann bei jedem Update im Browser neu ausrechnen? Der Svelte-Compiler analysiert die Komponente statisch und erzeugt imperativen JavaScript-Code, der genau die betroffenen DOM-Knoten aktualisiert. Kein Diff-Baum, kein Vergleich zur Laufzeit. Der Compiler weiß schon, dass sich bei einer Änderung von `count` genau dieser eine Textknoten ändern muss, und schreibt exakt diese Anweisung hin.\n\nWichtig ist mir dabei eine Präzisierung, die in Blogposts gern verschwimmt: Svelte ist nicht „gar keine Runtime“. Der kompilierte Code bringt einen kleinen Kern an Hilfsfunktionen mit, in der Größenordnung von wenigen Kilobyte. Was fehlt, ist der Laufzeit-Diff-Algorithmus und ein schwergewichtiges Framework, das im Bundle mitreist. Der korrekte Satz lautet also: kein Virtual DOM, kein Laufzeit-Diffing – nicht: null Runtime.\n\n## Was der Compiler übernimmt\n\nBevor ich zum Code komme, lohnt sich der Blick darauf, welche Aufgaben in Svelte vom Compiler statt von einer Laufzeit-Bibliothek erledigt werden. Genau diese Verschiebung erklärt, warum das Ganze weniger Overhead im Browser bedeutet:\n\n- Die statische Analyse, welcher DOM-Knoten von welcher Zustandsvariablen abhängt – das Ergebnis landet als fester Code im Bundle, nicht als Berechnung zur Laufzeit.\n- Die Erzeugung gezielter Update-Anweisungen, die nur die tatsächlich betroffenen Knoten anfassen, statt einen kompletten Baum zu vergleichen.\n- Die Auflösung der `$:`-Abhängigkeiten: Der Compiler bestimmt aus dem Quelltext, welche Variablen eine reaktive Anweisung liest, und erzeugt daraus den Code für die Neuauswertung.\n\nDieser letzte Punkt ist der, an dem die meisten Fallen liegen, und ihm widme ich weiter unten den größten Teil.\n\n## Reaktivität über Zuweisung\n\nSchauen wir uns die einfachste reaktive Komponente an. Eine Datei mit der Endung `.svelte` bündelt Skript, Markup und Style. Eine ganz normale `let`-Variable auf der obersten Ebene des `<script>`-Blocks ist bereits Komponentenzustand.\n\n```svelte\n<script>\n  let count = 0;\n\n  function handleClick() {\n    count += 1;\n  }\n</script>\n\n<button on:click={handleClick}>\n  Clicked {count} times\n</button>\n```\n\nEs gibt hier keine spezielle State-API. `count` ist eine Variable, `count += 1` ist eine Zuweisung. Der Punkt, an dem für mich alles hängt: Nicht die Variable an sich ist reaktiv, sondern die Zuweisung an sie ist das auslösende Event. Der Compiler hat gesehen, dass `count` im Markup referenziert wird. Also erzeugt er um jede Zuweisung herum den Code, der die Komponente als „dirty“ markiert und den betroffenen Textknoten neu schreibt. Was aussieht wie eine gewöhnliche Wertänderung, ist im kompilierten Ergebnis von einem gezielten Update begleitet.\n\nDas erklärt auch, warum manche Änderungen ins Leere laufen. Wer `count` nur liest oder in einer Hilfsfunktion herumreicht, löst nichts aus. Erst der Zuweisungsoperator ist das Signal.\n\n## Abgeleitete Werte mit `$:`\n\nDer nächste Baustein sind Werte, die sich aus anderen ergeben. In React greift man dafür zu `useMemo` oder rechnet im Render-Körper. In Svelte 3 gibt es die reaktive Deklaration mit dem `$:`-Label.\n\n```svelte\n<script>\n  let count = 0;\n  $: doubled = count * 2;\n\n  function handleClick() {\n    count += 1;\n  }\n</script>\n\n<button on:click={handleClick}>\n  Clicked {count} times\n</button>\n\n<p>{count} * 2 = {doubled}</p>\n```\n\n`$: doubled = count * 2;` liest sich wie eine normale Zuweisung mit einem seltsamen Präfix, ist aber eine Anweisung an den Compiler: „Halte `doubled` aktuell, sobald sich eine seiner Abhängigkeiten ändert.“ Die Abhängigkeiten muss ich dabei nicht selbst angeben. Der Compiler bestimmt sie zur Compile-Zeit aus dem Quelltext – es sind alle Variablen, die in der Anweisung gelesen, aber nicht zugewiesen werden. Hier also `count`. Ändert sich `count` per Zuweisung, läuft die Deklaration erneut, `doubled` bekommt einen neuen Wert, und der abhängige Textknoten aktualisiert sich.\n\n`$:` kann mehr als abgeleitete Werte. Man kann damit auch Side Effects an State-Änderungen koppeln:\n\n```svelte\n<script>\n  let count = 0;\n\n  $: if (count >= 10) {\n    alert(\"count is dangerously high!\");\n  }\n\n  $: console.log(`count is ${count}`);\n</script>\n```\n\nBeide Formen laufen erneut, sobald sich `count` ändert. Der Mechanismus ist derselbe wie bei der Deklaration: gelesene Variablen werden zu Abhängigkeiten, Zuweisungen an sie lösen die Neuauswertung aus. Ein Detail für die Praxis: Diese Anweisungen laufen auch beim serverseitigen Rendern und vor dem ersten Client-Render einmal durch. Sie gehören zum Reaktivitätsfluss selbst und sind kein Ersatz für einen Mount-Hook.\n\nDas folgende Diagramm zeigt diesen Fluss von der Zuweisung bis zum DOM-Update – inklusive des Seitenpfads, der später zur Falle wird.\n\n```mermaid\nflowchart TD\n  A[Zuweisung: count += 1] --> B[Variable als dirty markiert]\n  B --> C[reaktive $:-Deklarationen<br/>neu ausgewertet]\n  C --> D[gezieltes DOM-Update<br/>nur betroffene Knoten]\n  E[array.push item] -.-> F[keine Zuweisung<br/>keine Referenzänderung]\n  F -.-> G[kein Update ausgelöst]\n```\n\n## Build-Zeit gegen Laufzeit\n\nDer Kontrast zu React wird deutlich, wenn man beide Spuren nebeneinanderlegt. Svelte bestimmt Abhängigkeiten und erzeugt Update-Code beim Build; der Browser führt diesen Code bei jeder Änderung weiterhin aus. React erzeugt beim Rendern einen neuen Elementbaum und gleicht ihn zur Laufzeit ab. Svelte verschiebt also die Analyse, nicht die gesamte Aktualisierungsarbeit, in den Build.\n\n```mermaid\nflowchart LR\n  subgraph Build[Build-Zeit – Svelte]\n    S1[.svelte-Komponente] --> S2[Svelte-Compiler]\n    S2 --> S3[gezielter Update-Code<br/>optimiertes Vanilla-JS]\n  end\n  subgraph Runtime[Laufzeit – React]\n    R1[Render-Funktion] --> R2[neuer Virtual-DOM-Baum]\n    R2 --> R3[Diff gegen alten Baum]\n    R3 --> R4[Patch auf echtes DOM]\n  end\n```\n\nDer Kern des Bildes ist nicht „Svelte gut, React schlecht“, sondern eine andere Aufteilung der Arbeit. React gleicht Elementbäume zur Laufzeit ab. Svelte kennt die statisch sichtbaren Abhängigkeiten bereits nach dem Build und liefert dafür gezielten Update-Code aus. Der Nutzer führt diesen Code weiterhin aus, nur keinen Virtual-DOM-Diff für diese Aktualisierung.\n\nBei den Bundle-Größen bleibe ich bewusst vorsichtig. Der Svelte-Kern liegt in der Größenordnung von wenigen Kilobyte, React plus ReactDOM deutlich darüber. Ich nenne das als Größenordnung, nicht als exakte Messung – die konkreten Zahlen hängen von Version, Bundler und dem, was man tatsächlich nutzt, ab, und wer eine harte Zahl braucht, misst am eigenen Projekt.\n\n## Die push-Falle\n\nJetzt zur Kehrseite desselben Modells – der Teil, um den es mir hier eigentlich geht. Weil Reaktivität an die Zuweisung gebunden ist, gibt es eine Klasse von Änderungen, die Svelte 3 schlicht nicht bemerkt: in-place-Mutationen ohne Zuweisung. Der Klassiker ist `Array.push`.\n\n```svelte\n<script>\n  let numbers = [1, 2, 3, 4];\n\n  function addBroken() {\n    numbers.push(numbers.length + 1);\n  }\n</script>\n\n<button on:click={addBroken}>Add number</button>\n\n<p>{numbers.join(\", \")}</p>\n```\n\nMan klickt, die Konsole bestätigt, dass das Array wächst – und im Browser tut sich nichts. Kein Fehler, kein Warnhinweis, einfach kein Update. Der Grund ist konsequent aus dem Modell abgeleitet: `numbers.push(...)` verändert das bestehende Array, aber es gibt keine Zuweisung an `numbers`. Ohne Zuweisung markiert Svelte die Variable nicht als dirty, und ohne dirty-Markierung läuft kein Update. Der Compiler kann nicht wissen, dass eine Methode das Innere des Arrays angefasst hat – er sieht nur Zuweisungen.\n\nDer Fix ist so einfach wie das Problem, sobald man das Modell verinnerlicht hat: Man muss eine Zuweisung erzwingen. Zwei Wege sind gängig.\n\n```svelte\n<script>\n  let numbers = [1, 2, 3, 4];\n\n  function addWorking() {\n    numbers = [...numbers, numbers.length + 1];\n  }\n\n  function addAlsoWorking() {\n    numbers.push(numbers.length + 1);\n    numbers = numbers;\n  }\n</script>\n\n<button on:click={addWorking}>Add number</button>\n\n<ul>\n  {#each numbers as n}\n    <li>{n}</li>\n  {/each}\n</ul>\n```\n\n`numbers = [...numbers, ...]` erzeugt ein neues Array und weist es zu – die saubere, an anderen Frameworks geschulte Variante. `numbers = numbers` sieht dagegen aus wie eine Nulloperation, ist aber genau das, was der Compiler braucht: eine Zuweisung an `numbers`, die die dirty-Markierung setzt. Damit Svelte eine Änderung überhaupt bemerkt, muss der Name der Variablen also auf der linken Seite eines `=` landen.\n\nBei Objekten ist die Lage anders als beim Methodenaufruf: Eine direkte Zuweisung wie `obj.key = value` erkennt Sveltes Legacy-Compiler und aktualisiert abhängige Stellen. Nicht sichtbar bleibt eine Mutation, die nur innerhalb einer aufgerufenen Funktion oder Methode geschieht. Dann braucht es anschließend eine für den Compiler sichtbare Zuweisung oder einen immutable Ersatz per Spread.\n\n## Die stille Schwester: indirekte Abhängigkeiten\n\nEs gibt eine zweite Falle, die aus demselben Prinzip folgt und in Reviews seltener sofort erkannt wird. Der Compiler bestimmt die Abhängigkeiten einer `$:`-Anweisung daraus, welche Variablen im Body direkt referenziert werden. Versteckt man eine Variable hinter einem Funktionsaufruf, taucht sie im Body nicht auf – und wird nicht als Abhängigkeit erkannt.\n\n```svelte\n<script>\n  let count = 0;\n\n  function getCount() {\n    return count;\n  }\n\n  // count is not read directly here,\n  // so it is not a detected dependency\n  $: label = `value is ${getCount()}`;\n</script>\n```\n\n`label` wird beim ersten Durchlauf berechnet und danach nie wieder aktualisiert, weil `count` im Body der reaktiven Deklaration nicht sichtbar ist – dort steht nur `getCount()`. Der Compiler hat keine Möglichkeit, die Abhängigkeit durch die Funktionsgrenze hindurch zu erkennen. Die Lösung ist, die Abhängigkeit sichtbar zu machen, also `count` direkt in der Anweisung zu referenzieren. Eine Schwäche ist das nicht; es ist die logische Konsequenz eines Modells, das statisch zur Compile-Zeit analysiert, statt dynamisch zur Laufzeit zu verfolgen.\n\n## Was das für die Praxis heißt\n\nWenn ich diese beiden Fallen zusammenziehe, ergibt sich ein erstaunlich kompaktes mentales Modell für Svelte 3, das sich auf zwei Punkte eindampfen lässt:\n\n- Reaktivität wird im Legacy-Modus durch statisch sichtbare Zuweisungen ausgelöst. Dazu zählen auch direkte Property- und Index-Zuweisungen, nicht aber beliebige Methodenaufrufe mit internen Mutationen.\n- Abhängigkeiten von `$:` müssen im Body direkt sichtbar sein. Was hinter einem Funktionsaufruf verschwindet, wird nicht getrackt.\n\nDiese zwei Regeln decken einen großen Teil der Überraschungen ab, die mir in Legacy-Svelte-Projekten begegnen. Beide folgen aus derselben Designentscheidung: Die Abhängigkeiten werden beim Build statisch analysiert. Das verlangt Wachsamkeit an Funktionsgrenzen und bei Methoden, die intern mutieren.\n\nIn einem kleinen Daten-Client tragen genau diese reaktiven Zuweisungen den Datenfluss: Eine Antwort ersetzt den bisherigen Wert, und die abhängigen Ausdrücke werden vom Compiler gezielt aktualisiert.\n\n## Fazit\n\nSvelte kehrt eine Grundannahme vieler Frontend-Frameworks um: Statt zur Laufzeit einen Virtual DOM zu vergleichen, lässt es den Compiler beim Build bestimmen, welcher State welchen DOM-Knoten berührt, und erzeugt daraus gezielten Update-Code. Damit entfällt diese Kategorie von Laufzeit-Diffing; wie groß der praktische Vorteil ist, hängt von Anwendung und Update-Pattern ab. Der Alltagscode bleibt angenehm direkt – `count += 1` genügt. Im Legacy-Modus hängt Reaktivität an statisch sichtbaren Zuweisungen. Wer das verinnerlicht, versteht sowohl die `push`-Falle als auch indirekte Abhängigkeiten.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-svelte.html\n- [Svelte Docs](https://svelte.dev/docs) – die `$:`-Syntax und die zur Compile-Zeit bestimmten Abhängigkeiten im Component-Format\n- [Svelte Tutorial](https://svelte.dev/tutorial) – die Kapitel zu Reactivity, Assignments und Updating arrays and objects\n- [Virtual DOM is pure overhead](https://svelte.dev/blog/virtual-dom-is-pure-overhead) – Rich Harris zur Motivation hinter dem Compiler-Ansatz\n- [Write less code](https://svelte.dev/blog/write-less-code) – das Leitprinzip von Svelte, weniger Laufzeit-Code auszuliefern"},{"locale":"de","translation_key":"nodejs-eventemitter-und-ereignismodell","slug":"nodejs-eventemitter-und-ereignismodell","title":"EventEmitter: das Event-Modell im Kern von Node.js","summary":"EventEmitter ist der gemeinsame Nenner unter Streams, HTTP-Server und Prozessen: Ich zeige on/once/off/emit, das Sonderverhalten von 'error' und wie man Listener-Lecks vermeidet.","tags":["Software","Node.js","Backend"],"published_at":"2022-04-19T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-eventemitter-und-ereignismodell/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ff5d94a15642346e127bcaafecd57bac715ec8a6fce53096c5852d47e47c4974/nodejs-eventemitter-und-ereignismodell-vorlesen.mp3","audio_duration_secs":702,"text":"Dass `.on('data', …)` an einem Stream, `.on('request', …)` an einem HTTP-Server und `.on('exit', …)` an einem Kindprozess gleich aussehen, ist keine Konvention, an die sich die Modulautoren freiwillig halten. Die Ähnlichkeit hat einen technischen Grund: Diese Objekte erben alle von derselben Klasse – dem `EventEmitter`. Wer diese eine Klasse durchdrungen hat, versteht damit einen großen Teil der Standardbibliothek.\n\nDieser Artikel nimmt den `EventEmitter` auseinander: erst die Idee dahinter, dann die konkrete API, dann die zwei, drei Stellen, an denen es in der Praxis wehtut. Wer vorher noch einmal nachlesen will, warum Node überhaupt ereignisgetrieben arbeitet, findet das im Beitrag zum [Node.js-Training rund um den Event Loop](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/). Hier geht es um die Schicht direkt darüber.\n\n## Der gemeinsame Nenner unter allem\n\nNode.js ist im Kern ereignisgetrieben. Ein HTTP-Server wartet nicht in einer Schleife auf die nächste Anfrage, sondern meldet an: \"Wenn eine Anfrage kommt, ruf diese Funktion.\" Ein Lesestrom sagt nicht \"gib mir die Daten\", sondern \"sag mir Bescheid, wenn ein Datenstück da ist\". Dieses Muster – Interesse anmelden, später benachrichtigt werden – zieht sich durch die gesamte Plattform.\n\nDamit dieses Muster nicht in jedem Modul neu erfunden wird, gibt es eine gemeinsame Basisklasse. `net.Server`, `http.Server`, die Stream-Klassen `Readable` und `Writable`, das globale `process`-Objekt, die Objekte aus `child_process` – sie alle sind Emitter oder erben von `EventEmitter`. Das erklärt, warum sich `.on()` überall gleich anfühlt: Es ist buchstäblich dieselbe Methode.\n\n```mermaid\nclassDiagram\n  class EventEmitter {\n    +on(event, listener)\n    +once(event, listener)\n    +off(event, listener)\n    +emit(event, ...args)\n  }\n  EventEmitter <|-- HttpServer\n  EventEmitter <|-- Readable\n  EventEmitter <|-- Writable\n  EventEmitter <|-- Process\n  EventEmitter <|-- MyEmitter\n  class HttpServer[\"http.Server\"]\n  class Readable[\"stream.Readable\"]\n  class Writable[\"stream.Writable\"]\n  class Process[\"process\"]\n  class MyEmitter[\"eigene Klasse\"]\n```\n\nDie Klasse selbst liegt im eingebauten Modul `events`. Man erreicht sie klassisch über `require('events')` oder – seit Node 16 möglich – über den Prefix `require('node:events')`. Beide Schreibweisen liefern dieselbe Klasse; der Prefix macht nur unmissverständlich klar, dass ein eingebautes Modul gemeint ist und kein Paket aus `node_modules`.\n\n## Die vier Methoden, um die sich alles dreht\n\nDie API des Emitters ist erstaunlich klein. Vier Methoden reichen für den Alltag. Drei davon – `on`, `once` und `off` – geben den Emitter selbst zurück und sind damit verkettbar; `emit` bildet die Ausnahme und liefert stattdessen einen `boolean`, wie wir gleich sehen werden.\n\n```js\nconst { EventEmitter } = require('node:events');\n\nconst emitter = new EventEmitter();\n\nfunction onTask(job) {\n  console.log('received task', job.id);\n}\n\nemitter.on('task', onTask);        // register a listener\nemitter.emit('task', { id: 1 });   // trigger it synchronously\nemitter.off('task', onTask);       // remove it again\n```\n\n`on(eventName, listener)` hängt einen Listener ans Ende der Liste für dieses Event. `emit(eventName, ...args)` ruft alle registrierten Listener auf und reicht die zusätzlichen Argumente durch. `off(eventName, listener)` – Alias `removeListener` – nimmt einen Listener wieder heraus. Und `once(eventName, listener)` registriert einen Listener, der nach dem ersten Auslösen automatisch verschwindet.\n\nZwei Eigenschaften von `emit` sind für das Verständnis entscheidend, und beide werden gern übersehen:\n\n- `emit` ruft die Listener **synchron** auf. Es gibt hier nichts Asynchrones, keinen Umweg über den Event Loop, keine Verzögerung. Wenn `emit` zurückkehrt, sind alle Listener durchgelaufen.\n- Die Listener laufen **in der Reihenfolge ihrer Registrierung**. Wer zuerst `on()` aufgerufen hat, dessen Funktion läuft zuerst.\n\n```mermaid\nsequenceDiagram\n  participant C as Aufrufer\n  participant E as EventEmitter\n  participant L1 as Listener 1\n  participant L2 as Listener 2\n  C->>E: emit('task', data)\n  E->>L1: listener(data)\n  L1-->>E: fertig\n  E->>L2: listener(data)\n  L2-->>E: fertig\n  E-->>C: return true\n```\n\nDer Rückgabewert von `emit` ist ein `boolean`: `true`, wenn es für dieses Event mindestens einen Listener gab, sonst `false`. Was die Listener selbst zurückgeben, interessiert den Emitter nicht – Rückgabewerte von Listenern werden schlicht ignoriert. Wer aus einem Listener heraus etwas nach draußen melden will, muss das über einen anderen Weg tun, etwa ein weiteres Event oder einen geteilten Zustand.\n\n## on, once und off im Zusammenspiel\n\nDer Unterschied zwischen `on` und `once` klingt harmlos, hat aber Konsequenzen. Ein mit `once` registrierter Listener wird **vor** seinem eigenen Aufruf aus der Liste entfernt und dann ausgeführt. Er feuert also garantiert genau einmal, egal wie oft das Event danach noch ausgelöst wird.\n\n```js\nconst { EventEmitter } = require('node:events');\nconst queue = new EventEmitter();\n\nlet handled = 0;\nqueue.on('task', () => { handled += 1; });\n\nlet drained = 0;\nqueue.once('drain', () => { drained += 1; });\n\nqueue.emit('task');   // handled = 1\nqueue.emit('task');   // handled = 2\nqueue.emit('drain');  // drained = 1\nqueue.emit('drain');  // drained stays 1 - the listener is gone\n```\n\nBeim Entfernen lohnt ein genauer Blick. `off` entfernt **höchstens eine** Instanz eines Listeners. Wenn man dieselbe Funktion versehentlich zweimal mit `on` registriert hat, braucht man auch zwei `off`-Aufrufe, um sie vollständig loszuwerden. Und man kann nur entfernen, was man auch benennen kann – eine anonyme Arrow-Function, die man direkt an `on` übergibt, hat man nachher nicht mehr in der Hand. Deshalb registriere ich Listener, die ich später wieder abmelden will, immer als benannte Funktion oder als Variable.\n\nHier die Semantik der vier auf einen Blick:\n\n- `on` – Listener bleibt registriert und läuft bei jedem `emit` erneut.\n- `once` – Listener läuft genau einmal und entfernt sich vorher selbst.\n- `off` – entfernt eine Instanz eines benannten Listeners; anonyme Funktionen bekommt man so nicht mehr weg.\n- `emit` – ruft alle Listener synchron in Registrierungsreihenfolge auf und liefert `true`/`false` zurück.\n\nNeben diesen vieren gibt es noch nützliche Randmethoden: `prependListener` hängt einen Listener an den Anfang statt ans Ende, `removeAllListeners` räumt komplett auf, `listeners(eventName)` gibt eine Kopie der aktuellen Listener-Liste zurück und `eventNames()` verrät, für welche Events überhaupt jemand registriert ist. Man braucht sie selten, aber wenn man sie braucht, sind sie Gold wert – etwa beim Debuggen der Frage \"wer hört hier eigentlich alles zu?\".\n\n## Das error-Event ist ein Sonderfall\n\nDiese Eigenheit hat in einem Projekt einmal einen laufenden Prozess gekostet: Das Event `'error'` verhält sich anders als alle anderen. Bei einem gewöhnlichen Event ohne Listener passiert nichts – `emit` liefert `false` und gut ist. Beim `'error'`-Event ist das nicht so.\n\nLöst ein Emitter `emit('error', ...)` aus und es ist **kein** Listener für `'error'` registriert, dann wird der Fehler geworfen. Und weil er innerhalb der Emitter-Maschinerie geworfen wird und niemand ihn auffängt, reißt er im Zweifel den ganzen Prozess ab. Aus einem \"ein Stream hat sich beschwert\" wird so ein kompletter Absturz des Node-Prozesses.\n\n```js\nconst { EventEmitter } = require('node:events');\nconst source = new EventEmitter();\n\n// Without this listener the next line would crash the process:\nsource.on('error', (err) => {\n  console.error('handled:', err.message);\n});\n\nsource.emit('error', new Error('boom'));  // handled cleanly\n```\n\nDas ist übrigens keine Schikane, sondern eine bewusste Entscheidung des Node-Teams. Ein Fehler, den niemand behandelt, soll laut sein und nicht still verschluckt werden. Daraus folgt eine einfache Regel: Für jeden Emitter, der Fehler melden kann – und das sind praktisch alle Streams, alle Netzwerkobjekte, alle Kindprozesse – registriere ich einen `'error'`-Listener, bevor die eigentliche Arbeit losgeht. Er ist das Auffangnetz, ohne das die ganze Anwendung an einer einzigen unbehandelten Meldung zerbricht.\n\nEs gibt noch zwei weitere Spezial-Events, die intern verwendet werden: `'newListener'` feuert, bevor ein neuer Listener hinzugefügt wird, und `'removeListener'` feuert, nachdem einer entfernt wurde. Beide sind eher für Werkzeuge und Diagnose gedacht als für den Alltag, aber es ist gut zu wissen, dass es sie gibt, wenn man einmal beobachten will, wer sich wann an- oder abmeldet.\n\n## Zu viele Listener: die Leck-Warnung\n\nNode führt für jeden Emitter Buch darüber, wie viele Listener pro Event registriert sind. Überschreitet diese Zahl einen Schwellenwert – standardmäßig 10 –, gibt Node eine Warnung auf stderr aus: die `MaxListenersExceededWarning`.\n\nDiese Warnung ist keine Fehlermeldung und stoppt nichts. Sie ist eine Heuristik gegen eine sehr häufige Fehlerklasse: das Listener-Leck. Der typische Fall sieht so aus, dass irgendwo pro Anfrage, pro Schleifendurchlauf oder pro Wiederholung ein `on()` aufgerufen wird, das dazugehörige `off()` aber fehlt. Die Listener stapeln sich, der Speicher wächst, und irgendwann meldet sich Node.\n\n```js\nconst { EventEmitter } = require('node:events');\nconst bus = new EventEmitter();\n\n// Optional: make the warning itself visible\nprocess.on('warning', (warning) => {\n  console.log(warning.name, '- count:', warning.count);\n});\n\n// Anti-pattern: a new, never-removed listener on every iteration\nfor (let i = 0; i < 12; i += 1) {\n  bus.on('data', (chunk) => processChunk(chunk));\n}\n// From the 11th listener on, the MaxListenersExceededWarning appears.\n```\n\nEntscheidend ist: Die Warnung ist das Symptom, nicht die Ursache. Die Ursache ist die nie entfernte Registrierung. Wer die Warnung mit `emitter.setMaxListeners(Infinity)` zum Schweigen bringt, hat nur das Warnlämpchen abgeklebt – das Leck läuft weiter, der Speicher wächst weiter. Richtig ist, die Listener wieder abzumelden, wenn man sie nicht mehr braucht, oder sie gleich als `once` zu registrieren, wenn sie ohnehin nur einmal feuern sollen.\n\n```js\nfunction onData(chunk) {\n  processChunk(chunk);\n}\n\nbus.on('data', onData);\n// ... later, when done:\nbus.off('data', onData);   // cleanly removed, no pile-up\n```\n\nDas heißt nicht, dass der Schwellenwert von 10 in Stein gemeißelt ist. Es gibt legitime Fälle, in denen ein Emitter bewusst mehr Listener hat. Dann justiert man das absichtlich: `emitter.setMaxListeners(n)` hebt das Limit für einen einzelnen Emitter an, `events.defaultMaxListeners = n` verschiebt den globalen Standardwert. Der Wert `0` beziehungsweise `Infinity` schaltet die Warnung ganz ab. Wichtig ist nur, dass diese Entscheidung eine bewusste ist und kein Reflex, um die Meldung im Log loszuwerden.\n\n## Eine eigene Klasse bauen\n\nDer `EventEmitter` ist nicht nur etwas, von dem die Standardbibliothek erbt – man kann ihn genauso gut selbst als Basis nehmen. Immer dann, wenn eine eigene Komponente ihre Umgebung über Dinge informieren soll, ohne die Empfänger fest zu kennen, ist ein Emitter die naheliegende Wahl.\n\nDas Muster ist `class MyThing extends EventEmitter` mit einem `super()`-Aufruf im Konstruktor. Hier eine kleine Aufgabenwarteschlange, die meldet, wenn eine Aufgabe hinzukommt, wenn sie abgearbeitet ist und wenn etwas schiefgeht:\n\n```js\nconst { EventEmitter } = require('node:events');\n\nclass TaskQueue extends EventEmitter {\n  constructor() {\n    super();\n    this.pending = [];\n  }\n\n  add(job) {\n    this.pending.push(job);\n    this.emit('task', job);\n  }\n\n  run() {\n    while (this.pending.length > 0) {\n      const job = this.pending.shift();\n      try {\n        job.handler();\n        this.emit('done', job);\n      } catch (cause) {\n        // Only emit 'error' when a listener exists -\n        // otherwise it crashes the process:\n        if (this.listenerCount('error') > 0) {\n          this.emit('error', cause);\n        } else {\n          throw cause;\n        }\n      }\n    }\n    this.emit('drain');\n  }\n}\n\nconst queue = new TaskQueue();\n\nqueue.on('task', (job) => console.log('queued', job.id));\nqueue.on('done', (job) => console.log('done', job.id));\nqueue.once('drain', () => console.log('all work finished'));\nqueue.on('error', (err) => console.error('failed:', err.message));\n\nqueue.add({ id: 1, handler: () => {} });\nqueue.add({ id: 2, handler: () => { throw new Error('bad job'); } });\nqueue.run();\n```\n\nAn diesem Beispiel sieht man mehrere Dinge zusammenwirken. Die Queue kennt ihre Listener nicht – sie ruft `emit` auf und wer will, hört zu. `once('drain', ...)` sorgt dafür, dass die Abschlussmeldung genau einmal kommt. Und beim Fehlerfall prüfe ich mit `listenerCount('error')`, ob überhaupt jemand zuhört, bevor ich `emit('error', ...)` aufrufe. So vermeide ich den Absturz durch ein unbehandeltes `'error'`-Event und lasse den Fehler stattdessen als gewöhnliche Exception weiterlaufen, wenn niemand ihn abfängt.\n\nEin kleiner, aber wiederkehrender Stolperstein bei eigenen Klassen betrifft `this`. In einem klassischen Function-Listener zeigt `this` auf den Emitter, der das Event ausgelöst hat – praktisch, wenn man von innen auf den Emitter zugreifen will. In einer Arrow-Function gilt das nicht; dort behält `this` seine Bedeutung aus dem umgebenden Kontext. Beides ist legitim, man muss sich nur bewusst sein, welche Variante man wählt.\n\n## Synchron heißt synchron\n\nZum Schluss noch eine Klarstellung, die im Alltag Fehler verhindert. Weil Node so stark mit Asynchronität verbunden ist, nehmen viele intuitiv an, `emit` würde die Listener irgendwann später aufrufen. Das tut es nicht. Der Aufruf ist synchron, und die Listener blockieren den aufrufenden Code, bis sie durch sind.\n\nDas ist meistens genau richtig, denn es macht den Ablauf vorhersehbar. Wer aber innerhalb eines Listeners bewusst etwas aus dem aktuellen Ablauf herauslösen will – damit lange Arbeit den `emit`-Aufrufer nicht aufhält –, muss das ausdrücklich tun, etwa mit `setImmediate` oder `process.nextTick`. Der Emitter selbst plant nichts um; er ruft nur der Reihe nach auf, was registriert ist.\n\n## Fazit\n\nDer `EventEmitter` ist eine kleine Klasse mit großer Reichweite. Vier Methoden – `on`, `once`, `off`, `emit` – tragen den Alltag, und weil ein großer Teil der Standardbibliothek von genau dieser Klasse erbt, überträgt sich das Verständnis unmittelbar auf Streams, Server und Prozesse. Zwei Dinge sollte man dabei nie aus den Augen verlieren: Das `'error'`-Event stürzt ohne Listener den Prozess ab, deshalb gehört überall dort, wo Fehler gemeldet werden können, ein `'error'`-Listener hin. Und die `MaxListenersExceededWarning` ist ein ehrliches Warnsignal für ein Leck, kein lästiger Hinweis, den man wegkonfiguriert. Mit diesen beiden Reflexen schreibt man ereignisgetriebenen Node-Code, der auch dann noch stabil läuft, wenn es ungemütlich wird.\n\n## Weiterführende Quellen\n\n- Node.js-Doku: [Events-API](https://nodejs.org/docs/latest-v16.x/api/events.html)\n- Node.js-Guide: [The Node.js Event emitter](https://nodejs.org/en/learn/asynchronous-work/the-nodejs-event-emitter)\n- Node.js-Doku: [Stream-API](https://nodejs.org/docs/latest-v16.x/api/stream.html) (erbt von `EventEmitter`)\n- Eigener Beitrag: [Node.js-Training rund um den Event Loop](https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/)"},{"locale":"de","translation_key":"graphql-paginierung-und-connections","slug":"graphql-paginierung-und-connections","title":"GraphQL-Paginierung: Cursor, Connections und das Relay-Pattern","summary":"Warum offset/limit bei bewegten Listen Duplikate und Lücken produziert und wie cursor-basierte Paginierung mit dem Connections-Pattern stabil bleibt – inklusive Schema, Resolver-Skizze und den Fallstricken aus der Projektpraxis.","tags":["Software","GraphQL","API"],"published_at":"2022-03-08T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/graphql-paginierung-und-connections/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/e808d98c926de740f80ca7763d4ba6fcf557691e34fd1142243cf20286bc0aa0/graphql-paginierung-und-connections-vorlesen.mp3","audio_duration_secs":743,"text":"Wer eine Liste über Positionen durchblättert, verlässt sich stillschweigend darauf, dass in der Zwischenzeit niemand schreibt. Im Produktivbetrieb trägt diese Annahme selten. Eine Position ist kein Anker in den Daten, sie ist eine Zählung – und Zählungen verschieben sich, sobald vorne ein Datensatz dazukommt oder verschwindet. Die Folgeanfrage stellt dann nicht mehr die Frage, die der Client stellen wollte.\n\nPaginierung ist deshalb einer der Punkte, an denen sich zeigt, ob eine API robust ist oder nur im Demo-Fall funktioniert. Solange die Liste stillsteht, tut offset/limit tadellos seinen Dienst. Sobald sie sich unter dem blätternden Client verändert – und das ist der Normalfall, nicht die Ausnahme – entstehen Fehler, die schwer zu reproduzieren und noch schwerer zu erklären sind. Genau dafür hat die GraphQL-Community mit dem Connections-Pattern eine eigene Konvention etabliert. Darum geht es hier.\n\n## Warum offset/limit bei bewegten Listen versagt\n\nMachen wir das Problem konkret. Ich habe eine nach Erstelldatum absteigend sortierte Liste und blättere sie in Zweierschritten durch. Der Client fragt die erste Seite an: `offset: 0, limit: 2`. Er bekommt die Einträge an den Positionen 0 und 1. Für die nächste Seite fragt er `offset: 2, limit: 2`.\n\nDas Tückische: `offset` ist eine reine Positionszählung. Es sagt \"überspringe die ersten zwei Elemente\" – aber es hat keine Ahnung, *welche* zwei Elemente das beim ersten Aufruf waren. Wenn zwischen den beiden Anfragen vorne ein neuer Eintrag eingefügt wird, rutscht die ganze Liste um eine Position nach hinten. Das Element, das eben noch auf Position 1 lag, liegt jetzt auf Position 2 – und wird dem Client bei `offset: 2` ein zweites Mal ausgeliefert. Ein Duplikat.\n\nDer umgekehrte Fall ist genauso ärgerlich: Wird vorne ein Eintrag gelöscht, rückt alles eine Position nach vorne. Das Element, das auf Position 2 lag, springt auf Position 1 – und wird bei `offset: 2` übersprungen. Eine Lücke. Der Nutzer sieht einen Eintrag nie, obwohl er existiert.\n\n```mermaid\nflowchart TB\n  subgraph stabil[\"Stabil: cursor-basiert\"]\n    direction LR\n    a1[\"Anfrage 1<br/>first: 2\"] --> a2[\"liefert A, B<br/>endCursor = B\"]\n    a2 --> a3[\"Anfrage 2<br/>after: Cursor von B\"]\n    a3 --> a4[\"liefert C, D<br/>kein Duplikat\"]\n  end\n  subgraph kaputt[\"Verschoben: offset/limit\"]\n    direction LR\n    b1[\"Anfrage 1<br/>offset 0, limit 2\"] --> b2[\"liefert A, B\"]\n    b2 --> b3[\"neuer Eintrag X<br/>wird vorne eingefügt\"]\n    b3 --> b4[\"Anfrage 2<br/>offset 2, limit 2\"]\n    b4 --> b5[\"liefert B, C<br/>B doppelt\"]\n  end\n```\n\nDer Kern ist immer derselbe: Offset zählt Positionen, und Positionen sind kein stabiler Anker, sobald sich die Liste vorne verändert. Offset ist wie die Ansage im Zug \"steigen Sie am dritten Halt aus\" – wunderbar, solange niemand einen Zwischenhalt einlegt.\n\n## Der cursor-basierte Ausweg\n\nDie Lösung ist ein Wechsel der Frage. Statt \"gib mir die Elemente ab Position N\" fragt der Client \"gib mir die Elemente *nach diesem konkreten Element*\". Dieses \"diesem konkreten Element\" wird durch einen **Cursor** repräsentiert – einen opaken Zeiger, den der Server ausgibt und den der Client unverändert zurückreicht.\n\nDer entscheidende Unterschied: Ein Cursor ist an ein Element beziehungsweise dessen Sortierwert gebunden, nicht an eine Position. Wenn der Client sagt \"weiter nach dem Element mit Cursor X\", dann bleibt diese Aussage korrekt, egal wie viele Einträge davor eingefügt oder gelöscht werden. Das Fenster verschiebt sich nicht, weil es nicht an einer Zählung hängt, sondern an einem Anker in den Daten.\n\nEin Punkt, der in Code-Reviews regelmäßig auffällt: Der Cursor ist **opak**. Der Client darf keine Struktur annehmen und keine Arithmetik damit treiben. Er darf ihn nur wieder zurückgeben. Das ist bewusst so – der Server bestimmt allein, was ein Cursor bedeutet. Heute mag darin eine ID stecken, morgen eine Kombination aus Sortierfeld und ID, übermorgen etwas völlig anderes. Solange der Client den Cursor nur durchreicht, kann der Server seine Cursor-Implementierung wechseln, ohne dass ein einziger Client kaputtgeht. Üblich ist eine Base64-Kodierung – aber das ist Konvention, keine Vorschrift, und dient nur dazu, dass niemand in Versuchung gerät, den Inhalt zu interpretieren.\n\n## Das Connections-Pattern: edges, node, pageInfo\n\nDamit sind wir beim eigentlichen Thema. Die GraphQL-Community hat rund um cursor-basierte Paginierung eine Konvention formalisiert: die Relay Cursor Connections Specification. Man muss Relay als Framework nicht einsetzen, um von dem Muster zu profitieren – es hat sich als De-facto-Standard etabliert, weil es eine wichtige Frage sauber löst: Wo hänge ich eigentlich den Cursor hin?\n\nDie naive Antwort wäre, den Cursor direkt an den Datensatz zu kleben. Aber der Cursor ist keine Eigenschaft des Nutzers oder des Artikels – er ist eine Eigenschaft *dieser Position in dieser Liste*. Deshalb führt das Muster eine Zwischenschicht ein, die **Edge**. Eine Edge verbindet den eigentlichen Datensatz (`node`) mit seinem `cursor`. Der `node` bleibt sauber, die listenspezifische Information sitzt auf der Kante.\n\nDarüber liegt die **Connection**. Sie bündelt die Liste der Edges und ein Objekt namens `pageInfo`, das die Metainformationen fürs Weiterblättern trägt.\n\nWas liefern die einzelnen Bausteine konkret?\n\n- `edges` ist die Liste der Kanten. Jede Edge enthält `node` (den reinen Datensatz, ohne List-Wrapper) und `cursor` (den opaken Zeiger auf genau diese Edge).\n- `pageInfo.hasNextPage` sagt, ob es nach der aktuellen Seite noch weitere Elemente gibt. Das ist die maßgebliche Abbruchbedingung fürs Blättern.\n- `pageInfo.hasPreviousPage` ist das Gegenstück für die Rückwärtsrichtung.\n- `pageInfo.endCursor` ist der Cursor des letzten Elements der aktuellen Seite – genau der Wert, den der Client als `after` in die Folgeanfrage steckt.\n- `pageInfo.startCursor` ist das Pendant am Anfang der Seite, relevant fürs Rückwärtsblättern mit `before`.\n\nZur Namenskonvention: Der Connection-Typ endet auf `Connection`, der Edge-Typ auf `Edge`. `pageInfo` ist non-null, ebenso die beiden Booleans in `PageInfo`. Die beiden Cursor-Felder `startCursor` und `endCursor` dagegen sind nullable – bei einer leeren Seite gibt es schlicht keinen Cursor.\n\nEin oft gesehenes Feld ist `totalCount`, also die Gesamtzahl der Treffer. Das ist praktisch, hat aber einen Haken: `totalCount` ist **nicht** Teil der Connections-Spezifikation. Es ist eine verbreitete optionale Erweiterung, und je nach Datenquelle kann ein exaktes `COUNT` teuer sein. Wer es aufnimmt, sollte das bewusst tun und nicht in der Annahme, es gehöre zum Standard dazu.\n\n## Ein Beispiel-Schema\n\nGenug Prosa, schauen wir auf SDL. Eine Query, die Nutzer paginiert ausliefert, sieht im Connections-Pattern so aus:\n\n```graphql\ntype Query {\n  users(first: Int, after: String): UserConnection!\n}\n\ntype UserConnection {\n  edges: [UserEdge!]!\n  pageInfo: PageInfo!\n  totalCount: Int\n}\n\ntype UserEdge {\n  node: User!\n  cursor: String!\n}\n\ntype PageInfo {\n  hasNextPage: Boolean!\n  hasPreviousPage: Boolean!\n  startCursor: String\n  endCursor: String\n}\n\ntype User {\n  id: ID!\n  name: String!\n  createdAt: String!\n}\n```\n\nDie Argumente folgen der Spezifikation. Für Vorwärts-Paginierung gibt es `first: Int` (die gewünschte Seitengröße, nicht-negativ) und `after: String` (der Cursor, hinter dem es weitergehen soll). Für die Rückwärtsrichtung gibt es analog `last: Int` und `before: String`. `first` und `last` gleichzeitig zu senden ist laut Spezifikation ausdrücklich unerwünscht – das Ergebnis wäre mehrdeutig.\n\nEine Query vom Client liest sich dann so:\n\n```graphql\nquery FirstPage {\n  users(first: 2) {\n    edges {\n      cursor\n      node {\n        id\n        name\n      }\n    }\n    pageInfo {\n      hasNextPage\n      endCursor\n    }\n  }\n}\n```\n\nUnd die Folgeanfrage nimmt den `endCursor` der vorigen Antwort als `after`:\n\n```graphql\nquery NextPage {\n  users(first: 2, after: \"dXNlcjpjdXJzb3I6NDI=\") {\n    edges {\n      cursor\n      node {\n        id\n        name\n      }\n    }\n    pageInfo {\n      hasNextPage\n      endCursor\n    }\n  }\n}\n```\n\nViele Einführungsbeispiele – auch mein eigenes Grundlagenmaterial – zeigen vereinfachte Varianten, etwa `skip`/`take` oder ein `after: 99`, bei dem der Cursor verdächtig nach einer ID oder einem Offset aussieht. Zum Erklären taugt das, das echte Relay-Pattern ist es nicht. Ein produktiver Cursor ist opak und sieht eben *nicht* nach einer lesbaren Zahl aus. Diese Unterscheidung lohnt den zusätzlichen Satz, sonst rechnet später jemand auf dem Client mit dem Cursor herum.\n\n## Die Resolver-Skizze\n\nAuf der Serverseite muss der Resolver drei Dinge tun: den eingehenden Cursor dekodieren, die passende Datenmenge laden und daraus Edges plus `pageInfo` bauen. Der spannendste Trick steckt in der Ermittlung von `hasNextPage`.\n\nEin häufiger Anfängerfehler ist, `hasNextPage` daraus abzuleiten, ob das Ergebnis kleiner als `first` ist. Das ist unzuverlässig: Wenn zufällig genau `first` Elemente übrig sind, wüsste man nicht, ob danach noch etwas kommt. Der saubere Weg ist, ein Element mehr zu laden, als angefragt wurde – `first + 1`. Existiert dieses Extra-Element, gibt es eine nächste Seite. Anschließend kürzt man das Ergebnis wieder auf `first`.\n\n```js\nfunction encodeCursor(id) {\n  return Buffer.from(`cursor:${id}`).toString(\"base64\");\n}\n\nfunction decodeCursor(cursor) {\n  const decoded = Buffer.from(cursor, \"base64\").toString(\"utf8\");\n  return Number(decoded.split(\":\")[1]);\n}\n\nasync function usersResolver(_parent, args, context) {\n  const { first = 20, after } = args;\n  const limit = Math.min(first, 100); // enforce an upper bound\n  const afterId = after ? decodeCursor(after) : 0;\n\n  // load one extra row to detect a following page\n  const rows = await context.db.query(\n    `SELECT id, name, created_at\n       FROM users\n      WHERE id > $1\n      ORDER BY id ASC\n      LIMIT $2`,\n    [afterId, limit + 1]\n  );\n\n  const hasNextPage = rows.length > limit;\n  const pageRows = hasNextPage ? rows.slice(0, limit) : rows;\n\n  const edges = pageRows.map((row) => ({\n    node: row,\n    cursor: encodeCursor(row.id),\n  }));\n\n  return {\n    edges,\n    pageInfo: {\n      hasNextPage,\n      hasPreviousPage: Boolean(after),\n      startCursor: edges.length ? edges[0].cursor : null,\n      endCursor: edges.length ? edges[edges.length - 1].cursor : null,\n    },\n  };\n}\n```\n\nZwei Details lohnen den zweiten Blick. Erstens die Obergrenze: Ohne ein `Math.min` könnte ein Client `first: 1000000` senden und die Datenbank in die Knie zwingen. Eine erzwungene Obergrenze ist Pflicht, nicht Kür. Zweitens die Cursor-Helfer `encodeCursor`/`decodeCursor` – sie demonstrieren, dass hinter dem opaken String hier schlicht eine ID steckt, aber der Client das eben nicht wissen muss.\n\nDer Ablauf über mehrere Seiten sieht als Dialog zwischen Client und Server so aus:\n\n```mermaid\nsequenceDiagram\n  participant C as Client\n  participant S as Server\n  C->>S: users(first: 2)\n  S-->>C: edges A, B<br/>pageInfo endCursor=B, hasNextPage=true\n  C->>S: users(first: 2, after: Cursor B)\n  S-->>C: edges C, D<br/>pageInfo endCursor=D, hasNextPage=true\n  C->>S: users(first: 2, after: Cursor D)\n  S-->>C: edges E<br/>pageInfo endCursor=E, hasNextPage=false\n  Note over C,S: Schleife endet, sobald hasNextPage=false\n```\n\nDer Client blättert also in einer simplen Schleife: Solange `hasNextPage` wahr ist, schickt er die nächste Anfrage mit dem zuletzt erhaltenen `endCursor` als `after`. Kein Positionszählen, kein Nachrechnen.\n\n## Der Preis der Sortierung – und ein Datenbank-Bonus\n\nEin Punkt, an dem cursor-basierte Paginierung stillschweigend scheitert, ist eine mehrdeutige Sortierung. Der Cursor braucht eine **deterministische, eindeutige** Ordnung. Sortiere ich etwa nur nach `created_at`, und zwei Datensätze tragen denselben Zeitstempel, dann ist an dieser Gleichstands-Stelle nicht definiert, welcher zuerst kommt – und genau dort entstehen wieder Duplikate oder Auslassungen. Die Lösung ist ein Tie-Breaker: Man sortiert zusätzlich nach einer garantiert eindeutigen Spalte, in der Regel der ID. Aus `ORDER BY created_at` wird `ORDER BY created_at, id`.\n\nDamit fällt ein hübscher Side Effect ab. Cursor-Paginierung lässt sich in SQL als sogenannte Keyset-Pagination formulieren, und die skaliert deutlich besser als große Offsets:\n\n```sql\nSELECT id, created_at, name\n  FROM users\n WHERE (created_at, id) > (:cursor_created_at, :cursor_id)\n ORDER BY created_at, id\n LIMIT :page_size;\n```\n\nDer Grund: Ein großes `OFFSET n` zwingt die Datenbank, `n` Zeilen zu lesen und wegzuwerfen, bevor sie überhaupt anfängt zu liefern – bei tiefen Seiten wird das spürbar langsam. Die Keyset-Variante mit `WHERE (sort_key, id) > (...)` kann dagegen direkt über den Index an die richtige Stelle springen. Cursor-Paginierung ist also nicht nur korrekter bei bewegten Listen, sie ist bei tiefem Blättern oft auch schneller.\n\n## Wann offset trotzdem in Ordnung ist\n\nCursor-Paginierung ist kein Selbstzweck. Es gibt Fälle, in denen offset völlig ausreicht:\n\n- Die Liste ist im Wesentlichen stabil, etwa ein historisches Archiv oder ein abgeschlossener Report, in den nichts mehr eingefügt wird.\n- Der Nutzer soll gezielt zu Seite 7 springen können – nummerierte Seiten sind mit reinen Cursorn nicht ohne Weiteres darstellbar, weil man keine absolute Position kennt.\n- Die Datenmengen sind klein und die Seiten flach, sodass weder Konsistenz- noch Performance-Probleme auftreten.\n\nEs geht also nicht um Dogma, sondern um eine bewusste Wahl. Sobald eine Liste sich unter dem Nutzer verändern kann *und* er sie potenziell tief durchblättert – Feeds, Timelines, Aktivitätsströme – ist cursor-basierte Paginierung mit dem Connections-Pattern die richtige Antwort. Für ein stabiles, überschaubares Nachschlagewerk darf offset gern bleiben.\n\n## Fazit\n\nPaginierung wirkt banal, bis man sie unter Bewegung betrachtet. Offset zählt Positionen, und Positionen verschieben sich – das Ergebnis sind Duplikate und Lücken, die im ruhigen Demo-Betrieb nie auftauchen und im Produktivbetrieb schwer zu fassen sind. Der cursor-basierte Ansatz ersetzt die Frage \"ab welcher Position\" durch \"nach welchem Element\" und wird damit gegen Veränderungen an der Liste robust.\n\nDas Connections-Pattern gießt diese Idee in eine saubere Struktur: Edges tragen den listenspezifischen Cursor, Nodes bleiben reine Datensätze, und `pageInfo` liefert mit `hasNextPage` und `endCursor` genau die zwei Angaben, die ein Client zum korrekten Weiterblättern braucht. Dazu kommen die Details, die den Unterschied zwischen Demo und Produktion ausmachen – ein Extra-Element für `hasNextPage`, ein Tie-Breaker in der Sortierung, eine Obergrenze für die Seitengröße und die Disziplin, den Cursor wirklich opak zu behandeln. Wer diese vier Dinge beherzigt, hat eine Paginierung, die auch dann noch stimmt, wenn die Liste sich unter den Fingern des Nutzers bewegt.\n\n## Weiterführende Quellen\n\n- Grounding-Repository: [introduction-graphql](https://github.com/mikebild/introduction-graphql) (`introduction-graphql/paging.md`)\n- [GraphQL Pagination – offizielle Lernressource](https://graphql.org/learn/pagination/)\n- [GraphQL Cursor Connections Specification](https://relay.dev/graphql/connections.htm)"},{"locale":"de","translation_key":"sveltekit-adapter-aws","slug":"sveltekit-adapter-aws","title":"SvelteKit Adapter AWS: Framework trifft Cloud","summary":"Warum ich einen eigenen SvelteKit-Adapter für AWS gebaut habe und was die Übersetzung zwischen Framework-Build und Lambda, S3 und CloudFront über beide Seiten verrät.","tags":["Software","AWS","Cloud"],"published_at":"2022-01-12T10:00:00+00:00","updated_at":"2026-07-14T17:18:34.934208+00:00","url":"https://www.mikebild.dev/de/blog/sveltekit-adapter-aws/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/4e850c1423335c5bba5a826754dbb26d69a667201217af5d37c25bd776dc21ff/sveltekit-adapter-aws-vorlesen.mp3","audio_duration_secs":709,"text":"# SvelteKit Adapter AWS: Framework trifft Cloud\n\nWenn das Deployment-Modell eines Frameworks und die Zielplattform nicht zusammenpassen, entsteht in Projekten immer dasselbe Nebenprodukt: ein handgeschriebenes Deploy-Skript. Es kopiert Build-Ausgaben in einen S3-Bucket, zippt irgendwo einen Lambda-Handler, setzt Cache-Header von Hand und invalidiert am Schluss eine CloudFront-Verteilung. Das funktioniert – bis das Framework die Struktur seiner Build-Ausgabe ändert, bis ein Header vergessen wird oder bis die eine Person das Projekt verlässt, die das Skript noch erklären kann. Danach hat das Team ein Deployment, dem niemand mehr traut, und jedes Release wird zur Mutprobe.\n\nGenau an diesem Punkt stehen Anfang 2022 SvelteKit-Anwendungen, die auf AWS laufen sollen. SvelteKit selbst ist noch Beta – Version 1.0 ist angekündigt, aber nicht erschienen – und bringt für dieses Problem ein bemerkenswert klares Konzept mit: Adapter. Es gibt `adapter-node` für den eigenen Server, `adapter-static` für rein statische Seiten, `adapter-vercel` und `adapter-netlify` für die jeweiligen Plattformen. Einen offiziellen Adapter für AWS gibt es nicht. Also habe ich einen geschrieben: [sveltekit-adapter-aws](https://github.com/MikeBild/sveltekit-adapter-aws), ein Open-Source-Projekt, das eine SvelteKit-App per AWS CDK auf Lambda, S3 und CloudFront ausrollt. Beim Bauen ist mir einiges über beide Seiten aufgefallen – über das Framework und über die Cloud. Darum geht es hier.\n\n## Adapter sind eine Architekturgrenze\n\nEin SvelteKit-Adapter ist im Kern ein Node-Modul mit einer einzigen wesentlichen Funktion: `adapt()`. Nach dem eigentlichen Build ruft SvelteKit diese Funktion auf und übergibt ein `builder`-Objekt, über das der Adapter die Build-Ausgaben abholt: den Client-Code für den Browser, den Server-Code für das Rendering, die vorgerenderten Seiten. Was der Adapter daraus macht, ist seine Sache. `adapter-node` baut einen startbaren HTTP-Server, `adapter-static` eine Verzeichnisstruktur für beliebige Webserver, `adapter-vercel` genau das Format, das die Vercel-Plattform erwartet.\n\nDiese Grenze ist bewusst gezogen. Das Framework weiß, wie aus Routen, Komponenten und Endpoints eine Anwendung wird. Es weiß nicht – und will nicht wissen –, wo diese Anwendung später läuft. Alles Plattformspezifische wandert hinter die Adapter-Schnittstelle. Für den Anwender reduziert sich die Entscheidung auf eine Zeile in der `svelte.config.js`:\n\n```javascript\nimport { adapter } from 'sveltekit-adapter-aws';\nimport preprocess from 'svelte-preprocess';\n\nexport default {\n  preprocess: preprocess(),\n  kit: {\n    adapter: adapter({\n      autoDeploy: true,\n      FQDN: 'demo.example.com',\n      MEMORY_SIZE: 256,\n      LOG_RETENTION_DAYS: 7,\n    }),\n  },\n};\n```\n\nMit `autoDeploy: true` rollt der Build-Schritt die Anwendung direkt aus – `svelte-kit build` endet dann nicht mit einem Verzeichnis, sondern mit einem laufenden CloudFormation-Stack. Das ist für Prototypen und kleine Projekte angenehm; für alles andere lässt sich über `cdkProjectPath` eine eigene CDK-App einhängen, die den Adapter-Output als Baustein verwendet.\n\n## Warum es den AWS-Adapter nicht gab\n\nDass Vercel und Netlify eigene Adapter haben und AWS nicht, ist kein Zufall und kein Versäumnis. Vercel und Netlify sind Plattformen: Sie kontrollieren beide Seiten der Schnittstelle und können exakt definieren, welches Artefakt sie erwarten. AWS ist keine Plattform in diesem Sinn, sondern ein Baukasten. Es gibt keinen einzelnen Dienst namens „SvelteKit-Hosting\", sondern Dutzende Primitive, aus denen man sich eines von vielen möglichen Deployments zusammensetzt.\n\nEin AWS-Adapter muss deshalb etwas tun, was die Plattform-Adapter nicht tun müssen: eine Architektur festlegen. Welcher Dienst beantwortet SSR-Anfragen? Wo liegen die statischen Dateien? Wer verteilt den Traffic? Das sind Entscheidungen, die sonst ein Architekt in einem Design-Dokument trifft – hier stecken sie in einem npm-Paket. Genau das macht so einen Adapter zu einem interessanten Stück Software: Er ist geronnene Architektur, versioniert und wiederverwendbar.\n\n## Die Architektur: drei Dienste, eine Anwendung\n\nDie Aufteilung, für die ich mich entschieden habe, folgt dem Charakter der Build-Ausgaben. Eine gebaute SvelteKit-App zerfällt in zwei grundverschiedene Teile: statische Dateien (Client-Bundles, Assets, vorgerenderte Seiten), die sich beliebig cachen lassen, und einen Server-Teil, der pro Anfrage rechnen muss. Statisches gehört in S3, Dynamisches in eine Lambda-Function, und davor sitzt CloudFront als gemeinsamer Eingang, der anhand des Pfads entscheidet, wohin eine Anfrage geht.\n\n```mermaid\nflowchart LR\n  B[Browser] --> CF[CloudFront<br/>Verteilung]\n  CF -->|/_app/*, Assets,<br/>vorgerenderte Seiten| S3[S3 Bucket<br/>statische Dateien]\n  CF -->|alle übrigen<br/>Anfragen| GW[API Gateway<br/>HTTP API]\n  GW --> L[Lambda<br/>SvelteKit SSR]\n  R53[Route 53 + ACM<br/>eigene Domain] -.-> CF\n```\n\nProvisioniert wird das Ganze mit dem AWS CDK, und zwar in der Version 2, die erst im Dezember 2021 allgemein verfügbar geworden ist – das Projekt setzt also auf ziemlich frischem Fundament auf. CDK v2 räumt vor allem das Paket-Chaos der v1 auf: eine Bibliothek `aws-cdk-lib` statt Dutzender einzeln zu versionierender Module. Für einen Adapter, der als npm-Abhängigkeit in fremde Projekte wandert, ist das ein spürbarer Unterschied, denn Versionskonflikte zwischen CDK-Teilpaketen waren in v1 ein Dauerthema. Der Kern des Stacks, leicht gekürzt:\n\n```typescript\nimport { Stack, StackProps, Duration } from 'aws-cdk-lib';\nimport * as lambda from 'aws-cdk-lib/aws-lambda';\nimport { RetentionDays } from 'aws-cdk-lib/aws-logs';\n\nexport class AWSAdapterStack extends Stack {\n  constructor(scope: Construct, id: string, props: StackProps) {\n    super(scope, id, props);\n\n    const serverHandler = new lambda.Function(this, 'ServerFunction', {\n      runtime: lambda.Runtime.NODEJS_14_X,\n      handler: 'index.handler',\n      code: lambda.Code.fromAsset(process.env.SERVER_PATH!),\n      memorySize: parseInt(process.env.MEMORY_SIZE ?? '128'),\n      timeout: Duration.seconds(15),\n      logRetention: RetentionDays.ONE_WEEK,\n    });\n    // ... HTTP API, S3 bucket, CloudFront distribution, Route 53 records\n  }\n}\n```\n\nEin Detail, das leicht untergeht: Die Log-Aufbewahrung steht bewusst auf sieben Tagen. CloudWatch-Logs ohne Aufbewahrungsregel wachsen unbegrenzt, und bei einer SSR-Funktion, die jede Seitenanfrage protokolliert, summiert sich das schneller, als man denkt. Solche Betriebs-Voreinstellungen gehören meiner Erfahrung nach in den Adapter, nicht in eine Wiki-Seite mit Empfehlungen.\n\n## Vom Lambda-Event zur Framework-Antwort\n\nDie eigentliche Übersetzungsarbeit passiert an zwei Stellen. Die erste ist der Build: Der Server-Teil der SvelteKit-Ausgabe wird mit esbuild zu einer einzigen CommonJS-Datei gebündelt – Format `cjs`, Ziel Node 14, die eingebauten Node-Module bleiben extern. Lambda bekommt damit ein Artefakt ohne `node_modules`-Verzeichnis, was Paketgröße und Kaltstart gutgetan hat. Die zweite Stelle ist die Runtime selbst: Ein kleiner Handler-Shim nimmt das Event von API Gateway entgegen, formt daraus die Anfrage-Struktur, die der SvelteKit-Server erwartet, und übersetzt die Antwort zurück:\n\n```javascript\n// index.js – bridges API Gateway events to the SvelteKit server\nimport { init, render } from './app.js';\n\ninit();\n\nexport async function handler(event) {\n  const { rawPath, rawQueryString, headers, requestContext } = event;\n\n  const response = await render({\n    method: requestContext.http.method,\n    path: rawPath,\n    query: new URLSearchParams(rawQueryString),\n    headers,\n    rawBody: event.body\n      ? Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8')\n      : undefined,\n  });\n\n  return {\n    statusCode: response.status,\n    headers: response.headers,\n    body: response.body,\n  };\n}\n```\n\nDieser Shim ist unspektakulär, aber er ist der Ort, an dem Framework-Welt und Cloud-Welt tatsächlich aufeinandertreffen. Hier entscheidet sich, ob Binärdaten korrekt durchgereicht werden, ob mehrfache `Set-Cookie`-Header überleben und ob Query-Parameter mit Sonderzeichen heil ankommen. Jede dieser Kleinigkeiten habe ich nicht am Schreibtisch entworfen, sondern nach einem konkreten Fehlverhalten nachgezogen. Der gesamte Ablauf vom Quellcode bis zum Stack sieht so aus:\n\n```mermaid\nflowchart LR\n  SRC[SvelteKit<br/>Quellcode] --> BUILD[svelte-kit build<br/>via Vite]\n  BUILD --> ADAPT[adapter adapt&#40;&#41;<br/>sortiert Ausgaben]\n  ADAPT --> ESB[esbuild<br/>SSR-Bundle, cjs]\n  ADAPT --> STATIC[statische Dateien<br/>+ Prerendered]\n  ESB --> CDK[AWS CDK v2<br/>synth + deploy]\n  STATIC --> CDK\n  CDK --> STACK[CloudFormation-Stack<br/>Lambda, S3, CloudFront]\n```\n\n## Gegen eine bewegliche API bauen\n\nDer unbequemste Teil des Projekts hat nichts mit AWS zu tun. SvelteKit ist Beta, und die Adapter-Schnittstelle gehört zu den Teilen, die sich am häufigsten bewegen. Methoden auf dem `builder`-Objekt wurden umbenannt, zusammengelegt und im Verhalten geändert; die Struktur der Server-Ausgabe hat sich ebenfalls mehr als einmal verschoben. Ein Adapter, der gegen SvelteKit von Oktober gebaut wurde, kompiliert im Dezember womöglich noch – und erzeugt trotzdem ein kaputtes Deployment.\n\nFür ein Open-Source-Projekt heißt das: Die Issues kommen nicht von eigenen Fehlern, sondern von der Drift zwischen der Framework-Version des Nutzers und der Version, gegen die der Adapter entwickelt wurde. Ein typischer Fehlerbericht beginnt mit „funktioniert bei mir nicht\" und endet nach etwas Grabarbeit bei einer SvelteKit-Version, die drei Wochen neuer ist als meine letzte Anpassung. Dagegen helfen nur unspektakuläre Maßnahmen: die getestete SvelteKit-Version im Projekt festnageln, Beispiel-Repositories aktuell halten, Änderungen am Framework zeitnah nachziehen. Das ist der reale Preis dafür, gegen eine Beta zu bauen – und ich halte ihn für angemessen. Wer wartet, bis eine Schnittstelle stabil ist, überlässt die Erfahrung aus der Zwischenzeit anderen. Nebenbei zwingt einen ein Adapter dazu, das Framework wirklich zu verstehen: Man arbeitet nicht mit der dokumentierten Oberfläche, sondern mit den Build-Ausgaben und ihren Annahmen.\n\nWas der Adapter beim Build konkret übernimmt, ist überschaubar und genau deshalb gut wartbar:\n\n- Client-Bundles, Assets und vorgerenderte Seiten in ein Artefakt-Verzeichnis sortieren\n- den Server-Teil mit esbuild zu einer Lambda-tauglichen Datei bündeln\n- den Handler-Shim für API Gateway daneben legen\n- einen CDK-Stack synthetisieren und auf Wunsch direkt ausrollen\n- Domain, Zertifikat und DNS-Einträge über Route 53 und ACM verdrahten, wenn ein `FQDN` gesetzt ist\n\n## Was Serverless nicht abnimmt\n\nAuf der anderen Seite der Grenze wartet die zweite Ernüchterung: Auch mit fertigem Adapter ist AWS keine Plattform, die einem den Betrieb abnimmt. Serverless verschiebt Arbeit, es beseitigt sie nicht. Ein paar Punkte sind mir beim Betreiben eigener SvelteKit-Deployments deutlich geworden.\n\nKaltstarts sind real, aber handhabbar. Eine per esbuild gebündelte SSR-Funktion startet in dieser Größenordnung schnell genug für die meisten Seiten – wer aber schwere Abhängigkeiten in den Server-Teil zieht, bezahlt das bei jeder kalten Anfrage. Die Speichergröße ist bei Lambda zugleich der CPU-Regler: Die 128-MB-Voreinstellung ist für Rendering oft zu knapp, und mehr Speicher kann Antwortzeiten so weit verbessern, dass es sich trotz höherem Preis pro Millisekunde rechnet. Messen statt raten.\n\nDazu kommt das Caching. CloudFront entlastet die Funktion nur, wenn die Cache-Schlüssel und Header stimmen – eine SSR-Antwort mit `Cache-Control` auf `private` trifft die Lambda bei jedem Aufruf. Für kleine Umschreibungen direkt an der Kante gibt es seit letztem Jahr CloudFront Functions, die deutlich leichtgewichtiger sind als Lambda@Edge; für das eigentliche Rendering sind beide der falsche Ort. Und CloudFormation macht Deployments nachvollziehbar und rückrollbar, aber nicht schnell: Eine Änderung an der CloudFront-Verteilung kann etliche Minuten dauern. Wer von Vercel kommt, muss sich an diese Taktung erst gewöhnen.\n\nÜbrig bleibt eine ehrliche Arbeitsteilung. Der Adapter beantwortet die Frage „wie kommt die App nach AWS\" – diese Fragen bleiben beim Team:\n\n- Beobachtbarkeit: welche Logs, Metrics und Alarme zeigen, dass das Rendering leidet?\n- Kosten: was kosten Anfragen, Datenverkehr und Logs bei realem Traffic?\n- Sicherheit: welche Rechte hat die SSR-Funktion, und welche braucht sie wirklich?\n- Lifecycle: wer zieht Framework- und Adapter-Updates nach, und wie wird ein Rollback geprobt?\n\n## Unterm Strich\n\nDas Projekt hat mir zwei Dinge gezeigt, die über SvelteKit und AWS hinausreichen. Erstens: Die Adapter-Schnittstelle ist ein gelungenes Beispiel dafür, wie ein Framework eine Grenze ziehen kann, ohne sich für eine Plattform zu entscheiden. Alles Plattformspezifische – von der Verzeichnisstruktur bis zur Architekturentscheidung – bekommt einen klaren Ort, und dieser Ort ist versionierbar, testbar und austauschbar. Dass eine Einzelperson in einem überschaubaren Repository einen kompletten AWS-Unterbau für ein Framework bereitstellen kann, spricht für den Schnitt dieser Schnittstelle.\n\nZweitens: Ein Deployment-Ziel ist nie nur Konfiguration. Der Weg von `svelte-kit build` zu einem laufenden CloudFront-Endpoint besteht aus lauter kleinen Entscheidungen – Bundling, Routing-Regeln, Cache-Verhalten, Speichergrößen, Log-Aufbewahrung –, und jede davon hat Konsequenzen im Betrieb. Ein handgeschriebenes Deploy-Skript trifft dieselben Entscheidungen, nur unsichtbar und unversioniert. Ein Adapter macht sie explizit und teilt sie mit allen, die dasselbe Problem haben. Genau deshalb lohnt es sich, so etwas als Open Source zu bauen, auch wenn das Framework noch Beta ist und die Schnittstelle unter den Händen wackelt: Die Alternative ist nicht „kein Adapter\", sondern hundert private Skripte, die alle dieselben Fehler noch einmal machen.\n\n## Weiterführende Quellen\n\n- Repository: https://github.com/MikeBild/sveltekit-adapter-aws\n- SvelteKit-Dokumentation zu Adaptern: https://svelte.dev/docs/kit/adapters\n- AWS CDK v2 Developer Guide: https://docs.aws.amazon.com/cdk/v2/guide/home.html\n- Amazon CloudFront Functions: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-functions.html"},{"locale":"de","translation_key":"preview-umgebungen-pro-pull-request","slug":"preview-umgebungen-pro-pull-request","title":"Preview-Umgebungen pro Pull Request","summary":"Ephemere Umgebungen pro Pull Request verkürzen das Feedback und machen Reviews konkret: Man klickt die Änderung, statt sie sich aus dem Diff vorzustellen.","tags":["Software","Delivery"],"published_at":"2021-11-24T10:00:00+00:00","updated_at":"2026-07-13T08:41:54.963229+00:00","url":"https://www.mikebild.dev/de/blog/preview-umgebungen-pro-pull-request/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/91d363160d1227a5bf8dea88a779e35acfb7cd3c9344b2d022fea1b8e0ac3c12/preview-umgebungen-pro-pull-request-vorlesen.mp3","audio_duration_secs":728,"text":"# Preview-Umgebungen pro Pull Request\n\n„Ist Staging frei?“ – diese Frage im Team-Chat ist der eigentliche Flaschenhals. Solange eine Umgebung für alle reichen muss, entscheidet die Reihenfolge darüber, wann jemand eine Änderung überhaupt zu sehen bekommt. Bekommt dagegen jeder Pull Request seine eigene, wegwerfbare Instanz, dreht sich das Verhältnis um: Nicht das Review wartet auf die Umgebung, die Umgebung entsteht mit ihm.\n\n## Das Problem hinter dem Diff\n\nEin Review endet oft schon hier: Jemand öffnet einen Pull Request, ein Kollege liest den Diff, denkt sich das Verhalten dazu und schreibt „LGTM“. Das ist ein Ratespiel. Ein Diff zeigt, welche Zeilen sich geändert haben – nicht, wie sich die Anwendung danach anfühlt. Ob der neue Checkout-Flow auf dem Smartphone bedienbar ist, ob der Ladezustand flackert, ob ein Sonderfall in der Fachlichkeit stimmt: Das steht in keinem `git diff`.\n\nDie klassische Antwort war ein gemeinsames Staging. Ein Team, eine Umgebung, eine Queue. Wer testen will, deployt seinen Branch, überschreibt damit den vorigen und blockiert alle anderen. Bei zwei parallelen Features ist das eine Quelle für Konflikte, bei fünf ein permanenter Stau. Das eigentliche Ziel – schnelles, konkretes Feedback – geht in der Koordination unter.\n\nDer Stau ist dabei nur die sichtbare Seite. Die unsichtbare ist, dass ein geteiltes Staging nie einen definierten Zustand hat: Es trägt immer die Reste des letzten Deploys, halb migrierte Schemata, Testdaten aus einem fremden Feature. Wenn ein Reviewer dort etwas Merkwürdiges sieht, weiß niemand mit Sicherheit, ob das der aktuelle PR ist oder ein Artefakt von gestern. Genau dieses „liegt es an meiner Änderung oder an der Umgebung?“ frisst Zeit und Vertrauen. Eine frisch hochgezogene Instanz kennt dieses Problem nicht – sie beginnt bei jedem Lauf im selben, reproduzierbaren Nullzustand.\n\nDie These dieses Artikels ist einfach: Jeder Pull Request bekommt seine eigene, wegwerfbare Umgebung mit eigener URL. Reviewer klicken die laufende Änderung an, statt sie sich vorzustellen. Und weil die Umgebung ephemer ist, verschwindet sie beim Merge wieder – ohne Aufräum-Ritual, ohne wachsende Kostenrechnung.\n\n## Der Outcome, nicht die Mechanik\n\nBevor es um `app.json` und CI-Pipelines geht, lohnt der Blick auf das Warum. Der Nutzen liegt in der kürzeren Feedback-Schleife – und die zahlt direkt auf messbare Delivery-Leistung ein.\n\n*Accelerate* (Forsgren, Humble, Kim, 2018) hat das mit Daten unterlegt: Kleine Batches, kurze Lead Time for Changes und hohe Deployment Frequency sind die Treiber leistungsfähiger Softwareauslieferung. Eine Preview-Umgebung pro Pull Request drückt genau dort. Sie belohnt kleine Änderungen – ein winziger PR ist in Sekunden deploybar und in Minuten reviewt. Sie senkt die Hemmschwelle, überhaupt zu integrieren, weil Feedback nicht auf den nächsten Staging-Slot warten muss. Das passt bruchlos zu Trunk-Based Development und zu dem, was Humble und Farley schon 2010 in *Continuous Delivery* beschrieben haben: kurzlebige Branches, schnelle Integration, der PR als Integrationseinheit.\n\nDer vielleicht unterschätzteste Effekt ist sozial. Sobald es eine klickbare URL gibt, kann auch reviewen, wer keine Entwicklungsumgebung aufsetzt: QA, Produktmanagement, Design. Ein Designer, der die reale Umsetzung im Browser sieht, gibt in fünf Minuten Feedback, für das sonst ein Meeting und drei Screenshots nötig wären. Das ist der Punkt, an dem aus einem Technik-Feature ein Delivery-Vorteil wird.\n\nKonzeptionell ist das eng verwandt mit der Build-Measure-Learn-Schleife aus Ries' *Lean Startup* (2011). Eine Preview ist ein konkretes Artefakt, an dem man messen und lernen kann, bevor etwas in Produktion geht. Je kleiner der Batch, desto schneller kann die Schleife werden. Wirtschaftlich ist eine Umgebung pro PR aber nur, wenn Provisionierung, Daten, Laufzeit und Abbau beherrscht sind. Sonst verlagert die Preview die Reibung lediglich vom Review in den Betrieb.\n\n## Der Lifecycle einer ephemeren Umgebung\n\nDie Mechanik ist bei allen etablierten Produkten dieselbe – ob Heroku „Review Apps“, GitLab „Review Apps“, Netlify „Deploy Previews“ oder Vercels „Preview Deployments“. Der PR ist der Auslöser, der Merge das Ende.\n\n```mermaid\nsequenceDiagram\n    participant Dev as Developer\n    participant PR as Pull Request\n    participant CI as CI Pipeline\n    participant Env as Preview Environment\n    Dev->>PR: open / push commit\n    PR->>CI: trigger build (HEAD commit)\n    CI->>Env: deploy isolated instance (own URL + own DB)\n    Env-->>PR: post preview URL as commit status\n    Dev->>Env: reviewer clicks and tests\n    Dev->>PR: push new commit\n    PR->>CI: rebuild and redeploy\n    Dev->>PR: merge or close\n    PR->>Env: destroy environment\n```\n\nWichtig ist das Wort *isolated*. Statt eines Stagings für alle laufen n Previews parallel – jede mit eigener URL, im Idealfall mit eigener Datenschicht. Der Kontrast zum alten Modell ist der ganze Punkt:\n\n```mermaid\ngraph LR\n    subgraph Classic[\"One staging for all\"]\n        A[PR 1] --> S[Shared Staging]\n        B[PR 2] --> S\n        C[PR 3] --> S\n        S --> Q[Queue and conflicts]\n    end\n    subgraph Ephemeral[\"Preview per PR\"]\n        D[PR 1] --> P1[preview-1.example.com]\n        E[PR 2] --> P2[preview-2.example.com]\n        F[PR 3] --> P3[preview-3.example.com]\n    end\n```\n\n## Deklarativ statt Skript-Grab\n\nDer eleganteste Ansatz beschreibt die Umgebung deklarativ, statt sie in einer Kette von Shell-Schritten zusammenzusetzen. Heroku macht das über eine `app.json` vor: Was eine Review App braucht – Add-ons, Migrationen, Feature-Flags – steht an einer Stelle, versioniert im Repository.\n\n```json\n{\n  \"name\": \"my-app\",\n  \"environments\": {\n    \"review\": {\n      \"addons\": [\"heroku-postgresql:hobby-dev\"],\n      \"scripts\": {\n        \"postdeploy\": \"bundle exec rake db:migrate db:seed\"\n      },\n      \"env\": {\n        \"FEATURE_FLAGS\": \"preview\"\n      }\n    }\n  }\n}\n```\n\nDer Reiz liegt im `postdeploy`-Hook: Jede Preview bekommt eine frische Datenbank, migriert das Schema und spielt Seed-Daten ein. Die Umgebung ist damit reproduzierbar aus dem Nichts – und genau das macht sie wegwerfbar.\n\nWer nicht auf einer PaaS wie Heroku oder Netlify sitzt, baut dasselbe Muster mit GitHub Actions selbst. Die drei Schritte bleiben gleich: bauen, in eine isolierte Instanz deployen, die URL zurück in den PR schreiben. Wie das Deploy-Skript intern arbeitet – ob es einen Container-Host anspricht, eine App auf einer eigenen Plattform hochzieht oder ein statisches Bundle ausliefert – ist für dieses Gerüst zweitrangig; entscheidend ist der saubere Vertrag aus Name, Image und Host.\n\n```yaml\nname: preview\non:\n  pull_request:\n    types: [opened, synchronize, reopened]\n\njobs:\n  deploy-preview:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n\n      - name: Build and push image\n        run: |\n          docker build -t registry.example.com/app:${{ github.sha }} .\n          docker push registry.example.com/app:${{ github.sha }}\n\n      - name: Deploy preview instance\n        run: |\n          ./scripts/deploy-preview.sh \\\n            --name \"pr-${{ github.event.number }}\" \\\n            --image \"registry.example.com/app:${{ github.sha }}\" \\\n            --host \"pr-${{ github.event.number }}.preview.example.com\"\n\n      - name: Comment preview URL\n        run: |\n          gh pr comment ${{ github.event.number }} \\\n            --body \"Preview ready: https://pr-${{ github.event.number }}.preview.example.com\"\n        env:\n          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n```\n\nGenauso wichtig wie das Deploy ist das Teardown. Eine Preview, die niemand abräumt, ist kein Feature, sondern eine Kostenstelle. Deshalb gehört ein zweiter Workflow dazu, der beim Schließen des PR aufräumt:\n\n```yaml\nname: preview-teardown\non:\n  pull_request:\n    types: [closed]\n\njobs:\n  destroy-preview:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Tear down environment\n        run: |\n          ./scripts/destroy-preview.sh --name \"pr-${{ github.event.number }}\"\n```\n\nOb das Deploy-Ziel nun ein Kubernetes-Namespace, eine Heroku-App oder ein statischer Netlify-Build ist, spielt konzeptionell keine Rolle. Das Muster ist portabel: PR öffnet, Instanz entsteht, URL landet im PR, Merge räumt auf.\n\n## Ephemere Umgebungen als Prüfstand\n\nEine isolierte, produktionsnahe Instanz ist mehr als eine Klick-Vorschau. Sie ist ein sauberer Ort, um automatisierte Checks gegen ein echtes Deployment laufen zu lassen – nicht nur gegen Mocks. Zwei Beispiele, die sich in der Praxis bewähren:\n\nContract-Tests mit Pact prüfen, ob ein Service die Erwartungen seiner Konsumenten noch erfüllt. Gegen eine echte, hochgefahrene PR-Instanz verifiziert, ist das aussagekräftiger als gegen einen Stub. Und architektonische Fitness Functions, wie sie Ford, Parsons und Kua in *Building Evolutionary Architecture* (2017) beschreiben, lassen sich gegen die laufende Preview scharf stellen: Antwortzeiten, Abhängigkeitsregeln, Bundle-Größen. So wird die Preview zum Gate, das nicht nur „sieht gut aus“, sondern „hält die Regeln ein“ beantwortet.\n\nFeature-Flags ergänzen das Bild. Eine Preview mit gesetztem `FEATURE_FLAGS=preview` zeigt den Zielzustand, während dieselbe Änderung in Produktion noch dunkel geschaltet bleibt – Review und Rollout werden entkoppelt. Wer die Flag-Idee ernst nimmt, kann eine Änderung mehrfach mergen, ohne sie freizuschalten, und sie später per Toggle live nehmen. Das reduziert lange Feature-Branches und passt zur Trunk-Based-Idee: integrieren, sichtbar machen, kontrolliert ausrollen.\n\nDer gedankliche Bogen dahinter ist derselbe wie bei blue-green oder canary: Man trennt „deployed“ von „für alle sichtbar“. Eine Preview ist in diesem Sinn ein canary für genau einen Reviewer – die kleinste denkbare Ausrollstufe. Wer diese Trennung einmal verinnerlicht hat, denkt Deployment und Freigabe nicht mehr als denselben Schritt, und das ist eine der wirkungsvollsten Entlastungen für ein Team, das oft und ruhig ausliefern will.\n\n## Wo es wirklich wehtut\n\nReibungslos ist das alles nicht. Der schwierige Teil ist nie das Deploy des Web-Prozesses – es ist alles darunter.\n\nAm härtesten ist die Datenschicht. Teilen sich alle Previews eine Datenbank, kontaminieren sie sich gegenseitig: Ein PR migriert ein Schema, ein anderer stolpert darüber. Eine Datenbank pro PR löst das, kostet aber Provisioning-Zeit und Geld – und jede Migration muss sauber von Null durchlaufen. Das ist übrigens ein unterschätzter Side Effect: Wer Previews ernst nimmt, testet damit bei jedem PR auch seinen Migrationspfad auf der grünen Wiese. Migrationen, die nur auf gewachsenen Datenbeständen funktionieren, fallen hier sofort auf, statt beim nächsten frischen Setup zu überraschen. Externe Dienste verschärfen das Bild noch: Zahlungen, E-Mail-Versand, Drittanbieter-APIs dürfen aus einer Preview niemals echt feuern. Dafür braucht es Sandbox-Modi oder Stubs, und die müssen konfiguriert sein, bevor der erste Reviewer klickt – sonst verschickt die Vorschau eines Marketing-Features versehentlich echte Mails an echte Adressen.\n\nDer zweite Dauerbrenner ist der Lifecycle. Vergessene Umgebungen kosten Geld und driften vom aktuellen Stand weg. Das Teardown bei Merge oder Close muss zuverlässig greifen, ergänzt um eine TTL oder einen Idle-Shutdown für PRs, die wochenlang offen liegen. Ein einzelner nicht gefeuerter Close-Event – etwa weil ein PR ins Leere gelöscht wurde – darf keine verwaiste Instanz hinterlassen, deshalb gehört neben dem ereignisgetriebenen Abbau ein regelmäßiger Aufräum-Job dazu, der nach Alter oder Inaktivität kehrt. Und der Feedback-Vorteil kippt, wenn der Build zehn Minuten dauert: Kalte Starts und lange Pipelines untergraben genau das, wofür man das Ganze baut. Ein schneller, aggressiv gecachter Build ist die Voraussetzung dafür, dass die kurze Schleife überhaupt kurz bleibt.\n\nDrittens Secrets und Zugriff. Preview-URLs sind oft öffentlich und erratbar – `pr-42.preview.example.com` ist keine Sicherheitsgrenze. Ungeschützt leaken solche Vorschauen unfertige Features oder echte Daten. Secrets gehören sicher injiziert, der Zugriff hinter Basic Auth, SSO oder Passwortschutz. Netlify bietet Password Protection für Deploy Previews genau aus diesem Grund.\n\nUnd schließlich der Konfig-Skew. Eine Preview nützt nur, wenn sie produktionsnah ist. Weicht sie zu stark ab, bekommt man das schlechteste aller Ergebnisse: grünes Review, roter Prod-Deploy. Dann hat die Umgebung Vertrauen erzeugt, das sie nicht decken konnte. Die Gegenmittel sind unspektakulär, aber wirksam: dasselbe Container-Image von der Preview bis in die Produktion durchreichen, Konfiguration konsequent über Umgebungsvariablen statt über abweichende Build-Pfade steuern und die wenigen bewusst gesetzten Unterschiede – Sandbox-Endpoints, kleinere Ressourcen, aktive Feature-Flags – an einer Stelle sichtbar halten. Je näher die Preview an Produktion liegt, desto mehr ist ein grünes Review tatsächlich wert.\n\n## Der rote Faden\n\nPreview-Umgebungen pro Pull Request sind 2021 gängige, produktisierte Praxis – von Heroku über GitLab und Netlify bis Vercel. Der Kern ist überall gleich und in wenigen Sätzen erzählt: Der PR erzeugt eine isolierte, wegwerfbare Instanz mit eigener URL, jeder neue Commit deployt neu, der Merge räumt auf.\n\nDer Gewinn ist die kürzere und ehrlichere Feedback-Schleife. Reviewer beurteilen laufendes Verhalten statt Zeilen im Diff. Nicht-Entwickler können mitreden. Kleine Batches werden belohnt, der Staging-Stau verschwindet. Das ist die *Accelerate*-Logik in Reinform: Reibung raus, Zyklen kürzer, Qualität früher sichtbar.\n\nDer Einstieg ist deshalb unspektakulär: Fang beim Outcome an, nicht bei der Plattform. Die schwierigen Fragen sind Datenbank, Lifecycle und Zugriffsschutz – nicht das Deploy des Web-Prozesses. Wer die sauber löst, bekommt Reviews, die man anklickt statt sich vorstellt. Und das ist der Unterschied zwischen „LGTM“ und „ich habe es gesehen“.\n\n## Weiterführende Quellen\n\n- [Heroku Review Apps](https://devcenter.heroku.com/articles/github-integration-review-apps)\n- [Netlify: Introducing Deploy Previews (2016)](https://www.netlify.com/blog/2016/07/20/introducing-deploy-previews-in-netlify/)\n- [GitLab Review Apps](https://docs.gitlab.com/ci/review_apps/)\n- [Vercel: Every push now receives a unique URL](https://vercel.com/changelog/every-push-now-receives-a-unique-url)\n- [Using the Four Keys to measure your DevOps performance (DORA)](https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance)\n- Forsgren, Humble, Kim: *Accelerate* (2018)\n- Humble, Farley: *Continuous Delivery* (2010)\n- Ford, Parsons, Kua: *Building Evolutionary Architecture* (2017)"},{"locale":"de","translation_key":"jamstack-architektur","slug":"jamstack-architektur","title":"Jamstack als Architekturstil für Webanwendungen","summary":"Jamstack beschreibt einen Architekturstil mit vorgerendertem Frontend und entkoppelten Diensten. Der Beitrag ordnet die ursprünglichen Bausteine JavaScript, APIs und Markup im Stand von 2021 ein.","tags":["Software","Architektur"],"published_at":"2021-11-15T10:00:00+00:00","updated_at":"2026-07-13T13:32:54.201633+00:00","url":"https://www.mikebild.dev/de/blog/jamstack-architektur/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/a6a2771076c4cfa5c4045be101cf50af68dd03408c0b82f37c72406b53f23e4a/jamstack-architektur-vorlesen.mp3","audio_duration_secs":792,"text":"Jamstack lässt sich nicht per `npm install` in ein Projekt holen, und kaufen kann man ihn auch nirgends. Es ist ein Architekturstil für Webanwendungen, der Vorrendering und die Entkopplung von Oberfläche und Diensten betont.\n\nDeshalb fällt die Entscheidung auch eine Ebene höher als die Wahl des nächsten Frameworks. Genau dort setzt Jamstack an.\n\nDer Name wurde ursprünglich aus **JavaScript, APIs und Markup** gebildet. Geprägt haben ihn Matt Biilmann und Chris Bach bei Netlify; Biilmann machte ihn 2015/2016 öffentlich bekannt. Schon 2021 wurde Jamstack breiter als das Akronym verwendet. Geblieben sind zwei Prinzipien: Vorrendering und Entkopplung. Statt bei jeder Anfrage frisch HTML auf dem Server zu erzeugen, wird Markup vorab gebaut und über ein CDN ausgeliefert; dynamische Teile greifen getrennt auf APIs zu.\n\n## Der Paradigmenwechsel: klassisches SSR gegen Jamstack\n\nUm zu verstehen, warum das relevant ist, lohnt sich der Blick auf das klassische Modell. Bei serverseitigem Rendering im traditionellen Sinn passiert bei jedem Seitenaufruf dasselbe: Der Browser schickt einen Request, ein Applikationsserver nimmt ihn entgegen, fragt eine Datenbank ab, baut daraus HTML zusammen und schickt es zurück. Jeder einzelne Besucher löst diese Kette erneut aus. Das ist bewährt, aber es bindet Serverkapazität pro Anfrage und macht den App-Server zum Nadelöhr und zur Angriffsfläche zugleich.\n\nDer Jamstack dreht diese Reihenfolge um. Die Arbeit passiert nicht mehr pro Request, sondern einmalig zur Build-Zeit. Ein Static-Site-Generator zieht Inhalte aus Datenquellen, rendert daraus fertige HTML-Seiten und legt sie als statische Dateien ab. Diese Dateien landen auf einem CDN und werden von dort global, nah am Nutzer, ausgeliefert. Was dynamisch sein muss – ein Warenkorb, ein Login, eine Suche – wird nachträglich clientseitig über APIs nachgeladen.\n\n```mermaid\nflowchart LR\n  subgraph Classic[\"Klassisches SSR\"]\n    B1[\"Browser\"] -->|\"Request\"| S1[\"App-Server\"]\n    S1 --> DB[(\"Datenbank\")]\n    DB --> S1\n    S1 -->|\"HTML pro Request\"| B1\n  end\n  subgraph Jam[\"Jamstack\"]\n    B2[\"Browser\"] -->|\"statische Seite\"| CDN[\"CDN<br/>(pre-rendered)\"]\n    B2 -->|\"Dynamik zur Laufzeit\"| API[\"APIs /<br/>Serverless\"]\n  end\n```\n\nEine Klarstellung, die in Diskussionen regelmäßig untergeht: Der Jamstack verbietet serverseitiges Rendering nicht. Er verlagert den Standardfall. Statt „jede Seite pro Request auf dem Server“ heißt es „jede Seite einmal im Build“ – und dort, wo es wirklich nötig ist, darf ich serverseitiges Rendering weiterhin gezielt einsetzen. Genau darum geht es im nächsten Abschnitt.\n\n## Static-Site-Generatoren und Hybrid-Rendering\n\nDer Motor des Jamstack ist der Static-Site-Generator. Im einfachsten Fall ist das ein Prozess, der Inhalte einliest und daraus HTML schreibt. Ein bewusst reduziertes Beispiel macht das Prinzip greifbar – Markdown rein, HTML raus:\n\n```jsx\nimport { loadMarkdown, renderToHtml, writeFile } from \"./ssg\";\n\nfor (const post of loadMarkdown(\"content/**/*.md\")) {\n  const html = renderToHtml(post);\n  writeFile(`dist/${post.slug}/index.html`, html);\n}\n```\n\nIn der Praxis übernehmen das ausgereifte Werkzeuge. Gatsby etwa ist ein React-basierter Generator mit einem GraphQL-Data-Layer und einem großen Plugin-Ökosystem. Next.js – aktuell in Version 12, erschienen Ende Oktober 2021 mit einem neuen, deutlich schnelleren Rust-Compiler auf SWC-Basis – bietet mehrere Rendering-Modi nebeneinander an. Und SvelteKit, das sich seit dem Frühjahr 2021 in einer öffentlichen Beta befindet, geht denselben Weg über ein Adapter-Konzept. SvelteKit ist bewusst noch als jung einzuordnen; es ist pre-1.0 und im Beta-Stadium, aber die Richtung ist bereits klar erkennbar.\n\nDer entscheidende Punkt moderner Generatoren ist, dass ich das Rendering nicht global festlege, sondern pro Seite oder Route entscheide. Am Beispiel von Next.js lässt sich das gut sortieren:\n\n- SSG (Static Site Generation) über `getStaticProps` und `getStaticPaths` rendert die Seite im Build; danach ist sie reines Markup vom CDN.\n- SSR (Server-Side Rendering) über `getServerSideProps` erzeugt die Seite pro Request auf dem Server, für echt dynamische Inhalte.\n- ISR (Incremental Static Regeneration), seit Version 9.5 aus dem Jahr 2020 verfügbar, baut eine statische Seite zeit- oder ereignisgesteuert im Hintergrund neu.\n- CSR (Client-Side Rendering) über Hooks und Datenbibliotheken wie SWR lädt die Daten erst im Browser nach.\n\nEin typisches SSG-Pattern mit einem Hauch ISR sieht so aus:\n\n```ts\nexport async function getStaticProps() {\n  const posts = await fetchFromCMS();\n\n  return {\n    props: { posts },\n    revalidate: 3600, // ISR: regenerate at most once per hour\n  };\n}\n```\n\nDas `revalidate` ist der Übergang vom rein Statischen ins Hybride: Die Seite bleibt statisch und CDN-schnell, altert aber nicht ein, weil sie sich nach der angegebenen Zeit selbst erneuert. Diese Mischung – statisch, wo möglich, serverseitig oder clientseitig, wo nötig – ist in meiner Erfahrung der realistische Normalfall, nicht die reine Lehre.\n\n## CDN und Performance\n\nWarum der ganze Aufwand? Weil vorgerenderte Assets vom CDN oft schneller beim Nutzer ankommen. Statt einer Rechenkette aus Server und Datenbank liefert ein naher Edge-Standort eine fertige Datei aus. Das kann die Time to First Byte (TTFB) deutlich verbessern. Für die Interaktivität reicht fertiges Markup allein jedoch nicht: Viel JavaScript und teure Hydration können den Vorteil wieder aufzehren. Deshalb messe ich Auslieferung und Interaktivität getrennt, statt beides dem Pre-Rendering gutzuschreiben.\n\nHinzu kommt der Effekt auf SEO. Suchmaschinen bekommen bei vorgerendertem Markup sofort vollständigen Inhalt zu sehen, ohne auf clientseitiges Nachladen angewiesen zu sein. Für inhaltsgetriebene Seiten – Blogs, Dokumentationen, Marketing – ist das ein handfester Vorteil, den ich nicht der reinen Ladegeschwindigkeit unterordnen würde.\n\nEin häufiges Missverständnis will ich hier ausräumen: Das CDN liefert die statischen Assets aus, nicht die APIs. Die dynamischen Daten kommen weiterhin über API-Requests – entweder direkt aus dem Frontend oder über eine vorgelagerte Frontend-API. Das CDN beschleunigt also die Auslieferung des Gerüsts, während die dynamischen Teile getrennt davon bedient werden.\n\n## Entkopplung und API-Orchestrierung\n\nDamit sind wir beim zweiten großen Prinzip: der Entkopplung. Im Jamstack sind Auslieferung des Frontends und dynamische Datenzugriffe getrennt. Das Backend kann weiterhin eine zusammenhängende Anwendung sein oder aus mehreren Diensten bestehen; entscheidend ist, dass das Frontend während Build oder Laufzeit über APIs darauf zugreift. Authentifizierung kann ein externer Dienst übernehmen, Inhalte können aus einem Headless-CMS kommen, und eigene Geschäftslogik kann in Serverless-Functions liegen. Das sind verbreitete Bausteine, keine Definition der Architektur.\n\nDie spannende Frage ist dann, wo diese vielen APIs zusammengeführt werden. Zwei Wege haben sich etabliert. Entweder orchestriere ich direkt im Frontend, indem die Komponenten die benötigten Endpoints selbst abfragen:\n\n```jsx\nimport useSWR from \"swr\";\n\nconst fetcher = (url) => fetch(url).then((res) => res.json());\n\nfunction Cart() {\n  const { data, error } = useSWR(\"/api/cart\", fetcher);\n  if (error) return <p>Failed to load</p>;\n  if (!data) return <p>Loading…</p>;\n  return <CartView items={data.items} />;\n}\n```\n\nOder ich lege eine Frontend-API davor – häufig über GraphQL, etwa mit AWS AppSync oder dem GraphQL-Endpoint eines Headless-CMS. Das Frontend stellt dann eine einzige, konsolidierte Anfrage, und die Orchestrierung der dahinterliegenden Dienste passiert eine Schicht tiefer. Für größere Anwendungen mit vielen Datenquellen bevorzuge ich diesen Weg, weil er das Frontend von der Detailkenntnis über jedes einzelne Backend entlastet.\n\nDie Serverless-Functions selbst sind bewusst schlank und zustandslos. Ein Handler im Netlify- beziehungsweise Lambda-Stil sieht typischerweise so aus:\n\n```js\nexports.handler = async (event, context) => {\n  const { name } = JSON.parse(event.body);\n\n  return {\n    statusCode: 200,\n    body: JSON.stringify({ message: `Hello ${name}` }),\n  };\n};\n```\n\nDer wirtschaftliche Reiz dahinter kann das Abrechnungsmodell sein: pay-per-execution. Je nach Plattform, Grundgebühr und Lastprofil zahlt man stärker für tatsächliche Aufrufe und Rechenzeit als für dauerhaft vorgehaltene Server. Auch die Skalierung übernimmt der Anbieter innerhalb seiner Limits weitgehend. Laufzeitgrenzen, verteilte Fehler, Quoten und die Kosten einzelner Aufrufe bleiben trotzdem Architekturfragen.\n\n## Build und CI: der Git-Push als Auslöser\n\nDie Vorrenderei muss natürlich irgendwann passieren. Häufig startet ein Git-Push eine CI-Pipeline – etwa über GitHub Actions –, die den Static-Site-Generator ausführt und das Ergebnis auf ein CDN bringt. Viele spezialisierte Plattformen veröffentlichen diese Artefakte atomar und versioniert, sodass eine neue Version geschlossen aktiv wird und sich zurückrollen lässt. Das ist eine Eigenschaft des gewählten Deployment-Systems, nicht automatisch jedes Jamstack-Builds.\n\n```mermaid\nflowchart LR\n  Dev[\"git push\"] --> CI[\"GitHub Actions<br/>(CI)\"]\n  CI --> SSG[\"Static Site Generator<br/>(Build)\"]\n  SSG --> Deploy[\"atomic deploy\"]\n  Deploy --> CDN[\"CDN<br/>(global edge)\"]\n  CDN --> User[\"User\"]\n  SSG -.->|\"großer Katalog\"| Shard[\"Sharding /<br/>parallele Builds\"]\n  Shard --> Deploy\n```\n\nEin einfacher Workflow, der genau das tut, ist schnell aufgeschrieben:\n\n```yaml\nname: build-and-deploy\non:\n  push:\n    branches: [main]\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v2\n        with:\n          node-version: \"16\"\n      - run: npm ci\n      - run: npm run build\n      - run: npx netlify deploy --prod --dir=dist\n```\n\nBei kleinen Seiten ist der Build in Sekunden durch. Bei großen Katalogen mit vielen tausend Seiten wird die Build-Zeit selbst zum Thema – hier hilft Sharding, also das Aufteilen des Builds in parallele Teilprozesse. Das ist gleichzeitig ein guter Übergang zu den Grenzen, die ich weiter unten anspreche.\n\n## Sicherheit und Betriebsvorteile\n\nEin Side Effect der Architektur, der leicht übersehen wird, betrifft die Sicherheit. Wenn zur Laufzeit gar kein Applikationsserver pro Request angesprochen wird, schrumpft die Angriffsfläche erheblich. Kein monolithischer Server, der bei jeder Anfrage Datenbankzugriffe fährt und dabei angreifbar wird. Ausgeliefert werden statische Dateien, und die dynamischen Teile stecken in klar abgegrenzten, einzeln absicherbaren APIs. In Summe ergibt sich daraus eine handliche Liste an Vorteilen:\n\n- Die TTFB kann sinken, weil vorgerendertes Markup direkt vom Edge kommt; die Interaktivität hängt zusätzlich am ausgelieferten JavaScript.\n- Für statische Seiten entfällt ein Applikationsserver pro Lesezugriff; die APIs bleiben eine eigene Angriffsfläche.\n- CDN und Plattform können einen großen Teil der Skalierung übernehmen, jeweils innerhalb ihrer Quoten und Laufzeitgrenzen.\n- Pay-per-execution kann bei passendem Lastprofil Kosten sparen, ist aber nicht grundsätzlich billiger.\n- Die Entwicklererfahrung profitiert von klarer Trennung, Git-basierten Deploys und schnellen Rollbacks.\n\n## Drei Fallstudien aus der Praxis\n\nDamit das nicht theoretisch bleibt, drei Szenarien, die ich in dieser Reihenfolge fast als Reifegrad lese.\n\nDas erste ist der statische Blog oder das Portfolio. Hier spielt der Jamstack seine Stärken aus: Inhalte werden im Build gerendert, es gibt kaum Dynamik, und das CDN kann sie ohne Anwendungsserver ausliefern. Für diese Klasse von Projekten ist reines SSG oft schon die vollständige Antwort.\n\nDas zweite Szenario ist B2C-E-Commerce. Sobald Sessions, Warenkörbe und Transaktionen ins Spiel kommen, reicht das rein Statische nicht mehr. Produktseiten lassen sich hervorragend statisch vorrendern und über das CDN ausliefern, während Warenkorb, Checkout und Nutzerkonto clientseitig über APIs bedient werden. Das ist der klassische Hybrid-Fall, bei dem ISR zusätzlich hilft, Produktdaten aktuell zu halten, ohne jede Seite pro Request neu zu bauen.\n\nDas dritte Szenario sind B2B-, SaaS- und IoT-Anwendungen. Hier dominieren Dashboards, personalisierte Ansichten und Echtzeitdaten. Ein statisches Gerüst kann zur schnellen Erstauslieferung beitragen; geschützte Bereiche lassen sich je nach Produkt clientseitig, serverseitig oder hybrid rendern. Auch eine GraphQL-Frontend-API kann sinnvoll sein, wenn tatsächlich mehrere Datenquellen für die Oberfläche gebündelt werden müssen.\n\n## Wo der Jamstack an Grenzen stößt\n\nSo überzeugend das Modell ist, ehrlich bleibe ich bei den Rändern. Reines SSG skaliert nicht beliebig. Bei einigen tausend Seiten wird die Build-Zeit langsam relevant, bei Millionen von Seiten wird das vollständige Vorrendern schlicht unpraktikabel. Genau an diesem Punkt kommen die bereits genannten Hilfsmittel ins Spiel: ISR rendert nur das nach, was sich wirklich ändert; Hybrid-Rendering erlaubt serverseitiges Erzeugen für die selten besuchten oder hochdynamischen Routen; und Sharding verteilt große Builds auf parallele Prozesse.\n\nAuch bei der Werkzeugauswahl lohnt Nüchternheit. SvelteKit ist Ende 2021 vielversprechend, aber noch Beta. Azure Static Web Apps ist erst seit Mai 2021 allgemein verfügbar und damit ebenfalls recht jung, integriert dafür Azure Functions als Backend direkt mit. Schnelle Build-Bausteine wie esbuild von Evan Wallace beschleunigen die Pipeline enorm, sind aber selbst noch vor der 1.0. Wer hier baut, wählt bewusst zwischen etabliert und aufstrebend.\n\n## Fazit\n\nDer Jamstack ist für mich weniger eine Technologie als eine Haltung zur Architektur. Er verschiebt geeignete Arbeit vom Request in den Build und trennt die Auslieferung des Frontends von dynamischen Datenzugriffen. Ob dahinter eine Enterprise-Anwendung, mehrere Dienste oder Serverless-Functions stehen, ist eine eigene Entscheidung. Schnelle Auslieferung über das CDN, eine kleinere Laufzeitfläche und einfache Deployments können daraus folgen, wenn Anwendung und Plattform dazu passen.\n\nEntscheidend ist, dass der Jamstack technologieoffen bleibt. Er schreibt mir kein Framework vor, sondern eine Denkweise, innerhalb derer ich Next.js, Gatsby oder SvelteKit ebenso einsetzen kann wie Netlify, Vercel oder Azure. Und er ist kein Dogma: Reines SSG für den Blog, Hybrid für den Shop, serverseitig plus API-Orchestrierung für die SaaS-Plattform. Mit dieser Abstufung fällt die Architekturentscheidung dort, wo sie hingehört – eine Ebene über dem Framework.\n\n## Weiterführende Quellen\n\n- Mike Bild: „JAMstack-Architektur“ – der ausführliche Originalartikel: https://www.developer-world.de/dwx-insights/architecture-patterns/jamstack-architektur\n- Offizielle Jamstack-Ressource: https://jamstack.org/\n- [Jamstack: Definition und Herkunft des Namens](https://jamstack.org/what-is-jamstack/)\n- Next.js 12 (Release vom 26.10.2021): https://nextjs.org/blog/next-12\n- SvelteKit Public Beta: https://svelte.dev/blog/sveltekit-beta\n- Azure Static Web Apps GA (Mai 2021): https://www.infoq.com/news/2021/05/azure-static-web-apps-ga/"},{"locale":"de","translation_key":"ses-email-hook-serverless","slug":"ses-email-hook-serverless","title":"Transaktionale E-Mails serverless: SES und Lambda","summary":"Wie SES zum ereignisgetriebenen E-Mail-Baustein wird: ausgehende Bestätigungsmails aus einer Lambda-Function und eingehende Receipt Rules, die aus einer Mail einen Handler auslösen.","tags":["Software","AWS","Cloud"],"published_at":"2021-11-09T10:00:00+00:00","updated_at":"2026-07-13T08:41:19.011377+00:00","url":"https://www.mikebild.dev/de/blog/ses-email-hook-serverless/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/76e901a3677cedd9ce69bf8a1ad1f51dd207024d8f2519d378217799ef4a273d/ses-email-hook-serverless-vorlesen.mp3","audio_duration_secs":949,"text":"Ein `SendEmail`-Aufruf trägt bis zu 50 Empfänger und 10 MB Message. Ein eingehendes SES-Event trägt null Byte Mailtext: Es liefert Header und Metadaten, der Body liegt in S3. Diese zwei Zahlen sagen mehr über den Dienst als jede Feature-Liste – die ausgehende Richtung ist in einer halben Stunde erledigt, die eingehende hat eigene Regeln, die man kennen muss.\n\nDahinter steckt eine Entscheidung, die im Team wie Konfiguration klingt: „Und wie schicken wir jetzt die Bestätigungsmail raus?“ Häufig steht da schon ein Signup-Flow, vielleicht mit einer User-Verwaltung wie in [Serverless-Auth mit Cognito User Pools](https://www.mikebild.dev/de/blog/cognito-userpool-auth-serverless/), und die Mail wirkt wie der letzte, triviale Baustein. Genau da liegt der Denkfehler. Die eigentliche Frage lautet: Behandle ich E-Mail als externen Side Effect, den ich ans Ende eines Flows klebe, oder als vollwertiges Domänen-Event – rein wie raus –, das dieselbe Behandlung verdient wie ein API-Aufruf oder eine Queue-Message?\n\nDiese Weichenstellung entscheidet, ob der E-Mail-Teil später sauber in die Architektur passt oder als Fremdkörper Reibung erzeugt. SES – der Simple Email Service – ist deshalb lehrreich, weil er beide Richtungen mit denselben Bausteinen bedient: Lambda auf der einen Seite, Receipt Rules auf der anderen. Der Hebel liegt nicht in den API-Feldern, sondern in dieser Symmetrie. Im Folgenden gehe ich beide Richtungen durch – zuerst die ausgehende Bestätigungsmail aus einer Funktion, danach den eingehenden Mail-Hook, der aus einer echten E-Mail zum Beispiel ein Support-Ticket macht. Der Code ist bewusst schlank gehalten, damit der rote Faden – Event rein, Event raus – sichtbar bleibt.\n\n## SES als Baustein in zwei Richtungen\n\nBevor wir Code schreiben, lohnt sich ein Blick auf das mentale Modell. SES sitzt an der Systemgrenze zwischen deiner Anwendung und der Außenwelt der E-Mail. Nach außen: Deine App löst ein Event aus – ein neuer Account, eine bezahlte Bestellung – und eine Lambda-Function ruft `SendEmail` auf. Nach innen: Jemand schickt eine Mail an eine deiner Adressen, und SES verarbeitet sie über sogenannte Receipt Rules weiter, etwa an S3, an SNS oder direkt an eine Lambda-Function.\n\nDiese Symmetrie ist der Kern. Sobald SES im Entwurf als ereignisgetriebener Baustein auftaucht, fügt er sich sauber in die übrige Serverless-Architektur ein. Bleibt er ein reiner „Mail-Versender“, hängt er hinterher außen dran. Die ausgehende Richtung ist dabei die häufigere und der einfachere Einstieg.\n\n- Ausgehend: `SendEmail` oder `SendTemplatedEmail`, ein verifizierter Absender, Sandbox und Quota im Blick, ausgelöst durch ein App-Event.\n- Eingehend: ein Receipt Rule Set mit Actions für S3, Lambda oder SNS, nur in bestimmten Regionen verfügbar, ausgelöst durch eine eintreffende Mail, Body über S3 nachgeladen.\n\nHalten wir diese beiden Zeilen im Kopf – sie strukturieren den Rest des Artikels.\n\n## E-Mail als Domänen-Event, nicht als SES-Konfiguration\n\nDer Unterschied klingt akademisch, hat aber handfeste Konsequenzen. Wer SES als Konfigurationsaufgabe begreift, hört bei „Absender verifiziert, `SendEmail` läuft“ auf. Wer E-Mail als Domänen-Event modelliert, fragt weiter: Welches fachliche Event löst diese Mail aus, und welches Event erzeugt eine eintreffende Mail in meinem System? Aus „ich versende eine Message“ wird „ein Signup ist passiert“, und aus „jemand hat gemailt“ wird „ein Support-Fall ist eingegangen“. Die Mail ist dann nur noch der Transport, nicht das Event selbst.\n\nDiese Perspektive kostet etwas und bringt etwas. Der Preis ist zusätzliche Sorgfalt an der Systemgrenze: verifizierte Identitäten, ein aktives Rule Set, korrekte Berechtigungen, das Wissen, dass eingehende Bodies in S3 liegen. Der Ertrag ist Anschlussfähigkeit. Ein Event lässt sich weiterreichen, orchestrieren, protokollieren und testen – eine „verschickte Mail“ dagegen ist eine Sackgasse.\n\nFür die Frage, ob SES der richtige Baustein ist, helfen ein paar Entscheidungskriterien:\n\n- Kopplung und Kontrolle: SES bleibt vollständig in AWS und IAM, ohne zweiten Anbieter und ohne zusätzlichen Vertrag. Dafür trägst du die regionale Einschränkung beim Empfang und das MIME-Parsing selbst.\n- Kosten: SES rechnet pro tausend Mails ab und verursacht im Leerlauf nichts. Ein spezialisierter Transaktions-Anbieter bringt bessere Zustellbarkeits-Werkzeuge und fertige Templates mit, aber eben auch eine eigene Rechnung und ein zweites System, das jemand betreiben muss.\n- Wirkung: Erst wenn die eingehende Mail ein echtes Event ist, lässt sich die Nachbearbeitung automatisieren – Klassifizierung, Zuweisung, Antwortentwurf. Genau das verkürzt die Zyklen, die sonst an manueller Triage hängen.\n\nSolange E-Mail eine Event Source und -senke innerhalb einer AWS-Architektur ist, ist SES die reibungsärmste Wahl. Sobald Marketing-Zustellbarkeit, Bounce-Analytics und Kampagnen-Tooling im Vordergrund stehen, ist ein dedizierter Anbieter ehrlicher. Für den transaktionalen Kern – Bestätigung raus, Ticket rein – gewinnt der ereignisgetriebene SES-Baustein.\n\n## Die ausgehende Bestätigungsmail\n\nFangen wir mit der ausgehenden Richtung an. Eine Lambda-Function wird durch ein Event ausgelöst – sagen wir, ein API-Gateway-Aufruf nach erfolgreicher Registrierung – und soll eine kurze Bestätigungsmail verschicken.\n\nDas folgende Diagramm zeigt den Weg des Events. Das Event kommt rein, die Lambda-Function übersetzt es in einen `SendEmail`-Aufruf, SES nimmt die Message an. Das ist noch keine Zustellgarantie: Bounces und Complaints laufen über eigene SES-Events. Wird das auslösende Event wiederholt, kann auch die Mail doppelt versendet werden. Für einen produktiven Flow brauche ich deshalb einen stabilen Ereignisschlüssel und einen gespeicherten Versandstatus oder eine Outbox.\n\n```mermaid\nflowchart LR\n  A[Event: Signup] --> B[Lambda: sendConfirmationEmail]\n  B --> C[ses:SendEmail]\n  C --> D[Recipient Inbox]\n```\n\nDer zugehörige Handler ist überschaubar. Ich nutze hier das AWS SDK für JavaScript in der Version 3, also die modularen `@aws-sdk/client-ses`-Pakete – die etablierte Version 2 mit `new AWS.SES()` funktioniert genauso, ist mir für neue Funktionen aber schlicht zu monolithisch im Import.\n\n```ts\nimport { SESClient, SendEmailCommand } from \"@aws-sdk/client-ses\";\n\nconst ses = new SESClient({ region: \"eu-west-1\" });\n\nexport async function sendConfirmationEmail(event: {\n  email: string;\n  name: string;\n}) {\n  const command = new SendEmailCommand({\n    Source: \"no-reply@example.com\",\n    Destination: {\n      ToAddresses: [event.email],\n    },\n    Message: {\n      Subject: {\n        Data: \"Willkommen bei uns\",\n        Charset: \"UTF-8\",\n      },\n      Body: {\n        Html: {\n          Data: `<p>Hallo ${event.name}, dein Konto ist aktiv.</p>`,\n          Charset: \"UTF-8\",\n        },\n      },\n    },\n  });\n\n  const result = await ses.send(command);\n  return { messageId: result.MessageId };\n}\n```\n\nDrei Dinge sind hier verpflichtend und deshalb einen genaueren Blick wert. `Source` ist die Absender-Adresse und muss eine 7-bit-ASCII-Adresse einer verifizierten Identität sein. `Destination` bündelt die Empfänger nach `ToAddresses`, `CcAddresses` und `BccAddresses`. `Message` trägt `Subject` und `Body`, wobei der Body Text und HTML enthalten kann, jeweils als Objekt aus `Data` und `Charset`. Zurück kommt eine `MessageId` – die einzige Quittung, die du für den erfolgreichen Aufruf bekommst. Optional lässt sich noch einiges ergänzen, etwa `ReplyToAddresses` oder ein `ConfigurationSetName`, aber für die Bestätigungsmail reicht das Gezeigte.\n\n### Verifizierte Absender, Sandbox und Quota\n\nDer Code ist selten die Stolperstelle. Es sind drei organisatorische Punkte, die man vorher klären muss.\n\nErstens die Absender-Identität. SES verschickt nur von verifizierten Absendern. Du kannst eine einzelne Adresse verifizieren oder – für die Produktion deutlich sinnvoller – eine ganze Domain über DKIM- und TXT-Einträge im DNS. Ist der Absender nicht verifiziert, quittiert SES den Aufruf mit „Email address not verified“, und die Mail geht nicht raus.\n\nZweitens die Sandbox. Jeder neue SES-Account startet in der Sandbox. Das bedeutet: Du darfst nur an verifizierte Empfänger senden beziehungsweise an den SES Mailbox Simulator, und die Sending-Quota ist reduziert. Die Bestätigungsmail an einen echten Kunden schlägt in der Sandbox also fehl, solange dessen Adresse nicht selbst verifiziert ist. Für den Produktionsbetrieb muss man den Produktionszugang per Support-Case beantragen.\n\nDrittens die Quota. Jeder Empfänger einer Message zählt gegen dein Sending-Kontingent. Ein `SendEmail`-Aufruf darf maximal 50 Empfänger über `To`, `Cc` und `Bcc` zusammen adressieren und die Message bis zu 10 MB groß sein.\n\nFür Demos und Tests ist der Mailbox Simulator Gold wert. Ein Aufruf an `success@simulator.amazonses.com` verhält sich wie eine erfolgreiche Zustellung, ohne dass du in der Sandbox anecken oder echte Postfächer belasten musst.\n\n### Templates statt String-Konkatenation\n\nSobald mehr als eine Mail-Art im Spiel ist, wird das Zusammenbauen von HTML im Code unübersichtlich. SES bietet dafür serverseitige Templates. Man legt einmalig ein Template mit `CreateTemplate` an – mit `SubjectPart`, `TextPart` und `HtmlPart`, in denen Platzhalter in doppelten geschweiften Klammern stehen – und verschickt dann mit `SendTemplatedEmail`.\n\n```ts\nimport { SESClient, SendTemplatedEmailCommand } from \"@aws-sdk/client-ses\";\n\nconst ses = new SESClient({ region: \"eu-west-1\" });\n\nexport async function sendWelcome(email: string, name: string) {\n  const command = new SendTemplatedEmailCommand({\n    Source: \"no-reply@example.com\",\n    Destination: { ToAddresses: [email] },\n    Template: \"WelcomeTemplate\",\n    TemplateData: JSON.stringify({ name }),\n  });\n\n  return ses.send(command);\n}\n```\n\n`TemplateData` ist ein JSON-String, dessen Schlüssel die Platzhalter im Template füllen. Der Vorteil: Der Text steht nicht mehr im Deployment-Artefakt, sondern liegt als Ressource bei SES und lässt sich unabhängig vom Code aktualisieren. Für viele Empfänger auf einmal gibt es außerdem `SendBulkTemplatedEmail` – im transaktionalen Kontext braucht man das aber selten, weil dort meist eine Mail an eine Person geht.\n\n## Der eingehende Mail-Hook\n\nJetzt drehen wir die Richtung um. Die zweite, oft übersehene Fähigkeit von SES: Es kann eintreffende E-Mails empfangen und daraus ein Event in deiner Architektur machen. Das ist die Grundlage für Muster wie „aus einer Mail an support@ wird automatisch ein Ticket“.\n\nVerwaltet wird das über ein Receipt Rule Set. Es gibt pro Account mehrere Rule Sets, aber immer nur eines ist aktiv. Innerhalb eines Rule Sets definierst du einzelne Receipt Rules, die auf bestimmte Empfänger-Adressen matchen und eine Liste von Actions abarbeiten. Als Actions stehen unter anderem zur Verfügung: die Ablage in einem S3-Bucket, das Publizieren an ein SNS-Topic, das Aufrufen einer Lambda-Function, das Hinzufügen eines Headers, ein Bounce oder ein Stop.\n\nDer übliche Aufbau für einen Ticket-Flow kombiniert zwei Actions: Erst wird die Roh-Mail nach S3 geschrieben, dann eine Lambda-Function ausgelöst, die sich um die Verarbeitung kümmert.\n\n```mermaid\nflowchart LR\n  A[Incoming Mail] --> B[SES Receipt Rule]\n  B --> C[S3: raw MIME]\n  B --> D[Lambda: handleInboundEmail]\n  D --> E[Ticket / DB]\n  B -.-> F[SNS Notification]\n```\n\n### Die Receipt Rule als Infrastruktur\n\nDie Receipt Rule selbst gehört in Infrastructure-as-Code, nicht in ein manuell geklicktes Konsolen-Setup – sonst ist sie nach dem nächsten Account-Wechsel weg. Als Skizze in CloudFormation-naher Form sieht eine Regel etwa so aus:\n\n```yaml\nResources:\n  SupportRule:\n    Type: AWS::SES::ReceiptRule\n    Properties:\n      RuleSetName: default-rule-set\n      Rule:\n        Name: support-inbound\n        Enabled: true\n        Recipients:\n          - support@example.com\n        Actions:\n          - S3Action:\n              BucketName: inbound-mail-bucket\n          - LambdaAction:\n              FunctionArn: !GetAtt InboundFn.Arn\n              InvocationType: Event\n```\n\nZwei Details sind hier wichtig. Die Reihenfolge der Actions zählt: Erst muss die Mail in S3 liegen, dann wird die Lambda-Function gerufen, die sie von dort liest. Und `InvocationType: Event` bedeutet asynchroner Aufruf – das ist die empfohlene Variante. Der synchrone `RequestResponse`-Aufruf existiert ebenfalls, hat aber ein hartes Timeout von 30 Sekunden und erlaubt der Lambda-Function, den weiteren Regelverlauf per Rückgabe zu steuern, etwa mit `{ disposition: \"STOP_RULE\" }`. Für einen Ticket-Handler, der ohnehin nichts am Mailfluss steuern will, ist `Event` die richtige Wahl.\n\n### Der Handler und der häufigste Irrtum\n\nKommen wir zum Handler – und zum Fallstrick, der in Projekten am zuverlässigsten zuschlägt. Die naheliegende Annahme ist, dass das Lambda-Event den Mailtext enthält. Das tut es nicht. Das Event, das SES an die Lambda-Function übergibt, trägt nur Metadaten und Header – Absender, Betreff, Message-ID –, aber nicht den Body. Der komplette MIME-Inhalt landet in S3, und von dort muss der Handler ihn nachladen.\n\nDas Event ist um ein `Records`-Array herum aufgebaut, mit `eventSource: \"aws:ses\"` und den Feldern `ses.receipt` sowie `ses.mail`. Letzteres enthält unter `commonHeaders` die aufbereiteten Header und unter `messageId` den Schlüssel, unter dem die Roh-Mail in S3 liegt.\n\n```ts\nimport { S3Client, GetObjectCommand } from \"@aws-sdk/client-s3\";\nimport { Readable } from \"stream\";\n\nconst s3 = new S3Client({ region: \"eu-west-1\" });\n\nasync function streamToString(stream: Readable): Promise<string> {\n  const chunks: Buffer[] = [];\n  for await (const chunk of stream) {\n    chunks.push(Buffer.from(chunk));\n  }\n  return Buffer.concat(chunks).toString(\"utf-8\");\n}\n\nexport async function handleInboundEmail(event: any) {\n  const record = event.Records[0];\n  const mail = record.ses.mail;\n  const messageId = mail.messageId;\n\n  const raw = await s3.send(\n    new GetObjectCommand({\n      Bucket: \"inbound-mail-bucket\",\n      Key: messageId,\n    })\n  );\n\n  const mime = await streamToString(raw.Body as Readable);\n\n  // parse MIME, then create a support ticket\n  await createTicket({\n    from: mail.commonHeaders.from?.[0],\n    subject: mail.commonHeaders.subject,\n    body: mime,\n  });\n\n  return { status: \"processed\" };\n}\n```\n\nDie eigentliche MIME-Zerlegung habe ich hier bewusst ausgespart – dafür nimmt man eine Bibliothek, denn multipart-Mails mit Anhängen von Hand zu parsen ist keine gute Idee. Der Punkt ist der Ablauf: Header aus dem Event, Body aus S3, dann die fachliche Aktion. Das S3-Objekt darf dabei bis zu 40 MB groß sein.\n\n### Berechtigungen und DNS, sonst passiert stumm nichts\n\nDer zweite Fallstrick beim Empfang ist unspektakulär und deshalb tückisch: Ohne die richtigen Berechtigungen verarbeitet SES eintreffende Mail einfach stillschweigend nicht. SES braucht eine Resource-Policy, die ihm erlaubt, in den S3-Bucket zu schreiben, an das SNS-Topic zu publizieren oder die Lambda-Function aufzurufen. Fehlt eine dieser Erlaubnisse, gibt es keine laute Fehlermeldung – die Mail versickert.\n\nDazu kommt DNS. Damit Mail überhaupt bei SES ankommt, müssen die MX-Einträge deiner Domain auf `inbound-smtp.<region>.amazonaws.com` zeigen. Und es gibt eine harte regionale Einschränkung: E-Mail-Empfang bietet SES nur in ausgewählten Regionen an – Stand heute us-east-1, us-west-2 und eu-west-1. Lambda und SNS für den eingehenden Flow müssen in derselben Region wie der SES-Endpoint liegen. Wer seine übrige Infrastruktur in einer anderen Region betreibt, muss diesen Teil bewusst dorthin ziehen.\n\n## Wo SES in die größere Architektur passt\n\nDie beiden Richtungen ergeben zusammen ein hübsches Bild: Lambda ist der gemeinsame Rechenkern, SES die Systemgrenze zur E-Mail-Welt. Nach außen übersetzt eine Funktion App-Events in Mails, nach innen übersetzt SES eintreffende Mails in Funktionsaufrufe.\n\nInteressant wird es, wenn der eingehende Hook nicht das Ende, sondern der Anfang einer längeren Verarbeitung ist. Eine Support-Mail, die geparst wird, kann eine Kette von Schritten anstoßen – Klassifizierung, Zuweisung, Antwortentwurf. Genau dafür lohnt sich der Blick auf eine Orchestrierung, wie ich sie in [Serverless-Workflows mit AWS Step Functions](https://www.mikebild.dev/de/blog/step-functions-serverless-workflows/) beschrieben habe: Die SES-Lambda legt das Ticket an und übergibt an eine State Machine, die den Rest koordiniert. So bleibt der Mail-Hook klein und macht genau eine Sache, während die Fachlogik ihren eigenen, nachvollziehbaren Ablauf bekommt.\n\n## Fazit\n\nDer Aha-Moment bei SES liegt in der eingehenden Richtung: wenn klar wird, dass eintreffende Mail kein Sonderfall ist, sondern ein ganz normaler Event-Trigger – genauso wie ein API-Aufruf oder eine Queue-Message. Ausgehend ist der Dienst schnell erklärt: verifizierter Absender, `SendEmail` oder ein Template, Sandbox und Quota im Kopf behalten. Eingehend braucht mehr Sorgfalt: ein aktives Rule Set, die richtigen Berechtigungen, MX-Einträge und das Wissen, dass der Body in S3 liegt und nicht im Event.\n\nDer Gewinn dieser Perspektive ist konkret. Kürzere Zyklen, weil ein eingehender Mail-Hook Nachbearbeitung anstößt, statt sie in einem Postfach zu parken. Weniger Reibung, weil E-Mail denselben ereignisgetriebenen Regeln folgt wie der Rest der Architektur und nicht als Fremdkörper danebensteht. Höhere Qualität, weil ein modelliertes Event testbar, protokollierbar und orchestrierbar ist, wo eine lose verschickte Mail eine Sackgasse bleibt. Und klare Grenzen: Sobald Zustellbarkeit im großen Stil, Bounce-Analytics oder Kampagnen im Vordergrund stehen, ist ein spezialisierter Anbieter die ehrlichere Wahl – SES glänzt im transaktionalen Kern. Wer diese beiden Muster einmal sauber gebaut hat, denkt nicht mehr „wie verschicke ich eine Mail“, sondern „E-Mail ist einfach eine weitere Event Source und -senke“ – rein wie raus.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-aws-serverless.html\n- Repository: `introduction-aws`, Kapitel `ses.md` und `examples/email-hook`\n- [SendEmail (SES API Reference)](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendEmail.html)\n- [SendTemplatedEmail (SES API Reference)](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendTemplatedEmail.html)\n- [Verifizierte Identitäten anlegen](https://docs.aws.amazon.com/ses/latest/dg/creating-identities.html)\n- [E-Mail-Empfang – Konzepte](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-concepts.html)\n- [Invoke-Lambda-Action](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-action-lambda.html)\n- [Beispiel für ein eingehendes Mail-Event](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-action-lambda-event.html)\n- [Deliver-to-S3-Action](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-action-s3.html)\n- [Berechtigungen für den E-Mail-Empfang](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-permissions.html)"},{"locale":"de","translation_key":"state-management-vergleich","slug":"state-management-vergleich","title":"State-Management in React: Redux Toolkit, leichte Stores, MobX","summary":"Wenn ein State wirklich app-weit ist, stellt sich die Werkzeugfrage – Redux Toolkit, ein leichter Store wie Zustand oder Jotai, oder das reaktive Modell von MobX. Warum diese Wahl aber erst nach der Gegenprobe kommt und meistens kleiner ausfällt als gedacht.","tags":["Software","Frontend","React"],"published_at":"2021-10-26T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/state-management-vergleich/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/2a0fd3f8e39f217c6a1c4143b5fa1d07579216e5cf768bc7650a14d34cc26fef/state-management-vergleich-vorlesen.mp3","audio_duration_secs":732,"text":"# State-Management in React: Redux Toolkit, leichte Stores, MobX\n\nEin globaler Store gehört nicht zur Grundausstattung einer React-Anwendung. Er ist die Ausnahme, die man begründen muss. So steht es im React-Überblick, wo die Besitzfrage im Mittelpunkt stand – wo gehört ein State hin? Offen blieb dort, was man denn nimmt, wenn ein State die Begründung tatsächlich besteht, wenn er also wirklich app-weit ist. Den Vergleich hatte ich versprochen. Hier ist er.\n\n**Redaktionelle Einordnung (Juli 2026):** Der Werkzeugteil ist eine Momentaufnahme vom Oktober 2021: Redux Toolkit 1.x, Zustand 3.x, Jotai 1.x und MobX 6. Die wichtigere Trennung ist weniger vergänglich: URL State, Server-Cache und eigener Client State haben verschiedene Besitzer. Aktuelle Versionen können die Ergonomie ändern, nicht diese Zuständigkeiten.\n\nBevor wir über Werkzeuge reden, muss ich aber auf die Bremse treten. Die Frage „Redux, Zustand oder MobX?“ wird meistens viel zu früh gestellt – zu einem Zeitpunkt, an dem noch gar nicht feststeht, ob überhaupt ein Store gebraucht wird. Beim genauen Hinsehen entpuppt sich der vermeintlich globale State oft als gar keiner. Deshalb kommt zuerst die Gegenprobe, und erst danach der eigentliche Vergleich.\n\nNicht jede State-Art braucht denselben Speicher. Die Wahl beginnt mit Besitz, Lebensdauer und Synchronisationsbedarf.\n\n::::comparison{title=\"State nach Verantwortung einordnen\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Lokaler UI State\"}\n- Besitzer · eine Komponente oder ein begrenzter Teilbaum\n- Lebensdauer · an die Darstellung gebunden\n- Beispiele · geöffneter Dialog und Eingabefokus\n:::\n:::side{label=\"Geteilter Client State\"}\n- Besitzer · mehrere Oberflächenbereiche\n- Lebensdauer · innerhalb der Anwendungssitzung\n- Beispiele · lokale Auswahl und noch nicht gespeicherter Arbeitsstand\n:::\n:::side{label=\"Server State\"}\n- Besitzer · Backend oder Fachsystem\n- Lebensdauer · unabhängig vom Browser\n- Beispiele · Datensätze, Berechtigungen und freigegebene Revisionen\n:::\n::::\n\nDie Matrix empfiehlt keine Bibliothek. Sie verhindert zunächst, dass Serverdaten wie lokaler State oder kurzlebige UI-Details wie globale Fachobjekte behandelt werden.\n\n## Die Gegenprobe zuerst\n\nIn einem Projekt, das „unbedingt einen globalen Store“ brauchte, haben wir zuerst aufgeschrieben, was da eigentlich alles hinein sollte – und dann angefangen zu streichen. Ein überraschend großer Teil davon war in Wahrheit URL State: Filter, Seite, Auswahl oder Tab, sofern sie teilbar, navigierbar oder mit einem Lesezeichen speicherbar sein sollten. Kurzlebige Darstellungsdetails dürfen lokal bleiben. Ein Store, der navigierbare Werte zusätzlich hält, baut dagegen leicht eine zweite Wahrheit neben der Adresse auf.\n\nDer nächste große Block ist noch tückischer, weil er wie State aussieht und sich wie State anfühlt: geladene Daten. Die Liste der Rechnungen, das Nutzerprofil, das Suchergebnis. Das sind Cache-Kopien von etwas, dessen Wahrheit dem Backend gehört. Dafür braucht es Server-Cache-Semantik wie Schlüssel, Frische, Invalidierung und Fehlerzustände – ob sie eine spezialisierte Bibliothek oder etwa RTK Query innerhalb des Redux-Stores bereitstellt. Problematisch ist nicht der physische Speicherort, sondern ein handverwalteter Slice, der diese Semantik nachbaut.\n\nNimmt man diese beiden Blöcke heraus – navigierbaren State in die Adresse, Serverdaten in einen Cache –, bleibt oft wenig übrig. Der echte app-weite Client State kann ein kleiner Kern sein: Theme, Sprache, ein lokaler Entwurf oder ein Warenkorb, sofern dessen Wahrheit tatsächlich im Client liegt. Identität und Rechte stammen dagegen meist vom Server; lokal liegt nur ihre Cache-Kopie. Für den verbleibenden Kern lohnt sich ein Store, und weil dieser Kern klein ist, darf auch das Werkzeug klein sein.\n\n```mermaid\nflowchart TB\n  Start[\"Ein Wert, der wie<br/>globaler State aussieht\"]\n  Start --> Global{\"Wirklich app-weit,<br/>oder nur lokal gebraucht?\"}\n  Global -->|nur eine Ecke| Lokal[\"useState / useReducer<br/>in der Komponente\"]\n  Global -->|app-weit| URL{\"Gehört er in die URL?<br/>Filter, Seite, Auswahl\"}\n  URL -->|ja| Adresse[\"Router / URL<br/>teilbar, überlebt Reload\"]\n  URL -->|nein| Server{\"Gehört die Wahrheit<br/>dem Backend?\"}\n  Server -->|ja| Cache[\"Server-Cache<br/>TanStack Query / SWR\"]\n  Server -->|nein| Store[\"Echter Kern: erst<br/>jetzt Store-Wahl\"]\n```\n\nAuf die Reihenfolge kommt alles an. Wer mit der Werkzeugfrage anfängt, füllt den Store mit Dingen, die dort nichts zu suchen haben, und wundert sich später über Synchronisationsbugs. Wer mit der Gegenprobe anfängt, kommt oft mit `useState` und der URL durch und braucht gar keinen Store. Erst wenn nach dem Streichen ein Kern übrig bleibt, lohnt der Rest dieses Beitrags.\n\n## Drei Familien für den echten Kern\n\nAngenommen, dieser Kern ist da. Dann gibt es grob drei Denkschulen, wie man app-weiten State hält. Ich zeige jede an einem winzigen Beispiel und sage dazu ehrlich, was sie kostet – denn keine ist umsonst.\n\n### Redux Toolkit: das klassische Modell, entschlackt\n\nRedux hat ein klares Modell: Es gibt genau einen Store, einen zentralen State-Baum. Man ändert ihn nie direkt, sondern schickt Actions – beschreibende Nachrichten wie „increment“ –, und Pure Functions namens Reducer berechnen aus altem State plus Action den neuen. Dieses Modell hat Redux jahrelang den Ruf eingebracht, umständlich zu sein: viel Zeremonie, Action-Typen als Konstanten, Boilerplate für jeden Handgriff.\n\nRedux Toolkit – kurz RTK, heute die offiziell empfohlene Art, Redux zu schreiben – nimmt genau diese Zeremonie ab. Ein `createSlice` bündelt State, Actions und Reducer in einem Stück. Bemerkenswert ist der Reducer-Code: Er sieht aus, als würde man den State direkt mutieren, bleibt aber intern immutabel, weil RTK die Bibliothek Immer benutzt, die aus den scheinbaren Mutationen eine saubere neue Kopie macht.\n\n```js\nimport { configureStore, createSlice } from \"@reduxjs/toolkit\";\n\nconst cartSlice = createSlice({\n  name: \"cart\",\n  initialState: { items: [] },\n  reducers: {\n    addItem(state, action) {\n      // looks mutable, stays immutable via Immer\n      state.items.push(action.payload);\n    },\n    clear(state) {\n      state.items = [];\n    },\n  },\n});\n\nexport const { addItem, clear } = cartSlice.actions;\nexport const store = configureStore({ reducer: { cart: cartSlice.reducer } });\n```\n\nDas `configureStore` setzt den Store mit sinnvollen Voreinstellungen auf – die DevTools sind schon angebunden, gängige Middleware ist dabei. In TypeScript legt man sich zusätzlich einmal typsichere Hooks an (`useAppSelector`, `useAppDispatch`), sodass State und Actions durchgehend typisiert sind.\n\nDie Stärke von RTK liegt in der Nachvollziehbarkeit. Jede State-Änderung ist eine benannte Action, die durch einen Reducer läuft – ein protokollierbarer, reproduzierbarer Übergang. Die DevTools zeigen jede Action in der Reihenfolge, erlauben Time-Travel durch die Zustandshistorie und machen aus „warum steht da plötzlich dieser Wert?“ eine Frage, die man beantworten kann, statt sie zu erraten. In großen Teams und bei komplexen Abläufen ist das Gold wert: Der Zustandsfluss ist eine Konvention, die alle teilen, und keine Frage des persönlichen Stils. Der Preis ist ebenso ehrlich zu nennen: mehr Struktur, mehr Dateien, ein zentraler Baum, durch den alles läuft. Für den kleinen Kern einer mittelgroßen Anwendung ist das oft mehr Apparat, als der Kern verdient.\n\n### Leichte Stores: Zustand und Jotai\n\nDie zweite Familie setzt genau dort an: minimale API, kein Provider-Zwang, so wenig Code wie möglich. Zwei Vertreter aus demselben Umfeld, die aber unterschiedlich denken.\n\nZustand (ja, die Bibliothek heißt so – ein deutsches Wort als Name) gibt einem eine Funktion `create`, die einen Hook zurückliefert. Aus diesem Hook liest man per Selektor genau die Scheibe des States, die eine Komponente braucht. Der Selektor ist der Clou: Eine Komponente, die nur `count` liest, rendert nicht neu, wenn sich ein anderes Feld im Store ändert. Die Re-Renders bleiben granular, ohne dass man Context-Provider verschachteln muss.\n\n```js\nimport { create } from \"zustand\";\n\nconst useCartStore = create((set) => ({\n  items: [],\n  addItem: (item) => set((state) => ({ items: [...state.items, item] })),\n  clear: () => set({ items: [] }),\n}));\n\n// in a component: read only what you need\nconst count = useCartStore((state) => state.items.length);\n```\n\nJotai geht von der anderen Seite heran. Statt eines Stores, aus dem man Scheiben liest, gibt es viele kleine, atomare State-Einheiten – Atoms –, die man frei kombiniert. Ein Atom hält einen Wert, abgeleitete Atoms rechnen aus anderen Atoms. Eine Komponente abonniert genau die Atoms, die sie liest, und mehr nicht.\n\n```js\nimport { atom, useAtom } from \"jotai\";\n\nconst itemsAtom = atom([]);\nconst countAtom = atom((get) => get(itemsAtom).length);\n\n// in a component\nconst [count] = useAtom(countAtom);\n```\n\nDie Stärke beider ist offensichtlich: sehr wenig Code, feingranulare Updates, ein kleines Bundle. Man ist in Minuten produktiv, es gibt kaum Konzepte zu lernen. Der Preis ist die Kehrseite derselben Medaille – weniger Konvention, weniger vorgegebene Struktur. Redux zwingt einen in ein Muster; ein leichter Store lässt einem alle Freiheiten, auch die, sich ein Chaos zu bauen. Die Disziplin, den Store klein und geordnet zu halten und nicht doch wieder Serverdaten hineinzukippen, liegt beim Team. Für den kleinen Kern, um den es hier geht, ist das oft genau die richtige Größe.\n\n### MobX: der reaktive Ansatz\n\nDie dritte Familie denkt grundsätzlich anders. Redux und die leichten Stores sind im Kern immutabel: State ändern heißt, einen neuen State herstellen. MobX dreht das um. Man beschreibt beobachtbaren State, mutiert ihn ganz direkt, und die Bibliothek verfolgt selbständig, wer was liest, und aktualisiert genau die Stellen, die es angeht.\n\nMan macht ein Objekt mit `makeAutoObservable` beobachtbar. Abgeleitete Werte deklariert man als `computed` – hier als Getter –, und sie aktualisieren sich von allein, sobald sich ihre Grundlage ändert. Komponenten, die man in `observer` einwickelt, reagieren gezielt auf genau die beobachteten Werte, die sie im Rendern gelesen haben.\n\n```jsx\nimport { makeAutoObservable } from \"mobx\";\nimport { observer } from \"mobx-react-lite\";\n\nclass CartStore {\n  items = [];\n  constructor() {\n    makeAutoObservable(this);\n  }\n  addItem(item) {\n    this.items.push(item); // direct mutation is fine here\n  }\n  get count() {\n    return this.items.length; // derived, recomputes automatically\n  }\n}\n\nconst cart = new CartStore();\nconst CartBadge = observer(() => <span>{cart.count}</span>);\n```\n\nMobX glänzt, wenn viel State voneinander abgeleitet ist. Wo man in Redux Selektoren schreiben und memoisieren müsste, ergibt sich der abgeleitete Wert bei MobX von selbst und wird nur dann neu berechnet, wenn seine Eingaben sich ändern. Es bleibt auffällig wenig Code übrig, der nur Werte miteinander verbindet. Der Preis ist die Implizitheit: Genau weil man nichts explizit dispatcht, ist die Frage „wo kommt diese Änderung her?“ schwerer zu beantworten – die Aktualisierung passiert im Hintergrund, ausgelöst durch eine Mutation, die irgendwo im Code steht. Und es ist ein anderes mentales Modell als der Rest des React-Ökosystems: gezielte Mutation statt Immutabilität. Wer aus der Redux-Welt kommt, muss umdenken; wer objektorientiert denkt, fühlt sich sofort zu Hause.\n\n## Woran man die Wahl festmacht\n\nEs gibt keine Rangliste, die für alle stimmt – die Wahl hängt an ein paar Eigenschaften des Projekts. Je mehr Leute an demselben State arbeiten, desto mehr kann eine feste Konvention helfen. Für protokollierbare Übergänge und das Zurückspulen der Zustandshistorie sind die Redux-DevTools eine starke, aber nicht exklusive Lösung. Bei viel abgeleitetem State spielt das reaktive Modell von MobX seine Stärke aus. Dazu kommen Bundle-Budget, vorhandene Tooling-Anforderungen und die Vertrautheit des Teams; harte Größenurteile sollte man am konkreten Build messen, nicht aus einer Tabelle übernehmen.\n\nDaraus lassen sich ein paar Faustregeln ableiten, ohne dass sie Gesetze wären. Ist der Kern wirklich klein – eine angemeldete Person, ein Theme, ein Warenkorb –, reichen [Context mit `useReducer`](https://www.mikebild.dev/de/blog/context-richtig-einsetzen/) oder ein leichter Store wie Zustand, und mehr wäre überzogen. Steht ein großes Team vor komplexen Abläufen mit dem Wunsch nach auditierbaren Übergängen, ist Redux Toolkit die naheliegende Wahl, weil es genau diese Nachvollziehbarkeit zur Konvention macht. Lebt die Anwendung von viel abgeleitetem State, der sich kaskadierend aktualisieren soll, ist MobX in seinem Element. Und wenn zwei Optionen gleich gut passen, gibt die Vertrautheit des Teams den Ausschlag.\n\n## Die Wahl ist nachrangig\n\nKein Werkzeug ist „das beste“. Diese Vergleiche werden mit einer Ernsthaftigkeit geführt, die der Sache nicht angemessen ist – als hinge der Projekterfolg an Redux gegen MobX. Tut er nicht. Die Wahl des Stores ist nachrangig gegenüber der Besitzfrage, die davor kommt. Wer die URL für das nutzt, was in die URL gehört, und Serverdaten als Cache behandelt statt als State, hält den echten Client State so klein, dass fast jede der drei Familien reicht – und die Entscheidung dazwischen zur Geschmacksfrage schrumpft.\n\nDer Fehler, den die Werkzeugdebatte verdeckt, ist der teurere: einen großen globalen Store zu bauen und ihn mit URL State und Serverdaten zu füllen, die dort nicht hingehören. Kein Redux Toolkit und kein MobX rettet einen vor den Bugs, die daraus entstehen. Umgekehrt kommt man mit sauber gezogenen Grenzen und dem simpelsten der leichten Stores erstaunlich weit. Deshalb steht die Gegenprobe am Anfang dieses Beitrags und nicht am Ende: Sie entscheidet mehr als die Tabelle mit den drei Spalten danach.\n\n## Weiterführende Quellen\n\n- Repository introduction-react (Kapitel react-hooks, state-management): https://github.com/mikebild/introduction-react\n- Redux Toolkit, offizielle Dokumentation: https://redux-toolkit.js.org/\n- Zustand: https://github.com/pmndrs/zustand\n- Jotai: https://jotai.org/\n- MobX: https://mobx.js.org/"},{"locale":"de","translation_key":"dynamodb-datenmodellierung-single-table","slug":"dynamodb-datenmodellierung-single-table","title":"DynamoDB-Datenmodellierung: Single-Table-Design","summary":"DynamoDB belohnt ein anderes Denken als eine relationale Datenbank: nicht vom Datenmodell her, sondern von den Access Patterns. Single-Table-Design fasst mehrere Entity Types über zusammengesetzte Keys in einer Tabelle zusammen.","tags":["Software","AWS","Cloud"],"published_at":"2021-09-21T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/dynamodb-datenmodellierung-single-table/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/d146f748faf791163106431a1acbcfd3ad2a7b0788826f275bd7a6cf24048946/dynamodb-datenmodellierung-single-table-vorlesen.mp3","audio_duration_secs":700,"text":"# DynamoDB-Datenmodellierung: Single-Table-Design\n\nWer in DynamoDB den Partition Key festlegt, hat damit bereits entschieden, welche Queries später billig sind und welche gar nicht gehen. Es gibt keinen Optimizer, der eine ungeschickte Wahl im Nachhinein rettet, und keinen server-seitigen Join, der zwei Tabellen zur Laufzeit verbindet. Die Frage „Wo trage ich die Fremdschlüssel ein?“ hat schlicht keine Antwort – die Beziehung muss im Key stehen, bevor das erste Item geschrieben wird.\n\nDamit dreht sich die gewohnte Reihenfolge um. Bei einer relationalen Datenbank entwerfe ich zuerst ein sauberes, normalisiertes Modell und überlege mir die Queries später; der Optimizer sorgt schon dafür, dass die meisten Queries irgendwie funktionieren. Bei DynamoDB schreibe ich zuerst auf, welche Fragen die Anwendung an die Daten stellen wird, und leite daraus das Key-Schema ab. Das Datenmodell ist das Ergebnis dieser Muster, nicht ihr Ausgangspunkt.\n\n## Die drei Bausteine, mit denen alles anfängt\n\nSingle-Table steht und fällt mit drei Grundbausteinen. Solange die nicht sitzen, hängt jede Beschreibung des Musters in der Luft.\n\nEine DynamoDB-Tabelle hat einen Primary Key in einer von zwei Formen. Entweder ein Simple Primary Key – nur ein Partition Key (PK, historisch „hash key“). Oder ein Composite Primary Key aus Partition Key plus Sort Key (SK, „range key“). Bei der zusammengesetzten Variante muss die Kombination aus PK und SK pro Item eindeutig sein, der PK allein darf sich wiederholen. Genau das ist der Hebel für alles Weitere.\n\nDer Partition Key bestimmt über einen internen Hash, auf welcher physischen Partition ein Item landet. Der Sort Key ordnet die Items innerhalb einer Partition und erlaubt Range-Bedingungen. Alle Items mit demselben Partition Key bilden eine Item Collection – und diese Item Collection ist der eigentliche Kern von Single-Table-Design.\n\nDie `Query`-API liest immer genau eine Item Collection, also genau einen PK-Wert. Optional schränkt eine Bedingung auf den Sort Key das Ergebnis ein, mit Operatoren wie `=`, `<`, `<=`, `>`, `>=`, `BETWEEN` oder `begins_with`. Ein Aufruf liefert bis zu 1 MB, danach wird über `LastEvaluatedKey` paginiert. Der Gegensatz dazu ist der `Scan`, der die ganze Tabelle durchgeht – das will ich im Produktivbetrieb praktisch nie.\n\nDamit die Rollen klar bleiben, die Aufgabenverteilung im Überblick:\n\n- PK bestimmt Partition und Verteilung. Jede Query braucht genau einen PK-Wert – er entscheidet, welche Item Collection überhaupt gelesen wird.\n- SK ordnet und filtert innerhalb der Collection, über Range-Bedingungen und `begins_with`. Damit modelliere ich 1:n-Beziehungen und Hierarchien.\n- GSI (Global Secondary Index) definiert eine neue PK/SK-Kombination für zusätzliche Access Patterns. Jederzeit hinzufügbar, nur eventually consistent, mit eigenem Durchsatz.\n\nDer LSI (Local Secondary Index) ist der Kontrastfall: gleicher PK wie die Basistabelle, nur ein alternativer SK. Er unterstützt strong consistency, muss aber schon bei der Tabellenerstellung feststehen und bindet die Item Collection je PK an eine 10-GB-Grenze. Im Zweifel nehme ich den GSI.\n\n## Warum es keinen Join gibt – und was stattdessen passiert\n\nDynamoDB kennt keine server-seitigen Joins. Das klingt zunächst nach einem Mangel, ist aber eine bewusste Entscheidung für vorhersagbare Latenz. Der Trick: Ich verbinde die Daten nicht beim Lesen, sondern beim Schreiben. Wenn verschiedene Entity Types denselben Partition Key tragen, liegen sie in derselben Item Collection und lassen sich mit einem einzigen Query zusammen lesen. Das ist Pre-Joining – die Beziehung ist schon im Key-Schema angelegt, bevor der erste Lesezugriff passiert.\n\nNehmen wir ein kleines CMS mit Nutzern, deren Beiträgen und den Kommentaren zu einem Beitrag. Das zentrale Access Patterns lautet: „Hole einen Nutzer und alle seine Beiträge in einem Aufruf.“ Genau daraus leite ich das Key-Design ab, nicht aus einem ER-Diagramm.\n\n```mermaid\nflowchart LR\n  A[\"Zugriffsmuster:<br/>Hole User + seine Posts\"] --> B[\"PK wählen:<br/>USER#id\"]\n  B --> C[\"SK-Prefix wählen:<br/>USER# und POST#\"]\n  C --> D[\"Query auf PK = USER#123<br/>liefert eine Item Collection\"]\n  D --> E[\"Ergebnis:<br/>User-Item + alle Post-Items\"]\n```\n\nDie Ableitungsrichtung ist wichtig: Ich starte links beim Muster und arbeite mich zum Key vor. Das ist die Denkbewegung, die relationale Entwickler am Anfang irritiert.\n\n## Ein Single-Table-Layout\n\nSingle-Table-Design heißt: mehrere Entity Types in einer einzigen Tabelle, zusammengehalten über generische, zusammengesetzte Keys. Statt sprechender Attributnamen wie `UserId` nutze ich bewusst generische Namen wie `PK` und `SK`, denn dieselbe Spalte trägt je nach Entity Type unterschiedliche Bedeutungen. Für das CMS sieht ein Layout so aus:\n\n```text\nPK              SK                    weitere Attribute\n--------------  --------------------  -----------------------------\nUSER#123        USER#123              name, email, createdAt\nUSER#123        POST#2021-09-01T...   title, body, status\nUSER#123        POST#2021-09-14T...   title, body, status\nPOST#987        COMMENT#2021-09-15..  author, text\nPOST#987        COMMENT#2021-09-16..  author, text\n```\n\nDer Nutzer und seine Beiträge teilen sich den Partition Key `USER#123` und bilden damit eine Item Collection. Das User-Item hat einen SK, der den PK wiederholt (`USER#123`), die Beiträge nutzen den Prefix `POST#` gefolgt von einem Zeitstempel. Der Zeitstempel im Sort Key sortiert die Beiträge nebenbei chronologisch – ganz ohne zusätzlichen Index.\n\nFür das Muster „Hole alle Kommentare zu einem Beitrag“ reicht der Primärindex nicht, weil Kommentare unter einem anderen PK sinnvoll gebündelt sind. Hier kommt ein GSI ins Spiel. Ich lege zusätzliche Attribute `GSI1PK` und `GSI1SK` an und projiziere darüber einen Index, der Post-zu-Comment rückwärts lesbar macht. Das ist die Idee des Inverted Index: ein GSI mit vertauschten Rollen, um eine Beziehung aus der Gegenrichtung zu lesen.\n\nDie Tabelle selbst definiere ich mit generischen Keys und einem GSI. Ein Ausschnitt der `CreateTable`-Parameter:\n\n```json\n{\n  \"TableName\": \"cms\",\n  \"BillingMode\": \"PAY_PER_REQUEST\",\n  \"AttributeDefinitions\": [\n    { \"AttributeName\": \"PK\", \"AttributeType\": \"S\" },\n    { \"AttributeName\": \"SK\", \"AttributeType\": \"S\" },\n    { \"AttributeName\": \"GSI1PK\", \"AttributeType\": \"S\" },\n    { \"AttributeName\": \"GSI1SK\", \"AttributeType\": \"S\" }\n  ],\n  \"KeySchema\": [\n    { \"AttributeName\": \"PK\", \"KeyType\": \"HASH\" },\n    { \"AttributeName\": \"SK\", \"KeyType\": \"RANGE\" }\n  ],\n  \"GlobalSecondaryIndexes\": [\n    {\n      \"IndexName\": \"GSI1\",\n      \"KeySchema\": [\n        { \"AttributeName\": \"GSI1PK\", \"KeyType\": \"HASH\" },\n        { \"AttributeName\": \"GSI1SK\", \"KeyType\": \"RANGE\" }\n      ],\n      \"Projection\": { \"ProjectionType\": \"ALL\" }\n    }\n  ]\n}\n```\n\n`BillingMode: PAY_PER_REQUEST` ist der On-Demand-Modus, der seit Ende 2018 verfügbar ist. Für Beispiele und schwankende Last nehme ich ihn gerne, weil ich mich nicht um vorab reservierte Kapazität kümmern muss. Bei einem GSI wähle ich über `ProjectionType` bewusst, welche Attribute mitkommen – `KEYS_ONLY`, `INCLUDE` oder `ALL`. `ALL` ist bequem, kostet aber mehr Speicher und Schreib-Durchsatz.\n\n## Der Query über eine Item Collection\n\nJetzt der Teil, der die ganze Modellierung rechtfertigt. Mit dem SDK v3 und dem `DynamoDBDocumentClient` aus `@aws-sdk/lib-dynamodb` hole ich alle Beiträge eines Nutzers mit genau einem Aufruf:\n\n```ts\nimport { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\nimport { DynamoDBDocumentClient, QueryCommand } from \"@aws-sdk/lib-dynamodb\";\n\nconst client = DynamoDBDocumentClient.from(new DynamoDBClient({}));\n\nasync function getPostsByUser(userId: string) {\n  const result = await client.send(\n    new QueryCommand({\n      TableName: \"cms\",\n      KeyConditionExpression: \"PK = :pk AND begins_with(SK, :prefix)\",\n      ExpressionAttributeValues: {\n        \":pk\": `USER#${userId}`,\n        \":prefix\": \"POST#\",\n      },\n    })\n  );\n\n  return result.Items ?? [];\n}\n```\n\nDie `KeyConditionExpression` adressiert genau eine Item Collection über `PK = :pk` und schneidet mit `begins_with(SK, :prefix)` die Beiträge heraus. DynamoDB liest nur die Items, die auf `POST#` passen – der Prefix wirkt direkt auf dem Sort Key, nicht als nachträglicher Filter. Will ich den Nutzer samt aller Beiträge, lasse ich die `begins_with`-Bedingung weg und bekomme die komplette Collection in einem Rutsch.\n\nFür das Rückwärtsmuster über den Inverted Index ändert sich nur wenig. Ich adressiere den GSI und nutze dessen Keys:\n\n```ts\nasync function getCommentsByPost(postId: string) {\n  const result = await client.send(\n    new QueryCommand({\n      TableName: \"cms\",\n      IndexName: \"GSI1\",\n      KeyConditionExpression: \"GSI1PK = :g AND begins_with(GSI1SK, :prefix)\",\n      ExpressionAttributeValues: {\n        \":g\": `POST#${postId}`,\n        \":prefix\": \"COMMENT#\",\n      },\n    })\n  );\n\n  return result.Items ?? [];\n}\n```\n\nDas ist im Kern dieselbe Query-Mechanik, nur auf einem anderen Index. Wer das Primärmuster verstanden hat, überträgt es ohne Umgewöhnung auf den GSI.\n\n## Der Fallstrick mit dem FilterExpression\n\nDie `FilterExpression` sieht aus wie eine günstige Abkürzung, ist aber keine. Anders als die `KeyConditionExpression` filtert sie erst, nachdem die Items gelesen wurden. Das heißt, ich bezahle die Read Capacity Units auch für die Items, die der Filter anschließend wegwirft. Schlimmer noch, in Kombination mit `Limit` kann ich leere Seiten zurückbekommen, obwohl es passende Daten gibt – weil das Limit vor dem Filter greift.\n\nDie Konsequenz ist klar: Selektivität gehört ins Key-Design, nicht in den Filter. Wenn ich häufig nach einem Kriterium filtere, sollte dieses Kriterium in den Sort Key oder in einen GSI wandern. `FilterExpression` nutze ich nur für seltene, unkritische Verfeinerungen am Rand.\n\n## Wann Single-Table lohnt – und wann es überzogen ist\n\nSo elegant das Muster ist, es ist kein Selbstzweck. Single-Table wird auch dort eingeführt, wo es vor allem im Konferenzvortrag beeindruckend aussah – und handelt der Anwendung dann Komplexität ein, die ihr niemand zurückzahlt. Deshalb lohnt der ehrliche Blick auf die Motivation.\n\nSingle-Table lohnt sich, wenn die Access Patterns stabil und bekannt sind und wenn es darauf ankommt, viele zusammengehörige Daten mit möglichst wenigen Roundtrips zu lesen. Der Gewinn ist Performance und Skalierung bei vorhersagbarer Latenz, nicht Speicherersparnis. Datenduplizierung und Denormalisierung nehme ich dabei bewusst in Kauf – das ist ein Feature, kein Versehen.\n\nÜberzogen ist der Ansatz in mehreren Situationen:\n\n- Die Access Patterns sind früh im Projekt noch unklar oder ändern sich häufig. Single-Table macht nachträgliche Änderungen der Muster teuer, weil das Key-Schema tief in den Daten verankert ist.\n- Die Anwendung braucht Ad-hoc-Auswertungen oder Analytics. Ohne SQL wird die Export- und Reporting-Story mühsam, und ein Single-Table-Layout mit vielen Entity Types macht das nicht einfacher.\n\nAlex DeBrie, dessen Texte zu DynamoDB ich gerne weiterreiche, nennt einen weiteren Fall: GraphQL. Ein GraphQL-Server löst Felder ohnehin einzeln über Resolver auf, sodass der große Vorteil des Ein-Query-Ladens verpufft. Dort gibt ein Multi-Table-Ansatz oft mehr Flexibilität. Wie GraphQL und DynamoDB auf AWS konkret zusammenspielen, habe ich in [GraphQL-APIs mit AppSync und DynamoDB](https://www.mikebild.dev/de/blog/appsync-dynamodb-graphql-api/) beschrieben.\n\nEin technisches Detail, das bei vielen Entity Types in einer Tabelle zum Problem wird, sind DynamoDB Streams: AWS empfiehlt, pro Shard nicht mehr als zwei gleichzeitige Consumer zu betreiben, sonst drohen Throttling-Effekte. Wenn unterschiedliche Entities unterschiedliche Verarbeitungslogik brauchen, drängen sich schnell mehr Consumer auf, als ein Stream verträgt.\n\n## Ein Wort zu den harten Grenzen\n\nDamit die Modellierung nicht an physischen Limits scheitert, halte ich ein paar Zahlen präsent, die 2021 stabil gelten. Ein Item darf maximal 400 KB groß sein. Ein Query liefert pro Aufruf höchstens 1 MB, danach wird paginiert. `BatchGetItem` holt bis zu 100 Items oder 16 MB. Pro Tabelle sind standardmäßig bis zu 20 GSIs und maximal 5 LSIs möglich. Diese Grenzen zwingen zu bewusstem Design – etwa dazu, sehr große oder unbegrenzt wachsende Item Collections gar nicht erst entstehen zu lassen.\n\n## Fazit\n\nDer entscheidende Umbau findet im Kopf statt, nicht im Code. Wer DynamoDB wie eine relationale Datenbank behandelt, kämpft gegen das System. Wer bei den Access Patterns beginnt und daraus Partition Key, Sort Key und passende GSIs ableitet, arbeitet mit ihm. Single-Table-Design folgt dann aus dem Wunsch, zusammengehörige Daten mit einem Query und ohne Join zu lesen – und nicht aus dem Reiz des Musters selbst.\n\nPragmatisch führt der Weg über drei Schritte: erst die Access Patterns aufschreiben, dann das Key-Schema entwerfen, dann prüfen, ob ein einziger Primärindex plus wenige GSIs die Muster abdeckt. Wenn die Muster noch wackeln oder Ad-hoc-Analysen zentral sind, ist ein einfacheres Multi-Table-Layout die ehrlichere Wahl. Das Ziel ist nie das eleganteste Diagramm, sondern die Anwendung, die unter Last vorhersagbar bleibt.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-aws-serverless.html\n- Repository und begleitender Artikel: [GraphQL-APIs mit AppSync und DynamoDB](https://www.mikebild.dev/de/blog/appsync-dynamodb-graphql-api/)\n- AWS Docs, Core Components (Tables, Items, Keys, Item Collections): https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html\n- AWS Docs, Query-API: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html\n- AWS Docs, Global Secondary Indexes: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html\n- AWS Docs, Local Secondary Indexes: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html\n- AWS Docs, Best Practices und relationale Modellierung: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-relational-modeling.html\n- Alex DeBrie, „The What, Why, and When of Single-Table Design“: https://www.alexdebrie.com/posts/dynamodb-single-table/\n- Alex DeBrie, „How to model one-to-many relationships“: https://www.alexdebrie.com/posts/dynamodb-one-to-many/\n- AWS Database Blog, „Single-table vs. multi-table design in Amazon DynamoDB“: https://aws.amazon.com/blogs/database/single-table-vs-multi-table-design-in-amazon-dynamodb/"},{"locale":"de","translation_key":"cdn-construct-infrastruktur-api","slug":"cdn-construct-infrastruktur-api","title":"CDN Construct: eine kleine Infrastruktur-API","summary":"Warum ein eigenes CDK-Construct für statische Websites mehr ist als gesparte Zeilen: eine Schnittstelle mit Meinung über S3, CloudFront, Zertifikate und DNS.","tags":["Software","AWS","Cloud"],"published_at":"2021-09-14T10:00:00+00:00","updated_at":"2026-07-14T17:16:42.516469+00:00","url":"https://www.mikebild.dev/de/blog/cdn-construct-infrastruktur-api/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/047c3b151f89b25871cd02994dec8d367ee77c7f4015e9ba69b9551a5f8853c7/cdn-construct-infrastruktur-api-vorlesen.mp3","audio_duration_secs":712,"text":"# CDN Construct: eine kleine Infrastruktur-API\n\nRund 280 Zeilen CloudFormation, verteilt auf zwei Stacks in zwei Regionen – das war zuletzt der Preis dafür, eine statische Website „richtig\" auf AWS auszurollen. Vierzehn Ressourcen für eine Handvoll HTML-Dateien: ein S3-Bucket, eine Bucket-Policy, eine Origin Access Identity, eine CloudFront-Distribution mit Cache- und Fehlerverhalten, ein ACM-Zertifikat samt DNS-Validierung – zwingend in us-east-1, deshalb der zweite Stack –, dazu A- und AAAA-Alias-Records in Route53. Nichts davon ist für sich genommen schwierig. Aber alles zusammen ist Verdrahtung, die bei jedem neuen Projekt wieder ansteht und jedes Mal ein kleines bisschen anders gerät.\n\nGenau diese Wiederholung hat mich dazu gebracht, die ganze Kette in ein eigenes, kleines AWS-CDK-Construct zu packen: `cdk-cdn-construct`. Statische Inhalte – eine Single-Page-Application oder eine klassische statische Website – landen in einem S3-Bucket und werden über CloudFront als CDN ausgeliefert. Der Aufruf im eigenen Stack schrumpft auf wenige Zeilen. Das ist der sichtbare Gewinn. Der interessantere Gewinn ist ein anderer, und um den geht es in diesem Artikel: Ein gutes Construct ist eine Schnittstelle mit Meinung. Es macht Entscheidungen explizit, die vorher in Copy-and-paste-Templates versteckt waren, und es lässt genau die Knöpfe frei, die von Projekt zu Projekt wirklich variieren.\n\n## Was da eigentlich verdrahtet wird\n\nBevor die Abstraktion trägt, lohnt der Blick auf das, was sie kapselt. Eine statische Website hinter CloudFront besteht aus mehr Teilen, als der Satz „S3-Bucket mit CDN davor\" vermuten lässt:\n\n- ein privater S3-Bucket, bei dem Block Public Access vollständig aktiv ist\n- eine Origin Access Identity (OAI), über die CloudFront – und nur CloudFront – lesend auf den Bucket zugreift\n- die passende Bucket-Policy, die genau dieser Identität `s3:GetObject` erlaubt\n- eine CloudFront-Distribution mit HTTPS-Zwang, Default Root Object und sinnvollem Fehlerverhalten für Client-seitiges Routing\n- ein ACM-Zertifikat in us-east-1 samt DNS-Validierung\n- A- und AAAA-Alias-Records in der Route53-Zone, die auf die Distribution zeigen\n- der eigentliche Upload des Build-Outputs, inklusive Cache-Invalidierung nach dem Deployment\n\nAls Diagramm sieht die Verdrahtung so aus:\n\n```mermaid\nflowchart LR\n  Browser[Browser] -->|HTTPS| CF[CloudFront-Distribution]\n  CF -->|nur via OAI| S3[S3-Bucket<br/>privat, Block Public Access]\n  ACM[ACM-Zertifikat<br/>us-east-1] -.->|TLS| CF\n  R53[Route53<br/>A/AAAA-Alias] -.->|löst Domain auf| CF\n  Build[Build-Output<br/>z. B. ./build] -->|Upload + Invalidierung| S3\n```\n\nJede dieser Kanten ist eine Entscheidung. Der Bucket könnte auch öffentlich sein und Website-Hosting direkt anbieten – dann bräuchte es keine OAI, aber der Bucket wäre am CDN vorbei erreichbar und HTTPS auf der eigenen Domain fiele weg. Das Zertifikat könnte importiert statt DNS-validiert sein. Die Fehlerseiten könnten auf `404.html` zeigen statt auf `index.html`. In handgeschriebenen Templates stehen diese Entscheidungen nirgends als Entscheidung. Sie stehen da als 280 Zeilen YAML, und ob eine Abweichung Absicht oder Versehen ist, sieht man ihnen nicht an.\n\n## Vom Template zur API\n\nDas AWS CDK bietet mit seinen Construct-Ebenen ein brauchbares Vokabular dafür. L1-Constructs sind generierte Eins-zu-eins-Abbilder der CloudFormation-Ressourcen. L2-Constructs sind handgeschriebene Klassen mit Defaults und Hilfsmethoden – `Bucket` statt `CfnBucket`. Und L3-Constructs, in der Dokumentation auch Patterns genannt, bündeln mehrere Ressourcen zu einem Muster mit Absicht. AWS selbst pflegt seit letztem Jahr mit den Solutions Constructs eine ganze Bibliothek solcher Muster.\n\nMein Construct ist so ein L3-Baustein, technisch als eigener Stack umgesetzt, damit er sich als Ganzes in eine bestehende CDK-App einhängen lässt. Die Benutzung sieht so aus:\n\n```typescript\n#!/usr/bin/env node\nimport { App } from '@aws-cdk/core';\nimport { CdkCdnConstructStack } from 'cdk-cdn-construct';\n\nconst app = new App();\n\n// ... your own stacks ...\n\nnew CdkCdnConstructStack(app, 'MyWebsite', {\n  namespace: 'my-app-namespace',\n  env: {\n    account: process.env.CDK_DEFAULT_ACCOUNT,\n    region: process.env.CDK_DEFAULT_REGION,\n  },\n});\n```\n\nWas von außen konfigurierbar bleibt, folgt bewusst einer schlichten Konvention über Umgebungsvariablen – Name, Build-Verzeichnis, Domain:\n\n```\nCDK_DEFAULT_REGION=eu-central-1\nCDK_DEFAULT_ACCOUNT=default\nCDK_CDN_NAME=your-host-and-bucket-name\nCDK_CDN_PATH=./build\nCDK_CDN_DOMAIN=example.com\n```\n\nDas ist der ganze öffentliche Umfang. Kein Schalter für die Preisklasse der Distribution, keiner für TTLs, keiner für die Frage, ob der Bucket vielleicht doch öffentlich sein soll. Das ist keine Faulheit, sondern der Kern der Sache. Eine Schnittstelle mit Meinung sagt: Diese Punkte sind entschieden, und zwar so. Wer eine andere Meinung braucht, soll sie nicht durch einen Parameter hindurchfädeln, sondern ein anderes Construct nehmen – oder ein eigenes schreiben.\n\nDas Projekt ist dabei ehrlicherweise Work in Progress, ein Baustein aus der eigenen Werkstatt und kein poliertes Produkt. Aber gerade deshalb taugt es als Anschauungsmaterial: Die Frage, welche Knöpfe eine Infrastruktur-API frei lässt, stellt sich bei einem kleinen Construct genauso wie bei einer großen Plattform – nur dass man sie hier noch in einer Kaffeepause diskutieren kann.\n\n## Ein Blick ins Innere\n\nIm Inneren passiert genau das, was vorher im Template stand – nur einmal, benannt und mit Defaults, die man im Code-Review lesen kann. Der Kern lässt sich mit den CDK-v1-Bausteinen so skizzieren:\n\n```typescript\nconst originAccessIdentity = new cloudfront.OriginAccessIdentity(this, 'WebsiteOAI');\n\nconst websiteBucket = new s3.Bucket(this, 'WebsiteBucket', {\n  blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,\n});\nwebsiteBucket.grantRead(originAccessIdentity);\n\nconst certificate = new acm.DnsValidatedCertificate(this, 'WebsiteCertificate', {\n  domainName: props.domainName,\n  hostedZone: props.hostedZone,\n  region: 'us-east-1', // CloudFront accepts ACM certificates from us-east-1 only\n});\n\nconst distribution = new cloudfront.Distribution(this, 'WebsiteDistribution', {\n  defaultBehavior: {\n    origin: new origins.S3Origin(websiteBucket, { originAccessIdentity }),\n    viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,\n  },\n  domainNames: [props.domainName],\n  certificate,\n  defaultRootObject: 'index.html',\n});\n\nnew route53.ARecord(this, 'WebsiteAliasRecord', {\n  zone: props.hostedZone,\n  recordName: props.domainName,\n  target: route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)),\n});\n```\n\nDrei Details daran finde ich bemerkenswert, weil sie zeigen, was ein L2/L3-Zuschnitt gegenüber rohem CloudFormation tatsächlich leistet.\n\nErstens: `websiteBucket.grantRead(originAccessIdentity)` ist eine Zeile. Dahinter steht die komplette Bucket-Policy mit dem kanonischen Principal der OAI – ein Stück JSON, das ich in Template-Zeiten regelmäßig aus dem letzten Projekt kopiert habe, inklusive der Gelegenheit, dabei etwas zu verschleppen. Die Methode drückt die Absicht aus („diese Identität darf lesen\"), nicht den Mechanismus.\n\nZweitens: `DnsValidatedCertificate` mit explizitem `region: 'us-east-1'`. CloudFront akzeptiert nur Zertifikate aus dieser einen Region, egal wo der Rest des Stacks liegt. Wer das zum ersten Mal übersieht, bekommt beim Deployment eine Fehlermeldung, die auf das Zertifikat zeigt, aber nicht auf die Ursache – mir ist das seinerzeit mit einem Zertifikat in eu-central-1 passiert, und die Suche hat einen halben Nachmittag gekostet. Im Construct ist dieser Stolperstein jetzt eine kommentierte Zeile. Ein Kollege hat im Review genau darauf gezeigt und gefragt, warum die Region fest verdrahtet ist – und genau dieses Gespräch ist der Punkt: Die Regel steht jetzt an einer Stelle, an der man sie diskutieren kann, statt in drei Projekten implizit richtig oder falsch kopiert zu sein.\n\nDrittens: Der Alias-Record entsteht im selben Zug wie die Distribution. In der Template-Welt waren DNS-Einträge gern der manuelle Rest, „den machen wir nachher in der Konsole\" – und drei Monate später wusste niemand mehr, warum die Staging-Umgebung auf eine gelöschte Distribution zeigte. Wenn der Record Teil desselben Bausteins ist, gibt es diesen Rest nicht.\n\n## Defaults sind Meinung, nicht Magie\n\nDer übliche Einwand gegen solche Bausteine lautet: Abstraktion versteckt, was passiert, und in der Cloud heißt versteckt schnell teuer oder unsicher. Der Einwand trifft schlechte Constructs, aber er trifft nicht das Prinzip. Der Unterschied liegt darin, ob Defaults implizit oder explizit sind.\n\nEin kopiertes Template hat auch Defaults – sie heißen nur nicht so. Sie sind das, was der Autor des ersten Templates vor zwei Jahren für richtig hielt, verteilt über 280 Zeilen, ohne Namen und ohne Begründung. Ein Construct dagegen zwingt zur Entscheidung: Was ist fest? Was ist Parameter? Was ist bewusst nicht vorgesehen? Diese drei Fragen einmal sauber zu beantworten hat mich beim Bau des Constructs mehr Zeit gekostet als die eigentliche Verdrahtung – und es war die besser investierte Zeit.\n\nBeim CDN-Baustein sind die festen Meinungen zum Beispiel: Der Bucket ist privat, immer. Ausgeliefert wird ausschließlich über CloudFront, immer über HTTPS. Das Zertifikat wird per DNS validiert und liegt dort, wo CloudFront es verlangt. Frei bleiben Domain, Namensraum und der Pfad zum Build-Output – also genau die Dinge, die zwei Projekte tatsächlich unterscheiden. Alles andere zu öffnen hieße, die Wiederholung nur zu verschieben: Wer zwanzig Parameter durchreicht, hat am Ende wieder CloudFormation, nur mit anderen Klammern.\n\nEs gibt dabei eine Grenze, die ich anfangs unterschätzt habe: Ein Construct ist eine API, und Infrastruktur-APIs haben härtere Kompatibilitätsregeln als Bibliotheks-APIs. Wenn ich in einer Bibliothek eine Klasse umbenenne, brechen Builds. Wenn ich in einem Construct die Struktur ändere, ändern sich unter Umständen die logischen IDs der Ressourcen – und CloudFormation ersetzt dann Dinge, statt sie zu ändern. Bei einem S3-Bucket mit Inhalt ist das keine theoretische Sorge. Ein Construct zu versionieren heißt deshalb nicht nur, semantische Versionsnummern zu vergeben, sondern sich zu merken, welche Änderungen ein Replacement auslösen. Das steht in keinem Typsystem, und genau deshalb gehört es in die Meinung des Bausteins.\n\n## Wann sich ein eigenes Construct lohnt\n\nMan muss dieses Rad nicht selbst bauen. Die Solutions Constructs von AWS decken das Muster „CloudFront zu S3\" ab, und für viele Teams ist das die richtige Wahl. Ein eigenes Construct lohnt sich aus meiner Sicht dann, wenn die Meinung, die man kapseln will, spezifischer ist als die eines generischen Bausteins: eigene Namenskonventionen, eine feste Deploy-Konvention über Umgebungsvariablen, ein bestimmtes Fehlerverhalten für Single-Page-Applications, die hauseigene Tagging-Pflicht. Also immer dann, wenn man merkt, dass man den generischen Baustein in jedem Projekt mit denselben fünf Handgriffen nachjustiert – dann sind diese fünf Handgriffe das eigentliche Construct.\n\nDer Prozess dorthin folgt einem einfachen Ablauf, den man auch als Zyklus lesen kann:\n\n```mermaid\nflowchart TD\n  A[Verdrahtung im Projekt<br/>zum zweiten Mal getippt] --> B[Entscheidungen benennen:<br/>fest, Parameter, ausgeschlossen]\n  B --> C[Construct extrahieren<br/>mit minimaler Prop-Fläche]\n  C --> D[In zwei Projekten einsetzen]\n  D --> E{Nachjustiert?}\n  E -->|ja, immer gleich| B\n  E -->|nein| F[Meinung trägt]\n```\n\nWichtig ist die Reihenfolge: erst die Wiederholung erleben, dann extrahieren. Ein Construct, das vor dem zweiten Projekt entsteht, kapselt keine Erfahrung, sondern eine Vermutung – und Vermutungen mit zwanzig Parametern erkennt man daran, dass sie sich nicht trauen, etwas festzulegen.\n\nUmgekehrt gilt: Nicht jede Wiederholung verdient eine Abstraktion. Zwei ähnliche Stacks sind billiger als ein schlechtes gemeinsames Construct, das bei jeder Abweichung um einen Schalter wächst. Die ehrliche Frage ist, ob die Meinung stabil ist. Bei „statische Website hinter CloudFront\" bin ich mir da inzwischen sicher – das Muster hat sich über mehrere Projekte hinweg nicht bewegt, nur die Domains und Build-Verzeichnisse haben gewechselt. Das ist genau das Profil, bei dem sich die Extraktion trägt.\n\n## Unterm Strich\n\nAus 280 Zeilen in zwei Regionen werden ein Import, ein Konstruktoraufruf und fünf Umgebungsvariablen. Diese Rechnung ist real, aber sie ist nicht der eigentliche Ertrag. Der eigentliche Ertrag ist, dass die Infrastruktur-Entscheidung jetzt eine Adresse hat. Wenn jemand fragt, warum der Bucket privat ist, warum das Zertifikat in us-east-1 liegt oder warum es keinen TTL-Schalter gibt, dann zeigt die Antwort auf eine Stelle im Code – mit Namen, Kommentar und Git-Historie. Vorher zeigte sie auf ein Template, das irgendwann irgendwo kopiert wurde.\n\nIch habe lange Infrastruktur als etwas behandelt, das man beschreibt, und Anwendungscode als etwas, das man entwirft. Das CDK hebt diese Trennung auf, und ein kleines eigenes Construct ist der Punkt, an dem man das wirklich spürt: Auf einmal gelten die vertrauten Fragen des API-Designs – was ist öffentlich, was ist Default, was ist ausgeschlossen, was bricht bei einer Änderung – für Buckets und Distributionen genauso wie für Klassen und Module. Eine kleine Infrastruktur-API zu bauen ist deshalb weniger ein DevOps-Thema als eine ganz normale Entwurfsübung. Nur dass ein schlechter Default hier nicht in einer Exception endet, sondern in einer Rechnung oder einem öffentlichen Bucket.\n\n## Weiterführende Quellen\n\n- Projekt-Repository: [github.com/MikeBild/cdk-cdn-construct](https://github.com/MikeBild/cdk-cdn-construct)\n- AWS CDK v1: [Construct Library](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html)\n- CloudFront: [Restricting access to S3 origins mit Origin Access Identity](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html)\n- ACM: [Unterstützte Regionen – Zertifikate für CloudFront in us-east-1](https://docs.aws.amazon.com/acm/latest/userguide/acm-regions.html)\n- AWS Solutions Constructs: [github.com/awslabs/aws-solutions-constructs](https://github.com/awslabs/aws-solutions-constructs)"},{"locale":"de","translation_key":"outcome-vor-output","slug":"outcome-vor-output","title":"Outcome vor Output: warum Velocity die falsche Zahl ist","summary":"Erledigte Tickets sind Output, aber noch kein Beleg für Wirkung. Warum Velocity im Management-Reporting in die Irre führt und wie man Teams stattdessen an Outcomes ausrichtet.","tags":["Software","Produkt"],"published_at":"2021-08-26T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/outcome-vor-output/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/81a046fcdf437c7828cd32c32f177765c1c538c7371d4c0c9f59f58d5ea565df/outcome-vor-output-vorlesen.mp3","audio_duration_secs":749,"text":"```typescript\n// Sprint-Report, wie er im Statusdeck landet\nconst sprint42 = {\n  storyPointsCommitted: 34,\n  storyPointsCompleted: 38,\n  ticketsDone: 17,\n  velocityTrend: \"up\",\n};\n```\n\nAus diesem Objekt folgt genau eine Aussage: Das Team hat mehr Punkte abgeschlossen, als es zugesagt hatte. Ob ein Nutzer dadurch schneller ans Ziel kommt, ob ein System stabiler läuft, ob irgendwo Umsatz entsteht – dafür gibt es hier kein Feld, und es lässt sich auch nachträglich keines hineinrechnen. Trotzdem wandert genau diese Kurve Sprint für Sprint in Berichte, wird zwischen zwei Teams verglichen und landet gelegentlich neben dem Umsatz auf einer Board-Folie.\n\nDie Frage, die tatsächlich zählt, lautet nicht \"Wie viele Story Points hat das Team abgearbeitet?\", sondern \"Was hat sich für den Nutzer, für das System, für das Geschäft dadurch verändert?\". Das ist der Unterschied zwischen Output und Outcome. Und wer ihn verwischt, optimiert ein Team systematisch auf Beschäftigung statt auf Wirkung.\n\nDie Trennlinie verläuft zwischen einer beobachteten Aktivität und der belegbaren Veränderung, die daraus folgt.\n\n::::comparison{title=\"Aktivität und Wirkung beantworten andere Fragen\" role=\"primary\" preferredPattern=\"split-comparison\"}\n:::side{label=\"Output\"}\n- Beobachtung · Was wurde gebaut oder abgeschlossen?\n- Beispiele · Features, Tickets und Story Points\n- Nutzen · Planung und Nachverfolgung der Arbeit\n- Grenze · Belegt noch keine Veränderung beim Nutzer\n:::\n:::side{label=\"Outcome\"}\n- Beobachtung · Was hat sich im Verhalten oder Ergebnis verändert?\n- Beispiele · Aktivierung, Zeit bis zum ersten Wert und Fehlerquote\n- Nutzen · Prüft, ob eine Lösung auf das Ziel einzahlt\n- Grenze · Benötigt Kontext und eine belastbare Messung\n:::\n::::\n\nDamit bleibt Velocity als internes Planungsmaß brauchbar, ohne zur Aussage über Produktivität oder Geschäftswert zu werden.\n\n## Velocity misst Vorhersagbarkeit, nicht Produktivität\n\nFangen wir bei der Quelle an, denn Velocity ist zu Unrecht in Verruf geraten. Martin Fowler hat schon vor bald zwei Jahrzehnten präzise beschrieben, wofür die Zahl gedacht war: als Kalibrierungswerkzeug für Schätzungen. Das Prinzip heißt \"Yesterday's Weather\" – wir gehen davon aus, dass ein Team im nächsten Sprint ungefähr so viel schafft wie im letzten. Damit lassen sich Planungen realistisch halten, ohne dass jemand heldenhafte Zusagen macht.\n\nStory Points sind dabei eine teamspezifische Baseline. Sie bedeuten für Team A etwas anderes als für Team B, weil sie relativ zum jeweiligen Kontext geschätzt werden. Genau deshalb ist der Vergleich zweier Teams anhand ihrer Velocity nicht nur ungenau, sondern schlicht sinnlos – man vergleicht zwei verschiedene Maßeinheiten und tut so, als wären es dieselben.\n\nUnd dann passiert das Vorhersehbare. Sobald Velocity zum Management-Ziel wird, wird sie gespielt. Teams schätzen großzügiger, splitten Tickets feiner, deklarieren Nebensächliches als Story. Die Kurve steigt, die Lieferung bleibt gleich. Das ist keine Böswilligkeit, das ist Goodhart's Law in Reinform: \"When a measure becomes a target, it ceases to be a good measure.\" Jede Zahl, die man zum Erfolgsmaß erhebt, hört in demselben Moment auf, ehrlich zu sein.\n\nIch will Velocity also gar nicht verteufeln. Intern, als Planungs- und Vorhersagehilfe, ist sie völlig legitim und nützlich. Der Fehler liegt nicht in der Zahl, sondern in ihrer Beförderung zum Erfolgsmaß. Das ist eine wichtige Differenzierung, die im Eifer der \"Velocity ist böse\"-Debatten gern verschwindet.\n\n## Der wahre Output ist Wirkung – und die lässt sich nicht direkt messen\n\nFowlers eigentlich radikaler Punkt kommt danach: \"True output is business value.\" Der wahre Ertrag eines Teams ist nicht die Menge an Features, sondern der geschaffene Wert. Sein Beispiel bringt es auf den Punkt: Ein Team, das weniger Features liefert, aber zehn Millionen Gewinn erzeugt, ist produktiver als eines mit mehr Features und fünf Millionen Wert.\n\nDer Haken daran ist ernüchternd. Business Value hinkt der Investition zeitlich nach, oft um Jahre. Was ein Team heute baut, zahlt sich – wenn überhaupt – erst später aus, verzahnt mit Markt, Vertrieb, Timing und einem Dutzend anderer Faktoren. Eine sofortige, saubere Produktivitätsmessung ist damit schlicht unmöglich. Fowlers ehrliche Konsequenz: \"We have to admit our ignorance.\" Wir können Produktivität nicht direkt messen. Punkt.\n\nDas klingt entmutigend, ist aber befreiend. Denn wenn die perfekte Zahl nicht existiert, hören wir auf, sie zu suchen, und wenden uns dem zu, was wir tatsächlich beeinflussen und beobachten können: der Wirkung unserer Arbeit auf Nutzer und System.\n\n## Outcome statt Output: der Kern moderner Produktarbeit\n\nGenau hier setzt die Produktseite an. Teresa Torres unterscheidet in ihrer Arbeit zu Continuous Discovery sauber: Outputs sind das, was wir bauen – Features, Screens, Endpoints. Outcome ist die Veränderung im Verhalten von Nutzern, die einen Wert für Kunde und Geschäft erzeugt. Wer Outputs zum Ziel erklärt, produziert einen \"disconnect\" zwischen der Aktivität des Teams und dem gelieferten Wert. Das Team ist ausgelastet, das Board ist voll, und trotzdem bewegt sich beim Nutzer nichts.\n\nMarty Cagan formuliert dieselbe Beobachtung noch schärfer: \"Empowered teams get outcomes, feature teams get output.\" Ein Feature-Team bekommt eine Roadmap vorgesetzt und arbeitet sie ab – Output. Ein \"empowered\" Team bekommt ein Problem und ein Outcome-Ziel und darf selbst herausfinden, wie es dorthin kommt. Der Unterschied ist nicht kosmetisch. Er entscheidet darüber, ob Menschen mitdenken oder nur abarbeiten.\n\nDas Werkzeug, mit dem ich dabei die besten Erfahrungen gemacht habe, ist der Opportunity Solution Tree. An der Wurzel steht genau ein Outcome, zum Beispiel \"Aktivierungsrate um X Prozent erhöhen\". Darunter verzweigen sich Opportunities – konkrete Nutzerprobleme oder -bedürfnisse, die auf dieses Outcome einzahlen. Darunter wiederum Solutions, und ganz unten die Experimente, mit denen wir prüfen, ob eine Lösung tatsächlich wirkt. Der Baum zwingt zu der Frage, die die Velocity-Kurve nie stellt: Zahlt das, was wir gerade bauen, überhaupt auf die Wurzel ein?\n\n```mermaid\ngraph TD\n    subgraph output[\"Output-Sicht (Vanity)\"]\n        B[Backlog] --> S[Sprint]\n        S --> V[\"Velocity-Chart<br/>viele erledigte Tickets\"]\n        V --> U[\"up and to the right\"]\n    end\n    subgraph outcome[\"Outcome-Sicht\"]\n        O[\"Outcome<br/>activation rate +X%\"] --> OP1[Opportunity A]\n        O --> OP2[Opportunity B]\n        OP1 --> SOL[Solution]\n        SOL --> EXP[Experiment]\n    end\n    V -. \"bewegt der Output<br/>die Wurzel?\" .-> O\n```\n\nDas Diagramm zeigt die beiden Welten nebeneinander. Links die Output-Pipeline, die zuverlässig nach oben zeigt. Rechts der Baum, der die Wirkung nachvollziehbar macht. Der gestrichelte Pfeil dazwischen ist die eigentliche Managementfrage – und genau dieser Pfeil fehlt in den Berichten, die ich zu sehen bekomme, fast durchgängig.\n\n## Vanity Metrics: die Engineering-Variante der Selbsttäuschung\n\nEric Ries hat für diese Sorte Zahlen im Lean-Startup-Kontext den Begriff Vanity Metrics geprägt. Registrierungen, Pageviews, Downloads – Zahlen, die \"up and to the right\" gehen und sich gut anfühlen, ohne echten Fortschritt zu belegen. Velocity und erledigte Tickets sind die Engineering-Variante genau dieses Musters. Sie steigen zuverlässig, sie erzeugen ein gutes Gefühl, und sie sagen nichts darüber, ob wir dem Ziel näher gekommen sind.\n\nDem gegenüber stehen Actionable Metrics: Zahlen, die eine Ursache-Wirkungs-Beziehung zeigen und aus denen eine Entscheidung folgt. Die Fortschrittseinheit ist bei Ries nicht \"Feature ausgeliefert\", sondern \"validated learning\" – bestätigtes Lernen darüber, was beim Nutzer tatsächlich wirkt. Der Rahmen dafür heißt Innovation Accounting, der Zyklus Build-Measure-Learn.\n\nIn der Praxis heißt das: Man instrumentiert nicht, was man gebaut hat, sondern was der Nutzer daraufhin tut. Ein Event, das ein Outcome trackt, sieht anders aus als eines, das Output zählt.\n\n```typescript\n// Actionable: measures what actually moves the user\ntrack(\"activation_completed\", {\n  userId,\n  cohort,\n  timeToValueSeconds, // how fast does the user reach first value?\n});\n\n// Vanity: feels like progress, says nothing about impact\n// track(\"features_shipped\", { count });\n// track(\"story_points_done\", { total });\n```\n\nDer entscheidende Schritt kommt danach: Man rollt das Feature hinter einem Flag aus und vergleicht das Outcome-Delta zwischen zwei Cohorts. Erhöht die neue Lösung die Aktivierungsrate messbar, oder nicht? Das ist Build-Measure-Learn in einer Zeile Infrastruktur – und es verlagert die Erfolgsfrage vom \"haben wir es gebaut?\" zum \"hat es gewirkt?\".\n\n## Bessere Proxys: DORA und Fitness Functions\n\nNun wird an dieser Stelle gern eingeworfen: Es gibt doch DORA. Die vier Kennzahlen aus der Accelerate-Forschung von Forsgren, Humble und Kim – Deployment Frequency, Lead Time for Changes, Change Failure Rate und Time to Restore Service – sind ein großer Fortschritt. Sie messen bewusst Team-Outcomes statt individueller Outputs. Ausdrücklich kein Lines-of-Code, keine Story Points, keine Auslastung, weil das siloartige Beschäftigungszahlen sind. Und sie balancieren Geschwindigkeit gegen Stabilität, sodass man nicht eine Zahl auf Kosten des Gesamtsystems optimieren kann.\n\nDORA hilft, mit einer Einschränkung: Auch diese Metrics sind Proxys, keine echten Outcomes. Deployment Frequency ist nicht Nutzerwirkung. Ein Team kann fünfzigmal am Tag deployen und trotzdem am Bedarf vorbei. DORA misst die Fähigkeit, schnell und stabil zu liefern – ein exzellenter Indikator für Delivery-Gesundheit, aber eben nicht das Ziel selbst. Wer das verwechselt, hat nur eine Vanity-Zahl durch vier ersetzt.\n\nAuf der Architekturebene gibt es ein Instrument, das mir besonders am Herzen liegt, weil es Outcome ausführbar macht: Fitness Functions aus der Evolutionary Architecture von Ford, Parsons und Kua. Eine Fitness Function ist eine objektive, automatisierte Bewertung einer Architektureigenschaft. Statt in einem Ticket \"Performance verbessert\" abzuhaken, schreibt man einen Test, der die Systemwirkung selbst prüft:\n\n```python\ndef test_checkout_latency_stays_within_budget():\n    \"\"\"Architectural fitness function: checkout stays fast under load.\"\"\"\n    result = load_test(endpoint=\"/checkout\", concurrent_users=200)\n\n    assert result.p99_ms < 500       # latency budget, not a story point\n    assert result.error_rate < 0.01  # reliability is the real outcome\n```\n\nDer Charme daran: Erfolg ist hier keine Statusmeldung mehr, sondern eine messbare Systemeigenschaft, die entweder gehalten wird oder nicht. Der Test ist grün, weil das System die versprochene Wirkung liefert – nicht, weil jemand eine Story auf \"done\" geschoben hat. Ähnlich funktionieren Consumer-Driven Contracts, etwa mit Pact: Ein Test schlägt fehl, wenn ein Service ein Versprechen gegenüber seinem Konsumenten bricht. Auch das ist ein outcome-naher Test – er prüft die tatsächliche Wirkung an der Schnittstelle statt die bloße Existenz von Code.\n\n## Wie man Teams wirklich auf Outcome ausrichtet\n\nWenn ich das in einer Organisation aufsetze, folge ich einem einfachen Ablauf. Er ist bewusst schlank, weil der ganze Sinn der Übung ist, Prozess-Overhead durch Klarheit zu ersetzen, nicht neue Zeremonien zu schaffen.\n\n```mermaid\nflowchart LR\n    A[\"Outcome definieren<br/>ein Ziel, messbar\"] --> B[\"Opportunities<br/>Nutzerprobleme kartieren\"]\n    B --> C[\"Experimente<br/>hinter Feature-Flags\"]\n    C --> D[\"Wirkung messen<br/>Cohort-Delta\"]\n    D -->|\"wirkt\"| E[\"skalieren\"]\n    D -->|\"wirkt nicht\"| B\n```\n\nAm Anfang steht genau ein Outcome, formuliert als messbare Verhaltensänderung – nicht \"Checkout-Redesign ausliefern\", sondern \"Abbruchrate im Checkout senken\". Dazu passt der Gedanke der North Star Metric und, auf Zielebene, OKRs: Das Objective beschreibt die Richtung, die Key Results sind die Outcome-Signale, an denen wir Fortschritt erkennen.\n\nDer zweite Schritt sammelt die Opportunities: An welchen Stellen bricht der Nutzer tatsächlich ab, wo entsteht Reibung? Erst danach kommen Lösungen, und die werden nicht ausgerollt und abgehakt, sondern als Experiment hinter einem Flag getestet. Zeigt das Cohort-Delta eine Wirkung, skalieren wir. Zeigt es keine, gehen wir zurück zu den Opportunities – ohne schlechtes Gewissen, denn ein widerlegtes Experiment ist validated learning und damit selbst ein Ergebnis.\n\nEin wichtiger Vorbehalt gehört dazu, sonst tappt man in die nächste Falle. Goodhart gilt auch für Outcome-KPIs. Auch eine Aktivierungsrate lässt sich spielen, und der Zeitverzug aus Fowlers Beobachtung bleibt bestehen: Wirkung braucht Zeit, und die Attribution ist selten eindeutig. Wer ein Outcome-Ziel setzt, muss diese Unschärfe einkalkulieren, statt sie wegzudefinieren – sonst konstruiert man falsche Kausalitäten und ist keinen Schritt weiter als beim Velocity-Chart.\n\n## Fazit\n\nDer rote Faden durch all das ist einfach: Output ist notwendig, aber Wirkung ist das Ziel. Erledigte Tickets, Story Points und Velocity beschreiben Arbeit und Planung – nicht, ob sich für Nutzer oder Geschäft etwas verbessert hat. Als interne Planungshilfe sind sie legitim; als Erfolgsmaß fürs Management lenken sie in die falsche Richtung, weil eine Zielzahl optimiert wird und Beschäftigung noch keine Wirkung belegt.\n\nDer Ausweg ist keine bessere Einzelzahl, sondern eine Haltung. Wir richten Teams an einem messbaren Outcome aus, machen die Wirkung über Actionable Metrics, Fitness Functions und Experimente sichtbar, und behandeln DORA als das, was es ist – einen guten Proxy für Lieferfähigkeit, nicht als Ziel. Das Ergebnis ist in meiner Erfahrung kein schwererer, sondern ein leichterer Prozess: kürzere Zyklen, weil wir Irrwege früh abbrechen; weniger Reibung, weil Teams selbst entscheiden dürfen; und höhere Qualität, weil Erfolg an der Wirkung hängt und nicht an der Statusfarbe eines Tickets.\n\nFowlers nüchternes Eingeständnis bleibt der beste Ausgangspunkt: Wir können Produktivität nicht direkt messen. Aber wir können aufhören, die falsche Zahl zu feiern, und anfangen, die richtige Frage zu stellen – bewegt das, was wir bauen, überhaupt die Wurzel?\n\n## Weiterführende Quellen\n\n- Martin Fowler: [CannotMeasureProductivity](https://martinfowler.com/bliki/CannotMeasureProductivity.html) und [XpVelocity](https://martinfowler.com/bliki/XpVelocity.html)\n- Teresa Torres: [Continuous Discovery Habits](https://www.goodreads.com/book/show/58046715-continuous-discovery-habits) (2021)\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate* (2018); [Four Keys to measure DevOps performance](https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance)\n- Eric Ries: [The Lean Startup – Principles](https://theleanstartup.com/principles) (2011)\n- Neal Ford, Rebecca Parsons, Patrick Kua: [Building Evolutionary Architectures – Fitness Functions](https://www.oreilly.com/library/view/building-evolutionary-architectures/9781491986356/ch02.html) (2017)"},{"locale":"de","translation_key":"datenanalyse-mit-pandas","slug":"datenanalyse-mit-pandas","title":"Datenanalyse mit NumPy, Pandas und Matplotlib","summary":"Von Rohdaten zur Erkenntnis: Wie NumPy, pandas und Matplotlib zusammenspielen – vektorisiertes Rechnen, groupby-Aggregation und ein schneller Plot in einer kleinen Pipeline.","tags":["Software","Python","Daten"],"published_at":"2021-08-24T10:00:00+00:00","updated_at":"2026-07-13T10:03:09.962873+00:00","url":"https://www.mikebild.dev/de/blog/datenanalyse-mit-pandas/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0d0283b0c8a9113bdad599cce9a9111e4e793b3728fe981d70f7ccba34b4d8c9/datenanalyse-mit-pandas-vorlesen.mp3","audio_duration_secs":1025,"text":"Ein `DataFrame` ist keine Tabellenkalkulation und keine Datenbanktabelle. Er ist eine Sammlung typisierter Spalten im Arbeitsspeicher, jede davon ein NumPy-Array, alle über einen gemeinsamen Index verbunden. Diese Herkunft erklärt fast alles, was später überrascht: warum das Durchlaufen einzelner Zeilen so teuer ist, warum eine Auswahl mal eine Sicht auf die Originaldaten und mal eine Kopie liefert, und warum ein `groupby` in einem Ausdruck erledigt, wofür man sonst eine Schleife samt Cache bauen müsste.\n\nDer erste Reflex vor einer CSV-Datei mit ein paar hunderttausend Zeilen ist trotzdem die Python-Schleife. Öffnen, Zeile für Zeile durchgehen, Werte summieren, am Ende ausgeben. Das funktioniert – für hundert Zeilen. Bei einer Million Zeilen wartet man dann und fragt sich, warum das so lange dauert.\n\nDie Frage nach der Schleife ist in Wahrheit die kleinere. Die größere entscheidet sich weiter oben: Eine Analyse ist selten Selbstzweck. Am Ende hängt an ihr eine Entscheidung. Ein Preis wird angepasst, ein Budget umgeschichtet, eine Region ausgebaut oder zurückgefahren. Der Wert einer Analyse bemisst sich deshalb nicht daran, wie elegant sie rechnet, sondern daran, wie belastbar ihr Ergebnis eine Entscheidung trägt. Und genau da liegt das eigentliche Risiko: nicht in der Laufzeit, sondern in der Frage, ob die Zahl am Ende stimmt und ob ich morgen dieselbe Zahl noch einmal herstellen kann.\n\nDer Werkzeugkasten aus NumPy, pandas und Matplotlib ist die Antwort auf diese Anforderung, nicht nur auf das Geschwindigkeitsproblem. Die drei Bibliotheken bilden zusammen einen Weg von den Rohdaten bis zur fertigen Grafik, und jede übernimmt dabei eine klar umrissene Aufgabe. Entscheidend ist, dass dieser Weg wiederholbar wird: derselbe Code, dieselben Rohdaten, dasselbe Ergebnis, unabhängig davon, wer ihn ausführt. In diesem Artikel gehe ich den Weg einmal komplett durch, erst das schnelle Rechnen mit NumPy, dann strukturierte Tabellen mit pandas, schließlich die Visualisierung mit Matplotlib. Am Ende steht eine kleine Pipeline, die lädt, bereinigt, gruppiert und plottet. Ich lege dabei den Blick weniger auf einzelne Funktionsaufrufe als auf die Stellen, an denen eine Analyse ihre Verlässlichkeit gewinnt oder verliert. Wer sich vorher noch fragt, wie die Daten überhaupt ins Programm kommen, findet in [Daten einlesen in Python](https://www.mikebild.dev/de/blog/python-daten-einlesen/) die Grundlagen dazu.\n\n## Warum keine Python-Schleife? NumPy und das ndarray\n\nDer Kern von NumPy ist ein einziger Datentyp: das `ndarray`. Auf den ersten Blick sieht es aus wie eine Liste, aber der Unterschied steht im Speicher. Eine Python-Liste hält Verweise auf beliebige Objekte, die irgendwo verstreut im Speicher liegen. Ein `ndarray` ist homogen typisiert und zusammenhängend abgelegt – alle Elemente haben denselben Datentyp und stehen direkt hintereinander.\n\nDieser Aufbau ist die Voraussetzung für das, was NumPy schnell macht: vektorisierte Operationen. Statt in Python über einzelne Elemente zu iterieren, wird die Rechnung als Ganzes an kompilierten C-Code übergeben. Ein Beispiel macht den Unterschied deutlich.\n\n```python\nimport numpy as np\n\nvalues = np.arange(1_000_000)   # 0, 1, 2, ... 999999\nresult = values * 2 + 1         # vectorized, no Python loop\ntotal = result.mean()\n\nprint(result.shape)             # (1000000,)\nprint(result.dtype)             # int64\nprint(total)                    # 1000000.0\n```\n\nDie Zeile `values * 2 + 1` rechnet auf allen Millionen Elementen, ohne dass eine einzige Python-`for`-Schleife läuft. Der Ausdruck ist nicht nur schneller, er ist auch kürzer und liest sich näher an der mathematischen Absicht. Das ist der eigentliche Gewinn: Man beschreibt, *was* gerechnet werden soll, nicht *wie* über die Elemente iteriert wird.\n\nNeben den arithmetischen Operationen gibt es zwei Werkzeuge, die in praktisch jeder Auswertung vorkommen. Das eine sind Reduktionen wie `.sum()`, `.mean()`, `.std()` oder `.min()` und `.max()`, die aus einem Array eine Kennzahl machen. Das andere sind Boolean-Masken.\n\n```python\nimport numpy as np\n\ndata = np.array([-3, 7, -1, 4, 9, -8])\n\nmask = data > 0                 # array of True/False\npositives = data[mask]          # keep only positive values\nclipped = np.where(data < 0, 0, data)   # replace negatives with 0\n\nprint(positives)                # [7 4 9]\nprint(clipped)                  # [0 7 0 4 9 0]\n```\n\n`data > 0` erzeugt kein einzelnes `True` oder `False`, sondern ein ganzes Array aus Wahrheitswerten. Damit lässt sich dann filtern (`data[mask]`) oder mit `np.where` fallweise ersetzen. Auch hier keine Schleife, keine Bedingung im Python-Code – die Logik steckt komplett in der vektorisierten Operation.\n\nEng verwandt mit der Vektorisierung ist das Broadcasting. Damit lassen sich Arrays unterschiedlicher Form miteinander verrechnen, solange ihre Dimensionen zueinander passen. Ein Skalar wird dabei gedanklich auf die gesamte Form des Arrays ausgedehnt – deshalb funktioniert `values * 2 + 1`, ohne dass man die `2` und die `1` erst selbst auf eine Million Elemente aufblasen müsste. Bei zweidimensionalen Daten greift dieselbe Regel: Ein Zeilenvektor mit passender Spaltenzahl lässt sich auf jede Zeile einer Matrix anwenden, etwa um von jeder Spalte den Mittelwert abzuziehen. Broadcasting erspart damit viele explizite Schleifen und hält den Code nah an der mathematischen Notation. Wichtig ist nur, die Formen im Kopf zu behalten: Passen die Dimensionen nicht zusammen, quittiert NumPy das mit einem `ValueError`, statt stillschweigend etwas Falsches zu rechnen.\n\n## Pandas: Tabellen mit Beschriftung\n\nNumPy rechnet gut mit Zahlen, aber reale Daten haben Struktur. Spalten haben Namen, Zeilen haben eine Bedeutung, und oft mischen sich Zahlen mit Text und Datumsangaben. Hier kommt pandas ins Spiel, und pandas baut direkt auf NumPy auf. Unter den Tabellen von pandas stecken NumPy-Arrays.\n\nDie zwei zentralen Strukturen sind `Series` und `DataFrame`. Eine `Series` ist eine eindimensionale Spalte mit einem Index. Ein `DataFrame` ist eine zweidimensionale Tabelle mit beschrifteten Zeilen und Spalten – im Grunde eine Sammlung von `Series`, die sich denselben Index teilen.\n\n```python\nimport pandas as pd\n\ndf = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"north\", \"west\", \"south\"],\n    \"amount\": [120.0, 80.0, 45.0, 200.0, 95.0],\n    \"channel\": [\"online\", \"store\", \"online\", \"store\", \"online\"],\n})\n\nprint(df.shape)                 # (5, 3)\nprint(df[\"amount\"].mean())      # 108.0\n```\n\nDas Einlesen aus einer Datei läuft meist über `pd.read_csv`, das eine CSV-Datei in ein `DataFrame` verwandelt. Ab dann arbeitet man mit derselben Tabelle weiter, egal woher sie stammt.\n\n### Auswahl mit loc und iloc – der klassische Stolperstein\n\nSobald man Zeilen und Spalten gezielt herausgreifen will, tauchen zwei Zugriffsarten auf, die Anfänger zuverlässig durcheinanderbringen: `.loc` und `.iloc`. Der Unterschied ist eigentlich einfach, aber man muss ihn einmal bewusst gelernt haben.\n\n`.loc` ist label-basiert. Man greift über die Beschriftung von Zeilen und Spalten zu, und – das ist die Eigenheit – der Endpoint eines Bereichs ist **inklusiv**. `.iloc` ist positionsbasiert. Man greift über die ganzzahlige Position zu, und der Endpoint ist **exklusiv**, genau wie beim normalen Python-Slicing.\n\n```python\nimport pandas as pd\n\ndf = pd.DataFrame(\n    {\"amount\": [120, 80, 45, 200, 95]},\n    index=[\"a\", \"b\", \"c\", \"d\", \"e\"],\n)\n\n# label-based, endpoint INCLUDED -> rows a, b, c\nprint(df.loc[\"a\":\"c\", \"amount\"])\n\n# position-based, endpoint EXCLUDED -> rows a, b, c (positions 0, 1, 2)\nprint(df.iloc[0:3, 0])\n```\n\nBeide Ausdrücke liefern hier dieselben drei Zeilen, aber aus unterschiedlichen Gründen: einmal weil `\"c\"` als Label eingeschlossen wird, einmal weil Position `3` gerade nicht mehr mitgenommen wird. Wer das verwechselt, erntet entweder einen Off-by-one-Fehler oder einen `KeyError`. Labels also immer über `.loc`, Positionen immer über `.iloc`, und die beiden nie in einem Ausdruck mischen.\n\nZum Filtern nutzt man Boolean-Masken – genau wie in NumPy, nur dass die Bedingung sich auf eine Spalte bezieht.\n\n```python\nimport pandas as pd\n\ndf = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"north\", \"west\"],\n    \"amount\": [120, 80, 45, 200],\n})\n\nbig = df[df[\"amount\"] > 100]              # keep rows above 100\nbig_regions = df.loc[df[\"amount\"] > 100, \"region\"]   # filter + pick column\n```\n\n## Der häufigste Fehler: verkettetes Indizieren\n\nJetzt zu einem Fallstrick, der in Code-Reviews regelmäßig auftaucht und der zu einer der meistgesuchten Warnungen im pandas-Umfeld führt: dem `SettingWithCopyWarning`. Er entsteht durch verkettetes Indizieren – also zwei aufeinanderfolgende Zugriffe in einem Ausdruck.\n\n```python\n# problematic: chained indexing\ndf[df[\"amount\"] > 100][\"tier\"] = \"high\"     # may write into a copy!\n```\n\nDas Tückische daran: `df[df[\"amount\"] > 100]` liefert je nach Situation eine Sicht auf die Originaldaten oder eine Kopie davon – und es ist nicht sicher vorhersagbar, welches von beiden. Schreibt man dann in das Ergebnis, landet die Zuweisung womöglich in einer Kopie, die sofort wieder verworfen wird. Das Original bleibt unverändert, und pandas warnt genau davor. Die korrekte Form nutzt einen einzigen `.loc`-Zugriff, der Zeilenauswahl und Spalte in einem Schritt adressiert:\n\n```python\n# correct: single .loc access\ndf.loc[df[\"amount\"] > 100, \"tier\"] = \"high\"\n```\n\nUnd wenn man bewusst mit einer eigenständigen Kopie weiterarbeiten will, sagt man das ausdrücklich mit `df.copy()`. Dann ist klar, dass Änderungen das Original nicht berühren sollen. Diese eine Regel – Auswahl und Zuweisung in einem `.loc` – erspart erfahrungsgemäß die meisten dieser Warnungen.\n\nDer zweite Fehler in derselben Kategorie ist das Iterieren über Zeilen. Wer aus der klassischen Programmierung kommt, greift instinktiv zu `df.iterrows()` und geht Zeile für Zeile durch. Das ist langsam und speicherhungrig, weil pandas für jede Zeile ein neues Objekt bauen muss und der ganze Geschwindigkeitsvorteil des vektorisierten NumPy-Unterbaus verloren geht. Fast immer lässt sich dieselbe Absicht mit einer Spaltenoperation, mit `groupby` oder mit `np.where` ausdrücken – und läuft dann um Größenordnungen schneller.\n\n## Gruppieren und aggregieren mit groupby\n\nDie vielleicht wichtigste Operation für Analysen ist `groupby`. Sie folgt einem Muster, das unter dem Namen Split-Apply-Combine bekannt ist: Die Daten werden nach einem Schlüssel in Gruppen aufgeteilt (split), auf jede Gruppe wird eine Aggregatfunktion angewendet (apply), und die Teilergebnisse werden zu einer neuen Tabelle zusammengefügt (combine).\n\n```python\nimport pandas as pd\n\ndf = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"north\", \"west\", \"south\"],\n    \"amount\": [120.0, 80.0, 45.0, 200.0, 95.0],\n})\n\nsummary = (df.groupby(\"region\")\n             .agg(total=(\"amount\", \"sum\"),\n                  avg=(\"amount\", \"mean\"))\n             .reset_index())\n\nprint(summary)\n#   region  total    avg\n# 0  north  165.0   82.5\n# 1  south  175.0   87.5\n# 2   west  200.0  200.0\n```\n\nDie benannte Aggregation `total=(\"amount\", \"sum\")` ist meine bevorzugte Schreibweise: Sie sagt in einer Zeile, welche Spalte mit welcher Funktion aggregiert wird und wie die Ergebnisspalte heißen soll. Das Ergebnis ist eine kompakte Tabelle, die sich direkt weiterverarbeiten lässt. Das `.reset_index()` am Ende holt den Gruppierungsschlüssel aus dem Index zurück in eine normale Spalte – praktisch, wenn man gleich danach plotten will.\n\nOft liegen die Daten nicht in einer einzigen Tabelle, sondern verteilt. Verkaufszahlen hier, Regionsinformationen dort. Zum Zusammenführen dient `merge`, das nach dem Vorbild von Datenbank-Joins arbeitet:\n\n```python\nimport pandas as pd\n\nsales = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"west\"],\n    \"amount\": [165, 175, 200],\n})\nmanagers = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"east\"],\n    \"manager\": [\"Ada\", \"Ben\", \"Cleo\"],\n})\n\njoined = sales.merge(managers, how=\"inner\", on=\"region\")\nprint(joined)\n#   region  amount manager\n# 0  north     165     Ada\n# 1  south     175     Ben\n```\n\nHier lohnt ein wacher Blick auf den Parameter `how`. Mit `how=\"inner\"` bleiben nur Regionen, die in beiden Tabellen vorkommen – „west“ und „east“ fallen heraus. Ein `how=\"outer\"` würde alle Regionen behalten und die fehlenden Werte mit `NaN` auffüllen. Wer den falschen Modus wählt, verliert entweder unbemerkt Zeilen oder handelt sich unerwartete Lücken ein. Es lohnt sich, vor und nach einem `merge` einmal auf `.shape` zu schauen und zu prüfen, ob die Zeilenzahl zu den Erwartungen passt.\n\n## Die Pipeline: laden, bereinigen, gruppieren, plotten\n\nSetzen wir die Teile zusammen. Eine typische Analyse durchläuft immer dieselben Stationen, und es hilft, diesen Ablauf einmal als Bild vor Augen zu haben.\n\n```mermaid\nflowchart LR\n    A[Rohdaten<br/>CSV-Datei] --> B[Laden<br/>pandas.read_csv]\n    B --> C[Bereinigen<br/>dropna / fillna]\n    C --> D[Transformieren<br/>groupby / agg]\n    D --> E[Plotten<br/>matplotlib]\n```\n\nVor dem Gruppieren steht meist das Bereinigen. Reale Daten haben Lücken, und `groupby` oder Rechnungen darauf reagieren empfindlich auf fehlende Werte. Zwei Werkzeuge decken die meisten Fälle ab: `dropna` wirft Zeilen mit fehlenden Werten weg, `fillna` ersetzt sie durch einen Vorgabewert. Welches von beiden richtig ist, hängt von der Frage ab – manchmal ist eine Lücke ein echtes Nichts, manchmal eine getarnte Null.\n\n```python\nimport pandas as pd\n\ndf = pd.read_csv(\"sales.csv\")\n\n# clean: drop rows without an amount\ndf = df.dropna(subset=[\"amount\"])\n\n# transform: aggregate per region\nsummary = (df.groupby(\"region\")\n             .agg(total=(\"amount\", \"sum\"))\n             .reset_index())\n```\n\n## Datenqualität und Reproduzierbarkeit als Entscheidungsrisiko\n\nDer Schritt `df.dropna(subset=[\"amount\"])` sieht nach einer Formsache aus. Er ist keine. In dem Moment, in dem ich fehlende Werte wegwerfe statt sie zu füllen, entscheide ich darüber, welche Zahl am Ende beim Entscheider ankommt. `dropna` verkleinert die Grundmenge und kann eine Region verschwinden lassen, die schlicht schlecht erfasst war. `fillna(0)` macht aus einem „unbekannt“ eine harte Null und zieht damit jeden Mittelwert nach unten. Beides ist manchmal richtig und manchmal falsch, aber nie neutral. Die Frage ist immer dieselbe: Ist die Lücke ein echtes Nichts oder eine getarnte Null? Diese Entscheidung gehört dokumentiert, nicht stillschweigend getroffen.\n\nDer zweite, teurere Risikofaktor ist stiller Datenverlust. Ein `merge` mit dem falschen `how` lässt Zeilen ohne Warnung fallen, eine Bereinigung halbiert unbemerkt die Grundmenge, und das Balkendiagramm sieht trotzdem plausibel aus. Genau darin liegt die Gefahr: Eine falsche Analyse sieht einer richtigen zum Verwechseln ähnlich. Deshalb baue ich Prüfungen direkt in die Pipeline, statt auf den Augenschein zu vertrauen.\n\n```python\nbefore = len(df)\ndf = df.dropna(subset=[\"amount\"])\nassert len(df) >= before * 0.9, \"dropped more than 10% of rows\"\nassert df[\"amount\"].between(0, 10_000).all(), \"amount out of expected range\"\n```\n\nSolche Zusicherungen kosten Minuten in der Entwicklung. Eine Entscheidung, die auf einer um zehn Prozent geschrumpften Grundmenge fußt, kostet deutlich mehr, und der Fehler fällt oft erst auf, wenn er schon gewirkt hat. Das ist der eigentliche Trade-off: ein wenig Reibung beim Schreiben gegen eine belastbare Zahl beim Entscheiden.\n\nDer dritte Punkt ist Reproduzierbarkeit. Eine Analyse, die ich in einer Tabellenkalkulation zusammenklicke, ist nach zwei Wochen nicht mehr nachvollziehbar. Niemand weiß mehr, welche Zellen von Hand angefasst wurden. Eine Analyse als Code ist das Gegenteil: derselbe Code auf denselben Rohdaten liefert dasselbe Ergebnis, jederzeit, für jeden im Team. Die Rohdaten bleiben unangetastet, jede Transformation steht sichtbar im Skript, und das Ergebnis lässt sich bis zur Quelle zurückverfolgen. Damit wird aus einer einmaligen Zahl ein Vorgang, den ich prüfen, versionieren und verteidigen kann. Genau das hebt eine Analyse von einer netten Grafik zu einer Entscheidungsgrundlage.\n\n## Matplotlib: aus Zahlen wird ein Bild\n\nAm Ende der Pipeline steht die Visualisierung. Matplotlib ist die etablierte Bibliothek dafür, und ich empfehle von Anfang an den objektorientierten Stil: erst mit `plt.subplots()` eine Figur und eine Achse erzeugen, dann alles auf dieser Achse aufbauen. Das ist etwas mehr Tipparbeit als der schnelle `plt.plot()`-Einzeiler, aber es bleibt übersichtlich, sobald eine Grafik mehr als eine Kurve enthält.\n\n```python\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.bar(summary[\"region\"], summary[\"total\"])\nax.set_xlabel(\"Region\")\nax.set_ylabel(\"Total sales\")\nax.set_title(\"Sales by region\")\nplt.show()\n```\n\nFür die drei häufigsten Diagrammtypen gibt es je eine passende Funktion auf der Achse. Ein Balkendiagramm mit `ax.bar(x, height)` vergleicht Kategorien – ideal für das `groupby`-Ergebnis von eben. Ein Liniendiagramm mit `ax.plot(x, y)` zeigt Verläufe, etwa eine Kennzahl über mehrere Monate hinweg. Und ein Streudiagramm mit `ax.scatter(x, y)` zeigt den Zusammenhang zweier Größen. Beschriftungen über `set_xlabel`, `set_ylabel` und `set_title` gehören für mich immer dazu; eine Grafik ohne Achsenbeschriftung ist nur eine halbe Aussage.\n\n## Wer macht was? Die Rollenteilung im Überblick\n\nDie Aufgabenteilung im Werkzeugkasten ist klar geschnitten, und wer sie kennt, greift für ein Problem nicht zur falschen Bibliothek:\n\n- NumPy bildet die numerische Basis: homogene Arrays, vektorisiertes Rechnen, mathematische Operationen. Alles darüber baut darauf auf.\n- pandas kümmert sich um strukturierte, beschriftete Tabellendaten: einlesen, bereinigen, auswählen, filtern, gruppieren, zusammenführen – der gesamte Umgang mit realen, unordentlichen Daten.\n- Matplotlib übernimmt die Visualisierung: Aus den fertig aufbereiteten Zahlen wird ein Diagramm, das eine Aussage transportiert.\n\nDiese Reihenfolge ist kein Zufall. Sie beschreibt genau den Weg, den die Daten nehmen: von rohen Zahlen über eine strukturierte Tabelle bis zum Bild.\n\n## Roter Faden\n\nDer eigentliche Denkwechsel bei der Datenanalyse mit Python ist der Abschied von der Schleife. Nicht mehr Element für Element durchgehen, sondern ganze Spalten und ganze Tabellen als Einheit behandeln. NumPy macht das über vektorisierte Operationen auf dem `ndarray`, pandas hebt dieselbe Idee auf beschriftete Tabellen, und `groupby` fasst nach dem Split-Apply-Combine-Pattern ganze Gruppen auf einmal zusammen. Der Gewinn ist aber nicht nur Tempo. Wer die zwei Anfängerfallen kennt, verkettetes Indizieren und das Iterieren über Zeilen, umgeht die häufigsten Reibungspunkte und schreibt Code, der bei einer Million Zeilen genauso ruhig bleibt wie bei hundert.\n\nWirkung entfaltet dieser Werkzeugkasten dort, wo Analyse auf Entscheidung trifft. Eine Pipeline aus Code verkürzt den Zyklus von der Frage zur Antwort: Ändern sich die Rohdaten, läuft dasselbe Skript erneut, und die neue Zahl steht in Minuten statt in einem halben Tag Handarbeit. Sie senkt die Reibung im Team, weil jeder dasselbe Ergebnis reproduzieren kann, statt eine fremde Tabelle zu entziffern. Und sie hebt die Qualität, weil Prüfungen und dokumentierte Bereinigungsentscheidungen dafür sorgen, dass eine falsche Zahl auffällt, bevor sie eine Entscheidung trägt. Die Grenze ist ebenso klar: Diese Werkzeuge arbeiten dort gut, wo die Daten in den Arbeitsspeicher passen und eine Analyse im Batch genügt. Bei Datenmengen jenseits einer einzelnen Maschine oder bei laufenden Datenströmen beginnt ein anderes Werkzeugfeld, und die Kunst besteht darin, diese Grenze rechtzeitig zu erkennen, statt pandas über seinen Einsatzbereich hinaus zu prügeln.\n\nDer Rest ist Übung: laden, bereinigen, gruppieren, plotten, und diesen Kreislauf so oft gehen, bis er in den Fingern sitzt. Das Werkzeug wird erst dann nützlich, wenn die Schritte reproduzierbar bleiben und eine zweite Person dieselbe Zahl erhält.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-python.html\n- Repository `introduction-python` mit lauffähigen Beispielen zu NumPy, pandas und Matplotlib\n- NumPy – „the absolute basics for beginners“: https://numpy.org/doc/stable/user/absolute_beginners.html\n- pandas – Indexing and Selecting Data (loc/iloc, chained indexing): https://pandas.pydata.org/docs/user_guide/indexing.html\n- pandas – Group by: split-apply-combine: https://pandas.pydata.org/docs/user_guide/groupby.html\n- pandas – Merge, join, concatenate: https://pandas.pydata.org/docs/user_guide/merging.html\n- Matplotlib – pyplot API: https://matplotlib.org/stable/api/pyplot_summary.html"},{"locale":"de","translation_key":"wann-cqrs-und-event-sourcing-zu-viel-ist","slug":"wann-cqrs-und-event-sourcing-zu-viel-ist","title":"Wann CQRS und Event Sourcing zu viel sind","summary":"Für die meisten Systeme reicht CRUD. CQRS und Event Sourcing lohnen sich nur unter klaren Bedingungen – dieser Beitrag liefert einen ehrlichen Entscheidungsleitfaden statt Muster als Selbstzweck.","tags":["Software","Architektur"],"published_at":"2021-07-13T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/wann-cqrs-und-event-sourcing-zu-viel-ist/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/759367c6923eba28889d4d50637b54fa67b84c7a39f3a8c83ebcdbec47eccdf8/wann-cqrs-und-event-sourcing-zu-viel-ist-vorlesen.mp3","audio_duration_secs":665,"text":"# Wann CQRS und Event Sourcing zu viel sind\n\nEine E-Mail-Adresse ändern kostet im CRUD-Handler drei Zeilen: laden, Feld setzen, speichern. Mit CQRS und Event Sourcing sind es fünf Teile – ein Command, ein Event, ein Aggregat mit Replay-Pfad, ein Append in den Event Store und eine Projection, die das Read Model nachzieht. Dazu kommt ein Zeitfenster, in dem eine Query noch die alte Adresse liefert. Fünf bewegliche Teile und ein Konsistenzproblem, das es vorher nicht gab.\n\nDiesen Preis kann man zahlen, und unter bestimmten Bedingungen zahlt er sich aus. Ich mag beide Muster und habe sie in anderen Beiträgen verteidigt. Für den Großteil der Systeme sind sie trotzdem zu viel.\n\nDas ist keine steile These. Martin Fowler formuliert es fast identisch: \"For most systems CQRS adds risky complexity.\" Und ungewöhnlich deutlich für ihn: In der Mehrzahl der Fälle, die ihm begegnet sind, war CQRS keine gute Wahl, sondern brachte ein erhebliches Risiko mit, das System in ernste Schwierigkeiten zu bringen. Wenn der Autor, der ein Muster bekannt gemacht hat, so warnt, lohnt sich ein ehrlicher Entscheidungsleitfaden.\n\n## Die Baseline heißt CRUD\n\nBevor ich über Alternativen rede, halte ich fest, was die Standardlösung eigentlich leistet. CRUD bedeutet: ein einziges Datenmodell für Lesen und Schreiben, direkte Persistenz des aktuellen Zustands, meist gegen eine Tabelle über ein ORM. Create, Read, Update, Delete. Fowler nennt das nüchtern: \"Many systems do fit a CRUD mental model, and so should be done in that style.\"\n\nDer entscheidende Punkt ist, dass CRUD nicht die primitive Vorstufe ist, die man später durch etwas Besseres ersetzt. Für ein Formular, das gespeichert und wieder angezeigt wird, ist CRUD nicht der Kompromiss, sondern die richtige Antwort. Ein illustrativer Handler dafür ist unspektakulär – und genau das ist die Stärke:\n\n```ts\nasync function updateCustomerEmail(id: string, email: string): Promise<void> {\n  const customer = await repo.findById(id);\n  customer.email = email;\n  await repo.save(customer); // read and write share the same model\n}\n```\n\nEin Modell, ein Zugriff, keine Latenz zwischen Schreiben und Lesen. Wer diesen Wert wegoptimiert, ohne ein Problem zu haben, tauscht Einfachheit gegen Komplexität ein und bekommt dafür nichts zurück.\n\n## Was CQRS und Event Sourcing wirklich sind\n\nDamit die Entscheidung sauber wird, trenne ich die beiden Begriffe, die gern in einem Atemzug genannt werden. CQRS – Command Query Responsibility Segregation – heißt, dass man ein anderes Modell zum Ändern von Daten benutzt als zum Lesen. Die Schreibseite nimmt Commands an, prüft Invarianten und gibt nichts zurück. Die Leseseite beantwortet Queries, liefert Daten und ändert nichts. Das ist mehr als das Command-Query-Separation-Prinzip von Bertrand Meyer: CQS trennt Methoden auf einem Objekt, CQRS trennt ganze Modelle.\n\nEvent Sourcing ist etwas anderes. Hier wird jede Zustandsänderung als Event festgehalten, und der aktuelle Zustand entsteht durch erneutes Abspielen der Events. Der Event Store ist die maßgebliche Quelle der Wahrheit, der Zustand ist rein abgeleitet. Fowlers Analogie dazu ist die Versionskontrolle: Das Commit-Log entspricht dem Event Store, der Arbeitsbaum dem aktuellen Systemzustand. Diesen Gedanken habe ich in [Event Sourcing: der Event-Store als Logbuch](https://www.mikebild.dev/de/blog/event-sourcing-der-event-store-als-logbuch/) ausführlicher entwickelt.\n\nWichtig für den heutigen Beitrag: Beide Muster sind unabhängig voneinander. Greg Young stellt das mehrfach klar – CQRS ist nicht Event Sourcing, braucht keinen Message Bus und ist auch nicht zwingend an DDD gekoppelt. Man kann CQRS ohne Event Sourcing betreiben, also mit getrennter Lese-Datenbank, aber klassischer Zustandspersistenz. Und man kann Event Sourcing mit nur einem Modell betreiben. Wer beide zusammen einführt, entscheidet sich also für zwei Kostenblöcke, nicht für einen.\n\n## Die Kosten, die man selten mitplant\n\nGetrennte Modelle erzwingen faktisch Eventual Consistency. Sobald die Schreibseite ein Event erzeugt und die Leseseite daraus erst eine Projection baut, existiert ein Zeitfenster, in dem eine Query den gerade geschriebenen Wert noch nicht sieht. Fowler nennt das offen: Getrennte Modelle erhöhen die Wahrscheinlichkeit, Eventual Consistency einsetzen zu müssen. Das ist keine Funktion, sondern eine Kostenposition.\n\nEin illustrativer Kontrast zum CRUD-Handler oben zeigt die zusätzlichen beweglichen Teile. Erst die Messages:\n\n```ts\ninterface ChangeEmail {\n  type: \"ChangeEmail\";\n  id: string;\n  email: string;\n}\n\ninterface EmailChanged {\n  type: \"EmailChanged\";\n  id: string;\n  email: string;\n  version: number;\n}\n```\n\nDann das Write Model, das aus seinen Events rehydriert wird und beim Ändern eine Invariante prüft, statt einfach ein Feld zu überschreiben:\n\n```ts\nclass Customer {\n  private constructor(\n    private readonly id: string,\n    private email: string,\n    private version: number,\n  ) {}\n\n  static empty(): Customer {\n    return new Customer(\"\", \"\", 0);\n  }\n\n  static from(events: EmailChanged[]): Customer {\n    // fold the event stream into current state (replay)\n    return events.reduce(\n      (state, event) => state.apply(event),\n      Customer.empty(),\n    );\n  }\n\n  private apply(event: EmailChanged): Customer {\n    return new Customer(event.id, event.email, event.version);\n  }\n\n  changeEmail(email: string): EmailChanged[] {\n    if (email === this.email) return []; // no change, no event\n    return [{ type: \"EmailChanged\", id: this.id, email, version: this.version + 1 }];\n  }\n}\n```\n\nUnd schließlich der Handler, der lädt, entscheidet, anhängt – und die Projection getrennt davon nachzieht:\n\n```ts\nasync function handle(command: ChangeEmail): Promise<void> {\n  const events = await store.load(command.id);\n  const customer = Customer.from(events);\n  const newEvents = customer.changeEmail(command.email);\n  await store.append(command.id, newEvents); // source of truth\n  // read model is updated asynchronously by a projection\n}\n```\n\nDie Leseseite ist ein eigenes, bewusst dummes Read Model, das aus denselben Events entsteht:\n\n```ts\nclass CustomerListView {\n  private rows = new Map<string, { id: string; email: string }>();\n\n  on(event: EmailChanged): void {\n    this.rows.set(event.id, { id: event.id, email: event.email });\n  }\n\n  // a query right after append may still return the previous email (stale read)\n  find(id: string) {\n    return this.rows.get(id);\n  }\n}\n```\n\nZwischen dem ersten CRUD-Beispiel und dieser Variante liegt kein Fortschritt, sondern eine Abwägung. Ich habe mehr Typen, mehr Indirektion, einen Replay-Pfad, eine Projection und ein Konsistenzfenster eingetauscht – gegen einen Nutzen, der nur unter bestimmten Bedingungen überhaupt entsteht.\n\nEvent Sourcing bringt darüber hinaus eigene, oft unterschätzte Kosten mit. Alte Events müssen praktisch für immer lesbar bleiben, was Event-Versionierung und Schema-Evolution zu einer Daueraufgabe macht. Projections und Read Models müssen aufgebaut und neu aufgebaut werden können. Externe Side Effects beim Replay wollen sorgfältig behandelt sein, sonst verschickt ein Neuaufbau versehentlich echte E-Mails. Und ein einfaches Ad-hoc-Query auf den aktuellen Zustand gibt es nicht mehr geschenkt. Diese Punkte kommen zusätzlich zu den CQRS-Kosten obendrauf.\n\n## Ein Entscheidungsfluss\n\nIch mache die Entscheidung an wenigen Fragen fest, in dieser Reihenfolge. Wichtig dabei: Das gilt pro Bounded Context, nicht global. Greg Young ist hier eindeutig – CQRS ist kein Top-Level-Pattern, es wird innerhalb einer Komponente angewandt, nicht über das ganze System gestülpt.\n\n```mermaid\nflowchart TD\n  Start([Neuer Context]) --> Inv{Echtes Domänenmodell<br/>mit kollidierenden Invarianten?}\n  Inv -->|nein| Crud[CRUD genügt]\n  Inv -->|ja| Asym{Starke Read/Write-Asymmetrie<br/>ODER Audit-/Zeitreise-Anforderung?}\n  Asym -->|nein| Lite[Weiter CRUD<br/>oder CQRS-lite]\n  Asym -->|ja| Team{Team trägt Eventual Consistency<br/>und Event-Versionierung?}\n  Team -->|nein| Kompromiss[CRUD oder Kompromiss]\n  Team -->|ja| Cqrs[CQRS – plus Event Sourcing,<br/>wenn Audit oder Temporal]\n```\n\nDer Nutzen von CQRS ist eng an zwei Bedingungen gebunden. Erstens eine komplexe Domäne, in der ein gemeinsames Modell für Lesen und Schreiben tatsächlich zu kompliziert wird. Zweitens eine ausgeprägte Lese-/Schreib-Asymmetrie – viele Lesezugriffe, wenige Schreibzugriffe –, sodass sich die unabhängige Skalierung von Lese- und Schreibseite auszahlt. Fehlen beide, führt Fowlers Beobachtung geradewegs in die Falle: CQRS auf einer Domäne, die nicht dazu passt, erhöht die Komplexität, senkt die Produktivität und steigert das Risiko. Das Muster vereinfacht nicht von sich aus, sondern nur dort, wo bereits echte Modell- oder Invarianten-Komplexität liegt.\n\n## Signale dafür und dagegen\n\nIm konkreten Projekt hängt die Antwort an ein paar Signalen, die man meist früher sieht, als man sie ernst nimmt.\n\nDafür spricht:\n\n- ein task-basiertes UI mit vielen nebenläufig Zusammenarbeitenden, deren Aktionen fachlich kollidieren können\n- harte Audit-, Compliance- oder Zeitreise-Anforderungen, die eine lückenlose Historie verlangen – hier zieht besonders Event Sourcing\n- eine ausgeprägte Read/Write-Asymmetrie mit getrennten Skalierungszielen\n- eine reichhaltige Domäne mit echten, konkurrierenden Invarianten und deutlich unterschiedlichen Lese- gegenüber Schreib-Formen\n\nDagegen spricht:\n\n- eine klassische CRUD- oder Formular-Anwendung ohne echte Invarianten-Komplexität\n- ein kleines Team, das mit Eventual Consistency noch keine Erfahrung hat\n- keine Audit- oder Historien-Anforderung, die den Aufwand rechtfertigt\n- der Wunsch nach einer globalen Einheitsarchitektur – oder schlicht \"weil es alle machen\"\n\nDer letzte Punkt führt zum eigentlichen Fallstrick.\n\n## Der Fallstrick: das Muster als Selbstzweck\n\nDas größte Risiko ist nicht die falsche Technik, sondern die falsche Motivation. Greg Young beschreibt den Kern präzise: Teams wollen CQRS und Event Sourcing überall implementieren, als Cookie-Cutter-Architektur – und genau das ist ein massives Risiko. Ein Muster wird eingeführt, weil es glänzt, nicht weil ein konkretes Problem danach verlangt. Fowler rät zur Vorsicht, weil das Muster schwer gut einzusetzen ist.\n\nDrei Symptome verraten den Cargo Cult. Es gibt Events, aber niemand kann eine fachliche Invariante nennen, die sie schützen. Es gibt eine Projection, aber die Leseform ist identisch zur Schreibform. Und es gibt einen Event Store, aber keine Anforderung an Audit oder Historie. Wenn diese drei Dinge zusammenkommen, ist das Muster dekorativ, nicht tragend.\n\nDazu kommen die üblichen Verwechslungen. CQRS ist nicht Event Sourcing – beide sind orthogonal und einzeln einsetzbar. CQRS ist keine Architektur und kein Top-Level-Pattern, sondern eine Entscheidung innerhalb eines Bounded Context. CQRS ist nicht CQS, weil es Modelle trennt und nicht Methoden. CQRS braucht weder Message Bus noch DDD. Und Event Sourcing ist nicht dasselbe wie ereignisgetriebene Integration über Pub/Sub – es ist ein interner Persistenz- und Source-of-Truth-Mechanismus, kein Kommunikationsstil zwischen Systemen. Fowler trennt diese Bedeutungen von \"Event-Driven\" bewusst, weil sonst vier verschiedene Dinge unter einem Wort verschwimmen.\n\n## Mehr bewegliche Teile, sichtbar gemacht\n\nEin direkter Kontrast der Pfade macht die Abwägung greifbar. Der CRUD-Pfad ist kurz, der CQRS-Pfad mit Event Sourcing hat mehr Stationen – und jede Station ist ein Ort, an dem etwas schiefgehen kann.\n\n```mermaid\nflowchart LR\n  subgraph CRUD\n    C1[Client] --> H1[Handler] --> DB[(Database)]\n  end\n  subgraph CQRS_ES\n    Cmd[Command] --> Agg[Aggregate] --> ES[(Event Store)]\n    ES --> Proj[Projection] --> RM[(Read Model)]\n    RM --> Q[Query]\n  end\n```\n\nDiese Grafik verkauft nichts. Sie macht nur ehrlich, dass die untere Variante mehr Komponenten, mehr Verträge und mehr Fehlerpfade bedeutet. Wer diesen Preis kennt und trotzdem zahlt, weil die Domäne ihn wert ist, trifft eine gute Entscheidung. Wer ihn zahlt, ohne den Gegenwert zu haben, baut Komplexität auf Vorrat.\n\n## Fazit\n\nCQRS und Event Sourcing sind keine besseren Standardarchitekturen, sondern gezielte Werkzeuge für gezielte Probleme. Die ehrliche Ausgangslage ist CRUD, und für den Großteil der Systeme bleibt sie die richtige Antwort. Die beiden Muster lohnen sich, wenn eine Domäne echte, kollidierende Invarianten hat, wenn Lese- und Schreiblast stark auseinanderlaufen oder wenn Audit- und Zeitreise-Anforderungen eine lückenlose Historie verlangen – und wenn das Team bereit ist, Eventual Consistency und Event-Versionierung zu tragen. Sie werden zum Overhead bei einfachen CRUD-Apps, in kleinen Teams, ohne echte Invarianten-Komplexität und immer dann, wenn das Muster aus Mode statt aus Not gewählt wird.\n\nDer beste Umgang damit ist eine bewusste, kontextlokale Entscheidung. Nicht global, nicht als Cookie-Cutter, sondern pro Bounded Context, mit einem klaren \"Wofür\". Dass CQRS diese fachliche Grenze braucht und kein Framework ist, habe ich in [CQRS ist eine fachliche Grenze](https://www.mikebild.dev/de/blog/cqrs-fachliche-grenze-kein-framework/) beschrieben. Die reifste Architekturqualität zeigt sich oft nicht darin, ein anspruchsvolles Muster einzusetzen – sondern darin, es begründet nicht einzusetzen.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html\n- Martin Fowler, CQRS: https://martinfowler.com/bliki/CQRS.html\n- Martin Fowler, Event Sourcing: https://martinfowler.com/eaaDev/EventSourcing.html\n- Martin Fowler, Command Query Separation: https://martinfowler.com/bliki/CommandQuerySeparation.html\n- Martin Fowler, What do you mean by Event-Driven?: https://martinfowler.com/articles/201701-event-driven.html\n- Greg Young, CQRS is not an Architecture (2012): https://gregfyoung.wordpress.com/2012/09/09/cqrs-is-not-an-architecture/\n- Greg Young, CQRS (2012): https://gregfyoung.wordpress.com/2012/03/02/cqrs/\n- Vaughn Vernon, Implementing Domain-Driven Design (Sample): https://ptgmedia.pearsoncmg.com/images/9780321834577/samplepages/0321834577.pdf\n- Eigenes Vortragsmaterial \"CQRS + Event Sourcing\" (SlideShare)\n\nDie Quellen sichern die Begriffe gegen Standards ab. Die eigentliche Aussage bleibt die kontextlokale Entscheidung, das Muster nur dort einzusetzen, wo die Domäne es verdient."},{"locale":"de","translation_key":"graphql-konzepte-schema-resolver-ausfuehrung","slug":"graphql-konzepte-schema-resolver-ausfuehrung","title":"GraphQL-Konzepte: Schema, Resolver, Ausführung","summary":"Die Ideen hinter GraphQL, die bleiben, egal welcher Server gerade modern ist – das Schema als typisierter Vertrag, die Query als Form, das Resolver-Modell und die Reihenfolge der Ausführung. Eine konzeptuelle Vertiefung mit Diagrammen.","tags":["Software","API","GraphQL"],"published_at":"2021-06-24T10:00:00+00:00","updated_at":"2026-07-13T13:20:27.930931+00:00","url":"https://www.mikebild.dev/de/blog/graphql-konzepte-schema-resolver-ausfuehrung/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/696afd56ecc7b30fef42c875c1aace24d4483f9442d400c45407ea3abff6ebb6/graphql-konzepte-schema-resolver-ausfuehrung-vorlesen.mp3","audio_duration_secs":498,"text":"# GraphQL-Konzepte: Schema, Resolver, Ausführung\n\nGraphQL ist keine Query Language für Datenbanken, und ein Resolver ist kein Controller. Beide Vergleiche tragen ein Stück weit und brechen dann – spätestens bei der Query, die harmlos aussieht und im Server dreißig einzelne Datenbankabrufe auslöst. Die Erklärung dafür steht nicht im Handbuch des jeweiligen Servers, sondern in der Spezifikation. Wer ihre Ausführungsregeln sauber verstanden hat, liest unterschiedliche GraphQL-Server mit demselben mentalen Modell.\n\nDer GraphQL-Überblick hat das Thema einmal in der Breite ausgelegt, vom Schema bis zur föderierten Architektur. Hier geht es eine Ebene tiefer, zu den Ideen hinter den Werkzeugen: Was ein Schema wirklich ist, warum eine Query aussieht wie ihre Antwort, und wie die Ausführung Feld für Feld durch den Baum wandert. Das klingt nach Grundlagen, aber gerade an ihnen entscheidet sich, ob man GraphQL beherrscht oder nur benutzt.\n\n## Das Schema ist ein typisierter Graph\n\nEin Schema wirkt beim ersten Lesen wie eine Sammlung von Datentypen. Das ist es auch, aber die entscheidende Eigenschaft steckt in den Beziehungen zwischen den Typen. Nehmen wir wieder ein Blog:\n\n```graphql\ntype Author {\n  id: ID!\n  name: String!\n  posts: [Post!]!\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  author: Author!\n}\n```\n\n`Author` verweist auf `Post`, `Post` verweist zurück auf `Author`. Damit beschreibt das Schema keinen flachen Katalog, sondern einen Graphen: Die Typen sind Knoten, die Felder, die auf andere Typen zeigen, sind Kanten. Der Name ist wörtlich gemeint. Eine Query ist dann nichts anderes als ein Pfad durch diesen Graphen, den der Client selbst wählt.\n\nDie Modifizierer sind Teil des Vertrags, nicht Dekoration. `String!` heißt: Dieses Feld ist garantiert vorhanden. `[Post!]!` heißt: garantiert eine Liste, garantiert ohne Lücken darin. Ein Client kann sich darauf verlassen und muss nicht defensiv gegen `null` prüfen, wo das Schema `null` ausschließt. Umgekehrt zwingt ein nicht-nullbares Feld, das doch `null` liefert, einen Fehler herbei – die Garantie wird also durchgesetzt, nicht bloß versprochen.\n\nUnd dann gibt es die drei Wurzeltypen: `Query`, `Mutation` und `Subscription`. Sie sind die einzigen Türen in den Graphen. Alles, was ein Client tun kann, beginnt an einem Feld eines dieser drei Typen. Was dort nicht steht, existiert für den Client nicht. Das macht das Schema zu einem vollständigen, verbindlichen Vertrag – und zu einer der wenigen API-Beschreibungen, die zugleich Dokumentation, Validierungsregel und Typdefinition sind.\n\n## Eine Query ist eine Form\n\nDer zweite Gedanke ist einfach und trotzdem der, den Umsteiger am längsten überrascht: Eine GraphQL-Query hat dieselbe Gestalt wie ihre Antwort.\n\n```graphql\nquery {\n  author(id: \"1\") {\n    name\n    posts {\n      title\n    }\n  }\n}\n```\n\nDie Antwort darauf ist strukturgleich – ein `author` mit `name` und einer Liste `posts`, in der jeder Eintrag ein `title` hat. Man beschreibt nicht, wie Daten geholt werden, sondern welche Form man am Ende haben will. Das ist dieselbe deklarative Haltung, die auch anderswo in der modernen Frontend-Welt auftaucht: Man nennt das Ziel, nicht den Weg.\n\nDaraus folgt das bekannte Versprechen, Over- und Under-Fetching auf der Schnittstelle zu verringern. Der Client erhält nur die ausgewählten Felder und kann zusammenhängende Daten in einem Dokument anfordern. Das garantiert weder eine einzige Netzwerk-Runde unter jeder Transportarchitektur noch effiziente Zugriffe hinter den Resolvern. Der Server bekommt aber eine präzise Beschreibung des Bedarfs – eine gute Grundlage, um die Ausführung passend zu planen.\n\n## Das Resolver-Modell\n\nJetzt zur Ausführung. Für jedes Feld in der Query ruft der Server eine Funktion auf, den Resolver. Ein Resolver bekommt immer dieselben vier Argumente, in dieser Reihenfolge:\n\n```js\nfunction resolver(source, args, context, info) {\n  // source  – the parent object (the return value of the field above)\n  // args    – this field's arguments in the query\n  // context – a per-request object (e.g. the logged-in user, data access)\n  // info    – information about execution state (which field, which path)\n}\n```\n\nDas erste Argument ist der Schlüssel zum Verständnis der Kette. Der Rückgabewert eines Resolvers wird zum `source` für die Resolver der Felder darunter. Löst der Resolver für `author` einen Autor auf, bekommt der Resolver für dessen `posts` genau diesen Autor als `source` und kann darüber die Posts laden.\n\n```js\nconst resolvers = {\n  Query: {\n    author: (source, { id }, context) => context.db.loadAuthor(id),\n  },\n  Author: {\n    // source here is the author from the resolver above\n    posts: (author, args, context) => context.db.loadPostsForAuthor(author.id),\n  },\n  Post: {\n    // source here is a single post\n    author: (post, args, context) => context.db.loadAuthor(post.authorId),\n  },\n};\n```\n\nFür die meisten Felder schreibt man gar keinen Resolver. Wenn ein Feld `name` heißt und das Elternobjekt eine Eigenschaft `name` hat, greift der Standard-Resolver: Er liest die gleichnamige Eigenschaft aus dem `source`. Man schreibt Resolver also nur dort explizit, wo etwas zu tun ist – wo Daten geladen, berechnet oder umgeformt werden. Das hält die meisten Schemas erstaunlich schlank.\n\nDer `context` verdient einen eigenen Satz, weil an ihm viel hängt. Er wird einmal pro Anfrage gebaut und an jeden Resolver durchgereicht. Dort landet, wer die Anfrage stellt, und dort liegen die Zugänge zu den Datenquellen. Weil jeder Resolver denselben Kontext sieht, ist er der natürliche Ort für Authentifizierung und für geteilte Ressourcen – ohne dass man sie durch jede Funktionssignatur fädeln müsste.\n\n## Die Reihenfolge der Ausführung\n\nWie genau wandert die Ausführung durch den Baum? Sie folgt der Auswahl rekursiv von den Wurzelfeldern zu deren Unterfeldern. Ein Unterfeld kann erst aufgelöst werden, wenn der Wert seines Elternfelds vorliegt; unabhängige Geschwisterfelder dürfen dagegen parallel ausgewertet werden. Es ist also kein streng getakteter Breitendurchlauf Ebene für Ebene.\n\n```mermaid\nflowchart TB\n  Q[\"Query\"] --> A[\"author-Resolver<br/>liefert Autor\"]\n  A --> N[\"name<br/>(Standard-Resolver)\"]\n  A --> P[\"posts-Resolver<br/>liefert Liste\"]\n  P --> T1[\"title von Post 1\"]\n  P --> T2[\"title von Post 2\"]\n```\n\nZwei Feinheiten sind wichtig, weil sie im Alltag Konsequenzen haben. Erstens: Geschwisterfelder auf derselben Ebene löst der Server nebenläufig auf, nicht streng nacheinander. Gibt ein Resolver ein Promise zurück, wartet der Server es ab, aber er blockiert nicht die Geschwister. Deshalb dürfen Resolver keine Annahmen über ihre Ausführungsreihenfolge relativ zu Nachbarfeldern treffen – sie sollen unabhängig voneinander funktionieren.\n\nZweitens, und das ist die eine bewusste Ausnahme: Auf der obersten Ebene einer Mutation läuft die Ausführung seriell. Nennt eine Mutation mehrere Schreibfelder, führt der Server sie nacheinander in Dokumentreihenfolge aus. Das ersetzt weder Transaktionen noch Isolation. Bei Queries ist Freiheit von Side Effects eine wichtige Konvention, keine vom Ausführungsmodell erzwungene Garantie; deshalb darf der Server unabhängige Wurzelfelder parallel auswerten.\n\n## N+1 und warum Batching dazugehört\n\nAus dem Resolver-Modell folgt fast zwangsläufig ein Problem, das jeder GraphQL-Entwickler früher oder später trifft. Fragt jemand eine Liste von Autoren ab und zu jedem die Posts, läuft der `posts`-Resolver einmal pro Autor. Bei zehn Autoren sind das zehn Aufrufe – und wenn jeder eine eigene Datenbankabfrage macht, hat man zehn Queries plus die eine für die Autorenliste. Das ist das N+1-Problem: eine Query für die Liste, N weitere für die Kinder.\n\nDer Ausweg ist Batching. Statt sofort loszulaufen, sammelt man alle Anfragen, die innerhalb eines Ausführungstakts entstehen, und beantwortet sie mit einer einzigen Query. Die übliche Umsetzung ist die DataLoader-Bibliothek: Man fragt nicht mehr direkt die Datenbank, sondern einen Loader nach einer ID; der Loader wartet bis zum Ende des aktuellen Ticks, bündelt alle gesammelten IDs und löst sie in einem Rutsch auf. Nebenbei merkt er sich innerhalb der Anfrage, was er schon geladen hat, sodass dieselbe ID nicht zweimal geholt wird.\n\n```mermaid\nflowchart LR\n  R1[\"posts von Autor 1\"] --> L[\"DataLoader<br/>sammelt IDs im Tick\"]\n  R2[\"posts von Autor 2\"] --> L\n  R3[\"posts von Autor 3\"] --> L\n  L -->|eine gebündelte Abfrage| DB[(\"Datenbank\")]\n```\n\nBatching bügelt dabei keinen Designfehler aus. Es ist die konsequente Antwort auf die Natur des Resolver-Modells: Die feldweise Auflösung ist der Grund für die Flexibilität von GraphQL – und Batching ist der Preis und zugleich die saubere Lösung dafür. Ein Loader gehört in den `context`, damit er pro Anfrage frisch ist und sein Cache nicht über Anfragegrenzen hinweg bestehen bleibt.\n\n## Warum diese Konzepte bleiben\n\nMan kann GraphQL mit Apollo Server bauen, mit GraphQL Yoga, mit einer Bibliothek in C#, Go oder Python. Der Server wechselt, das Ökosystem verschiebt sich, die Spezifikation bekommt neue Fassungen. Aber das Schema bleibt ein typisierter Graph, die Query bleibt eine Form, die Resolver bleiben eine Kette mit denselben vier Argumenten, und die Ausführung bleibt ein Durchlauf von oben nach unten mit seriellen Mutationen und nebenläufigen Geschwistern.\n\nGenau deshalb lohnt es sich, diese Ebene zu verstehen und nicht nur die API eines bestimmten Servers. Wer weiß, was ein Resolver bekommt und wie die Ausführung durch den Baum läuft, kann N+1-Probleme gezielter eingrenzen, entwirft [Schemas, die mitwachsen](https://www.mikebild.dev/de/blog/graphql-schema-das-mitwaechst/), und findet sich in einem anderen Server schneller zurecht. Die Werkzeuge sind austauschbar. Die Konzepte sind es nicht.\n\n## Weiterführende Quellen\n\n- Repository introduction-graphql (Kapitel resolver, schema, subscriptions): https://github.com/mikebild/introduction-graphql\n- Folienübersicht zu diesem Themenkomplex: https://slides.mikebild.dev/introduction-graphql.html\n- GraphQL, Ausführung: https://graphql.org/learn/execution/\n- GraphQL, Schema und Typen: https://graphql.org/learn/schema/\n- GraphQL-Spezifikation, Execution: https://spec.graphql.org/\n- DataLoader (Batching und Caching pro Anfrage): https://github.com/graphql/dataloader"},{"locale":"de","translation_key":"appsync-dynamodb-graphql-api","slug":"appsync-dynamodb-graphql-api","title":"GraphQL-APIs mit AppSync und DynamoDB","summary":"AWS AppSync verschiebt den GraphQL-Server aus der eigenen Betriebsverantwortung in einen managed Dienst. Ich zeige am DynamoDB-Backend, wann diese Build-vs-Buy-Entscheidung trägt und wann managed zur Sackgasse wird, inklusive der VTL-Mapping-Templates, die 2021 der Preis dafür sind.","tags":["Software","AWS","Cloud"],"published_at":"2021-06-15T10:00:00+00:00","updated_at":"2026-07-13T10:02:55.07027+00:00","url":"https://www.mikebild.dev/de/blog/appsync-dynamodb-graphql-api/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/5714cf054303d183590a0d10cd1f87a4fdbe3b67369af1df0f9779cba71ffff8/appsync-dynamodb-graphql-api-vorlesen.mp3","audio_duration_secs":947,"text":"Wer ein GraphQL-Schema veröffentlicht, hat damit einen Serverbetrieb übernommen – auch wenn im Projektplan nur „Schema und Clients“ steht. Die Resolver müssen irgendwo laufen, die Verbindungen irgendwo enden, die Last irgendwo abgefangen werden. Diese Rechnung kommt nicht am Tag des Deployments, sie kommt jeden Monat danach.\n\nDie verbreiteten GraphQL-Einführungen enden vor dieser Rechnung. Typen definieren, Queries schreiben, Daten mit Apollo oder urql abholen: alles gut erklärt. Der Server mit den Resolvern, die Datenbank darunter, die Skalierung, die Real-time-Verbindungen – darüber schweigen sie. Wegdefinieren lässt sich diese Schicht trotzdem nicht. Jemand baut sie, deployt sie und hält sie im Betrieb.\n\nBleibt die Frage, wer dieses Jemand ist: das eigene Team oder ein managed Dienst. Ich mache die Antwort an einem konkreten Aufbau fest – AWS AppSync auf DynamoDB, so wie er Mitte 2021 tatsächlich aussieht, samt der VTL-Mapping-Templates, die beim ersten Kontakt gewöhnungsbedürftig sind. Der Code ist dabei nicht der Kern. Der Kern ist, was diese Entscheidung einbringt und was sie kostet.\n\n**Redaktionelle Einordnung (Juli 2026):** AppSync unterstützt heute neben VTL die JavaScript-basierte Resolver-Runtime `APPSYNC_JS`. VTL bleibt gültig, ist aber nicht mehr die einzige direkte Abbildung auf DynamoDB. Managed nimmt dem Team den GraphQL-Serverbetrieb ab; Schema, Resolver, Berechtigungen, Datenmodell, Deployment und Beobachtbarkeit bleiben eigene Arbeit.\n\n## Was AppSync eigentlich ist\n\nAppSync ist ein vollständig managed GraphQL-Layer. Der entscheidende Punkt: Man betreibt keinen eigenen GraphQL-Server. Es gibt keinen Node-Prozess mit Apollo Server, keinen Container, kein Hosting, keine Skalierungslogik, um die man sich kümmern müsste. Stattdessen lädt man ein Schema in der GraphQL Schema Definition Language (SDL) hoch und hängt an jedes Feld einen Resolver, der auf eine Data Source zeigt. AWS übernimmt den Rest.\n\nDiese Verschiebung ist der eigentliche Wert. In einem klassischen Setup ist der GraphQL-Server das Herzstück, das man selbst schreibt, deployt und betreibt. Bei AppSync liegt dieser Serverbetrieb bei AWS, während das Team die Abbildung zwischen Schema-Feld und Datenquelle sowie deren Infrastruktur beschreibt. Das ist der bekannte Serverless-Tausch: weniger eigener Betrieb gegen stärkere Bindung an den Dienst.\n\nEin Resolver verbindet dabei immer genau ein Schema-Feld mit einer Data Source. Und davon gibt es 2021 eine überschaubare, aber gut abgedeckte Auswahl:\n\n- DynamoDB-Tabellen als Key-Value- und Dokument-Store\n- AWS Lambda für beliebige Custom-Logik\n- HTTP-Endpoints, um bestehende REST-APIs anzubinden\n- Amazon Elasticsearch Service für Volltextsuche\n- relationale Datenbanken über RDS bzw. Aurora Serverless sowie „None“-Local-Resolver ohne externe Quelle\n\nFür diesen Beitrag konzentriere ich mich auf DynamoDB, weil das die häufigste Kombination in Serverless-Projekten ist und weil sich daran die VTL-Mechanik am besten zeigen lässt.\n\n## Der Request-Fluss\n\nBevor wir Code sehen, hilft ein Blick auf den Weg, den eine Anfrage nimmt. Ein Client schickt eine GraphQL-Query oder -Mutation an AppSync. AppSync prüft sie gegen das Schema und ruft für das angefragte Feld den passenden Resolver auf. Der Resolver hat zwei Teile: ein Request-Template, das die GraphQL-Anfrage in einen DynamoDB-Call übersetzt, und ein Response-Template, das das DynamoDB-Ergebnis zurück in GraphQL-Form bringt.\n\n```mermaid\nflowchart LR\n  Client[GraphQL Client] -->|Query / Mutation| AppSync[AppSync<br/>Schema + VTL Resolver]\n  AppSync -->|Request Template| DDB[(DynamoDB Table)]\n  DDB -->|Response Template| AppSync\n  AppSync -->|JSON Result| Client\n  AppSync -.->|other data sources| Lambda[AWS Lambda]\n  AppSync -.->|other data sources| HTTP[HTTP Endpoint]\n```\n\nDiese beiden Templates sind das Herzstück und zugleich der Teil, an dem sich 2021 die Geister scheiden. Sie sind nämlich nicht in JavaScript geschrieben, sondern in der Apache Velocity Template Language, kurz VTL.\n\n## VTL: die Sprache dazwischen\n\nVTL ist eine Template-Sprache, keine vollwertige Programmiersprache. Sie kann Werte einsetzen, einfache Bedingungen und Schleifen ausdrücken, aber sie ist bewusst schmal gehalten. Für die Übersetzung zwischen GraphQL-Argumenten und DynamoDB-Aufrufen reicht das in den meisten Fällen aus, und AWS liefert eine Reihe von Hilfsfunktionen mit, die die typischen Aufgaben abnehmen.\n\nNehmen wir ein kleines CMS als Beispiel. Wir wollen Blogposts anlegen, einzeln abrufen und bei neuen Posts in Echtzeit benachrichtigt werden. Das Schema dazu sieht so aus:\n\n```graphql\ntype Post {\n  id: ID!\n  title: String!\n  body: String!\n}\n\ntype Query {\n  getPost(id: ID!): Post\n}\n\ntype Mutation {\n  createPost(title: String!, body: String!): Post\n}\n\ntype Subscription {\n  onCreatePost: Post @aws_subscribe(mutations: [\"createPost\"])\n}\n```\n\nDas ist reines SDL, wie man es aus jeder GraphQL-Einführung kennt. Der einzige AppSync-spezifische Zusatz ist die Direktive `@aws_subscribe` auf dem Subscription-Feld, dazu später mehr. Zunächst zu den Resolvern für `createPost` und `getPost`.\n\n### Ein PutItem-Resolver\n\nWenn ein Client `createPost` aufruft, soll ein neues Item in der DynamoDB-Tabelle landen. Das Request-Template beschreibt genau diesen `PutItem`-Aufruf:\n\n```vtl\n{\n  \"version\": \"2017-02-28\",\n  \"operation\": \"PutItem\",\n  \"key\": {\n    \"id\": $util.dynamodb.toDynamoDBJson($util.autoId())\n  },\n  \"attributeValues\": $util.dynamodb.toMapValues($ctx.args)\n}\n```\n\nHier passiert einiges auf engem Raum. Der Versionsstring `\"2017-02-28\"` legt das Format des Templates fest. Das ist 2021 der Standardwert, den man ohne besonderen Grund nicht ändert. Das `operation`-Feld sagt DynamoDB, was zu tun ist. Der Key wird über `$util.autoId()` erzeugt, eine Hilfsfunktion, die eine UUID generiert, damit jeder Post einen eindeutigen Primärschlüssel bekommt.\n\nDer wichtigste Punkt versteckt sich in `$util.dynamodb.toDynamoDBJson(...)` und `$util.dynamodb.toMapValues(...)`. DynamoDB erwartet Werte nicht als nackte Strings oder Zahlen, sondern in einem typisierten Attribut-Format: ein String wird zu `{\"S\": \"...\"}`, eine Zahl zu `{\"N\": \"...\"}`. Diese Hilfsfunktionen übernehmen die Umwandlung automatisch. Wer sie vergisst und die Rohwerte direkt einsetzt, schreibt ein Item im falschen Format – der Fehler, über den beim Einstieg in AppSync fast alle einmal stolpern.\n\nDas Response-Template ist dagegen unspektakulär. Es gibt das geschriebene Item einfach als JSON zurück:\n\n```\n$util.toJson($ctx.result)\n```\n\n`$ctx`, auch als `$context` verfügbar, ist das Objekt, über das man an alles Relevante kommt: `$ctx.args` für die Argumente der GraphQL-Operation, `$ctx.identity` für Informationen zum aufrufenden Nutzer, `$ctx.result` für das Ergebnis der Data Source. Das Response-Template nutzt `$ctx.result`, um das eben geschriebene Item an den Client zurückzuspielen.\n\nNeben dem reinen Ergebnis liefert AppSync im Response-Template auch `$ctx.error`, falls die Data Source einen Fehler zurückgibt, etwa eine abgelehnte Bedingung bei einem `PutItem`. Wer das ignoriert, gibt im Fehlerfall stillschweigend `null` zurück, statt dem Client eine aussagekräftige Meldung zu geben. Mit `$util.error(...)` oder `$util.appendError(...)` lässt sich der Fehler kontrolliert an die GraphQL-Antwort durchreichen, sodass er im `errors`-Block der Response landet. Für die beiden schlichten Resolver hier ist das noch verzichtbar, aber sobald echte Bedingungen ins Spiel kommen, gehört diese Prüfung ins Template.\n\n### Ein GetItem-Resolver\n\nFür `getPost` ist die Sache noch schlichter. Das Request-Template beschreibt einen `GetItem`-Aufruf mit dem `id`-Argument als Key:\n\n```vtl\n{\n  \"version\": \"2017-02-28\",\n  \"operation\": \"GetItem\",\n  \"key\": {\n    \"id\": $util.dynamodb.toDynamoDBJson($ctx.args.id)\n  }\n}\n```\n\nAuch hier wandert der Wert aus `$ctx.args.id` durch `toDynamoDBJson`, damit er im richtigen Format bei DynamoDB ankommt. Das Response-Template ist identisch zum vorigen:\n\n```\n$util.toJson($ctx.result)\n```\n\nWenn man diese beiden Resolver nebeneinanderlegt, wird das Prinzip greifbar: Ein Resolver ist immer ein Paar aus Request- und Response-Template, das ein Schema-Feld mit einer konkreten DynamoDB-Operation verbindet. Mehr Magie steckt nicht dahinter.\n\nDie verfügbaren Operationen decken das übliche DynamoDB-Repertoire ab. Neben `GetItem` und `PutItem` stehen `UpdateItem` und `DeleteItem` bereit, dazu `Query` und `Scan` für Mehrfachtreffer sowie die Batch- und Transaktionsvarianten wie `BatchGetItem` oder `TransactWriteItems`. Für den Einstieg reichen die vier Einzeloperationen, und man wächst mit dem Datenmodell in die komplexeren Varianten hinein. Das Schöne daran: Das Muster bleibt immer gleich. Man ändert das `operation`-Feld, passt Key und Werte an, und der Aufbau des Templates verändert sich kaum. Diese Gleichförmigkeit ist es, die VTL trotz seiner Sperrigkeit im Alltag handhabbar macht.\n\n## Subscriptions ohne eigenen Aufwand\n\nDer Teil, der beim ersten Kontakt am meisten überrascht, sind die Real-time-Subscriptions. In einem selbstgebauten GraphQL-Server ist das der aufwendigste Teil überhaupt: WebSocket-Verbindungen verwalten, ein Pub/Sub-System betreiben, den Zustand über mehrere Serverinstanzen synchron halten. Bei AppSync ist davon nichts zu tun.\n\nErinnern wir uns an die Direktive aus dem Schema:\n\n```graphql\ntype Subscription {\n  onCreatePost: Post @aws_subscribe(mutations: [\"createPost\"])\n}\n```\n\nDiese eine Zeile genügt. `@aws_subscribe(mutations: [\"createPost\"])` bindet das Subscription-Feld `onCreatePost` an die Mutation `createPost`. Immer wenn diese Mutation erfolgreich durchläuft, schiebt AppSync das Ergebnis über eine WebSocket-Verbindung an alle Clients, die `onCreatePost` abonniert haben. Kein Polling, kein eigener Server, keine Verbindungsverwaltung.\n\n```mermaid\nsequenceDiagram\n  participant A as Client A\n  participant AS as AppSync\n  participant D as DynamoDB\n  participant B as Client B (subscribed)\n  A->>AS: mutation createPost\n  AS->>D: PutItem\n  D-->>AS: written item\n  AS-->>A: created Post\n  AS-->>B: onCreatePost (WebSocket push)\n```\n\nDie Verbindung läuft dabei über WebSockets, die AppSync von Haus aus bereitstellt. Der Client muss sich nur einmal auf `onCreatePost` subscriben und bekommt danach jeden neuen Post automatisch zugestellt. Für ein Live-Feed, ein Chat-Feature oder ein Dashboard ist das eine enorme Vereinfachung, weil der gesamte Real-time-Teil aus der eigenen Betriebsverantwortung verschwindet.\n\nEin Detail, das man dabei nicht übersehen darf: Ohne die `@aws_subscribe`-Direktive passiert schlicht nichts. Ich habe mehr als einmal erlebt, dass jemand eine Subscription definiert, den Client verbindet und sich dann wundert, warum keine Events ankommen. Die Antwort war jedes Mal dieselbe: die Direktive fehlte oder verwies auf die falsche Mutation. Das Subscription-Feld muss explizit an die auslösende Mutation gekoppelt sein.\n\n## Wo VTL an seine Grenzen kommt\n\nSo elegant der Ansatz ist, so klar sind seine Ränder. VTL ist bewusst keine Programmiersprache, und das merkt man, sobald die Logik komplexer wird. Verschachtelte Bedingungen, mehrstufige Transformationen, das Zusammenführen mehrerer Quellen: all das lässt sich in VTL zwar irgendwie ausdrücken, aber die Templates werden schnell unleserlich und schwer zu warten.\n\nDie Grenze verläuft dort, wo ein Template mehr tut, als Argumente umzusortieren und in einen DynamoDB-Call zu gießen. Im Stand von 2021 gehörte komplexere Logik in einen Lambda-Resolver. Heute ist vorher zu prüfen, ob ein `APPSYNC_JS`-Resolver die Abbildung lesbarer ausdrückt; für freie Laufzeitlogik und externe Bibliotheken bleibt Lambda die weitergehende Grenze. VTL eignet sich weiterhin für schlanke, direkte Abbildungen auf DynamoDB.\n\nDer zweite Rand betrifft nicht AppSync, sondern DynamoDB selbst. Die Frage, ob ein Zugriff eine `Query` oder ein `Scan` wird, entscheidet sich am Tabellendesign. Eine `Query` nutzt Partition- und Sort-Key oder einen Global Secondary Index und ist schnell und günstig. Ein `Scan` liest im Zweifel die ganze Tabelle und wird mit wachsendem Datenbestand teuer und langsam. Diese Access Patterns muss man vor dem ersten Schreiben durchdenken, denn DynamoDB verzeiht ein schlecht geplantes Key-Design nur ungern nachträglich. Das schöne AppSync-Frontend ändert nichts daran, dass darunter eine DynamoDB-Tabelle liegt, die ihre eigenen Regeln hat.\n\n## Managed oder selbstbetrieben: die eigentliche Entscheidung\n\nBis hierher ging es um Mechanik. Der Grund, warum ich AppSync in Projekten überhaupt aufrufe, liegt eine Ebene höher. Ein GraphQL-Server ist kein Feature, das man einmal schreibt und dann vergisst. Er ist eine dauerhafte Betriebsverpflichtung. Er muss laufen, skalieren, aktualisiert und überwacht werden, und bei Real-time-Verbindungen kommt der ganze Zustand über mehrere Instanzen hinweg dazu. Diese Kosten fallen nicht einmalig beim Bauen an, sondern jeden Monat im Betrieb.\n\nBuild-vs-Buy heißt an dieser Stelle konkret: Selbst betreiben bedeutet einen Node-Prozess mit Apollo Server, ein Hosting, eine Skalierungsstrategie, ein Pub/Sub-System für Subscriptions und die Bereitschaft, das alles im Ernstfall nachts zu reparieren. Managed bedeutet, dass ich Schema, Resolver und Data Sources deklariere und den Rest an AWS abgebe. Ich zahle dann nicht mehr in Betriebsstunden, sondern in Nutzung und in einem Stück Kontrolle, das ich aus der Hand gebe.\n\nWann trägt managed? Immer dann, wenn der GraphQL-Server für das Produkt kein Alleinstellungsmerkmal ist, sondern eine Notwendigkeit. Ein CRUD-Backend mit Real-time-Feed ist selten der Teil, mit dem sich ein Team vom Wettbewerb abhebt. Genau solche Standardschichten kauft man besser ein, weil jede selbstbetriebene Stunde dort fehlt, wo das Team tatsächlich Wert schafft. Kleine Teams ohne eigene Plattformmannschaft, Projekte mit schwankender Last, Prototypen, die schnell live müssen: In all diesen Fällen ist der Wegfall des Betriebs mehr wert als die abgegebene Kontrolle.\n\nWann wird managed zur Sackgasse? Sobald die Abbildung, die der Dienst anbietet, nicht mehr zum eigenen Problem passt. Bei AppSync 2021 ist VTL diese Abbildung. Solange ich Argumente in DynamoDB-Calls gieße, ist das ein guter Tausch. Sobald ich verschachtelte Logik, mehrstufige Transformationen oder die Zusammenführung mehrerer Quellen in Templates presse, zahle ich den managed Komfort mit Wartbarkeit zurück. Der zweite Sackgassen-Marker ist der Lock-in. Schema und Clients bleiben portabel, die VTL-Resolver und das DynamoDB-Key-Design sind es nicht. Wer damit rechnet, den Anbieter später zu wechseln, sollte diese Grenzschicht bewusst dünn halten.\n\nDamit lässt sich die Entscheidung auf wenige Kriterien eindampfen. Ist die Schicht Standard oder Differenzierung? Wie teuer ist der Betrieb im Verhältnis zur Teamgröße? Wie gut passt die angebotene Abbildung auf das eigene Problem, heute und in zwei Jahren? Und wie tief reicht der Lock-in, falls die Antwort einmal nicht mehr passt? Managed ist keine Glaubensfrage, sondern eine Rechnung, die man pro Schicht neu aufmacht. Bei AppSync fällt sie für einen großen Teil der Serverless-Projekte klar zugunsten von Buy aus, aber eben nicht für alle.\n\n## Was am Ende bleibt\n\nIch komme zum Anfang zurück, zur Frage nach dem Betrieb des Servers. Die verbreiteten GraphQL-Inhalte behandeln Schema-Design und Client-Seite. Das ist wichtig und bleibt wichtig, egal welches Backend darunter liegt. AppSync mit DynamoDB ist die andere Hälfte, das managed Backend, bei dem der selbstgeschriebene Server zu einer Konfiguration aus Schema, Resolvern und Data Sources zusammenschmilzt.\n\nDie Wirkung dieser Entscheidung ist konkret: Das Team deployt weiterhin Schema, Resolver und Infrastruktur, betreibt aber keinen eigenen GraphQL-Prozess und keine eigene WebSocket-Schicht. Dadurch bleibt mehr Zeit für Datenmodell und fachliche Logik. Ob die Rechnung aufgeht, hängt daran, wie gut die Resolver-Runtimes und Datenquellen zum Problem passen.\n\nDer Preis dafür sind die VTL-Templates und ein Stück Bindung an AWS. Beides ist überschaubar, solange man die Grenzen kennt: schlanke Abbildungen in VTL, komplexe Logik in Lambda, ein Key-Design, das die Access Patterns vorwegnimmt. Wo diese Grenzen halten, ist der Tausch hervorragend. Wo sie reißen, gehört die Schicht selbst gebaut. Diese Linie sauber zu ziehen ist die eigentliche Architekturarbeit, nicht das Schreiben der Templates.\n\nAppSync steht nicht für sich allein. Es greift mit Lambda, DynamoDB und den übrigen Managed Services ineinander, und gerade im Zusammenspiel entfaltet es seinen Wert.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-aws-serverless.html\n- Repository mit den Schema- und Resolver-Beispielen aus meinen Serverless-Workshops\n- [DynamoDB-Resolver-Referenz (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html)\n- [`APPSYNC_JS`-Resolver-Referenz (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html)\n- [Tutorial: Simple Post Application mit DynamoDB-Resolvern (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-resolvers.html)\n- [Resolver-Mapping-Template-Overview (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-overview.html)\n- [$util-Utility-Referenz (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-util-reference.html)\n- [AppSync FAQs zu Data Sources und Subscriptions (AWS)](https://aws.amazon.com/appsync/faqs/)"},{"locale":"de","translation_key":"context-richtig-einsetzen","slug":"context-richtig-einsetzen","title":"Context richtig einsetzen: Verteilweg statt heimlicher globaler State","summary":"Context löst das Verteilen von Daten durch den Baum – aber nicht die Frage, wem der State gehört. Wer beides verwechselt, baut einen globalen Store durch die Hintertür ein und erzeugt bei unbedacht wechselnden Provider-Werten unnötige Renderläufe.","tags":["Software","Frontend","React"],"published_at":"2021-05-26T10:00:00+00:00","updated_at":"2026-07-13T07:56:47.211196+00:00","url":"https://www.mikebild.dev/de/blog/context-richtig-einsetzen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/83ed4db87748b158c4d6913ed23044ba1c821c3a5d4172f534aafaa353ece9ee/context-richtig-einsetzen-vorlesen.mp3","audio_duration_secs":616,"text":"# Context richtig einsetzen: Verteilweg statt heimlicher globaler State\n\n```jsx\nconst AppContext = createContext(null);\n\nfunction AppProvider({ children }) {\n  const [user, setUser] = useState(null);\n  const [filter, setFilter] = useState(\"\");\n  const [items, setItems] = useState([]);\n\n  return (\n    <AppContext.Provider value={{ user, setUser, filter, setFilter, items, setItems }}>\n      {children}\n    </AppContext.Provider>\n  );\n}\n```\n\nDrei States hängen an einem einzigen Provider, und das Objekt hinter `value` entsteht bei jedem Rendern neu. Ein Zeichen im Filterfeld genügt, und alles, was diesen Context liest, rendert mit – auch der Header, der nur den Namen der angemeldeten Person anzeigt. Aus einer Abkürzung durch den Komponentenbaum ist ein Store geworden, ohne dass jemand diese Entscheidung bewusst getroffen hätte.\n\nContext kann genau eine Sache: einen Wert oben bereitstellen und weiter unten lesbar machen, ohne dass die Schichten dazwischen ihn durchreichen. Alles andere – wo der Wert entsteht, wer ihn fortschreibt, wie oft er wechselt – bleibt Handarbeit und muss vorher entschieden sein. Fangen wir bei dem Problem an, für das Context gebaut wurde.\n\n## Das Problem: prop drilling\n\nDaten fließen in React von oben nach unten. Eine Komponente reicht Werte über Props an ihre Kinder, die reichen sie an ihre Kinder weiter, und so fort. Solange die Strecke kurz ist, ist das genau richtig – der Datenfluss ist sichtbar, man liest an den Props ab, was eine Komponente braucht.\n\nUnangenehm wird es, wenn ein Wert weit oben entsteht und weit unten gebraucht wird, aber alles dazwischen ihn gar nicht braucht. Die angemeldete Person zum Beispiel: Sie wird einmal ganz oben ermittelt, gebraucht wird sie im Header, in einem Kommentarformular tief im Baum und in einem Menü ganz woanders. Alle Komponenten auf dem Weg dorthin müssen den Wert entgegennehmen und weiterreichen, obwohl sie ihn nur durchschleusen.\n\n```jsx\nfunction Page({ user }) {\n  return <Layout user={user} />;\n}\n\nfunction Layout({ user }) {\n  return <Sidebar user={user} />;\n}\n\nfunction Sidebar({ user }) {\n  return <Profile user={user} />;\n}\n\nfunction Profile({ user }) {\n  return <span>{user.name}</span>;\n}\n```\n\n`Layout` und `Sidebar` interessieren sich nicht für `user`. Sie tragen die Prop nur weiter, weil weiter unten jemand sie braucht. Genau das nennt man prop drilling – man bohrt einen Wert durch eine Schicht Komponenten, die mit ihm nichts zu tun haben. Es macht Zwischenkomponenten schwerer wiederverwendbar, weil sie an Daten gekoppelt sind, die sie nur durchreichen, und jede neue Zwischenschicht muss die Prop von Hand mitnehmen.\n\n```mermaid\nflowchart TB\n  subgraph drilling[\"prop drilling\"]\n    P1[\"Page (user)\"] --> L1[\"Layout<br/>reicht user nur weiter\"]\n    L1 --> S1[\"Sidebar<br/>reicht user nur weiter\"]\n    S1 --> Pr1[\"Profile<br/>braucht user\"]\n  end\n  subgraph context[\"Context\"]\n    P2[\"Provider (user)\"] -.-> Pr2[\"Profile<br/>liest per useContext\"]\n  end\n```\n\n## Wie Context funktioniert\n\nContext dreht dieses Durchreichen um. Statt einen Wert Schicht für Schicht weiterzugeben, stellt man ihn oben einmal bereit und liest ihn unten direkt aus – ohne die Zwischenschichten zu belästigen. Drei Teile gehören dazu: `createContext` erzeugt das Objekt, ein `Provider` stellt den Wert für einen Teilbaum bereit, und `useContext` liest ihn dort aus, wo er gebraucht wird.\n\n```jsx\nimport { createContext, useContext } from \"react\";\n\nconst CurrentUserContext = createContext(null);\n\nfunction Page({ user }) {\n  return (\n    <CurrentUserContext.Provider value={user}>\n      <Layout />\n    </CurrentUserContext.Provider>\n  );\n}\n\nfunction Profile() {\n  const user = useContext(CurrentUserContext);\n  return <span>{user.name}</span>;\n}\n```\n\n`Layout` und `Sidebar` sind aus dem Spiel – sie kennen `user` nicht mehr und müssen nichts weiterreichen. `Profile` greift sich den Wert direkt beim nächstgelegenen Provider über sich. Genau das ist die Aufgabe von Context, und für diese Aufgabe ist er das richtige Werkzeug: Er ist ein Verteilweg, eine Abkürzung durch den Baum.\n\nWichtig ist, was hier nicht passiert. Der Provider erzeugt den Wert nicht. Er bekommt ihn von oben hereingereicht und stellt ihn zur Verfügung. Wo `user` herkommt, wer ihn ändert, wo er liegt – all das ist an dieser Stelle noch völlig offen. Und genau hier fangen die Probleme an, wenn man nicht aufpasst.\n\n## Die zentrale Falle: Context als Ersatz für State-Besitz\n\nWeil Context Werte so bequem überall verfügbar macht, liegt eine Versuchung nahe: Man legt einfach alles hinein, was mehrere Komponenten brauchen. Die geladene Liste, den aktuellen Filter, halb geöffnete Dialoge, den gesamten Anwendungszustand – Context wird zum Ablageort für alles Geteilte. Das fühlt sich anfangs großartig an und rächt sich später zuverlässig.\n\nZwei Konsequenzen fallen einem auf die Füße. Die erste ist das Rendern. React vergleicht den alten und neuen Provider-Wert mit `Object.is`. Ist er verschieden, werden die Komponenten neu gerendert, die diesen Context lesen; bloße Nachfahren ohne `useContext` sind damit nicht automatisch gemeint. Bei einem großen Objekt als Context betrifft eine geänderte Referenz allerdings auch Consumer, die nur ein anderes Feld daraus verwenden. Aus einem kleinen Update kann so eine Renderwelle werden.\n\n```mermaid\nflowchart TB\n  Change[\"Context-Wert ändert sich\"] --> P[\"Provider\"]\n  P --> C1[\"Consumer A<br/>zeigt den Wert\"]\n  P --> C2[\"Consumer B<br/>liest ein anderes Feld –<br/>rendert trotzdem\"]\n  P --> C3[\"Consumer C<br/>liest ein anderes Feld –<br/>rendert trotzdem\"]\n```\n\nIn einem Projekt lag neben dem Theme beiläufig auch der Wert eines Suchfelds im selben Context. Bei jedem Tastendruck im Suchfeld flackerte die halbe Oberfläche – Komponenten, die mit der Suche nichts zu tun hatten, renderten mit, nur weil sie am selben Context hingen. Der Wert war im falschen Behälter gelandet.\n\nDie zweite Konsequenz ist die Kopplung. Alles, was aus einem Context liest, ist an diesen Provider gebunden. Man kann eine solche Komponente nicht mehr isoliert verwenden, testen oder an anderer Stelle einsetzen, ohne den passenden Provider drumherum aufzubauen. Je mehr in einem Context steckt, desto mehr Komponenten hängen an ihm, und desto zäher wird die Anwendung. Context macht die Herkunft eines Wertes unsichtbar – das ist beim Verteilen ein Vorteil und beim Besitz ein Problem, weil man nicht mehr sieht, wer eigentlich für einen Wert verantwortlich ist.\n\nDer Kern des Missverständnisses ist dieser: Context beantwortet die Frage „wie kommen die Daten dorthin, wo sie gebraucht werden“. Er beantwortet nicht die Frage „wem gehören die Daten und wer darf sie ändern“. Die zweite Frage – den State-Besitz – muss man weiterhin selbst beantworten, mit `useState` oder `useReducer` in einer klar benannten Komponente. Context ersetzt diese Entscheidung nicht, er transportiert nur ihr Ergebnis.\n\n## Regeln für den sauberen Einsatz\n\nAus dieser Trennung folgen drei Regeln, mit denen Context genau das bleibt, was er sein soll – ein Transportmittel.\n\nErstens: der Besitz liegt oben, Context reicht nur durch. Der State gehört in eine klar benannte Komponente – nennen wir sie `CurrentUserProvider` –, die ihn mit `useState` oder `useReducer` hält. Diese Komponente ist die eine Stelle, an der der Wert liegt und geändert wird. Context transportiert ihn von dort nach unten, mehr nicht. Wer den Provider aufmacht und `useState` sucht, findet den Besitzer sofort; wer ihn nicht findet, hat wahrscheinlich einen versteckten globalen State gebaut.\n\nZweitens: den Wert stabil halten. Hier steckt der häufigste konkrete Fehler. Schreibt man ein frisches Objekt direkt ins `value`, erzeugt jedes Rendern der Provider-Komponente eine neue Referenz – und weil sich die Referenz ändert, rendern alle Consumer neu, selbst wenn sich inhaltlich nichts geändert hat:\n\n```jsx\nfunction CurrentUserProvider({ children }) {\n  const [user, setUser] = useState(null);\n\n  // new object on every render → all consumers re-render\n  return (\n    <CurrentUserContext.Provider value={{ user, setUser }}>\n      {children}\n    </CurrentUserContext.Provider>\n  );\n}\n```\n\nDie Lösung ist, den Wert zu memoisieren, sodass die Referenz nur wechselt, wenn sich tatsächlich etwas geändert hat:\n\n```jsx\nfunction CurrentUserProvider({ children }) {\n  const [user, setUser] = useState(null);\n  const value = useMemo(() => ({ user, setUser }), [user]);\n\n  return (\n    <CurrentUserContext.Provider value={value}>\n      {children}\n    </CurrentUserContext.Provider>\n  );\n}\n```\n\nBei State aus `useReducer` lohnt oft ein zweiter Schritt: State und Dispatch in zwei getrennte Contexts legen. Der Dispatch ist stabil, er ändert sich nie. Trennt man ihn ab, rendern Komponenten, die nur Aktionen auslösen und den State gar nicht anzeigen, bei einer State-Änderung nicht mehr mit – sie hängen nur am immutable Dispatch-Context.\n\n```jsx\nconst StateContext = createContext(null);\nconst DispatchContext = createContext(null);\n\nfunction StoreProvider({ children }) {\n  const [state, dispatch] = useReducer(reducer, initialState);\n\n  return (\n    <StateContext.Provider value={state}>\n      <DispatchContext.Provider value={dispatch}>\n        {children}\n      </DispatchContext.Provider>\n    </StateContext.Provider>\n  );\n}\n```\n\nDrittens: nicht jeden veränderlichen Wert hineinlegen. Manches, was man reflexhaft in einen Context steckt, gehört anderswo hin. Serverdaten – geladene Listen, Detaildaten, Suchergebnisse – sind kein Anwendungszustand, sondern ein Cache, und der gehört in eine Data-Fetching-Bibliothek, nicht in Context. Diese Grenze habe ich in „Client State vs. Server-Cache“ ausführlich behandelt. Und die aktuelle Auswahl, der Filter, die Seite in einer Liste gehören in die URL – teilbar, mit Lesezeichen speicherbar, überlebt einen Reload. Zieht man diese beiden Kategorien ab, bleibt für Context erstaunlich wenig übrig, und genau dieser Rest ist sein eigentliches Zuhause.\n\n## Wofür Context wirklich gut ist\n\nContext spielt seine Stärke bei selten wechselnden, app-weiten Dingen aus – bei dem, was eher die Umgebung einer Anwendung beschreibt als ihre eigentlichen Daten. Das aktive Theme, die eingestellte Sprache, die angemeldete Person, eine app-weite Service- oder Dispatch-Funktion: Solche Werte ändern sich selten, werden aber an vielen Stellen gebraucht. Genau dafür ist ein Verteilweg gedacht, der die Zwischenschichten überspringt.\n\nDer gemeinsame Nenner dieser guten Fälle ist, dass sie „Umgebung“ sind und nicht „Anwendungsdaten“. Sie wechseln nicht im Sekundentakt, also fällt die Renderwelle kaum ins Gewicht. Und sie sind tatsächlich app-weit, also stört die Kopplung an einen Provider nicht – man will diese Komponenten ohnehin nur innerhalb der Anwendung verwenden. Vor jedem neuen Context lohnt darum eine Prüffrage: Beschreibt der Wert die Umgebung, in der eine Komponente läuft, oder die Daten, die sie anzeigt? Nur das Erste gehört hinein.\n\n## Context und Reducer als kleiner globaler Kern\n\nFür einen überschaubaren globalen Kern lassen sich Context und `useReducer` zu einem leichten Muster kombinieren. Der Reducer hält den State und die Logik an einer Stelle, zwei getrennte Contexts verteilen State und Dispatch, und die Consumer greifen über kleine Hooks zu:\n\n```jsx\nfunction useStore() {\n  return useContext(StateContext);\n}\n\nfunction useDispatch() {\n  return useContext(DispatchContext);\n}\n```\n\nDas reicht überraschend weit – für einen Warenkorb, ein paar app-weite Einstellungen, eine kleine Sammlung von Aktionen. Der Besitz ist klar (im `StoreProvider`), der Transport ist sauber (zwei Contexts), und die Trennung von State und Dispatch hält die Renderings im Zaum.\n\nMan sollte aber die Grenze dieses Musters kennen und offen benennen: Context ist keine State Management, er ist Transport. Der Reducer daneben ist die eigentliche Logik, und Context reicht nur dessen Ergebnis durch. Solange der Kern klein bleibt, trägt das Muster. Wächst die Logik – viele voneinander abhängige Teilzustände, selektives Lesen einzelner Felder ohne Renderwellen, Middleware, Persistenz, Zeitreise beim Debuggen –, stößt die Kombination an ihre Grenzen. Dann braucht es einen echten Store, der genau für diese Aufgaben gebaut ist. Das ist keine Niederlage von Context, sondern die richtige Arbeitsteilung: Context hat nie behauptet, ein Store zu sein.\n\n## Was bleiben soll\n\nContext beantwortet eine einzige Frage sehr gut: wie die Daten dorthin kommen, wo sie gebraucht werden. Er beantwortet die andere, wichtigere Frage nicht: wem sie gehören und wer sie ändert. Diese zweite Frage muss man selbst beantworten, in einer klar benannten Komponente mit `useState` oder `useReducer`, bevor man Context überhaupt anfasst.\n\nWer diese beiden Fragen sauber trennt, benutzt Context als das, was er ist – einen Verteilweg für wenige, selten wechselnde, app-weite Werte, mit stabilem `value` und, wo nötig, getrennten State- und Dispatch-Contexts. Wer sie vermischt, baut sich einen globalen State durch die Hintertür, samt Renderwellen und Kopplung. Der Unterschied kostet beim Schreiben eine einzige bewusste Entscheidung und erspart hinterher eine Menge Fehlersuche.\n\n## Weiterführende Quellen\n\n- Repository introduction-react: https://github.com/mikebild/introduction-react\n- react.dev, „Passing Data Deeply with Context“: https://react.dev/learn/passing-data-deeply-with-context\n- react.dev, „Scaling Up with Reducer and Context“: https://react.dev/learn/scaling-up-with-reducer-and-context\n- [react.dev: `useContext`, Wertvergleich und Re-Rendering](https://react.dev/reference/react/useContext)"},{"locale":"de","translation_key":"python-daten-einlesen","slug":"python-daten-einlesen","title":"Daten einlesen in Python: CSV, JSON, Excel und Datenbank","summary":"Ein Werkzeugkasten für jede Datenquelle: Wann die Standardbibliothek reicht, wann pandas lohnt, und wie man Encoding, Speicher und SQL-Injection nicht zum Verhängnis werden lässt.","tags":["Software","Python","Daten"],"published_at":"2021-04-27T10:00:00+00:00","updated_at":"2026-07-13T10:32:52.212694+00:00","url":"https://www.mikebild.dev/de/blog/python-daten-einlesen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ebadcd9a409af7754516bb30cef1d50c01054977dd84d4c63f11d774f9393c81/python-daten-einlesen-vorlesen.mp3","audio_duration_secs":990,"text":"Ein Reader ist keine Transportfunktion. `csv.DictReader`, `json.load`, `pandas.read_excel` – sie alle machen aus fremden Bytes Python-Objekte, und in diesem Übergang entscheidet sich, ob ein `ä` ein `ä` bleibt, ob eine Pflichtspalte gefüllt ist und ob eine Eingabe später eine ganze Tabelle leert. Und die Quellen sind selten so aufgeräumt, wie man sie sich wünscht: eine CSV-Datei, die jemand aus einem Export gezogen hat. Eine JSON-Antwort von einer API. Eine Excel-Mappe mit drei Tabellenblättern und einer Kopfzeile, die erst in Zeile vier anfängt. Oder eine SQLite-Datei, die still im Projektordner liegt und darauf wartet, abgefragt zu werden.\n\nWelchen Reader ich dafür wähle, ist die kleinere Entscheidung. Die größere ist, an welcher Stelle Vertrauen entsteht: Stimmt das Encoding, sind Pflichtfelder gefüllt, passen die Typen? Ein falsch dekodierter Umlaut oder eine ungeprüfte Eingabe kostet beim Einlesen selten etwas – die Rechnung kommt später, im Report an den Kunden, in der Datenbank, im Modell, das auf Müll trainiert wurde. Das Einlesen ist damit die Grenze, an der sich Datenqualität entscheidet.\n\nDer Schritt ist unspektakulär, und trotzdem bleiben erstaunlich viele Projekte an ihm hängen. Schwer ist er nicht, nur unübersichtlich: Python hält für jedes Format einen eigenen Weg bereit, und welcher davon wann der richtige ist, verliert man schnell aus dem Blick. Dieser Artikel legt dafür einen kleinen Werkzeugkasten an: die Standardbibliothek für den direkten, zeilenweisen Zugriff, pandas für die tabellarische Analysearbeit, und eine parametrisierte Datenbankabfrage, die gar nicht erst in die häufigste Sicherheitsfalle führt. Die Werkzeuge sind schnell erklärt – interessanter ist die Haltung dahinter: Daten als Domäne zu behandeln, deren Qualität man aktiv verantwortet.\n\n## Daten sind eine Domäne, kein Nebenschauplatz\n\nBevor es um Reader geht, lohnt ein Schritt zurück. Wird das Einlesen als Transport verstanden – Bytes rein, Objekte raus, weiter im Text –, ist das eine teure Sicht, denn sie verschiebt das Vertrauen an die falsche Stelle. Prüfe ich erst spät – im Report, in der Auswertung, im produktiven Endpoint – dann prüfe ich Daten, die längst durch mein halbes System gewandert sind. Der Fehler ist dann nicht mehr eine Zeile in einer Datei, sondern ein Vorfall mit Namen: ein falscher Umsatz beim Kunden, ein Datensatz, der eine Auswertung kippt, eine Eingabe, die eine Tabelle leert.\n\nIch behandle das Einlesen deshalb als eigene kleine Domäne mit klarer Aufgabe: aus unbekannten Bytes vertrauenswürdige, typisierte Objekte machen – und alles zurückweisen, was das nicht erfüllt. Drei Fragen entscheiden dabei über das Produktrisiko, und alle drei fallen an der Systemgrenze an. Encoding: Ist ein Zeichen wirklich das gemeinte Zeichen? Ein `Ã¤` statt `ä` ist kein Schönheitsfehler. Es ist ein stiller Datenschaden, der sich durch jede spätere Suche, jeden Vergleich, jeden Export fortpflanzt. Vertrauen: Wem gehört die Quelle? Einen eigenen Export behandle ich anders als eine Nutzereingabe oder eine fremde API – bei allem von außen gilt die Annahme, dass es feindlich sein kann. Validierung: Sind die Felder da, und haben sie die erwartete Form?\n\nDie Abwägung liegt bei der Validierung, denn Prüfung kostet Zeit. Je weiter die Daten reisen und je mehr Menschen am Ende von ihnen abhängen, desto früher und strenger prüfe ich. Ein Wegwerf-Skript für eine einmalige Analyse darf großzügig sein. Ein Reader, der eine Kundendatenbank oder einen wiederkehrenden Report speist, prüft an der Grenze und weist Fehlerhaftes sichtbar zurück, statt es klaglos durchzureichen. Der Gewinn ist konkret: Ein Problem taucht dort auf, wo es entsteht, mit Datei und Zeile – statt drei Schichten später als rätselhaftes Fehlverhalten, das man rückwärts durch ein halbes System zurückverfolgen muss.\n\n## Die zwei Lager: Standardbibliothek oder pandas\n\nBevor wir Code schreiben, lohnt eine grobe Einordnung. Python bringt für die gängigsten Formate bereits alles mit, was du brauchst – `csv`, `json`, `xml.etree` und `sqlite3` sind Teil der Standardbibliothek, ohne dass du etwas installieren müsstest. Diese Module arbeiten nah an den Rohdaten: Du bekommst Listen, Dictionaries, einzelne Zeilen. Das ist ideal, wenn du eine Datei zeilenweise verarbeiten willst, wenig Speicher zur Verfügung hast oder schlicht keine externe Abhängigkeit in dein Projekt holen möchtest.\n\npandas gehört ins andere Lager. Es ist eine zusätzliche Bibliothek, und es lohnt sich immer dann, wenn deine Daten tabellarisch sind und du sie analysieren, filtern oder aggregieren willst. Statt für jedes Format ein eigenes mentales Modell zu pflegen, landest du in pandas immer im selben `DataFrame` – egal, ob die Quelle eine CSV, eine Excel-Mappe, ein JSON-Dokument oder eine SQL-Query war. `read_csv`, `read_excel`, `read_json`, `read_sql`: ein Reader je Format, ein gemeinsames Ziel. Dazu kommen Typinferenz und ein reichhaltiger Satz an Operationen.\n\nDer folgende Überblick zeigt den Weg von der Quelle zur Zielstruktur:\n\n```mermaid\nflowchart LR\n  CSV[CSV] --> STD[Standardbibliothek<br/>csv, json, etree, sqlite3]\n  JSON[JSON] --> STD\n  XML[XML] --> STD\n  DB[(SQLite/DB)] --> STD\n  CSV --> PD[pandas<br/>read_csv, read_excel, read_sql]\n  XLSX[Excel .xlsx] --> PD\n  DB --> PD\n  STD --> DICTS[dicts / Listen]\n  PD --> DF[DataFrame]\n```\n\nDie Einordnung, nach der ich entscheide, ist kurz: Zeilenweise, klein, ohne Zusatzabhängigkeit – Standardbibliothek. Tabellarisch, analytisch, mit Filtern und Aggregaten – pandas. Und Excel im modernen `.xlsx`-Format bekommst du ohnehin nur über pandas (mit einer Hilfsbibliothek) sinnvoll gelesen, denn die Standardbibliothek kann das nicht. Entscheidend ist nicht das bequemste API, sondern das Datenvolumen und die Arbeit, die danach mit den Daten passieren soll.\n\n## CSV mit der Standardbibliothek: der Klassiker\n\nCSV ist das Format, das dir am häufigsten begegnet, und gleichzeitig das mit den meisten kleinen Tücken. Die Standardbibliothek bietet zwei Wege: `csv.reader` liefert pro Zeile eine Liste, `csv.DictReader` liefert pro Zeile ein Dictionary und nutzt dafür die Kopfzeile automatisch als Schlüssel. In der Praxis greife ich fast immer zu `DictReader`, weil der Zugriff über sprechende Spaltennamen den Code lesbarer macht.\n\n```python\nimport csv\n\nwith open(\"customers.csv\", newline=\"\", encoding=\"utf-8\") as f:\n    reader = csv.DictReader(f)          # header row becomes dict keys\n    rows = [row for row in reader]      # each row is a dict\n\nfor row in rows[:3]:\n    print(row[\"name\"], row[\"email\"])\n```\n\nZwei Details an dieser `open`-Zeile sind wichtiger, als sie aussehen. Erstens `newline=\"\"`: Das `csv`-Modul kümmert sich selbst um Zeilenumbrüche innerhalb von Feldern, und wenn du die Datei nicht mit leerem `newline` öffnest, kann es unter bestimmten Bedingungen zu zerrissenen Zeilen kommen. Das steht so in der Dokumentation, und es ist eine dieser Regeln, die man einmal lernt und dann nie wieder vergisst – meist nach dem ersten kaputten Datensatz.\n\nZweitens `encoding=\"utf-8\"`. Dazu gleich mehr, denn hier steckt der Fallstrick, der in Projekten die meiste Verwirrung stiftet – kaum ein Datenfehler taucht so zuverlässig auf.\n\nEin schöner Side Effect von `DictReader`: Weil er die Datei als Iterator durchläuft, kannst du ihn auch für große Dateien nutzen, ohne alles auf einmal in den Speicher zu laden. Statt die Liste per Comprehension zu materialisieren, verarbeitest du dann Zeile für Zeile in der Schleife und behältst nur, was du wirklich brauchst.\n\n## JSON: von der Datei zum Python-Objekt\n\nJSON ist in Python angenehm unkompliziert, weil sich die Struktur fast eins zu eins auf Dictionaries und Listen abbildet. `json.load` liest aus einem geöffneten Datei-Objekt, `json.loads` aus einer Zeichenkette. Das Ergebnis ist ein ganz normales Python-Objekt, mit dem du sofort weiterarbeiten kannst.\n\n```python\nimport json\n\nwith open(\"config.json\", encoding=\"utf-8\") as f:\n    data = json.load(f)         # dict or list, depending on the document\n\nprint(data[\"version\"])\nfor item in data[\"items\"]:\n    print(item[\"id\"], item[\"title\"])\n```\n\nFür das Zurückschreiben gibt es die Gegenstücke `json.dump` und `json.dumps`. Beim Schreiben lohnt sich meist `ensure_ascii=False`, damit Umlaute als echte Zeichen und nicht als `\\u`-Escapes in der Datei stehen, sowie `indent=2` für eine lesbare Formatierung. Beim Lesen brauchst du diese Optionen nicht – da ist JSON erfreulich anspruchslos.\n\n## Excel: hier führt der Weg über pandas\n\nSobald echte Tabellen ins Spiel kommen – mehrere Blätter, Zahlenformate, Kopfzeilen – wird pandas zum Mittel der Wahl. `read_excel` liest ein `.xlsx` in einen DataFrame, und du kannst gezielt ein Tabellenblatt über `sheet_name` auswählen.\n\n```python\nimport pandas as pd\n\ndf = pd.read_excel(\"report.xlsx\", sheet_name=\"Sales\")  # openpyxl engine by default\nprint(df.head())\nprint(df[\"revenue\"].sum())\n```\n\nEin Punkt, über den viele beim ersten Mal stolpern: `read_excel` braucht für `.xlsx` eine zusätzliche Bibliothek namens `openpyxl`. Seit pandas 1.2.0 (Ende 2020) ist `openpyxl` der Standard-Engine für dieses Format – die ältere `xlrd`-Bibliothek unterstützt moderne `.xlsx`-Dateien nicht mehr und ist nur noch für die alten `.xls`-Dateien zuständig. Wenn du also eine Fehlermeldung über eine fehlende Engine bekommst, ist die Lösung fast immer ein `pip install openpyxl`.\n\nGibst du `sheet_name=None` an, liefert pandas dir ein Dictionary aller Tabellenblätter als DataFrames zurück – praktisch, wenn du eine Mappe komplett einlesen willst. Und wenn deine Kopfzeile nicht in der ersten Zeile steht, hilft der `header`-Parameter, die richtige Zeile als Spaltennamen zu setzen.\n\n## Datenbanken: sqlite3 und der wichtigste Sicherheitshinweis\n\nSQLite ist mein Standardwerkzeug für Datenbankzugriff in kleinen Projekten und Prototypen, weil es ohne Server auskommt und das Modul `sqlite3` bereits in der Standardbibliothek steckt. Der Ablauf ist immer gleich: Verbindung öffnen, einen Cursor holen, eine Query ausführen, das Ergebnis abholen, Verbindung schließen.\n\n```python\nimport sqlite3\n\nconn = sqlite3.connect(\"shop.db\")\ncur = conn.cursor()\n\ncategory = \"books\"\ncur.execute(\n    \"SELECT name, price FROM products WHERE category = ?\",\n    (category,),\n)\nresult = cur.fetchall()\n\nfor name, price in result:\n    print(name, price)\n\nconn.close()\n```\n\nDer entscheidende Teil steht in der `execute`-Zeile: das Fragezeichen als Platzhalter und der Wert als separates Tupel im zweiten Argument. Das ist keine Stilfrage, sondern eine Sicherheitsfrage. Wer stattdessen den Wert direkt in den SQL-String hineinbaut – per Konkatenation oder f-String – öffnet die Tür für SQL-Injection. Ein manipuliertes Eingabefeld kann dann die Query umschreiben, Daten auslesen oder ganze Tabellen löschen.\n\nDer Vergleich macht den Unterschied deutlich:\n\n```python\n# unsafe: never do this\ncur.execute(f\"SELECT name, price FROM products WHERE category = '{category}'\")\n\n# safe: the driver handles quoting and escaping\ncur.execute(\n    \"SELECT name, price FROM products WHERE category = ?\",\n    (category,),\n)\n```\n\nDer parametrisierte Weg hat noch einen zweiten Vorteil neben der Sicherheit: Der Datenbanktreiber übernimmt das Quoting und Escaping für dich. Du musst dir keine Gedanken um Anführungszeichen im Wert machen. Ein wichtiges Detail dabei: Der Platzhalter `?` steht **ohne** umschließende Anführungszeichen im SQL-Text – das Quoting macht der Treiber, nicht du.\n\nWenn du mehr Komfort willst oder zwischen verschiedenen Datenbanken wechseln möchtest, kommt SQLAlchemy ins Spiel. Mit `create_engine(\"sqlite:///shop.db\")` baust du eine Verbindung auf, und `pandas.read_sql(query, con)` liest das Ergebnis direkt in einen DataFrame. Damit schließt sich der Kreis zwischen Datenbank und Analyse: Die Query kommt aus SQL, das Ergebnis liegt sofort im vertrauten pandas-Modell.\n\n## Und XML? Nicht vergessen, aber selten gebraucht\n\nXML begegnet dir seltener als früher, taucht aber in Konfigurationen, Exporten und älteren Schnittstellen weiterhin auf. Die Standardbibliothek deckt das mit `xml.etree.ElementTree` ab. Du parst die Quelle zu einem Baum, holst dir die Wurzel und navigierst über `find`, `findall` und `iter` zu den Elementen, die dich interessieren.\n\n```python\nimport xml.etree.ElementTree as ET\n\ntree = ET.parse(\"catalog.xml\")\nroot = tree.getroot()\n\nfor product in root.findall(\"product\"):\n    name = product.find(\"name\").text\n    price = product.get(\"price\")        # read an attribute\n    print(name, price)\n```\n\nFür einfache Strukturen reicht das vollkommen. Bei komplexeren XML-Dokumenten mit Namespaces oder tiefer Verschachtelung wird es schnell fummelig – dann greife ich gern zu spezialisierten Bibliotheken. Für den Alltag deckt `ElementTree` aber die meisten Fälle ab.\n\n## Welcher Reader für welches Format?\n\nDamit du die Übersicht behältst, hier die Zuordnung als kompakte Liste:\n\n- Für CSV nimmst du `csv.DictReader` aus der Standardbibliothek zum zeilenweisen Lesen und `pandas.read_csv`, sobald es analytisch wird.\n- Für JSON reichen `json.load` und `json.loads` aus der Standardbibliothek; `pandas.read_json` hilft, wenn das JSON tabellarisch ist.\n- Für Excel im `.xlsx`-Format führt der Weg über `pandas.read_excel` mit installiertem `openpyxl` – die Standardbibliothek kann dieses Format nicht.\n- Für Datenbanken deckt `sqlite3` den direkten, parametrisierten Zugriff ab; `pandas.read_sql` oder SQLAlchemy kommen dazu, wenn Analyse oder Portabilität gefragt sind.\n- Für XML genügt `xml.etree.ElementTree` aus der Standardbibliothek bei überschaubaren Dokumenten.\n\n## Drei Fallstricke, die immer wieder zuschlagen\n\nIn der Praxis sind es selten die Reader selbst, die Probleme machen, sondern drei wiederkehrende Themen rund ums Einlesen.\n\n### Encoding\n\nWarum Encoding ein Produktrisiko ist, stand schon oben – hier der praktische Teil. Der Standard-Zeichensatz beim Öffnen einer Datei ist plattformabhängig, unter Windows oft `cp1252` statt UTF-8. Erscheinen Umlaute als `Ã¤` oder `Ã¶`, oder kommt ein `UnicodeDecodeError`, ist fast immer das Encoding schuld, und die Lösung ist, es explizit anzugeben: `encoding=\"utf-8\"`. Für Dateien, die aus Excel exportiert wurden, brauchst du oft `encoding=\"utf-8-sig\"`, weil Excel eine sogenannte Byte Order Mark an den Anfang setzt, die das schlichte `utf-8` als Sonderzeichen missdeutet.\n\n### Große Dateien komplett im Speicher\n\nEs ist verlockend, eine CSV einfach mit `pandas.read_csv(\"big.csv\")` komplett zu laden – bis die Datei mehrere Gigabyte hat und der Speicher überläuft. pandas bietet dafür `chunksize`: Statt eines DataFrames bekommst du dann einen Iterator, über den du die Datei in Blöcken abarbeitest.\n\n```python\nimport pandas as pd\n\ntotal = 0\nfor chunk in pd.read_csv(\"big.csv\", chunksize=100_000):\n    total += chunk[\"amount\"].sum()     # process one block at a time\n\nprint(total)\n```\n\nIn der Standardbibliothek erreichst du dasselbe, indem du über `DictReader` Zeile für Zeile iterierst, statt alles in eine Liste zu materialisieren. Ein Hinweis noch: `read_excel` kennt kein natives Chunking – bei sehr großen Tabellen lohnt es sich, die Daten vorher nach CSV oder in eine Datenbank zu überführen.\n\n### SQL-Injection\n\nWichtig genug für die Wiederholung: Baue niemals Benutzereingaben per String-Konkatenation oder f-String in eine SQL-Query ein. Nutze immer Platzhalter und übergib die Werte separat. Das kostet keine zusätzliche Zeile Code und erspart dir eine ganze Klasse von Sicherheitslücken.\n\nDer folgende Entscheidungsbaum fasst zusammen, wie ich in der Praxis den Weg wähle:\n\n```mermaid\nflowchart TD\n  A{Tabellarische<br/>Analyse nötig?} -->|ja| B[pandas]\n  A -->|nein| C{Zeilenweise,<br/>klein, ohne Abhängigkeit?}\n  C -->|ja| D[Standardbibliothek]\n  C -->|nein| B\n  B --> E{Sehr große Datei?}\n  E -->|ja| F[chunksize / Streaming]\n  E -->|nein| G[direkt einlesen]\n```\n\n## Fazit\n\nDie Werkzeugwahl ist schnell getroffen: Für zeilenweisen, direkten Zugriff ohne Zusatzabhängigkeit reicht die Standardbibliothek mit `csv`, `json`, `xml.etree` und `sqlite3`; sobald es tabellarisch und analytisch wird oder Excel im Spiel ist, zahlt sich pandas mit seinem einheitlichen DataFrame-Modell aus. Der Unterschied zwischen einem Skript, das läuft, und einem, dem man vertraut, entsteht nicht bei den Readern, sondern bei der Haltung: Encoding, Vertrauen und Validierung gehören an die Systemgrenze.\n\nWer diese Grenze bewusst zieht, verändert die Ökonomie des Projekts. Fehler tauchen früh und benannt auf, statt spät und rätselhaft – das verkürzt die Debugging-Zyklen und nimmt Reibung aus der Weiterarbeit. Die Daten, die durchkommen, sind die, denen man trauen kann, was die Qualität aller späteren Schritte anhebt. Und die drei Reflexe dazu kosten fast nichts: Encoding immer explizit setzen, damit Umlaute nicht zerfallen. Bei großen Dateien früh an `chunksize` oder zeilenweises Streamen denken, statt den Speicher vollzuladen. Datenbankabfragen ausnahmslos mit Platzhaltern, nie mit zusammengebautem SQL. Wichtig ist auch die klare Grenze nach oben: Nicht jedes Skript braucht volle Schema-Validierung, und wo Aufwand und Risiko nicht zusammenpassen, ist Großzügigkeit die richtige Wahl. Wer das entscheidet statt es dem Zufall zu überlassen, kommt schnell und sicher ans Ziel – und kann sich dem eigentlich Interessanten widmen: dem, was in den Daten steckt.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-python.html\n- Repository `introduction-python` – Beispiele zum Datenzugriff aus meinen Schulungen (`csv`, `json`, `sqlite3`, pandas).\n- csv – Python-Dokumentation: https://docs.python.org/3/library/csv.html\n- json – Python-Dokumentation: https://docs.python.org/3/library/json.html\n- sqlite3 – Python-Dokumentation: https://docs.python.org/3/library/sqlite3.html\n- xml.etree.ElementTree – Python-Dokumentation: https://docs.python.org/3/library/xml.etree.elementtree.html\n- pandas IO-Guide: https://pandas.pydata.org/docs/user_guide/io.html\n- pandas 1.2.0 – openpyxl als Default-Engine: https://pandas.pydata.org/docs/whatsnew/v1.2.0.html\n- SQLAlchemy-Dokumentation: https://docs.sqlalchemy.org/en/14/"},{"locale":"de","translation_key":"adr-entscheidungen-die-man-versteht","slug":"adr-entscheidungen-die-man-versteht","title":"Architecture Decision Records: Entscheidungen, die man in zwei Jahren noch versteht","summary":"Warum wir uns damals für PostgreSQL und gegen den Message-Bus entschieden haben? ADRs machen das Warum als versioniertes Markdown-Artefakt haltbar – statt es im Flurfunk versickern zu lassen.","tags":["Software","Architektur"],"published_at":"2021-03-26T10:00:00+00:00","updated_at":"2026-07-13T08:40:51.197927+00:00","url":"https://www.mikebild.dev/de/blog/adr-entscheidungen-die-man-versteht/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/8888fb4934ede6206b0c19ae9a3e2c5fb22820900259d449cc4f20153bf47f46/adr-entscheidungen-die-man-versteht-vorlesen.mp3","audio_duration_secs":703,"text":"Fünf Abschnitte reichen, um eine Architekturentscheidung haltbar zu machen: Title, Status, Context, Decision, Consequences. Michael Nygard hat dieses Format 2011 in seinem Blogpost „Documenting Architecture Decisions“ beschrieben und Architecture Decision Record genannt, kurz ADR – ein kleines, versioniertes Textartefakt, das genau eine Entscheidung samt ihrem Kräftefeld festhält. Eine Seite Markdown, mehr nicht.\n\nDer Anlass steht bei Nygard gleich im ersten Satz: „One of the hardest things to track during the life of a project is the motivation behind certain decisions.“ Das *Was* steht im Code. Das *Warum* steht nirgends – oder es steckt in einem Slack-Thread, einer Confluence-Seite, die keiner mehr findet, oder im Kopf von jemandem, der gerade Urlaub hat. Die teuerste Frage in einem Projekt ist deshalb selten „Wie bauen wir das?“, sondern „Warum haben wir das damals eigentlich so gebaut?“. Ein Team übernimmt ein System, stößt auf eine merkwürdige Entscheidung – eine ungewöhnliche Datenbank, ein selbstgebautes Caching, ein Verzicht auf den naheliegenden Message-Bus – und niemand kann sagen, ob das Absicht war oder ein Unfall. Die Leute, die es wussten, sind längst im nächsten Projekt oder in der nächsten Firma. Übrig bleibt Code, der eine Entscheidung ausführt, deren Begründung verdunstet ist.\n\n## Das Outcome zuerst: weniger Archäologie, schnellere Übergaben\n\nBevor ich über Format und Tooling rede, will ich sagen, was ADRs praktisch bringen – denn darum geht es, nicht um ein weiteres Dokumentationsritual. In den Projekten, in denen ich ADRs eingeführt habe, verkürzt sich vor allem eine Sache dramatisch: die Zeit, in der ein neues Teammitglied vom „Ich verstehe den Code, aber nicht die Logik dahinter“ zum „Ich kann hier mitentscheiden“ kommt. Onboarding wird von Ausgraben zu Nachlesen.\n\nDer zweite Effekt ist subtiler, aber wertvoller. Wenn eine Entscheidung aufgeschrieben werden *muss*, wird sie auch bewusster getroffen. Man merkt beim Schreiben, ob man wirklich Alternativen abgewogen hat oder nur den erstbesten Weg genommen hat. Das Artefakt zwingt nicht zu mehr Bürokratie – es zwingt zu Klarheit. Und Klarheit im Moment der Entscheidung ist billiger als jede spätere Rekonstruktion.\n\nWichtig ist mir dabei die Abgrenzung, die Nygard selbst macht: Agile Methoden sind nicht gegen Dokumentation, sie sind gegen *wertlose* Dokumentation. Das 80-seitige Architekturhandbuch, das schon beim ersten Commit veraltet, ist wertlos. Ein einseitiges ADR, das neben dem Code liegt und mit ihm durch die Git-History wandert, ist es nicht. ADRs sind der Leichtgewicht-Kompromiss zwischen „gar nichts aufschreiben“ und „alles totdokumentieren“.\n\n## Das Format: fünf Abschnitte, eine Entscheidung\n\nNygard beschreibt ADRs als „a format similar to an Alexandrian pattern“ – ein kurzer Text, der ein Kräftefeld beschreibt und *eine* Entscheidung als Antwort darauf festhält. Das Format ist bewusst minimal, und die Kürze ist kein Mangel, sondern das Feature: Kleine Dokumente werden eher aktuell gehalten als große.\n\nSo sieht ein ADR bei mir typischerweise aus. Es liegt als Markdown im selben Repository wie der Code, unter `docs/adr/`:\n\n```markdown\n# 7. Use PostgreSQL as primary datastore\n\nDate: 2021-03-12\n\n## Status\n\nAccepted   <!-- proposed | accepted | superseded by ADR-0012 -->\n\n## Context\n\nThe core service needs a transactional store. Expected load is\nmoderate (low thousands of writes per minute at peak). The team\nhas deep operational experience with PostgreSQL and none with\ndistributed NewSQL stores. Strong consistency is a hard requirement\nfor the billing path.\n\n## Decision\n\nWe will use PostgreSQL as the primary datastore for the core service.\n\n## Consequences\n\nPositive: strong consistency, mature tooling, no learning curve for the team.\nNegative: single-primary HA needs operational care; revisit this decision\nif sustained write throughput exceeds ~5k writes/second.\n```\n\nDer Context-Abschnitt ist der eigentliche Wert. Er beschreibt das, was Nygard „balancing of forces“ nennt – die Kräfte, die auf die Entscheidung wirken: erwartete Last, Team-Skills, Konsistenzgarantien, Kosten. Wer in zwei Jahren dieses ADR liest, sieht nicht nur, *dass* PostgreSQL gewählt wurde, sondern unter welchen Annahmen. Und – das ist entscheidend – der Consequences-Abschnitt nennt sogar die Bedingung, unter der man die Entscheidung neu bewerten sollte. Das ist kein Dogma, das ist ein Denkzustand, konserviert.\n\nEin Punkt daran wird oft übersehen: Der Context muss die Welt *zum Zeitpunkt der Entscheidung* beschreiben, nicht die Welt von heute. Ein ADR ist eine Momentaufnahme, kein Living Document. Das führt direkt zum wichtigsten Prinzip.\n\n## Immutability: ADRs werden nie überschrieben\n\nDer häufigste Fehler, den ich sehe, wenn Teams ADRs zum ersten Mal ausprobieren: Sie behandeln ein ADR wie eine Wiki-Seite und aktualisieren es, wenn sich die Entscheidung ändert. Das zerstört den ganzen Sinn. Ein ADR ist ein Log-Eintrag, kein Zustandsobjekt.\n\nDie Regel lautet: Ein einmal akzeptiertes ADR wird nie mehr inhaltlich verändert. Ändert sich die Entscheidung, schreibt man ein *neues* ADR, das das alte ablöst. Das alte bekommt den Status `superseded` und einen Verweis auf den Nachfolger. Die Nummerierung ist fortlaufend und wird nie wiederverwendet – 0001, 0002, 0003, auch wenn 0002 längst überholt ist. Was entsteht, ist ein Entscheidungs-*Log*: eine lückenlose Historie, die zeigt, welche Entscheidung wann galt und wodurch sie abgelöst wurde.\n\n```\ndocs/adr/          # sequential, zero-padded, never renumbered\n  0001-record-architecture-decisions.md\n  0002-use-markdown-for-adrs.md\n  0007-use-postgres-as-primary-datastore.md   # Status: superseded by 0012\n  0012-switch-to-cockroachdb.md               # Status: accepted\n```\n\nDiesen Lifecycle kann man gut als Zustandsdiagramm denken. Ein ADR wandert von `proposed` über `accepted` – und irgendwann, vielleicht, zu `superseded`, wobei der Zeiger auf das nachfolgende ADR verweist:\n\n```mermaid\nstateDiagram-v2\n    [*] --> proposed\n    proposed --> accepted: PR merged\n    proposed --> rejected: not adopted\n    accepted --> superseded: replaced by newer ADR\n    superseded --> [*]: points to successor ADR\n    rejected --> [*]\n```\n\nDer Charme daran ist, dass die Git-History und die ADR-History parallel laufen. Beide stecken im selben Repo, beide wandern durch dieselben Commits. Wenn ich einen alten Commit auschecke, sehe ich die ADRs, die zu diesem Stand gehörten. Das Warum reist mit dem Code durch die Zeit.\n\n## Flurfunk gegen Artefakt\n\nUm zu zeigen, was ADRs eigentlich verändern, hilft ein einfacher Kontrast. Auf der einen Seite steht der Normalzustand vieler Teams: Entscheidungen entstehen in Meetings, in Chat-Threads, im Vorbeigehen an der Kaffeemaschine. Sie sind real, sie prägen die Architektur – aber sie sind nirgends greifbar. Auf der anderen Seite steht das versionierte Markdown-Artefakt, das im Repo liegt und über den Pull-Request reviewt wird.\n\n```mermaid\nflowchart LR\n    subgraph Flurfunk\n        A[Slack thread] --> X[lost knowledge]\n        B[whiteboard photo] --> X\n        C[hallway talk] --> X\n        D[someone's memory] --> X\n    end\n    subgraph Artefakt\n        E[ADR in docs/adr/] --> G[reviewed via PR]\n        G --> H[versioned with the code]\n        H --> I[readable in two years]\n    end\n```\n\nDer Unterschied ist nicht, dass links keine Entscheidungen getroffen werden. Es werden dieselben Entscheidungen getroffen. Der Unterschied ist, ob die Begründung ein Artefakt wird oder verdunstet. Und das ist letztlich eine Frage der Reibung: Solange das Aufschreiben teurer ist als das Vergessen, wird vergessen. ADRs funktionieren, weil sie das Aufschreiben so billig machen – eine Markdown-Datei, ein Commit, fertig – dass es sich lohnt.\n\n## Tooling: gerade genug, um nicht im Weg zu stehen\n\nMan braucht für ADRs kein Werkzeug. Eine Textdatei und Git reichen. Trotzdem hilft ein bisschen Konvention, damit die Nummerierung und die Vorlage konsistent bleiben. Nat Pryce hat dafür `adr-tools` gebaut, ein schlankes CLI, das man sich per Homebrew installiert:\n\n```bash\n# create a new, auto-numbered ADR from the standard template\n$ adr new \"Use PostgreSQL as primary datastore\"\n# -> docs/adr/0007-use-postgres-as-primary-datastore.md\n\n# create an ADR that supersedes an earlier one\n$ adr new -s 7 \"Switch to CockroachDB\"\n# -> docs/adr/0012-switch-to-cockroachdb.md\n#    and sets ADR-0007 status to \"superseded by 0012\"\n```\n\nWer eine reichhaltigere Vorlage mag, findet mit MADR – „Markdown Any Decision Records“ – ein strukturierteres Template, das explizit Platz für abgewogene Optionen lässt. Für den Einstieg empfehle ich aber fast immer die nackten fünf Nygard-Abschnitte. Man kann später verfeinern; man kann schlecht nachträglich Disziplin einführen.\n\nDer wirkungsvollste Hebel ist ohnehin kein Tool, sondern eine Prozessgewohnheit: Eine architekturrelevante Änderung im Pull-Request wird nur gemergt, wenn das zugehörige ADR im selben PR liegt. Damit wird das ADR Teil des Reviews. Die Entscheidung wird nicht nur festgehalten, sondern im selben Moment von mindestens einer zweiten Person gegengelesen. Aus dem einsamen „Ich hab da mal was gebaut“ wird ein bewusster, geteilter Schritt.\n\nDass das Format tragfähig ist, ist übrigens keine Einzelmeinung. Der ThoughtWorks Technology Radar stufte „Lightweight Architecture Decision Records“ bereits im November 2017 auf *Adopt* – die höchste Empfehlungsstufe. Das ist keine Neuheit mehr, das ist etablierte Praxis.\n\n## Wo ADRs kippen – das ehrliche Kapitel\n\nADRs sind kein Selbstläufer. Sie scheitern, und zwar auf drei vorhersehbare Arten.\n\nDer erste Fehlerweg: ADRs veralten trotzdem. Wer sie nicht diszipliniert bei jeder relevanten Entscheidung schreibt, bekommt eine lückenhafte Historie. Und eine lückenhafte Historie ist gefährlicher als gar keine, weil sie Vollständigkeit vortäuscht. Wenn jemand liest „hier stehen unsere Entscheidungen“ und die entscheidende fehlt, zieht er falsche Schlüsse. Er verlässt sich auf ein Log, das lügt – nicht durch Falsches, sondern durch Weglassen. Disziplin schlägt Tooling, immer. Kein CLI und kein Template ersetzt die simple Gewohnheit, im Moment der Entscheidung kurz innezuhalten und sie festzuhalten.\n\nDer zweite Fehlerweg: zu groß, zu spät. Sobald ADRs zu Design-Dokumenten anschwellen, sinkt die Aktualisierungsquote, und Nygards ganzer Punkt – die Kürze – geht verloren. Besonders tückisch sind post-hoc geschriebene ADRs, also Begründungen, die man Wochen nach der Entscheidung nachreicht. Sie rationalisieren nur, statt das echte Kräftefeld einzufangen. Man schreibt dann nicht mehr auf, *warum* man sich entschieden hat, sondern warum die Entscheidung im Nachhinein gut aussieht. Das ist Selbstbetrug in Markdown – und er ist schwer zu entdecken, weil ein sauber formuliertes ADR überzeugend wirkt, ganz gleich, ob es die echten Kräfte einfängt oder nur eine hübsche Fassade davor baut.\n\nDer dritte Fehlerweg: falsche Granularität. Ohne definierten Auslöser passiert eins von zwei Dingen. Entweder wird jede Nichtigkeit ein ADR, dann ertrinkt das Signal im Rauschen. Oder niemand weiß, was „architekturrelevant“ heißt, dann wird gar nichts geschrieben. Eine grobe Schwelle, früh im Team vereinbart, hilft: Ein ADR entsteht, wenn eine Entscheidung schwer umkehrbar ist, mehrere Teams betrifft oder eine naheliegende Alternative bewusst verwirft. Alles andere ist ein Kommentar im Code, kein ADR. Diese Schwelle darf ruhig unscharf bleiben; wichtiger als die exakte Grenze ist, dass das Team überhaupt eine gemeinsame Vorstellung davon teilt.\n\nEin Gedanke noch, der ADRs über reine Dokumentation hinaushebt: Wer die Bedingung im Consequences-Abschnitt ernst nimmt – „revisit if write throughput exceeds 5k/s“ –, kann sie überprüfbar machen. In *Building Evolutionary Architecture* nennen Ford, Parsons und Kua das *fitness functions*: automatisierte Checks, die eine Architektureigenschaft messen. Ein ADR dokumentiert die Entscheidung, eine Fitness Function wacht darüber, dass ihre Annahme noch gilt. Beides zusammen macht aus einem toten Dokument einen lebenden Wächter.\n\n## Fazit\n\nADRs lösen kein technisches Problem. Sie lösen ein Gedächtnisproblem – und Gedächtnisprobleme sind auf lange Sicht teurer als technische, weil sie sich verzinsen. Jede undokumentierte Entscheidung wird mit der Zeit zu einer kleinen Schuld: Irgendwann muss jemand mit Mühe rekonstruieren, was man in fünf Minuten hätte aufschreiben können.\n\nDer Kern ist unspektakulär und genau deshalb tragfähig: In meiner Konvention bleibt ein angenommener Text unverändert; eine neue Entscheidung ersetzt ihn mit Verweis auf das alte ADR. So bleiben Kontext, Entscheidung und Konsequenzen versioniert neben dem Code und über den Pull-Request reviewbar. Dafür braucht es kein neues System, sondern die Disziplin, das Warum festzuhalten, solange es noch frisch ist.\n\nDer einfachste Anfang ist das erste ADR selbst – jenes, das festhält, dass ab jetzt ADRs geschrieben werden. `0001-record-architecture-decisions.md`. Alles Weitere ergibt sich, wenn die Gewohnheit einmal da ist. Und in zwei Jahren liest das jemand, den heute noch niemand im Team kennt.\n\n## Weiterführende Quellen\n\n- Michael Nygard, „Documenting Architecture Decisions“ (Cognitect, 2011): https://cognitect.com/blog/2011/11/15/documenting-architecture-decisions.html\n- Martin Fowler, bliki „Architecture Decision Record“: https://martinfowler.com/bliki/ArchitectureDecisionRecord.html\n- ThoughtWorks Technology Radar, „Lightweight Architecture Decision Records“ (Adopt, Nov 2017): https://www.thoughtworks.com/radar/techniques/lightweight-architecture-decision-records\n- adr.github.io – Community-Sammlung zu ADRs und Tooling: https://adr.github.io/"},{"locale":"de","translation_key":"graphql-schema-das-mitwaechst","slug":"graphql-schema-das-mitwaechst","title":"GraphQL-Schema, das mitwächst: Evolution ohne Bruch","summary":"Wie man ein GraphQL-Schema additiv weiterentwickelt, statt es zu versionieren – sichere Änderungen, echte Breaking Changes, @deprecated als Werkzeug und eine Feld-Migration Schritt für Schritt.","tags":["Software","API","GraphQL"],"published_at":"2021-03-24T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/graphql-schema-das-mitwaechst/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/fa3b8abe81f20e17d76756b2e2154c95f81f15dd3f6ebf1441445cfc5bd2519f/graphql-schema-das-mitwaechst-vorlesen.mp3","audio_duration_secs":810,"text":"# GraphQL-Schema, das mitwächst: Evolution ohne Bruch\n\nEin Schema bricht nicht daran, dass es wächst, sondern daran, dass es etwas zurücknimmt. Ein Feld mehr stört keinen laufenden Client; ein Feld weniger, ein umbenanntes Argument, eine zurückgezogene Garantie legen ihn still. Auf dieser einen Unterscheidung – ergänzen oder zurücknehmen – ruht die gesamte Schema-Evolution. Im Alltag ist sie nur weniger eindeutig, als sie klingt: Manches sieht nach Rücknahme aus und ist völlig harmlos, manches sieht rein additiv aus und bricht trotzdem.\n\nDer typisierte Vertrag zwischen Server und Client, den ich im GraphQL-Überblick und in den GraphQL-Konzepten beschrieben habe, ist in dem Moment einfach, in dem er festgeschrieben wird. Schwierig wird er im laufenden Betrieb: Ein neues Feld muss rein, ein altes ist überflüssig geworden, eine Signatur passt nicht mehr. Draußen laufen dabei Clients, die man teils nicht einmal kennt – Web, Mobil, ein Partner-Backend, eine App-Version von vor achtzehn Monaten, die noch im Feld ist. Ein GraphQL-Schema zu entwerfen, bekommt fast jeder hin. Es über Jahre zu pflegen, ohne bestehende Clients zu brechen, ist die eigentliche Disziplin.\n\n## Kein /v2, sondern ein Schema\n\nWer von REST kommt, hat einen Reflex: Für eine größere Änderung baut man `/v2`. Die alte URL bleibt, die neue läuft daneben, irgendwann schaltet man `/v1` ab. Das funktioniert, aber es kostet – jede Version ist Code, den jemand baut, testet, betreibt und dokumentiert, oft jahrelang parallel.\n\nGraphQL geht einen anderen Weg. Es gibt keine Versionsnummer in der URL, sondern genau ein Schema, das sich additiv weiterentwickelt. Der Grund dafür steckt in einer Eigenschaft, die ich in den Konzepten schon beschrieben habe: Ein Client bekommt nur, was er in seiner Query nennt. Er fragt `name` und `title`, also bekommt er `name` und `title` – und sonst nichts. Kommt morgen ein Feld `subtitle` ins Schema, merkt dieser Client es nicht einmal. Er hat es nie genannt, also taucht es in seiner Antwort nicht auf, und seine Antwort behält exakt dieselbe Form wie gestern.\n\nDas ist der Hebel. Weil der Client die Form seiner Antwort selbst bestimmt, stören ihn zusätzliche Felder im Schema grundsätzlich nicht. Man kann das Schema also wachsen lassen, ohne dass jede Ergänzung ein Event ist. Die offizielle Doku bringt es auf den Punkt: GraphQL nimmt eine klare Haltung gegen Versionierung ein und stellt stattdessen Werkzeuge für kontinuierliche Weiterentwicklung bereit.\n\n## Sichere Änderungen: das, was man einfach hinzufügen darf\n\nEine ganze Klasse von Änderungen ist von Natur aus ungefährlich, weil sie nur ergänzt und nie etwas wegnimmt, worauf ein Client sich verlässt. Ein neues Feld an einem bestehenden Typ bemerkt niemand, der es nicht abfragt. Ein neuer Typ oder ein neuer Query- beziehungsweise Mutation-Einstieg ist reines Angebot, keine Pflicht. Ein neues optionales Argument an einem bestehenden Feld lässt jeden, der es weglässt, beim alten Verhalten – vorausgesetzt, der Default entspricht dem, was vorher galt. Und ein neuer Enum-Wert ist ebenfalls additiv, allerdings mit einer Einschränkung, auf die ich gleich zurückkomme, denn hier lauert eine Falle.\n\nDer gemeinsame Nenner: Bestehende Queries liefern nach der Änderung dasselbe Ergebnis wie vorher. Das ist die eigentliche Definition von „nicht brechend“ – nicht, dass sich nichts ändert, sondern dass keine gültige Query von gestern heute plötzlich ungültig wird oder eine andere Form zurückgibt.\n\n## Breaking Changes: das, was Clients wirklich zerreißt\n\nAuf der anderen Seite stehen die Änderungen, die eine gestern gültige Query heute brechen. Die wichtigsten, mit konkreten Beispielen:\n\nAm offensichtlichsten ist es, ein Feld zu entfernen oder umzubenennen. Fragt ein Client `user { fullName }` und ich benenne `fullName` in `displayName` um, ist die Query sofort ungültig. Umbenennen ist aus Schema-Sicht nichts anderes als Löschen plus Hinzufügen – der alte Name verschwindet, und jede Query, die ihn nennt, läuft in einen Validierungsfehler.\n\nSubtiler, und regelmäßig für Überraschung gut, ist die Nullability in die falsche Richtung. Ein nullbares Feld auf non-null zu ziehen ist *nicht* brechend: Wer bisher mit einem möglichen `null` gerechnet hat, kommt auch damit klar, dass jetzt immer ein Wert kommt. Umgekehrt aber – ein non-null-Feld nullbar machen – *ist* brechend. Ein Client, der sich auf die Garantie `String!` verlassen und nie gegen `null` geprüft hat, bekommt plötzlich ein `null`, mit dem er nicht rechnet. Dieselbe Logik gilt für Argumente, nur spiegelverkehrt: Ein Pflichtargument optional zu machen ist harmlos, ein optionales zur Pflicht zu erheben bricht jeden, der es bisher weggelassen hat.\n\nAuch ein geänderter Argument-Typ oder ein neues Pflichtargument bricht. Wird aus einem `String`-Argument ein `Int`, passen bestehende Queries nicht mehr. Und ein neues *nicht-optionales* Argument macht jede Query ungültig, die es noch nicht mitliefert – deshalb oben die Betonung auf *optional*.\n\nUnd einen Enum-Wert zu entfernen bricht ebenso: Verschwindet ein Wert, den ein Client als Argument sendet oder in einer Antwort erwartet, bricht die Interaktion.\n\n```mermaid\nflowchart LR\n  subgraph Additiv[\"Sicher – additiv\"]\n    A1[\"Feld hinzufügen\"]\n    A2[\"Typ hinzufügen\"]\n    A3[\"optionales Argument\"]\n    A4[\"nullable → non-null\"]\n  end\n  subgraph Breaking[\"Bricht Clients\"]\n    B1[\"Feld entfernen/umbenennen\"]\n    B2[\"non-null → nullable\"]\n    B3[\"Pflichtargument hinzufügen\"]\n    B4[\"Enum-Wert entfernen\"]\n  end\n```\n\nDer Trick beim Lesen dieser Liste: Es geht nie um „mehr“ oder „weniger“, sondern immer um dieselbe Frage – kann eine gestern gültige Query nach der Änderung noch gültig laufen und dieselbe Form zurückgeben? Wenn ja, ist die Änderung additiv. Wenn nein, ist sie brechend, egal wie klein sie aussieht.\n\n## @deprecated: veralten statt entfernen\n\nWeil das Entfernen bricht, braucht man einen Weg, ein Feld loszuwerden, *ohne* es sofort zu entfernen. Genau dafür gibt es in GraphQL eine eingebaute Direktive: `@deprecated`.\n\n```graphql\ntype User {\n  id: ID!\n  fullName: String @deprecated(reason: \"Use `displayName` instead. Removal planned for a future release.\")\n  displayName: String!\n}\n```\n\nDas Feld bleibt voll funktionsfähig – jede Query, die `fullName` nennt, bekommt weiterhin eine Antwort. Aber das Schema trägt jetzt eine sichtbare Markierung. Über Introspection landet dieser Hinweis in jedem Tooling: Der GraphiQL-Explorer streicht das Feld durch, Editor-Plugins warnen beim Tippen, Codegen und Linter melden die Nutzung. Der `reason`-Text ist dabei die eigentliche Botschaft an das Team am anderen Ende – idealerweise mit Nachfolger *und* Frist. Client-Teams sehen den Hinweis, migrieren auf `displayName`, und erst viel später, wenn niemand `fullName` mehr abfragt, entferne ich es.\n\nMan kann übrigens nicht nur Felder deprecaten, sondern auch einzelne Enum-Werte und Argumente. Das Muster ist überall dasselbe: erst markieren, Zeit geben, dann entfernen. Damit ist Deprecation das wichtigste Werkzeug der Schema-Evolution überhaupt.\n\n## Nullability ist eine Design-Entscheidung, kein Reflex\n\nEin Punkt verdient mehr als eine Zeile, weil er beim Entwurf oft falsch entschieden wird und sich später kaum korrigieren lässt: die Frage, ob ein Feld non-null sein soll.\n\n`String!` fühlt sich sauber an. Es sagt: Hier kommt immer ein Wert. Aber non-null ist eine Garantie, und Garantien kann man in einem laufenden Vertrag nicht mehr zurücknehmen – der Weg von non-null zurück zu nullable ist, wie gesehen, ein Breaking Change. Man legt sich also fest, und zwar dauerhaft.\n\nSchwerer wiegt, was zur Laufzeit passiert, wenn die Garantie einmal nicht hält. Fällt der Resolver eines non-null-Feldes aus – die Datenbank hakt, ein Upstream-Service liefert nichts – dann *muss* GraphQL ein `null` verhindern, wo `null` verboten ist. Es kann den Wert nicht einfach durchlassen. Also lässt es das `null` nach oben durchschlagen: Der Fehler steigt zum nächsten nullbaren Elternfeld auf und macht dort alles `null`. Ein einziger fehlgeschlagener non-null-Resolver kann so einen ganzen Antwortpfad mitreißen, bis hoch zu einer Stelle, die `null` verträgt. Aus einem lokalen Problem wird ein großflächiger Ausfall in der Antwort.\n\nIm Zweifel also nullable beginnen. Non-null nur dort, wo die Garantie wirklich trägt – bei einer `id`, bei einem Feld, das strukturell nie fehlen kann. Für alles, was von einem externen System, einer optionalen Relation oder einer Berechnung abhängt, die scheitern darf, ist nullable die ehrlichere und robustere Wahl. Man kann später jederzeit von nullable auf non-null verschärfen, wenn sich die Garantie als stabil erwiesen hat. Den umgekehrten Weg hat man nicht.\n\n## Input-Typen: Mutationen zukunftssicher schneiden\n\nAdditive Evolution beginnt schon beim Entwurf, nirgends deutlicher als bei Mutationen. Wer eine Mutation mit einer Handvoll Einzelargumenten baut, verbaut sich die Zukunft:\n\n```graphql\ntype Mutation {\n  createPost(title: String!, body: String!, authorId: ID!): Post!\n}\n```\n\nKommt später ein Feld dazu – eine Kategorie, ein Veröffentlichungsdatum – wächst die Argumentliste, und jede Ergänzung, die nicht optional ist, bricht bestehende Aufrufer. Die Signatur ist starr.\n\nDeshalb kapselt man die Eingabe in einen eigenen `input`-Typ:\n\n```graphql\ninput CreatePostInput {\n  title: String!\n  body: String!\n  authorId: ID!\n}\n\ntype Mutation {\n  createPost(input: CreatePostInput!): Post!\n}\n```\n\nDie Mutation nimmt jetzt genau ein Argument, `input`. Neue Eingabefelder ergänzt man additiv im `input`-Typ – als *optionale* Felder, damit bestehende Aufrufer, die sie nicht setzen, gültig bleiben. Die Signatur der Mutation selbst rührt sich nie wieder. Dasselbe Prinzip gilt auf der Ausgabeseite: Ein eigener Payload-Typ statt eines nackten `Post!` gibt Raum, später etwa ein Fehler- oder Metadatenfeld zu ergänzen, ohne die Rückgabe umzubauen. Ein bisschen mehr Struktur am Anfang, dafür jahrelange additive Bewegungsfreiheit.\n\n## Enums vorsichtig erweitern\n\nZurück zu der Falle, die ich bei den sicheren Änderungen offengelassen habe. Einen Enum-Wert *hinzuzufügen* ist auf der Serverseite additiv – das Schema wird nur reicher. Der Bruch passiert woanders, nämlich im Client-Code.\n\nViele Clients behandeln Enum-Werte in einem `switch` oder einer `if`-Kette und decken genau die Werte ab, die es beim Bau gab. Kommt ein neuer Wert über die Leitung, fällt so ein Client in kein Muster – im besten Fall zeigt er nichts an, im schlechteren wirft er einen Fehler. Aus einer sauber-additiven Schema-Änderung wird so ein realer Bruch beim Nutzer.\n\nDie Lösung liegt nicht im Schema, sondern in der Client-Disziplin: Jeder Verbraucher eines Enums sollte einen Default- oder Fallback-Zweig für unbekannte Werte haben. Genau darauf weisen die GraphQL Best Practices ausdrücklich hin – Clients sollen sich so verhalten, dass ein künftiger, heute noch unbekannter Enum-Wert nichts zum Absturz bringt. Wer das von Anfang an einplant, darf Enums später bedenkenlos erweitern.\n\n## Eine Feld-Migration Schritt für Schritt\n\nFühren wir alles an dem Beispiel zusammen, das oben schon anklang: `fullName` soll `displayName` weichen. So läuft die Migration sauber ab, ohne dass zu irgendeinem Zeitpunkt ein Client bricht.\n\n```mermaid\nflowchart TB\n  S1[\"1 – displayName additiv<br/>hinzufügen\"] --> S2[\"2 – fullName mit<br/>@deprecated markieren\"]\n  S2 --> S3[\"3 – Clients migrieren<br/>(Frist läuft)\"]\n  S3 --> S4[\"4 – fullName entfernen,<br/>wenn niemand mehr fragt\"]\n```\n\nSchritt eins, hinzufügen: Ich lege `displayName` als neues Feld an. Rein additiv, niemand ist betroffen. Bestehende Clients fragen weiter `fullName`, neue können ab sofort `displayName` nehmen.\n\nSchritt zwei, deprecaten: Ich markiere `fullName` mit einem `@deprecated` und einem `reason`, der auf `displayName` und die geplante Frist verweist. Ab jetzt sehen alle Client-Teams über ihr Tooling, dass das alte Feld ausläuft – aber es funktioniert weiter.\n\nEntscheidend ist die Übergangszeit: Der Resolver liefert *beide* Felder korrekt.\n\n```js\nconst resolvers = {\n  User: {\n    // legacy field – kept working until the deprecation window closes\n    fullName: (user) => user.displayName,\n    displayName: (user) => user.displayName,\n  },\n};\n```\n\nSchritt drei, migrieren: Die Client-Teams stellen in ihrem eigenen Takt auf `displayName` um. Wie lange das dauert, hängt vom langsamsten relevanten Client ab – bei einer Mobil-App oft Monate, weil alte Versionen im Feld bleiben. Eine Schema-Registry oder Traffic-Analysen zeigen, ob `fullName` überhaupt noch abgefragt wird.\n\nSchritt vier, entfernen: Erst wenn die Frist abgelaufen *und* nachweislich kein Traffic mehr auf `fullName` liegt, entferne ich Feld und Resolver. Jetzt, und keinen Moment früher, wird aus dem Breaking Change ein Nicht-Event, weil niemand mehr da ist, der bricht.\n\n## Ein Sicherheitsnetz in der CI\n\nAll diese Regeln im Kopf zu behalten, ist die eine Sache. Sie bei jedem Merge zuverlässig einzuhalten, während mehrere Leute am Schema arbeiten, die andere. Deshalb gehört die Prüfung nicht in den Kopf, sondern in die Pipeline.\n\nEin Werkzeug wie graphql-inspector vergleicht das Schema eines Pull Requests mit dem aktuell veröffentlichten und klassifiziert jede Differenz – additiv, gefährlich oder brechend. Findet es einen Breaking Change, kann es den Build rot färben, bevor irgendetwas gemerged wird. Ein entferntes Feld, ein non-null gewordenes Argument, ein verschwundener Enum-Wert fällt so schon im Review auf, nicht erst, wenn draußen ein Client kaputtgeht. Wer das Schema zusätzlich in einer Registry führt, kann die Prüfung sogar gegen den real beobachteten Traffic laufen lassen: Ein „Breaking Change“ an einem Feld, das seit Monaten niemand mehr abfragt, ist eben doch keiner – und die Migration von oben lässt sich exakt an dieser Datenlage festmachen.\n\n## Gepflegt, nicht neu geschnitten\n\nEin GraphQL-Schema entwickelt sich anders als eine REST-API. Man setzt nicht alle paar Jahre ein `/v2` daneben und migriert alles auf einmal, sondern man pflegt einen einzigen Vertrag über seine ganze Lebenszeit. Das Wachstum ist additiv: neue Felder, neue Typen, neue optionale Argumente kommen laufend dazu, ohne dass jemand es merkt. Und wo doch etwas verschwinden muss, ersetzt disziplinierte Deprecation den harten Schnitt – markieren, Frist geben, migrieren lassen, dann entfernen.\n\nDas ist weniger spektakulär als ein großer Versionssprung, und genau das ist der Punkt. Ein gutes Schema fühlt sich für seine Clients an wie etwas, das einfach immer da war und nie weh getan hat. Diese Ruhe ist kein Zufall – sie ist das Ergebnis von ein paar Regeln, konsequent angewandt, und einem CI-Check, der über ihre Einhaltung wacht.\n\n## Weiterführende Quellen\n\n- Repository introduction-graphql (Kapitel schema, resolver): https://github.com/mikebild/introduction-graphql\n- GraphQL, Schema und Typen: https://graphql.org/learn/schema/\n- GraphQL Best Practices (Versionierung, Nullability, Deprecation): https://graphql.org/learn/best-practices/\n- graphql-inspector (Schema-Checks in der CI): https://github.com/kamilkisiela/graphql-inspector"},{"locale":"de","translation_key":"step-functions-serverless-workflows","slug":"step-functions-serverless-workflows","title":"Serverless-Workflows mit AWS Step Functions","summary":"Step Functions machen aus verschachtelten Lambda-Handlern eine deklarative State Machine: sichtbarer Ablauf, explizite Retry- und Catch-Pfade, Standard oder Express.","tags":["Software","AWS","Cloud"],"published_at":"2021-03-23T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/step-functions-serverless-workflows/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0f9d70957a7d9361faca7f6e5e9adfc29070e001817695edc404c111e7ed16cb/step-functions-serverless-workflows-vorlesen.mp3","audio_duration_secs":845,"text":"Die erste Funktion validiert und ruft die zweite, die berechnet und ruft die dritte, die benachrichtigt. Auf dem Whiteboard ergibt das eine saubere Kette. Zur Laufzeit bleibt davon nur eine Folge von Aufrufen übrig, die niemand von außen anhalten, prüfen oder wieder aufnehmen kann. Wer die Lambda-Functions in den Handlern aneinanderhängt, hat den Ablauf dem Betrieb entzogen: Bleibt eine Bestellung hängen, beginnt die Suche in den Logs.\n\nAWS Step Functions dreht das Verhältnis um. Statt den Ablauf in verschachtelten Handlern zu verstecken, beschreibt man ihn deklarativ als State Machine – und der State wird sichtbar, statt in Aufruf-Ketten zu verschwinden.\n\nEine State Machine macht den Ablauf als Reihe benannter States und ausdrücklich behandelter Ergebnisse sichtbar.\n\n:::process{title=\"Ein expliziter Workflow\" role=\"primary\" preferredPattern=\"connected-process\"}\n1. Eingabe · fachlichen Auftrag und benötigten Kontext übernehmen\n2. Task · genau eine begrenzte Fähigkeit ausführen\n3. Choice · anhand eines Ergebnisses den nächsten zulässigen Pfad wählen\n4. Parallel · unabhängige Zweige nur bei echter Concurrency starten\n5. Catch · erwartbare Fehler in einen benannten Behandlungspfad führen\n6. Abschluss · Erfolg oder Scheitern als eindeutigen Endzustand festhalten\n:::\n\nDie Darstellung behauptet keinen linearen Happy Path. Verzweigung und Error Handling bleiben Teil des Modells, statt in verstreuten Funktionsaufrufen zu verschwinden.\n\n## Das Problem: Orchestrierung im Code\n\nSchauen wir uns zuerst an, wie die Reflex-Lösung typischerweise aussieht. Eine Lambda-Function, die eine Bestellung verarbeitet, könnte intern so orchestrieren:\n\n```js\nexports.handler = async (event) => {\n  const order = await validateOrder(event);\n  if (!order.valid) {\n    await notifyFailure(order);\n    return { status: \"rejected\" };\n  }\n\n  if (order.amount > 1000) {\n    await requestManualReview(order);\n  } else {\n    await autoApprove(order);\n  }\n\n  const [inventory, payment] = await Promise.all([\n    reserveInventory(order),\n    chargePayment(order),\n  ]);\n\n  return finalize(order, inventory, payment);\n};\n```\n\nAuf den ersten Blick ist das lesbar. Aber jeder dieser Aufrufe kann fehlschlagen, und sobald man Robustheit will, wächst der Code. Was passiert, wenn `chargePayment` einen transienten Fehler wirft? Dann braucht man einen Retry mit Backoff. Was, wenn `reserveInventory` klappt, aber `chargePayment` endgültig scheitert? Dann muss die Reservierung wieder zurückgerollt werden. Nach und nach füllt sich der Handler mit try/catch-Blöcken, Zählern und Timeout-Logik. Der eigentliche fachliche Ablauf – validieren, entscheiden, parallel ausführen, abschließen – verschwindet unter der Error Handling.\n\nUnd der unangenehmste Teil kommt im Betrieb. Wenn eine Bestellung stecken bleibt, gibt es keinen Ort, an dem man den State ablesen kann. Man hat CloudWatch-Logs und muss rekonstruieren, wie weit der Prozess gekommen ist. Bei einer einzigen Funktion geht das noch. Bei fünf Funktionen, die sich gegenseitig aufrufen, wird es zur Detektivarbeit. Die Koordination mehrerer Funktionen gehört zu den Grenzen, an die man mit reinem Code schnell stößt.\n\n## Die Idee: der Ablauf als State Machine\n\nStep Functions verlagert die Orchestrierung aus dem Code heraus in eine deklarative Beschreibung. Diese Beschreibung ist in der **Amazon States Language** (ASL) formuliert, einem JSON-Format. Man definiert States, deren Übergänge und die Fehlerpfade – die einzelnen Lambda-Functions bleiben klein und machen jeweils genau eine Sache.\n\nDer entscheidende Gewinn: Der Ablauf steht nicht mehr in einem Handler, sondern liegt als eigenständiges Artefakt vor, das die Konsole grafisch darstellt. Man sieht bei jeder Ausführung, in welchem State sie sich befindet, welcher Übergang genommen wurde und wo etwas fehlgeschlagen ist.\n\nEine ASL-Definition hat auf oberster Ebene wenige Pflichtfelder. `StartAt` benennt den Einstiegszustand, `States` enthält die States als Objekt. Jeder State hat einen `Type` und verweist mit `Next` auf den Folgezustand oder markiert sich mit `\"End\": true` als terminal.\n\nBevor wir in eine konkrete Definition einsteigen, hier die acht State-Typen, die 2021 zur Verfügung stehen – das ist der komplette Baukasten:\n\n- `Task` führt Arbeit aus, typischerweise eine Lambda-Function.\n- `Choice` verzweigt anhand von Bedingungen, das if/else der State Machine.\n- `Parallel` führt mehrere Zweige gleichzeitig aus und sammelt deren Ergebnisse.\n- `Map` wendet einen Ablauf auf jedes Element einer Liste an, 2021 nur als Inline-Variante.\n- `Pass` reicht Eingabe durch oder injiziert feste Daten, nützlich zum Testen.\n- `Wait` pausiert für eine Dauer oder bis zu einem Zeitpunkt.\n- `Succeed` beendet die Ausführung erfolgreich.\n- `Fail` beendet die Ausführung mit einem Fehler.\n\nMit diesen acht Bausteinen lassen sich erstaunlich viele Prozesse abbilden, ohne eine Zeile Orchestrierungscode zu schreiben.\n\n## Ein Task mit Retry und Catch\n\nFangen wir mit dem Kern an: einem Task-State, der eine Lambda-Function aufruft und Fehler deklarativ behandelt. Das ist der Teil, der im Handler-Ansatz am meisten Code kostet – und in ASL zu ein paar Feldern schrumpft.\n\n```json\n{\n  \"Comment\": \"Order processing workflow\",\n  \"StartAt\": \"ValidateOrder\",\n  \"States\": {\n    \"ValidateOrder\": {\n      \"Type\": \"Task\",\n      \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:ValidateOrder\",\n      \"Retry\": [\n        {\n          \"ErrorEquals\": [\"Lambda.ServiceException\", \"Lambda.SdkClientException\"],\n          \"IntervalSeconds\": 2,\n          \"MaxAttempts\": 3,\n          \"BackoffRate\": 2.0\n        }\n      ],\n      \"Catch\": [\n        {\n          \"ErrorEquals\": [\"States.ALL\"],\n          \"Next\": \"NotifyFailure\"\n        }\n      ],\n      \"Next\": \"CheckAmount\"\n    },\n    \"NotifyFailure\": {\n      \"Type\": \"Task\",\n      \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:NotifyFailure\",\n      \"End\": true\n    }\n  }\n}\n```\n\nHier steckt viel drin, deshalb der Reihe nach. Der `Retry`-Block ist ein Array von Retrier-Objekten. `ErrorEquals` benennt, auf welche Fehler dieser Retrier reagiert – hier zwei transiente Lambda-Service-Fehler, die man nicht dem fachlichen Code anlasten sollte. `IntervalSeconds` legt die erste Wartezeit fest, `BackoffRate` multipliziert sie bei jedem weiteren Versuch (Default 2.0), `MaxAttempts` deckelt die Wiederholungen (Default 3). Ohne explizite Angabe würde AWS diese Defaults verwenden.\n\nDer `Catch`-Block greift, wenn die Retries erschöpft sind oder ein Fehler auftritt, den kein Retrier abdeckt. Jeder Catcher braucht `ErrorEquals` und ein `Next`, das den Übergang beschreibt. `States.ALL` ist der Auffang-Fehler, der alles matcht – und genau deshalb gibt es zwei Regeln, die man kennen muss: `States.ALL` muss allein in seinem `ErrorEquals` stehen und als letzter Eintrag kommen. Steht danach noch ein weiterer Retrier oder Catcher, ist die Definition ungültig.\n\nEin wichtiges Detail bei der Reihenfolge: Erst werden die passenden Retrier abgearbeitet, und nur wenn keiner mehr greift, wird der Catcher-Übergang genommen. Retry vor Catch, immer in dieser Ordnung. Das ist genau das Verhalten, das man im Code mühsam von Hand nachbauen würde – hier ist es Konvention der Sprache.\n\nEin Punkt, der regelmäßig für Diskussion sorgt: Nicht jeder `States.`-Fehler wird von allem gefangen. `States.TaskFailed` etwa matcht so ziemlich alles außer `States.Timeout` – wer also nur auf `States.TaskFailed` retryt und eine Zeitüberschreitung erwartet, wird überrascht. Und `States.DataLimitExceeded`, der bei Überschreitung des Payload-Limits (2021 sind das 256 KB zwischen den States) auftritt, wird von `States.ALL` nicht gefangen. Solche Fehler muss man bewusst vermeiden, nicht abfangen.\n\n## Verzweigen mit Choice\n\nNach der Validierung soll der Prozess entscheiden. Kleine Bestellungen werden automatisch freigegeben, große gehen in die manuelle Prüfung. Im Handler war das ein `if`, in ASL ist es ein Choice-State.\n\n```json\n{\n  \"CheckAmount\": {\n    \"Type\": \"Choice\",\n    \"Choices\": [\n      {\n        \"Variable\": \"$.amount\",\n        \"NumericGreaterThan\": 1000,\n        \"Next\": \"ManualReview\"\n      }\n    ],\n    \"Default\": \"FanOut\"\n  },\n  \"ManualReview\": {\n    \"Type\": \"Task\",\n    \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:RequestManualReview\",\n    \"Next\": \"FanOut\"\n  }\n}\n```\n\nDer Choice-State enthält ein `Choices`-Array. Jede Regel besteht aus einer `Variable` (ein Pfad in die aktuelle Eingabe, hier `$.amount`), einem Vergleichsoperator wie `NumericGreaterThan`, `StringEquals` oder `BooleanEquals`, und einem `Next`. Man kann Bedingungen auch mit `And`, `Or` und `Not` verschachteln. Trifft keine Regel zu, greift `Default`.\n\nGenau dieses `Default` ist ein häufiger Stolperstein. Choice hat kein `End` und keinen impliziten Ausgang. Ohne `Default` und ohne passenden Treffer läuft die Ausführung in einen `States.NoChoiceMatched`-Fehler. Ich empfehle deshalb, `Default` immer zu setzen, selbst wenn man theoretisch alle Fälle abgedeckt glaubt.\n\n## Parallel: mehrere Zweige gleichzeitig\n\nFür Reservierung und Zahlung, die unabhängig voneinander laufen, gibt es den Parallel-State. Er führt mehrere `Branches` gleichzeitig aus – jeder Branch ist selbst eine kleine State Machine mit eigenem `StartAt` und `States`.\n\n```json\n{\n  \"FanOut\": {\n    \"Type\": \"Parallel\",\n    \"Branches\": [\n      {\n        \"StartAt\": \"ReserveInventory\",\n        \"States\": {\n          \"ReserveInventory\": {\n            \"Type\": \"Task\",\n            \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:ReserveInventory\",\n            \"End\": true\n          }\n        }\n      },\n      {\n        \"StartAt\": \"ChargePayment\",\n        \"States\": {\n          \"ChargePayment\": {\n            \"Type\": \"Task\",\n            \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:ChargePayment\",\n            \"End\": true\n          }\n        }\n      }\n    ],\n    \"Next\": \"Finalize\"\n  },\n  \"Finalize\": {\n    \"Type\": \"Task\",\n    \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:Finalize\",\n    \"End\": true\n  }\n}\n```\n\nDer Output eines Parallel-States ist ein geordnetes Array – ein Eintrag pro Branch, in der Reihenfolge der Definition. `Finalize` bekommt also beide Ergebnisse gebündelt übergeben. Auch Parallel unterstützt `Retry` und `Catch` auf Zustandsebene, ebenso der Map-State, wenn man eine Liste iterativ abarbeitet.\n\n## Wie Daten zwischen den States fließen\n\nSobald man das erste Mal ernsthaft mit ASL arbeitet, stolpert man über eine Frage, die im Handler-Code nie auftaucht: Was genau bekommt der nächste State als Eingabe? In einer JavaScript-Funktion reicht man Werte einfach als Argumente weiter. In einer State Machine ist die Weitergabe geregelt, und die Regeln muss man kennen, sonst gehen Daten unbemerkt verloren.\n\nJeder State bekommt ein JSON-Objekt als Eingabe und gibt ein JSON-Objekt als Ausgabe. Vier Felder steuern diesen Fluss. `InputPath` filtert, welcher Ausschnitt der Eingabe überhaupt beim State ankommt. `Parameters` baut daraus das Objekt, das die Lambda-Function tatsächlich erhält. `ResultPath` bestimmt, an welcher Stelle das Ergebnis in die Eingabe eingefügt wird. `OutputPath` filtert zuletzt, was an den Folgezustand weitergereicht wird.\n\nDer häufigste Stolperstein steckt in `ResultPath`. Ohne Angabe steht der Default auf `$`, und das heißt: Das Ergebnis des Tasks ersetzt die komplette Eingabe. Wer nach `ValidateOrder` im Choice-State noch auf `$.amount` zugreifen will, muss das Ergebnis mit `\"ResultPath\": \"$.validation\"` unter einen eigenen Schlüssel legen, sonst ist die ursprüngliche Bestellung weg. Genau dieser Default ist der Grund, warum ein Choice-State danach ins Leere greift: Der Schlüssel, den die Bedingung erwartet, existiert nach dem Task gar nicht mehr. Solche Fehler wirken wie eine falsche Bedingung, sind in Wahrheit aber ein Datenfluss-Problem.\n\n## Der Ablauf als Bild\n\nDas eigentliche Argument für Step Functions ist die Sichtbarkeit. Was ich oben in JSON beschrieben habe, stellt die Konsole als Graph dar. Und genau diese Struktur lässt sich als Diagramm nachzeichnen:\n\n```mermaid\nflowchart TD\n    Start([Start]) --> Validate[ValidateOrder<br/>Task]\n    Validate --> Check{CheckAmount<br/>Choice}\n    Check -->|amount > 1000| Review[ManualReview<br/>Task]\n    Check -->|else| FanOut[FanOut<br/>Parallel]\n    Review --> FanOut\n    FanOut --> Reserve[ReserveInventory]\n    FanOut --> Charge[ChargePayment]\n    Reserve --> Finalize[Finalize<br/>Task]\n    Charge --> Finalize\n    Finalize --> Done([Succeed])\n    Validate -. \"Catch States.ALL\" .-> Notify[NotifyFailure<br/>Task]\n```\n\nDie gestrichelte Kante ist der Fehlerpfad, den der Catcher beschreibt. Bei einer laufenden Ausführung färbt die Konsole die durchlaufenen States ein, sodass man auf einen Blick sieht, wo der Prozess steht oder wo er hängengeblieben ist. Diesen Blick habe ich im Handler-Ansatz nie – und das ist der Unterschied zwischen „wir müssen die Logs durchsuchen“ und „schau einfach in die Ausführung“.\n\n## Standard oder Express\n\nBei der Erstellung einer State Machine muss man sich für einen Typ entscheiden, und diese Entscheidung ist danach fix. Wer sich vertut, baut eine neue State Machine. Deshalb lohnt es sich, die beiden Typen früh zu verstehen.\n\n**Standard** ist der Typ für lang laufende, auditierbare Prozesse. Eine Ausführung darf bis zu ein Jahr dauern, die Ausführung ist exactly-once, und die vollständige Historie steht bis zu 90 Tage über die API bereit. Abgerechnet wird pro State Transition. Wichtig für die Kostenrechnung: Jeder Retry-Versuch ist ein eigener Übergang und zählt mit. Das visuelle Debugging in der Konsole gibt es nur bei Standard.\n\n**Express** ist für hochfrequente, kurze Abläufe gedacht. Eine Ausführung darf höchstens fünf Minuten laufen. Asynchron ausgeführt ist die Garantie at-least-once, synchron über `StartSyncExecution` (verfügbar seit November 2020) at-most-once. Abgerechnet wird nach Anzahl der Ausführungen sowie Dauer und Speicher. Eine Ausführungshistorie in der Konsole gibt es nicht – man ist auf CloudWatch Logs angewiesen, und dafür muss Logging aktiv sein.\n\nDie Trennlinie verläuft entlang der Fachlichkeit: Bestellprozesse, Freigabe-Workflows, alles mit menschlicher Beteiligung oder Prüfpflicht gehört zu Standard. Event-Verarbeitung mit hohem Durchsatz, kurze Transformationen, IoT-Ingestion – das ist Express-Territorium. Der idempotente Charakter kurzer Express-Abläufe passt zur at-least-once-Semantik, während man bei einem Bezahlvorgang die exactly-once-Garantie von Standard haben will.\n\n## Wann Step Functions – und wann nicht\n\nIch rate nicht dazu, jede Aneinanderreihung von zwei Funktionen zur State Machine zu machen. Wenn eine Funktion eine andere aufruft und das war es, ist ein direkter Aufruf oder ein Event völlig in Ordnung. Der Aufwand von Step Functions zahlt sich ab dem Punkt aus, an dem es echte Ablauflogik gibt: Verzweigungen, Parallelität, Retries mit unterschiedlichen Strategien, Kompensation bei Teilfehlern, oder wenn man den State für den Betrieb sichtbar braucht.\n\nEin zweites Kriterium ist die Error Handling. Sobald man merkt, dass der Orchestrierungs-Handler mehr try/catch als Fachlogik enthält, ist das ein starkes Signal. Diese Behandlung deklarativ auszulagern macht den Code der einzelnen Funktionen wieder klein und lesbar – jede Funktion konzentriert sich auf ihre eine Aufgabe, die Koordination liegt in der State Machine.\n\nUnd Step Functions ersetzt nicht die anderen Serverless-Bausteine, sondern koordiniert sie. Die Lambda-Functions bleiben, die Datenbank bleibt, die Authentifizierung – etwa mit [Cognito User Pools](https://www.mikebild.dev/de/blog/cognito-userpool-auth-serverless/) – bleibt an ihrem Platz. Step Functions ist die Schicht darüber, die den Ablauf beschreibt.\n\n## Fazit\n\nDer Weg von verschachtelten Handlern zu einer State Machine ist vor allem ein Wechsel der Perspektive. Statt den Ablauf im Code zu verstecken, macht man ihn zum Artefakt: `StartAt`, ein paar States, `Next`-Übergänge, und die Fehlerpfade als `Retry` und `Catch` direkt am State. Die einzelnen Funktionen werden dadurch kleiner, weil sie die Koordination nicht mehr tragen müssen, und der Betrieb wird ruhiger, weil der State jeder Ausführung sichtbar ist.\n\nDie acht State-Typen sind schnell gelernt, und mit Task, Choice und Parallel deckt man bereits die meisten realen Abläufe ab. Mit der Reihenfolge von Retry und Catch im Hinterkopf, einem gesetzten `Default` bei Choice und einer bewussten Wahl zwischen Standard und Express ist das Fundament beisammen. Überzeugt hat in den Projekten, an denen ich beteiligt war, ohnehin erst die eingefärbte Ausführung in der Konsole. Ab da liegt der Ablauf nicht mehr in Logs vergraben, sondern ist ein Bild, auf das alle schauen können.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-aws-serverless.html\n- Repository zur Serverless-Schulung mit den ASL-Beispielen dieses Artikels\n- [AWS Step Functions – States (States)](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-states.html)\n- [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html)\n- [Standard vs. Express Workflows](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-standard-vs-express.html)\n- [Error Handling: Retry und Catch](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-error-handling.html)\n- [Task-State](https://docs.aws.amazon.com/step-functions/latest/dg/state-task.html)\n- [Choice-State](https://docs.aws.amazon.com/step-functions/latest/dg/state-choice.html)\n- [Tutorial: State Machine mit Lambda](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-creating-lambda-state-machine.html)"},{"locale":"de","translation_key":"event-sourcing-der-event-store-als-logbuch","slug":"event-sourcing-der-event-store-als-logbuch","title":"Event Sourcing: der Event-Store als Logbuch","summary":"Event Sourcing speichert nicht den aktuellen Zustand, sondern die Folge der Events als Wahrheitsquelle: der Event-Store als Logbuch, der Zustand als Faltungsergebnis. Nutzen, ehrliche Kosten und die Abgrenzung zu CQRS.","tags":["Software","Architektur"],"published_at":"2021-02-23T10:00:00+00:00","updated_at":"2026-07-13T08:40:37.248914+00:00","url":"https://www.mikebild.dev/de/blog/event-sourcing-der-event-store-als-logbuch/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ec46ce169f74038ce2f0721ec4e361598d785016db0e8905b94180ef87efd053/event-sourcing-der-event-store-als-logbuch-vorlesen.mp3","audio_duration_secs":729,"text":"```sql\nUPDATE accounts SET balance = 300 WHERE id = 42;\n```\n\nNach diesem Statement steht in der Datenbank, dass das Konto 300 Euro hat. Der vorherige Wert ist überschrieben, und mit ihm die Antwort auf die Frage, wie die 300 zustande kamen: eine Einzahlung über 300, oder zwei über 200 plus eine Abhebung über 100? Die Zeile weiß es nicht mehr. Jede Buchung frisst ihren Vorgänger, und das Feld `balance` behält nur das Ergebnis.\n\nEvent Sourcing dreht diese Reihenfolge um. Nicht der aktuelle Zustand ist die Wahrheit, sondern die Folge der Events, die ihn erzeugt haben. Der Event-Store ist ein Logbuch – ein append-only Log, an das nur angehängt wird und in dem nichts geändert oder gelöscht wird. Der aktuelle Zustand ist dann kein gespeichertes Faktum mehr, sondern ein abgeleitetes Artefakt: Man faltet die Events und bekommt den Zustand heraus.\n\nGenannt wird Event Sourcing fast immer im selben Atemzug mit CQRS, und genau dort entstehen die hartnäckigsten Missverständnisse. Deshalb zuerst der Kern, danach die Grenzen – bewusst scharf gezogen.\n\n## Der Zustand ist ein Left Fold\n\nMartin Fowler beschreibt Event Sourcing als „Capture all changes to an application state as a sequence of events.“ Jede Zustandsänderung wird als Event festgehalten, und der Anwendungszustand ist damit vollständig aus dem Event-Log ableitbar. Man kann den gecachten Zustand komplett wegwerfen und ihn durch erneutes Abspielen aller Events auf einem leeren Anfangszustand rekonstruieren.\n\nGreg Young hat dafür die didaktisch schönste Formel geprägt: „Current state is a left fold of previous behaviours.“ Der Zustand ist keine Tabelle, sondern das Ergebnis einer Faltung über die Event-Folge. In Code, den jeder sofort liest:\n\n```ts\ntype Event =\n  | { type: \"AccountOpened\"; owner: string }\n  | { type: \"MoneyDeposited\"; amount: number }\n  | { type: \"MoneyWithdrawn\"; amount: number };\n\ntype Account = { owner: string; balance: number };\n\nconst apply = (state: Account, event: Event): Account => {\n  switch (event.type) {\n    case \"AccountOpened\":\n      return { owner: event.owner, balance: 0 };\n    case \"MoneyDeposited\":\n      return { ...state, balance: state.balance + event.amount };\n    case \"MoneyWithdrawn\":\n      return { ...state, balance: state.balance - event.amount };\n  }\n};\n\nconst fold = (events: Event[]): Account =>\n  events.reduce(apply, { owner: \"\", balance: 0 });\n```\n\nDas ist der ganze Trick, und es ist bewusst wenig. `apply` nimmt einen Zustand und ein Event und liefert den nächsten Zustand. `fold` läuft mit `reduce` über den Stream und ist nichts anderes als ein `left fold` mit `apply` als Faltungsfunktion. Der Code hier ist illustrativ – kein lauffähiges Repository, sondern die Idee auf das Wesentliche reduziert.\n\nEin paar Eigenschaften stecken schon in diesen Zeilen. Die Events sind in der Vergangenheitsform benannt – `AccountOpened`, `MoneyDeposited`. Sie sind Fakten, die bereits geschehen sind, und deshalb immutable: Ein Event wird nie geändert und nie gelöscht, es kommt nur ein neues hinzu. Und `apply` hat keine Side Effects; es ist eine Pure Function vom alten in den neuen Zustand. Das ist kein Zufall, sondern die Bedingung dafür, dass Replay überhaupt verlässlich funktioniert.\n\nDamit läuft alles auf dieselbe Trennlinie hinaus wie in [Commands, Events und Queries trennen](https://www.mikebild.dev/de/blog/commands-events-queries-trennen/): Ein Command ist eine Absicht, die scheitern darf; ein Event ist das, was daraus tatsächlich geworden ist und nicht mehr scheitern kann. Event Sourcing speichert konsequent die zweite Sorte.\n\n## Das Logbuch als Wahrheitsquelle\n\nSchaut man auf den Fluss, ergibt sich ein einfaches Bild. Ein Command trifft ein, das Aggregat entscheidet und erzeugt daraus ein oder mehrere Events, die an das Log angehängt werden. Der Zustand entsteht danach durch Falten.\n\n```mermaid\nflowchart LR\n  C[Command] --> A[Aggregate decides]\n  A --> E[New Event]\n  E --> L[(Event Store<br/>append-only)]\n  L --> F[fold / apply]\n  F --> S[Current State]\n```\n\nWichtig an diesem Bild ist die Richtung. Der Command produziert ein Event, das Log wächst nur nach hinten, und der Zustand hängt am Ende der Kette. Fällt der Zustand weg – Cache verloren, neuer Service, geänderte Berechnung – lässt er sich jederzeit aus dem Log wiederherstellen. Das Log ist maßgeblich, der Zustand ist ableitbar.\n\nDaraus folgen drei Vorteile, die Event Sourcing attraktiv machen und die alle an derselben Eigenschaft hängen: Das Log bleibt vollständig erhalten.\n\n- Ein vollständiger Audit-Trail entsteht gratis. Nicht als nachgelagertes Protokoll, sondern weil das Event-Log der Zustand ist. Es beschreibt nicht nur, was passiert ist – es *ist* das, was passiert ist.\n- Temporale Queries werden möglich. Weil jeder frühere Zustand ein Zwischenergebnis der Faltung ist, kann ich fragen: Wie sah das Konto am 3. Januar aus? Ich falte einfach bis zu dem Event, das an dem Tag geschrieben wurde.\n- Projections lassen sich neu aufbauen. Ein Read Model, das ich heute nicht habe, kann ich morgen einführen, indem ich die vorhandenen Events erneut durchlaufe. Historie, die bei zustandsbasierter Speicherung längst überschrieben wäre, steht hier vollständig zur Verfügung.\n\nDer dritte Punkt wiegt in der Praxis am schwersten: Beim Schreiben muss niemand vorhersehen, welche Sichten später gebraucht werden.\n\n## Projections: Read Models aus dem Stream\n\nWenn der Zustand ohnehin abgeleitet ist, dann sind es beliebig viele Sichten auf denselben Stream. Genau das sind Projections, und sie sind der natürliche Übergang zu den [Read Models sind Projections](https://www.mikebild.dev/de/blog/read-models-sind-projektionen/): abgeleitete, für Lesezwecke optimierte Modelle, die wegwerfbar und jederzeit neu aufbaubar sind.\n\n```ts\ntype BalanceView = Record<string, number>;\n\nconst project = (events: Event[]): BalanceView =>\n  events.reduce((view, event) => {\n    switch (event.type) {\n      case \"AccountOpened\":\n        return { ...view, [event.owner]: 0 };\n      case \"MoneyDeposited\":\n        // update the read model per event\n        return view;\n      case \"MoneyWithdrawn\":\n        return view;\n    }\n  }, {} as BalanceView);\n```\n\nAuch `project` ist ein Fold, nur mit einem anderen Zielmodell. Die eine Faltung ergibt das Aggregat für Entscheidungen, die andere eine flache Übersicht für die Leseseite. Aus demselben Log lassen sich eine Kontoübersicht, ein monatlicher Umsatzbericht und eine Betrugserkennung ableiten – drei Projections, drei Faltungen, ein Stream.\n\n```mermaid\nflowchart LR\n  L[(Event Store<br/>append-only)] -->|project| A[Read Model A<br/>balances]\n  L -->|project| B[Read Model B<br/>monthly report]\n  L -->|project| C[Read Model C<br/>fraud signals]\n```\n\nZwei Dinge muss man hier ehrlich benennen. Erstens sind diese Read Models nur eventual consistent – sie hinken dem Write-Log hinterher, weil die Projection nach dem Anhängen läuft. Wer sofortige Konsistenz zwischen Schreiben und Lesen braucht, bekommt sie hier nicht geschenkt. Zweitens dürfen Projections keine externen Side Effects auslösen, und das führt direkt zum ersten ernsten Fallstrick.\n\n## Replay hat keine Unschuld\n\nFowler weist auf ein Detail hin, das in Demos nie auffällt und in Produktion teuer wird: Externe Systeme unterscheiden nicht zwischen echtem Verarbeiten und Replay. Wenn ich ein Read Model neu aufbaue und dabei die Events noch einmal durchlaufe, sieht ein Gateway, das beim ersten Mal eine E-Mail verschickt oder eine Zahlung ausgelöst hat, keinen Unterschied. Es würde die E-Mail erneut senden.\n\nDeshalb gilt die Regel: `apply` und `project` sind reine Faltungen ohne Side Effects. Alles, was nach außen wirkt – Mails, Zahlungen, Benachrichtigungen –, gehört nicht in die Faltung, sondern hinter Gateways, die einen Replay-Modus kennen und ihre Effekte dann unterdrücken. Wer das nicht trennt, baut sich beim ersten Rebuild eine Katastrophe.\n\n## Snapshots: der gemerkte Fold\n\nBleibt die Frage nach der Performance. Ein Konto mit zwanzig Buchungen faltet sich in Mikrosekunden. Ein Aggregat mit zweihunderttausend Events tut das nicht mehr bei jedem Zugriff. Die Antwort heißt Snapshot, und Greg Young hat sie so präzise gefasst, dass sich seine Formulierung kaum verbessern lässt: „A snapshot is a memoization of your left fold.“\n\nEin Snapshot ist eine gespeicherte Momentaufnahme des Faltungsergebnisses bei Event N. Man faltet dann ab dem Snapshot weiter, statt bei Event 0 anzufangen.\n\n```ts\ntype Snapshot = { version: number; state: Account };\n\nconst rebuild = (snapshot: Snapshot, newerEvents: Event[]): Account =>\n  newerEvents.reduce(apply, snapshot.state);\n// snapshot = memorized left fold at version N\n```\n\nEntscheidend ist dabei: Ein Snapshot ist eine reine Performance-Optimierung, keine neue Wahrheitsquelle. Weil die Events immutable sind, kann ein Snapshot nie ungültig werden – die Vergangenheit, aus der er gefaltet wurde, ändert sich ja nicht. Fällt ein Snapshot weg oder wird die Faltungslogik geändert, wirft man ihn weg und faltet neu von vorn. Das Log bleibt maßgeblich; der Snapshot ist nur ein Cache des Folds.\n\n## Die Abgrenzung: Event Sourcing ist nicht CQRS\n\nEvent Sourcing und CQRS werden fast immer zusammen genannt, und viele halten sie für dasselbe. Sie sind es nicht.\n\n[CQRS ist eine fachliche Grenze](https://www.mikebild.dev/de/blog/cqrs-fachliche-grenze-kein-framework/) – die Trennung von Schreibmodell und Lesemodell. Event Sourcing ist eine Persistenzstrategie – Events statt Zustand als das, was gespeichert wird. Das sind zwei verschiedene Entscheidungen auf zwei verschiedenen Achsen. Man kann CQRS ohne Event Sourcing betreiben: getrennte Schreib- und Leseseite, beide klassisch mit Zustandstabellen. Und man kann Event Sourcing ohne strenges CQRS betreiben, auch wenn die Read-Model-Projections die Trennung dann fast von selbst nahelegen.\n\nSie werden oft kombiniert, weil Event Sourcing sehr natürlich Read-Model-Projections erzeugt und CQRS genau dafür den passenden Rahmen bietet. Aber keins erzwingt das andere. Wer das trennt, trifft beide Entscheidungen bewusst statt eine im Schlepptau der anderen.\n\nUnd noch eine Abgrenzung, die in verteilten Systemen wichtig wird: Event Sourcing ist nicht Event-Driven Architecture. Event Sourcing ist Speicherung und Wahrheitsquelle innerhalb eines Aggregats. Pub/Sub-Messaging zwischen Diensten ist Integration. Ein Domain Event, das als Integrationsnachricht über einen Bus geht, ist nicht automatisch ein gespeichertes Event-Sourcing-Event. Wo beide Ebenen verschwimmen, entstehen Systeme, die nach einem Jahr niemand mehr durchschaut.\n\n## Die ehrlichen Kosten\n\nSo attraktiv das Logbuch klingt – Event Sourcing ist teuer. Dem Nutzen steht ein realer Preis gegenüber, und beide Seiten gehören nebeneinander auf den Tisch.\n\nDer Nutzen ist ein vollständiger Audit-Trail, sind temporale Queries, nachträglich einführbare Projections und eine gute fachliche Semantik durch absichtsvolle Events. Die Kosten sind die Event-Schema-Versionierung über die gesamte Lebensdauer, Replay-Performance samt Snapshot-Verwaltung, die Eventual Consistency der Read Models und eine insgesamt höhere Betriebskomplexität.\n\nDer größte Kostenblock ist die Versionierung. Events leben ewig, und ein Replay muss auch die alten Event-Versionen von vor drei Jahren noch lesen können. Ändert sich das Schema – ein Feld kommt hinzu, eine Bedeutung verschiebt sich –, brauche ich eine Strategie zum Upcasting: alte Events beim Lesen in die aktuelle Form überführen. Wer das unterschätzt, merkt beim ersten großen Rebuild, dass sein Log Events in fünf Generationen enthält, die alle noch gelesen werden wollen. Diesen Aufwand plant man von Anfang an ein oder man plant ihn schmerzhaft nach.\n\nDazu kommt Eventual Consistency – ein dauerhafter Begleiter, den kein Ticket wegdebuggt. Und Snapshots sind kein Gratiswerkzeug: zusätzliche Infrastruktur, die man verwalten, invalidieren und beim Ändern der Faltungslogik neu erzeugen muss.\n\n## Zwei Anti-Pattern, die den Nutzen zerstören\n\nZwei Fehler sehe ich so oft, dass sie einen eigenen Absatz verdienen.\n\nDer erste ist „CRUD in Verkleidung“. Wenn die Events `EntityUpdated` oder generische `FieldChanged` heißen, hat man Event Sourcing mechanisch eingebaut, aber die eigentliche Absicht weggeworfen. Ein `MoneyWithdrawn` erzählt, was fachlich geschah; ein `BalanceFieldSetTo` erzählt nur, dass irgendein Setter lief. Der ganze Wert – Intent, Audit, Semantik – steckt in der fachlichen Benennung. Generische Setter-Events sind CRUD mit mehr Zeremonie und weniger Nutzen.\n\nDer zweite ist „Event Sourcing überall“. Es ist keine Default-Persistenz. Es lohnt sich dort, wo Historie, Audit und temporale Fragen echten fachlichen Wert haben – Buchhaltung, Handel, alles mit regulatorischer Nachvollziehbarkeit. Für einen Stammdaten-CRUD-Dienst, der nur den letzten Stand braucht, ist es teurer Overhead. Die Kunst liegt darin, die Grenze zu ziehen, an der der Kontext das Logbuch wirklich rechtfertigt, und sie nicht aus Begeisterung über das ganze System zu verschieben.\n\n## Fazit\n\nEvent Sourcing verschiebt eine einzige Annahme: Nicht der Zustand ist die Wahrheit, sondern die Folge der Events, die ihn erzeugt haben. Der Event-Store wird zum Logbuch – append-only, immutable, maßgeblich –, und der Zustand fällt als Left Fold über diesen Stream heraus. Daraus wachsen Audit-Trail, temporale Queries und beliebig viele neu aufbaubare Projections, fast wie von selbst.\n\nDer Preis dafür ist real: Event-Versionierung über Jahre, Replay-Performance mit Snapshots als gemerktem Fold, Eventual Consistency und die Disziplin, Side Effects aus den Faltungen herauszuhalten. Und die wichtigste gedankliche Trennung: Event Sourcing ist eine Persistenzstrategie, CQRS eine fachliche Grenze – oft gemeinsam, nie voneinander erzwungen.\n\nWer das nüchtern gegeneinander abwägt, setzt Event Sourcing dort ein, wo die Historie den Aufwand zurückzahlt, und speichert sonst weiter guten alten Zustand. Genau diese Entscheidung – bewusst, nicht aus Mode – ist der eigentliche Gewinn.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html\n- Martin Fowler, *Event Sourcing*: https://martinfowler.com/eaaDev/EventSourcing.html\n- Martin Fowler, *Retroactive Event* (zu Korrekturen durch neue Events): https://martinfowler.com/eaaDev/RetroactiveEvent.html\n- Greg Young, Vortrag *CQRS and Event Sourcing*, Code on the Beach 2014 (Left Fold, Snapshots als „memorized fold“)\n- Greg Young, *Functional Domain Models and Event Sourcing* (2012)\n- Vaughn Vernon, *Implementing Domain-Driven Design* (2013) – Kapitel zu Event Sourcing und CQRS\n- Mike Bild, Vortragsmaterial *CQRS + Event Sourcing* (SlideShare) – Autoren-Material, aus dem dieser Artikel schöpft"},{"locale":"de","translation_key":"flask-apps-testen","slug":"flask-apps-testen","title":"Flask-Apps testen: der Test-Client und zuverlässige Endpoints","summary":"Wie ich Flask-Endpoints teste: mit app.test_client() ohne laufenden Server, pytest-Fixtures und geprüften JSON-Antworten.","tags":["Software","Python","Backend"],"published_at":"2021-02-16T10:00:00+00:00","updated_at":"2026-07-13T13:19:37.617788+00:00","url":"https://www.mikebild.dev/de/blog/flask-apps-testen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/e8a557c32517ead355faa68d08fc229829012a312f1c01f4a49c827f0afc79c1/flask-apps-testen-vorlesen.mp3","audio_duration_secs":692,"text":"`app.test_client()` ist kein HTTP-Client. Er öffnet keinen Socket, belegt keinen Port und braucht kein `app.run()`. Er ruft die WSGI-Anwendung direkt im selben Prozess auf und gibt zurück, was die View-Function produziert hat – ein Python-Objekt, keine Netzwerkantwort.\n\nDamit fällt die Begründung weg, Endpoints seien aufwendig abzusichern. Ein `curl` im Terminal zeigt, dass eine Route in diesem einen Augenblick das Richtige tut; nach dem nächsten Refactoring sagt es nichts mehr aus. Dieser Artikel baut auf [Web-APIs mit Flask](https://www.mikebild.dev/de/blog/web-apis-mit-flask/) auf und dreht die Perspektive um: nicht das Bauen der Endpoints, sondern das Absichern. Das Werkzeug dafür ist schlank – Flask bringt den Test-Client mit, pytest liefert die Struktur drumherum.\n\n## Ein Test ohne Server\n\nDer naheliegende Weg wäre, für einen Test die App zu starten und dann per HTTP-Bibliothek dagegen zu schießen. Das funktioniert, ist aber langsam, fehleranfällig und braucht einen freien Port. Flask bietet einen deutlich besseren Weg an. `app.test_client()` liefert einen Client, der die WSGI-Anwendung direkt im selben Prozess aufruft. Es gibt keinen Socket, keinen `app.run()`, keine echte Netzwerkverbindung – der Request wird als Python-Aufruf an die App durchgereicht und die Antwort kommt als Objekt zurück.\n\nDas ist der entscheidende Punkt: Der Test spricht mit deiner Anwendung, aber nicht über das Netz. Dadurch laufen die Tests schnell und funktionieren auch in einer CI-Umgebung ohne offene Ports. Die fehlende Netzwerk- und Serverstrecke entfernt einige Schwankungsquellen; deterministisch wird der Test aber erst, wenn auch Daten, Zeit und externe Abhängigkeiten kontrolliert sind.\n\n```mermaid\nflowchart LR\n    A[Test] -->|client.get / post| B[test_client]\n    B -->|WSGI in-process<br/>kein Socket, kein Server| C[Flask-App]\n    C --> D[View-Funktion]\n    D -->|Response<br/>status_code + body| B\n    B -->|Response-Objekt| A\n    A -->|assert| E[Status &amp; Body geprüft]\n```\n\nDer Client verhält sich wie ein kleiner Browser ohne Oberfläche. Ich rufe `client.get(\"/\")` oder `client.post(\"/json\", json={...})` auf und bekomme ein Response-Objekt zurück, das ich untersuchen kann. Die wichtigsten Attribute sind schnell aufgezählt: `response.status_code` als Ganzzahl, `response.data` als Rohbody in Bytes und `response.get_json()` für bereits deserialisierte JSON-Antworten.\n\n## Vom unittest-Stil zu pytest-Fixtures\n\nViele ältere Flask-Beispiele – auch das, mit dem ich früher in meinem Repository `introduction-python` gearbeitet habe – nutzen `unittest`. Der Aufbau sieht dann typischerweise so aus:\n\n```python\nimport unittest\nfrom examples.app import app\n\n\nclass HelloTestCase(unittest.TestCase):\n    def setUp(self):\n        app.testing = True\n        self.client = app.test_client()\n\n    def test_index(self):\n        result = self.client.get(\"/\")\n        self.assertEqual(result.status_code, 202)\n        self.assertEqual(result.data, b\"Hello World!\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n```\n\nDas funktioniert und ist ein guter Ausgangspunkt. Der Endpoint in meinem Beispiel gibt bewusst den ungewöhnlichen Status `202` zurück – genau deshalb eignet er sich zum Testen, denn ein falscher Status fällt sofort auf. Trotzdem modernisiere ich das inzwischen zu pytest, und zwar aus zwei Gründen: Die Tests werden kürzer und lesbarer, und die Fixtures machen das Setup wiederverwendbar, ohne dass ich es in jeder Testklasse wiederhole.\n\nDer zweite, subtilere Grund liegt im Detail des Codes oben. Die App wird als Modul-globales Objekt importiert und der Client teilt sich diese eine Instanz. Solange die App zustandslos ist, geht das gut. Sobald sie Daten hält, wird es heikel – dazu später mehr.\n\n## Fixtures in conftest.py\n\nBei pytest lege ich das Setup in eine Datei `tests/conftest.py`. Diese Datei wird von pytest automatisch gefunden, und die dort definierten Fixtures stehen allen Tests im Verzeichnis zur Verfügung. Ich definiere zwei Fixtures: eine für die konfigurierte App und eine für den Client.\n\n```python\nimport pytest\nfrom examples.app import app as flask_app\n\n\n@pytest.fixture\ndef app():\n    flask_app.config.update({\"TESTING\": True})\n    yield flask_app\n\n\n@pytest.fixture\ndef client(app):\n    return app.test_client()\n```\n\nZwei Dinge sind hier wichtig. Erstens die Konfiguration `TESTING = True`. Sie schaltet die Fehlerpropagierung ein: Wirft ein View-Fehler eine Exception, reicht Flask sie im Testmodus durch, statt sie in eine generische `500`-Antwort zu verpacken. Ohne dieses Flag debuggst du im Blindflug, weil du nur den Status `500` siehst und nicht den eigentlichen Stacktrace. Ich habe in einem Projekt eine halbe Stunde in einem Testlauf nach einer Ursache gesucht, die mit `TESTING=True` von Anfang an im Traceback gestanden hätte.\n\nZweitens die `client`-Fixture, die von der `app`-Fixture abhängt. pytest löst diese Abhängigkeit automatisch auf: Es baut erst die App, dann den Client. Jeder Test, der `client` als Argument deklariert, bekommt eine frische, sauber konfigurierte Instanz. Genau diese Frische ist der Schlüssel zu isolierten Tests.\n\n## Die AAA-Struktur\n\nWenn ich Tests schreibe, halte ich mich an das Muster AAA: Arrange, Act, Assert. Erst den Zustand vorbereiten, dann die eine Aktion ausführen, dann prüfen. Bei Flask-Tests fällt das Arrange größtenteils in die Fixtures, das Act ist der Request und das Assert die Prüfung der Antwort.\n\n```mermaid\nflowchart TD\n    A[\"Arrange<br/>Fixtures: App + Client<br/>TESTING = True\"] --> B[\"Act<br/>client.get / client.post\"]\n    B --> C[\"Assert<br/>status_code prüfen<br/>get_json / data prüfen\"]\n```\n\nEin erster, einfacher Test für den Index-Endpoint sieht damit so aus:\n\n```python\ndef test_index_returns_hello(client):\n    # Act\n    response = client.get(\"/\")\n\n    # Assert\n    assert response.status_code == 202\n    assert response.data == b\"Hello World!\"\n```\n\nKein `setUp`, keine Klasse, kein `self`. Die Fixture erledigt das Arrange, der Test bleibt bei der eigentlichen Aussage: Dieser Endpoint antwortet mit Status `202` und dem Body `Hello World!`.\n\n## Bytes sind nicht String\n\nÜber diese Stelle bin ich selbst oft genug gestolpert. Der naheliegende Vergleich\n\n```python\nassert response.data == \"Hello World!\"   # fails\n```\n\nschlägt fehl. `response.data` liefert Bytes, kein `str`. Der Vergleich zwischen `b\"Hello World!\"` und `\"Hello World!\"` ist in Python immer `False`. Es gibt zwei saubere Wege: Entweder ich vergleiche gegen ein Byte-Literal `b\"Hello World!\"`, oder ich hole den Body als Text.\n\n```python\ndef test_index_body_as_text(client):\n    response = client.get(\"/\")\n    assert response.get_data(as_text=True) == \"Hello World!\"\n```\n\n`get_data(as_text=True)` dekodiert den Body zu einem String. Beide Varianten sind korrekt – ich wähle je nachdem, ob ich Rohbytes oder lesbaren Text prüfen will. Was ich in diesem Kontext bewusst nicht nutze, ist `response.text`; diese String-Eigenschaft kam erst mit einer späteren Werkzeug-Version und steht bei Flask 1.1 noch nicht zur Verfügung.\n\n## JSON-Antworten prüfen\n\nDie meisten realen Endpoints liefern kein `Hello World!`, sondern JSON. Hier zeigt sich der zweite große Vorteil des Test-Clients. Statt den Rohbody selbst zu parsen, ruft man `response.get_json()` auf und bekommt bereits eine fertige Python-Struktur – ein `dict` oder eine `list`. Das trennt zwei Prüfebenen sauber voneinander: der Body als Bytes für den exakten Rohvergleich und die deserialisierte Struktur für die inhaltliche Prüfung.\n\nNehmen wir einen Endpoint, der ein JSON-Objekt entgegennimmt, es um Felder ergänzt und zurückgibt – ähnlich dem `/json`-Beispiel aus meinem Repository:\n\n```python\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n\n@app.route(\"/json\", methods=[\"POST\"])\ndef json_endpoint():\n    payload = request.json\n    result = {\"username\": \"John Doe\", \"role\": payload.get(\"role\")}\n    return jsonify(result)\n```\n\nDer zugehörige Test schickt JSON hin und prüft die deserialisierte Antwort:\n\n```python\ndef test_json_endpoint(client):\n    # Act\n    response = client.post(\"/json\", json={\"role\": \"admin\"})\n\n    # Assert\n    assert response.status_code == 200\n    data = response.get_json()\n    assert data[\"username\"] == \"John Doe\"\n    assert data[\"role\"] == \"admin\"\n```\n\nEin Detail lohnt die Erwähnung: Der `json=`-Parameter beim Client setzt automatisch den Content-Type auf `application/json` und serialisiert das Dictionary. Man muss also weder Header von Hand setzen noch selbst `json.dumps` aufrufen. Auf der Antwortseite nimmt `get_json()` einem das Parsen ab. Der Test bleibt dadurch nah an der eigentlichen Aussage über das Verhalten des Endpoints.\n\n## Fehlerfälle gehören dazu\n\nEin häufiger Fehler, der mir in Code-Reviews begegnet, ist, nur den Happy Path zu testen. Ein Endpoint, der bei korrekter Eingabe funktioniert, aber bei falscher Eingabe still das Falsche tut, ist nicht zuverlässig. Deshalb gehört zu jedem ernstgemeinten Testsatz mindestens ein Fehlerfall. Der einfachste ist die unbekannte Route:\n\n```python\ndef test_unknown_route_returns_404(client):\n    response = client.get(\"/does-not-exist\")\n    assert response.status_code == 404\n```\n\nWas ich mindestens abdecke, lässt sich in eine kurze Liste fassen:\n\n- Der Status-Code – erwarte ich `200`, `202`, `201` oder einen bewussten Fehlercode?\n- Der Response-Body beziehungsweise die JSON-Struktur – stimmen die Felder und Werte?\n- Die Fehlerfälle – etwa `404` für unbekannte Routen und `400` für ungültige Eingaben.\n\nDiese drei Ebenen sind nicht viel Arbeit, verändern aber die Aussagekraft eines Testsatzes grundlegend. Ein Test, der nur den Status prüft, übersieht falsche Inhalte. Ein Test, der nur den Body prüft, übersieht einen falschen Status. Zusammen ergeben sie ein belastbares Bild.\n\n## Der Fallstrick: geteilter Zustand\n\nJetzt kommen wir zu dem Problem, das ich weiter oben angedeutet habe und das in der Praxis die meisten schwer auffindbaren Testfehler verursacht: geteilter Zustand zwischen Tests. Solange eine App zustandslos ist, teilen sich alle Tests gefahrlos dieselbe Instanz. Sobald die App aber Daten hält – eine Liste im Speicher, ein globales Dictionary, eine Datenbank –, wird die Reihenfolge der Tests plötzlich relevant.\n\nStell dir einen Endpoint vor, der Einträge in einer modul-globalen Liste sammelt. Ein Test legt einen Eintrag an, ein anderer zählt die Einträge. Läuft der Zähl-Test nach dem Anlege-Test, sieht er einen Eintrag mehr als erwartet. Läuft er davor, sieht er null. Solche Tests sind mal grün, mal rot, je nach Reihenfolge – und nichts ist frustrierender als ein Test, der ohne Codeänderung mal so und mal so ausgeht.\n\nDie Lösung liegt in den Fixtures. Statt eine globale App zu importieren, baue ich sie pro Test frisch auf. pytest-Fixtures haben standardmäßig den Geltungsbereich `function`, das heißt, sie werden für jeden Testaufruf neu ausgeführt. Wenn die Fixture bei jedem Aufruf eine App mit leerem Zustand liefert, kann kein Test den nächsten beeinflussen.\n\n## Datenbanken sauber isolieren\n\nDasselbe Problem eine Nummer größer ist die nicht isolierte Datenbank. Schreiben Tests in dieselbe Datenbank, ohne aufzuräumen, kommen sie sich genauso in die Quere wie bei der globalen Liste. Ein Test legt einen Nutzer an, der nächste findet ihn vor und rechnet nicht damit.\n\nDie saubere Antwort ist Setup und Teardown rund um das `yield` der Fixture. Alles vor dem `yield` richtet den Zustand ein, alles danach räumt auf. In der Praxis nutze ich für Tests gern eine frische temporäre SQLite-Datenbank pro Test oder ein Transaktions-Rollback am Ende. Das Muster sieht schematisch so aus:\n\n```python\nimport pytest\nfrom myapp import create_app, db\n\n\n@pytest.fixture\ndef app():\n    app = create_app({\"TESTING\": True, \"DATABASE\": \":memory:\"})\n\n    with app.app_context():\n        db.create_all()      # Setup: fresh schema\n        yield app\n        db.drop_all()        # Teardown: clean up\n\n\n@pytest.fixture\ndef client(app):\n    return app.test_client()\n```\n\nDer Kern ist das `yield` in der Mitte. Davor steht das Anlegen des Schemas, danach das Aufräumen. Jeder Test bekommt so eine leere Datenbank, arbeitet darin und hinterlässt keine Spuren für den nächsten. Das ist etwas mehr Aufwand als eine geteilte Datenbank, aber es ist der Unterschied zwischen Tests, denen ich vertraue, und Tests, die ich bei jedem roten Lauf erst einmal misstrauisch anschaue.\n\n## Was am Ende zählt\n\nDer Test-Client von Flask macht das Absichern von Endpoints zu einer Fleißaufgabe statt zu einem Infrastrukturthema. Es braucht keinen laufenden Server und keine Netzwerkbibliothek, nur `app.test_client()`, ein paar Fixtures und die Disziplin, Status, Body und Fehlerfälle gemeinsam zu prüfen.\n\nDie drei Ideen, die sich für mich bewährt haben, sind schlicht. Erstens: in-process testen, ohne Server – dann sind die Tests schnell und unabhängig von Port und Netzwerk. Zweitens: pytest-Fixtures nutzen, damit jeder Test eine frische, konfigurierte App bekommt – die beste Verteidigung gegen geteilten Zustand. Drittens: bei allem, was Daten hält, an Setup und Teardown denken, sonst hängt das Ergebnis an der Testreihenfolge. Damit lässt sich die WSGI-Anwendung verlässlich gegen ihre HTTP-Semantik prüfen. Den realen Weg über WSGI-Server, Reverse Proxy, TLS und Netzwerk deckt diese Testebene bewusst nicht ab.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-python.html\n- Repository `introduction-python`, `web/4-testing.md` sowie die Beispiele `examples/5-testing.py`, `examples/app.py` und `examples/3-json.py`\n- Flask, Testing Flask Applications: https://flask.palletsprojects.com/en/1.1.x/testing/\n- Flask, API-Referenz zu `Flask.test_client` und der `TESTING`-Config: https://flask.palletsprojects.com/en/1.1.x/api/\n- Werkzeug, Test-Utilities und Response-Objekt (`get_json`, `data`): https://werkzeug.palletsprojects.com/en/stable/test/\n- pytest, Fixtures: https://docs.pytest.org/en/6.2.x/fixture.html\n- Flask-Tutorial, Test Coverage: https://flask.palletsprojects.com/en/1.1.x/tutorial/tests/"},{"locale":"de","translation_key":"react-zustand-erhalten-und-zuruecksetzen","slug":"react-zustand-erhalten-und-zuruecksetzen","title":"State erhalten und zurücksetzen: React und die Position im Baum","summary":"React speichert State nicht in der Komponente, sondern an ihrer Position im Render-Baum – wer das versteht, steuert Erhalt und Reset absichtlich statt zufällig.","tags":["Software","Frontend","React"],"published_at":"2021-01-26T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/react-zustand-erhalten-und-zuruecksetzen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/23c1369a4d37d384192e8f5eb8776e0f7c167c1aa2be26b0e4e32c2f7ba0335f/react-zustand-erhalten-und-zuruecksetzen-vorlesen.mp3","audio_duration_secs":603,"text":"# State erhalten und zurücksetzen: React und die Position im Baum\n\nZwei Angaben entscheiden darüber, ob der State einer Komponente eine Aktualisierung übersteht: die Position im Render-Baum und der Komponententyp, der an dieser Position steht. Bleiben beide gleich, reicht React den gemerkten State weiter. Ändert sich eine von beiden, ist er verworfen. Weitere Kriterien gibt es nicht – auch keine Ausnahme für „aber es ist doch dieselbe Komponente“.\n\nRätselhaft wird das nur, weil sich ein anderes Bild aufdrängt: Der State stecke in der Komponente, so wie eine Variable in einem Objekt steckt. Nach diesem Bild müsste `useState` seinen Wert dort halten, wo die Funktion steht. Das tut React nicht. Beim Aktualisieren vergleicht es zwei Bäume – den alten und den neuen – und leitet aus den Unterschieden ab, was am DOM zu tun ist ([Wie React den Baum rendert](https://www.mikebild.dev/de/blog/wie-react-den-baum-rendert-und-aktualisiert/)). Genau dieser Vergleich entscheidet auch über den State. Aus dem falschen Bild wachsen zwei Sorten von Bugs: mal geht ein State verloren, den man behalten wollte, mal bleibt einer kleben, den man loswerden wollte.\n\n## Der State hängt an der Position, nicht an der Komponente\n\nDas richtige Bild ist dieses: React speichert den State nicht in der Komponente, sondern an ihrer Position im Render-Baum. Jede Stelle im Baum – erstes Kind eines Containers, zweites Kind, das Element hinter dieser Bedingung – ist eine Adresse. An dieser Adresse merkt sich React, welche Komponente dort zuletzt stand und welchen State sie hatte. Steht bei der nächsten Aktualisierung dieselbe Komponente wieder an derselben Adresse, reicht React ihr den gemerkten State erneut. Steht dort etwas anderes – oder gar nichts mehr –, wirft React den State dieser Adresse weg.\n\nDaraus folgt die ganze Regel in einem Satz: Gleiche Komponente an gleicher Position behält ihren State. Ändert sich an einer Position der Typ, oder verschwindet die Position, wird der State dort verworfen. Alles Weitere in diesem Beitrag ist nur diese eine Regel, angewendet auf Fälle, die einem sonst rätselhaft vorkommen.\n\n## Beispiel A: zwei Counter, zwei Positionen\n\nNehmen wir zwei gleiche Komponenten nebeneinander. Beide sind derselbe `Counter`, geschrieben aus derselben Funktion:\n\n```jsx\nfunction Counter({ label }) {\n  const [count, setCount] = useState(0);\n  return (\n    <button onClick={() => setCount(count + 1)}>\n      {label}: {count}\n    </button>\n  );\n}\n\nfunction App() {\n  return (\n    <div>\n      <Counter label=\"left\" />\n      <Counter label=\"right\" />\n    </div>\n  );\n}\n```\n\nKlickt man den linken hoch, bleibt der rechte stehen. Das irritiert zunächst, denn es ist doch dieselbe Komponente – sollte sie sich nicht denselben State teilen? Nein, und die Positionsregel erklärt sofort, warum. Der linke `Counter` sitzt an der Adresse „erstes Kind des `div`“, der rechte an „zweites Kind“. Das sind zwei Adressen, also zwei getrennte States. Dass beide aus derselben Funktion stammen, spielt keine Rolle – die Funktion ist nur die Vorlage, der State hängt an der Position.\n\nJetzt der Fall, der den Punkt wirklich schärft. Wir blenden den rechten Zähler bedingt aus und wieder ein:\n\n```jsx\nfunction App() {\n  const [showRight, setShowRight] = useState(true);\n  return (\n    <div>\n      <Counter label=\"left\" />\n      {showRight && <Counter label=\"right\" />}\n      <button onClick={() => setShowRight(!showRight)}>toggle right</button>\n    </div>\n  );\n}\n```\n\nMan zählt den rechten auf 7 hoch, schaltet ihn aus, schaltet ihn wieder ein – und er steht bei 0. Der State ist weg, unwiederbringlich. Solange `showRight` falsch ist, steht an der zweiten Position nichts. React sieht eine Position, die verschwunden ist, und räumt ihren State ab. Kommt der `Counter` zurück, ist es aus Sicht von React eine frisch besetzte Adresse, kein Wiedersehen. Der State war nie „im Zähler“ – er war an eine Position gebunden, die zwischenzeitlich nicht existierte.\n\n## Beispiel B: dieselbe Position, anderer Typ\n\nDer Gegenfall zeigt dieselbe Regel von der anderen Seite. Solange an einer Position derselbe Komponententyp steht, überlebt der State jede Änderung der Props. Man kann einem `Counter` bei jeder Aktualisierung ein anderes `label` geben, seine Farbe umstellen, ihn von aktiv auf inaktiv schalten – der Zählerstand bleibt, weil an der Position weiter derselbe Typ steht. Props formen die Komponente neu, sie setzen sie nicht zurück.\n\nKippt an derselben Stelle dagegen der Typ, ist der State weg. Genau hier greift die Typ-Regel der Reconciliation, die ich in [Wie React den Baum rendert](https://www.mikebild.dev/de/blog/wie-react-den-baum-rendert-und-aktualisiert/) beschrieben habe: Trifft React an einer Position auf einen anderen Elementtyp als vorher, baut es den alten Teilbaum ab und den neuen von Grund auf neu auf – samt State. Ein verbreiteter Auslöser sieht harmlos aus:\n\n```jsx\nfunction Panel({ editing }) {\n  if (editing) {\n    return <input defaultValue=\"draft\" />;\n  }\n  return <p>draft</p>;\n}\n```\n\nAn dieser Position wechselt der Typ zwischen `<input>` und `<p>`. Jeder Wechsel wirft den alten Knoten weg – der `<input>` verliert seinen getippten Text, weil beim nächsten Umschalten dort ein `<p>` steht und danach ein ganz neuer `<input>`. Dasselbe passiert, wenn an einer Stelle mal die eine, mal eine andere Komponente gerendert wird: verschiedene Typen an einer Adresse heißt für React verschiedene Dinge, und Verschiedenes teilt sich keinen State.\n\n```mermaid\nflowchart TB\n  subgraph erhalten[\"gleiche Position, gleicher Typ\"]\n    A1[\"Counter an Position 2<br/>count = 7\"] --> A2[\"neue Props<br/>Typ bleibt Counter\"]\n    A2 --> A3[\"count = 7<br/>bleibt erhalten\"]\n  end\n  subgraph reset[\"gleiche Position, anderer Typ\"]\n    B1[\"p an Position 2\"] --> B2[\"jetzt input<br/>an Position 2\"]\n    B2 --> B3[\"alter Teilbaum weg,<br/>Zustand verworfen\"]\n  end\n```\n\n## State absichtlich zurücksetzen\n\nBis hierher klingt das nach einer Falle. Man kann die Regel aber umdrehen und sie zum Werkzeug machen. Manchmal will man einen Reset ja ausdrücklich – und dann sagt einem die Positionsregel genau, wie man ihn bestellt.\n\nDer grobe Weg: die Komponente an einer anderen Position rendern. Zwei Zweige eines `if`, die scheinbar denselben `Counter` zeigen, sind aus Sicht von React zwei verschiedene Positionen, wenn sie an unterschiedlichen Stellen im Baum hängen; wer zwischen ihnen umschaltet, bekommt jedes Mal einen frischen State. Das funktioniert, ist aber grobschlächtig und leicht versehentlich ausgelöst.\n\nDer elegante Weg führt über den `key`. Ein `key` sagt React ausdrücklich: „Das hier ist ein bestimmtes Element, unterscheide es von seinen Nachbarn.“ Aus [JSX genau](https://www.mikebild.dev/de/blog/jsx-genau-die-regeln-hinter-dem-markup/) kennt man Keys als das, was Listen stabil macht, damit React beim Umsortieren die Elemente wiedererkennt. Genau dieselbe Fähigkeit taugt aber auch außerhalb von Listen zum gezielten Reset. Ändert sich der `key` eines Elements, behandelt React es als ein neues Element an dieser Position – der alte Teilbaum wird abgebaut, der State frisch angelegt.\n\nDer Klassiker dafür ist ein Formular, das pro ausgewähltem Datensatz frisch starten soll:\n\n```jsx\nfunction ContactEditor({ selectedId }) {\n  return <Form key={selectedId} contactId={selectedId} />;\n}\n```\n\nOhne den `key` bliebe `Form` an derselben Position stehen; wechselt `selectedId`, bekäme das Formular nur neue Props, und der halb getippte Text des vorigen Kontakts stünde weiter im Feld. Mit `key={selectedId}` wechselt bei jeder neuen Auswahl der Schlüssel, React sieht ein neues Element, und das Formular startet leer – ohne dass man ein einziges Feld von Hand zurücksetzt. Der `key` erledigt genau die Arbeit, die man sonst mit einem Effect und viel `setState` nachbauen würde.\n\n```mermaid\nflowchart LR\n  S1[\"selectedId = 1\"] --> F1[\"Form key=1<br/>frischer Zustand\"]\n  S2[\"selectedId = 2\"] --> F2[\"Form key=2<br/>neues Element,<br/>Formular leer\"]\n  S3[\"selectedId = 2<br/>Feld getippt\"] --> F3[\"Form key=2<br/>Zustand bleibt\"]\n```\n\n## State erhalten, obwohl sich die Struktur ändert\n\nDas Gegenstück ist der Fall, in dem man den State behalten will, die Umgebung sich aber ändert. Hier gilt es, Position und Typ stabil zu halten, auch wenn drumherum umgebaut wird. Wer eine Komponente je nach Bedingung mal in den einen, mal in den anderen Zweig schreibt, verschiebt sie damit an eine andere Position – und wundert sich über den Reset. Oft lässt sich das vermeiden, indem man die Komponente an einer festen Stelle rendert und nur ihre Props umschaltet, statt sie im Baum wandern zu lassen.\n\nUnd wenn ein State einen echten Umbau überleben muss, gehört er meist nicht dorthin, wo er gerade steht. Dann zieht man ihn nach oben, zu einem gemeinsamen Elternteil, der von der Umstrukturierung unberührt bleibt. Der State hängt dann an einer Position, die stabil ist, und die Kinder darunter dürfen kommen und gehen, ohne ihn mitzureißen. Das ist dieselbe Bewegung wie beim klassischen Hochziehen von State. Der Grund ist hier ein anderer: Es geht ums Überleben einer Strukturänderung, nicht ums Teilen zwischen Geschwistern.\n\n## Der fieseste Bug: eine Komponente in einer Komponente\n\nDen unangenehmsten Fall hebe ich mir für den Schluss auf, weil er die Positionsregel auf die Probe stellt und weil er in echten Codebasen erstaunlich oft steckt. Er sieht so aus:\n\n```jsx\nfunction Page() {\n  function Sidebar() {\n    const [open, setOpen] = useState(true);\n    return <button onClick={() => setOpen(!open)}>{open ? \"hide\" : \"show\"}</button>;\n  }\n\n  return (\n    <div>\n      <Sidebar />\n    </div>\n  );\n}\n```\n\n`Sidebar` ist innerhalb von `Page` definiert. Das wirkt ordentlich – die Komponente steht ja da, wo sie gebraucht wird. Der Effect ist trotzdem verheerend. Bei jedem Rendern von `Page` läuft die Zeile `function Sidebar()` erneut und erzeugt eine neue Funktion. Es ist bei jedem Durchlauf buchstäblich eine andere Funktion mit einer anderen Identität. Für React ist die Identität der Funktion aber der Typ. Ein anderer Typ an einer Position heißt: alter Teilbaum weg, neuer aufgebaut, State verworfen.\n\nIn der Praxis sieht das gespenstisch aus. Jede noch so kleine Aktualisierung von `Page` setzt `open` zurück, das Eingabefeld darin verliert seinen Text, und wer gerade in einem Feld tippt, verliert mitten im Wort den Fokus, weil das DOM-Element unter ihm ersetzt wurde. Man sucht den Fehler überall – im Effect, im Event-Handler, im State-Management – nur nicht an der Stelle, wo die Komponente definiert ist. Dabei ist es genau das: eine bei jedem Rendern neu geborene Funktionsidentität, die React zwingt, den ganzen Teilbaum wegzuwerfen.\n\nDie Lösung ist unspektakulär und deshalb leicht zu übersehen: Komponenten gehören auf die Modulebene, nicht in den Rumpf einer anderen Komponente. Dann existiert `Sidebar` genau einmal, behält über alle Aktualisierungen dieselbe Identität, steht als derselbe Typ an derselben Position – und ihr State bleibt. Braucht die innere Komponente Daten von außen, reicht man sie als Props durch, nicht über die verschachtelte Definition.\n\n## Ort und Zeit im Baum\n\nState in React ist an Ort und Zeit gebunden: an eine Position im Render-Baum und an die Dauer, die diese Position mit demselben Typ besetzt bleibt. Fast alles, was am Verhalten von State rätselhaft wirkt, klärt sich, sobald man aufhört zu fragen „in welcher Komponente steht das?“ und stattdessen fragt „an welcher Position im Baum, und steht dort noch derselbe Typ?“.\n\nWer das verinnerlicht, hat beide Richtungen in der Hand. Einen Reset bestellt man mit einem `key` oder einer neuen Position, statt Felder einzeln zurückzusetzen. Erhalt sichert man, indem man Position und Typ stabil hält und den State notfalls nach oben zieht. Und den fiesesten Bug vermeidet man, bevor er entsteht, indem Komponenten dort stehen, wo sie hingehören – auf der Modulebene. Aus etwas, das sich wie Magie anfühlte, wird so eine Entscheidung, die man absichtlich trifft statt zufällig zu erleiden.\n\n## Weiterführende Quellen\n\n- Repository introduction-react: https://github.com/mikebild/introduction-react\n- React, „Preserving and Resetting State“: https://react.dev/learn/preserving-and-resetting-state\n- React, „State as a Snapshot“: https://react.dev/learn/state-as-a-snapshot\n- React, „Render and Commit“: https://react.dev/learn/render-and-commit"},{"locale":"de","translation_key":"cognito-userpool-auth-serverless","slug":"cognito-userpool-auth-serverless","title":"Serverless-Auth mit Cognito User Pools","summary":"Cognito User Pools als managed Identity-Backend: Sign-up, Confirm und Sign-in ohne eigenen Auth-Server, die drei Tokens richtig verstanden und ein API-Gateway-Endpoint, den ein Cognito-Authorizer absichert.","tags":["Software","AWS","Cloud"],"published_at":"2021-01-19T10:00:00+00:00","updated_at":"2026-07-13T10:01:52.666784+00:00","url":"https://www.mikebild.dev/de/blog/cognito-userpool-auth-serverless/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/a2b833d93b73891a6bfab0c63063011f4e70d077aa3ec3f49f6b06e4de6d41db/cognito-userpool-auth-serverless-vorlesen.mp3","audio_duration_secs":749,"text":"Cognito nimmt einem das Passwort-Handling ab – die Entscheidung darüber, wem die Identitäten der Nutzer gehören, nimmt es einem nicht ab. Diese beiden Dinge werden regelmäßig in einen Topf geworfen. Der Aufruf `signUp()` ist an einem Nachmittag integriert; die `sub`, die Cognito dabei vergibt, wandert danach als Fremdschlüssel durch jede Tabelle und bleibt Jahre. Die Integration ist billig, das Eigentum an den Identitäten teuer.\n\nPasswörter speichern, Bestätigungsmails verschicken, Tokens signieren und rotieren – gelöste Probleme, und selten das, was ein Produkt von der Konkurrenz unterscheidet. Ein selbstgebauter Auth-Server ist keine Differenzierung, sondern eine Fläche, die dauerhaft gepflegt und abgesichert werden will. AWS hat für diese Verantwortung einen managed Baustein: Cognito User Pools. Interessant ist daran weniger der API-Aufruf als der Trade-off dahinter: Welche Betriebsverantwortung gebe ich ab, und welchen Preis zahle ich bei einem späteren Wechsel? Genau den nehme ich hier auseinander – an einem durchgehenden Beispiel, das den Weg von der Registrierung bis zum abgesicherten Endpoint zeigt.\n\nServerless heißt für mich vor allem, Betriebsverantwortung dort abzugeben, wo sie keinen Wettbewerbsvorteil schafft. Ein eigener Auth-Server ist selten einer – er ist eine Angriffsfläche, die man pflegen muss.\n\n## Was ein User Pool eigentlich ist\n\nEin Cognito User Pool ist ein managed Verzeichnis für deine Endnutzer plus die komplette Maschinerie drumherum: Registrierung, E-Mail- oder SMS-Verifizierung, Anmeldung, Passwort-Reset und die Ausstellung von Tokens. Deine Anwendung speichert keine Passwörter mehr – sie redet nur noch mit Cognito. Das ist der entscheidende Perspektivwechsel: Nicht deine App entscheidet, ob ein Passwort stimmt, sondern der User Pool. Deine App bekommt am Ende nur ein signiertes Token in die Hand und muss diesem Token vertrauen können.\n\nZwei Objekte musst du dabei auseinanderhalten. Der **User Pool** selbst ist das Verzeichnis samt Policies – Passwortregeln, welche Attribute Pflicht sind, welche automatisch verifiziert werden. Der **App Client** ist die Anwendung, die sich beim Pool authentifiziert; er legt fest, welche Auth-Flows erlaubt sind und wie lange ein Refresh-Token gültig bleibt. Ein Pool kann mehrere App Clients haben – etwa einen fürs Web und einen für die native App.\n\nSo sieht das minimal in CDK aus. Ich bleibe bewusst bei den L1-Constructs (`Cfn...`), weil sie eins zu eins auf die CloudFormation-Ressourcen abbilden und man dadurch genau sieht, was entsteht:\n\n```js\nconst {\n  CfnUserPool,\n  CfnUserPoolClient,\n  CfnUserPoolGroup,\n} = require('@aws-cdk/aws-cognito');\n\nconst userPool = new CfnUserPool(this, 'UserPool', {\n  userPoolName: 'UserPool',\n  adminCreateUserConfig: {\n    allowAdminCreateUserOnly: false,\n  },\n  policies: {\n    passwordPolicy: {\n      minimumLength: 6,\n    },\n  },\n  schema: [\n    {\n      attributeDataType: 'String',\n      name: 'email',\n      required: true,\n    },\n  ],\n  autoVerifiedAttributes: ['email'],\n});\n\nconst userPoolClient = new CfnUserPoolClient(this, 'UserPoolClient', {\n  clientName: 'UserPoolClient',\n  explicitAuthFlows: ['ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],\n  refreshTokenValidity: 30,\n  userPoolId: userPool.ref,\n});\n```\n\n`autoVerifiedAttributes: ['email']` sorgt dafür, dass Cognito nach der Registrierung automatisch einen Bestätigungscode per E-Mail verschickt. `refreshTokenValidity: 30` setzt die Lebensdauer des Refresh-Tokens auf 30 Tage – dazu gleich mehr. Wer es lieber mit den höheren L2-Constructs (`UserPool`, `UserPoolClient`) baut, bekommt bequemere Defaults; für den Einstieg finde ich die explizite L1-Variante lehrreicher. Wenn du dich fragst, warum ich Infrastruktur überhaupt in einer Programmiersprache beschreibe statt in YAML: Das habe ich in [CDK: Infrastruktur als Programmiersprache](https://www.mikebild.dev/de/blog/cdk-infrastruktur-als-programmiersprache/) begründet.\n\n## Sign-up, Confirm, Sign-in\n\nDer Lebenszyklus eines Nutzers hat drei Stationen. Auf dem Client – oder wie in meinem Beispiel in einem dünnen Node-Backend – nutze ich dafür `amazon-cognito-identity-js`, das offizielle JavaScript-SDK für User Pools. Registrierung, Bestätigung, Anmeldung:\n\n```ts\nimport {\n  CognitoUserPool,\n  CognitoUser,\n  AuthenticationDetails,\n  CognitoUserAttribute,\n} from 'amazon-cognito-identity-js';\n\nconst userPool = new CognitoUserPool({\n  UserPoolId: process.env.USER_POOL_ID,\n  ClientId: process.env.USER_POOL_CLIENT_ID,\n});\n\n// 1) sign-up: create the user, Cognito emails a confirmation code\nuserPool.signUp(\n  username,\n  password,\n  [new CognitoUserAttribute({ Name: 'email', Value: username })],\n  [],\n  (err, result) => {\n    /* result.user is created but not yet confirmed */\n  }\n);\n\n// 2) confirm: user submits the code from the email\nconst cognitoUser = new CognitoUser({ Username: username, Pool: userPool });\ncognitoUser.confirmRegistration(code, true, (err, result) => {\n  /* result === 'SUCCESS' */\n});\n\n// 3) sign-in: authenticate and receive tokens\ncognitoUser.authenticateUser(\n  new AuthenticationDetails({ Username: username, Password: password }),\n  {\n    onSuccess(session) {\n      const idToken = session.getIdToken().getJwtToken();\n      const accessToken = session.getAccessToken().getJwtToken();\n      // refresh token is available too, but opaque\n    },\n    onFailure(err) {\n      /* wrong password, unconfirmed user, ... */\n    },\n  }\n);\n```\n\nDer wichtige Punkt: Zwischen Schritt eins und drei liegt der Confirm-Schritt. Ein frisch registrierter Nutzer ist zunächst `UNCONFIRMED` und kann sich nicht anmelden, bis er den per E-Mail zugestellten Code bestätigt hat. Diese E-Mail schickt Cognito selbst.\n\n## Die drei Tokens – und warum „drei JWT“ falsch ist\n\nNach erfolgreicher Anmeldung liefert Cognito genau drei Tokens zurück. Das klingt banal, aber hier sitzt ein hartnäckiger Denkfehler: Es heißt oft, man bekomme „drei JWT“. Das stimmt nicht. Zwei davon sind JWT, eines ist es ausdrücklich nicht.\n\nDas ID-Token ist ein JWT und trägt die Identität des Nutzers – Claims wie `sub`, `email` und `cognito:username`. Es beantwortet die Frage „wer ist dieser User?“ und ist das Standard-Token für den klassischen API-Gateway-Cognito-Authorizer. Das Access-Token ist ebenfalls ein JWT, trägt aber OAuth-Scopes und beantwortet „was darf dieser Client?“; es kommt ins Spiel, sobald du scope-basierte Autorisierung mit Resource Servern nutzt. Das Refresh-Token schließlich ist kein JWT, sondern ein verschlüsselter, nur für Cognito lesbarer String. Es ist langlebig – in meiner Konfiguration 30 Tage – und dient einzig dazu, ohne erneute Passworteingabe frische ID- und Access-Tokens einzutauschen.\n\nWarum ist das mehr als Begriffsklauberei? Weil man ein JWT lokal verifizieren kann – Signatur prüfen, Ablauf prüfen, fertig – ein opakes Token dagegen nicht. Und wer im Frontend das falsche Token an die API schickt, bekommt ein `401`, ohne zu verstehen warum. Für den REST-Cognito-Authorizer ohne konfigurierte Scopes gehört das ID-Token in den Header. Erst wenn du `authorizationScopes` konfigurierst, erwartet das Gateway das Access-Token. Genau diese Verwechslung ist eine der häufigsten Fehlerquellen.\n\nEin ID-Token, dekodiert, sieht im Kern so aus – man erkennt Issuer, Audience und den Verwendungszweck:\n\n```json\n{\n  \"sub\": \"a1b2c3d4-....\",\n  \"email\": \"user@example.com\",\n  \"cognito:username\": \"user@example.com\",\n  \"aud\": \"the-app-client-id\",\n  \"iss\": \"https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_ABC123\",\n  \"token_use\": \"id\",\n  \"exp\": 1611060000\n}\n```\n\n## Den Endpoint absichern – ohne eigenen Verifikationscode\n\nJetzt kommt der Teil, an dem sich managed Auth wirklich auszahlt. Ich könnte in jeder Lambda das Token selbst prüfen: das JWKS-Dokument des Pools laden, den passenden Schlüssel über die `kid` aus dem Token-Header finden, in ein PEM umwandeln und die Signatur verifizieren. In einem klassischen Express-Backend habe ich genau das gebaut, und es ist lehrreich, es einmal von Hand gesehen zu haben:\n\n```ts\nexport async function validateToken({ token, region, userPoolId }) {\n  const response = await fetch(\n    `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`\n  );\n  const { keys } = await response.json();\n\n  const decoded = jwt.decode(token, { complete: true });\n  if (!decoded) throw new Error('Invalid JWT');\n\n  const key = keys.find((k) => k.kid === decoded.header.kid);\n  if (!key) throw new Error('Invalid JWT');\n\n  const pem = jwkToPem({ kty: key.kty, n: key.n, e: key.e });\n  return new Promise((resolve, reject) => {\n    jwt.verify(token, pem, (err, payload) =>\n      err ? reject(new Error('Invalid JWT')) : resolve(payload)\n    );\n  });\n}\n```\n\nDas funktioniert – aber es ist Code, den ich schreiben, testen und pflegen muss, und der in jeder abgesicherten Route wieder auftaucht. Genau diese Arbeit nimmt einem der **API-Gateway-Cognito-Authorizer** ab. Man verweist das Gateway auf den User Pool, und es übernimmt die komplette Prüfung managed: Signatur gegen das Pool-JWKS, `exp`, `aud`, `iss`. Kommt ein gültiges Token, wird die Lambda aufgerufen; kommt ein ungültiges oder abgelaufenes, antwortet das Gateway mit `401`, bevor deine Funktion überhaupt startet. Kein eigener Verifikationscode.\n\nIn CDK verbindest du das über einen `CognitoUserPoolsAuthorizer` mit einer REST-API-Route:\n\n```ts\nimport {\n  RestApi,\n  CognitoUserPoolsAuthorizer,\n  AuthorizationType,\n  LambdaIntegration,\n} from '@aws-cdk/aws-apigateway';\n\nconst authorizer = new CognitoUserPoolsAuthorizer(this, 'Authorizer', {\n  cognitoUserPools: [userPool],\n});\n\nconst api = new RestApi(this, 'Api');\nconst items = api.root.addResource('items');\n\nitems.addMethod('GET', new LambdaIntegration(getItemsFn), {\n  authorizer,\n  authorizationType: AuthorizationType.COGNITO,\n});\n```\n\nWer direkt auf der API-Gateway-Ebene arbeitet – etwa in einer OpenAPI-Definition – erkennt dieselbe Konfiguration in der Rohform. Der Authorizer ist vom Typ `cognito_user_pools`, verweist per ARN auf den Pool und liest das Token aus dem `Authorization`-Header:\n\n```json\n{\n  \"type\": \"apiKey\",\n  \"name\": \"Authorization\",\n  \"in\": \"header\",\n  \"x-amazon-apigateway-authtype\": \"cognito_user_pools\",\n  \"x-amazon-apigateway-authorizer\": {\n    \"type\": \"cognito_user_pools\",\n    \"providerARNs\": [\n      \"arn:aws:cognito-idp:eu-central-1:123456789012:userpool/eu-central-1_ABC123\"\n    ],\n    \"identitySource\": \"method.request.header.Authorization\"\n  }\n}\n```\n\nDer Client schickt sein ID-Token also schlicht im `Authorization`-Header mit – in der Praxis meist als `Bearer <idToken>` – und muss sich um nichts weiter kümmern. Der gesamte Ablauf sieht so aus:\n\n```mermaid\nsequenceDiagram\n  participant C as Client\n  participant Cog as Cognito User Pool\n  participant GW as API Gateway\n  participant L as Lambda\n  C->>Cog: sign-in (username / password)\n  Cog-->>C: ID + Access + Refresh tokens\n  C->>GW: GET /items<br/>Authorization: Bearer idToken\n  GW->>Cog: verify JWT via JWKS (signature, exp, aud, iss)\n  GW->>L: invoke (token valid)\n  L-->>C: 200 OK\n```\n\n## Lambda-Trigger: eigene Logik in den Ablauf hängen\n\nManchmal reicht der Standardablauf nicht. Du willst zum Beispiel nur E-Mail-Adressen einer bestimmten Firmendomain zulassen oder beim Registrieren zusätzliche Daten in eine eigene Tabelle schreiben. Dafür bietet der User Pool **Lambda-Trigger** – Einsprungspunkte an definierten Stellen im Lifecycle. 2021 verfügbar sind unter anderem `PreSignUp`, `PostConfirmation`, `PreAuthentication`, `PostAuthentication`, `PreTokenGeneration` und `CustomMessage`.\n\nEin `PreSignUp`-Trigger läuft, bevor Cognito einen neuen Nutzer anlegt. Hier prüfe ich etwa die E-Mail-Domain:\n\n```js\nexports.handler = async (event) => {\n  const email = event.request.userAttributes.email || '';\n  if (!email.endsWith('@example.com')) {\n    throw new Error('Only example.com addresses are allowed');\n  }\n  // do NOT auto-confirm: keep the email verification step intact\n  event.response.autoConfirmUser = false;\n  return event;\n};\n```\n\nZwei Dinge sind hier entscheidend, und beide sind klassische Stolperfallen. Erstens: Der Trigger muss das `event`-Objekt am Ende unverändert – bis auf die gewollten Response-Felder – **zurückgeben**. Vergisst du das `return event`, bricht der Flow ab. Zweitens: `autoConfirmUser` und die verwandten Auto-Verify-Felder sind mächtig. Setzt du sie versehentlich auf `true`, umgeht ein Nutzer den E-Mail-Bestätigungsschritt komplett – und du wunderst dich später über unbestätigte Adressen im Pool.\n\nDas kleine Komponentenbild dazu:\n\n```mermaid\nflowchart LR\n  Pool[User Pool + App Client] -->|JWKS| GW[API Gateway<br/>Cognito Authorizer]\n  GW --> Fn[Lambda]\n  Trigger[PreSignUp trigger] -.-> Pool\n```\n\n## Der eigentliche Trade-off: managed Identity gegen Anbieterbindung\n\nAlles bisher Gezeigte ist die Habenseite: kein Passwort-Handling, keine selbstgebaute Token-Ausstellung, keine Verifikationslogik in jeder Route. Diese Verantwortung samt Angriffsfläche wandert zu AWS – meist der schwerere Posten. Die Sollseite verschweige ich trotzdem nicht: Bindung an den Anbieter.\n\nDiese Bindung ist konkreter, als sie zunächst wirkt. Deine Tokens sind gegen das JWKS dieses Pools signiert, dein Client redet über das Cognito-SDK, deine Trigger sind auf Cognitos Event-Struktur zugeschnitten – und am schwersten wiegend: Die `sub` jedes Nutzers ist eine von Cognito vergebene UUID, die als Fremdschlüssel quer durch deine Datenbanken wandert. Nicht der Login-Code klebt, sondern diese Identitäten.\n\nZwei Grenzfälle machen das greifbar. Cognito gibt keine Passwort-Hashes heraus: Wer wegzieht, kann seine Nutzer nicht still mitnehmen – entweder alle setzen ihr Passwort zurück, oder du migrierst sie lazy beim nächsten Login über einen `UserMigration`-Trigger auf dem Zielsystem. Und alles jenseits des Standards – Custom Attributes, SRP-Annahmen im Client, MFA-Konfiguration – ist Cognito-Vokabular, das ein anderer Anbieter nicht eins zu eins spricht. Das Migrationsrisiko sitzt also nicht im Auth-Flow, den man in Tagen neu baut, sondern in den Identitäten und ihren Referenzen, die über Jahre gewachsen sind.\n\nDaraus wird ein klares Entscheidungsraster. Für Standard-Anmeldung mit E-Mail und Passwort, kleine bis mittlere Teams ohne dediziertes Security-Personal und ohne Multi-Cloud-Zwang gewinnt managed Identity fast immer – der eingesparte Betrieb schlägt das Bindungsrisiko deutlich. Neu abwägen würde ich, sobald ein bestehender Identity-Provider im Haus steht, echte Anbieterportabilität gefordert ist oder Datenresidenz vorschreibt, wo Identitäten überhaupt liegen dürfen. Der Trade-off verschwindet nicht – aber man trifft ihn bewusst statt aus Reflex, und man trifft ihn am Anfang, wo er noch billig ist.\n\n## Wichtige Abgrenzung: Infrastruktur-Auth ist nicht Resolver-Auth\n\nZum Schluss die Unterscheidung, die in der Praxis am schnellsten verschwimmt. Was der Cognito-Authorizer am API Gateway macht, ist **Infrastruktur- oder Edge-Auth**. Er beantwortet eine einzige, grobe Frage: „Ist der Aufrufer überhaupt authentifiziert?“ Ist das Token gültig, kommt die Anfrage durch – ist es das nicht, fliegt sie mit `401` raus, noch bevor eigener Code läuft. Das ist ein Türsteher, kein Sachbearbeiter.\n\nWas der Authorizer nicht macht: entscheiden, ob *dieser konkrete Nutzer* *dieses konkrete Objekt* sehen oder verändern darf. Darf User A den Kommentar von User B löschen? Darf jemand nur die eigenen Bestellungen abfragen? Das ist feingranulare Autorisierung, und die gehört in deine Anwendungslogik – bei einer GraphQL-API zum Beispiel in den Resolver-Kontext, wo du die Identität aus dem Token gegen die tatsächlichen Datenobjekte prüfst. Der Authorizer liefert dir die verlässliche Identität; was du damit an Rechten durchsetzt, bleibt deine Aufgabe. Diese beiden Ebenen sauber zu trennen, erspart eine Menge Verwirrung – und verhindert den Trugschluss, mit einem Authorizer sei „die Autorisierung erledigt“.\n\nFür das hier gezeigte Setup – User Pool, Standard-Login und ein abgesicherter API-Endpoint – nimmt Cognito viel eigene Infrastruktur ab. Ein erster durchgängiger Pfad lässt sich damit überschaubar aufbauen; produktionsreif wird er erst mit geklärten Recovery-Flows, MFA, Monitoring und feingranularer Autorisierung. Der Authorizer liefert die verlässliche Identität, die Rechte auf konkrete Fachobjekte bleiben bewusst in deiner Anwendungslogik. Den Preis, die Anbieterbindung, zahlst du sehenden Auges – und du triffst die Entscheidung dort, wo sie hingehört: auf der Architekturebene, nicht beiläufig beim ersten API-Aufruf.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-aws-serverless.html\n- Repository mit dem vollständigen Beispiel: `introduction-aws/examples/userpool` (CDK-Stack, Sign-up/Confirm/Login und die manuelle Token-Prüfung als Kontrast zum Authorizer)\n- [Amazon Cognito – Using Tokens with User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html)\n- [Using the ID Token](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html) · [Using the Access Token](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html) · [Using the Refresh Token](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html)\n- [Control access to a REST API using Amazon Cognito user pools](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) · [Authorizer einrichten (ID- vs. Access-Token/Scopes)](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html)\n- [JWT dekodieren und verifizieren (JWKS)](https://repost.aws/knowledge-center/decode-verify-cognito-json-token)\n- [Customizing user pool workflows with Lambda triggers](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html)"},{"locale":"de","translation_key":"trunk-based-development-und-feature-flags","slug":"trunk-based-development-und-feature-flags","title":"Trunk-Based Development statt Branch-Friedhof","summary":"Kurze Integrationszyklen mit Feature Flags schlagen langlebige Branches: tägliche Integration ohne Merge-Hölle und ein Release, das zur Entscheidung wird statt zum Deploy-Event.","tags":["Software","Delivery"],"published_at":"2020-11-24T10:00:00+00:00","updated_at":"2026-07-13T08:39:51.028726+00:00","url":"https://www.mikebild.dev/de/blog/trunk-based-development-und-feature-flags/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/5e955e4d2b35e32f306b63c8298c2e37db086fbc74ec4954ba88da166724f4f1/trunk-based-development-und-feature-flags-vorlesen.mp3","audio_duration_secs":677,"text":"Wer Integration aufschiebt, hat den Konflikt nicht vermieden, sondern nur verzinst. Ein Branch namens `feature/redesign`, der sechs Wochen neben `master` herläuft, nimmt jeden Tag ein paar Änderungen auf, die niemand mehr gegen den aktuellen Stand prüft. Der Merge am Schluss ist dann kein Arbeitsschritt mehr, sondern eine Ausgrabung – und niemand kann vorher sagen, wie lange sie dauert. Repositories, in denen ein halbes Dutzend solcher Branches vor sich hin altert, nenne ich in Reviews den Branch-Friedhof.\n\nDer Ausweg führt nicht über das nächste Branching-Modell, sondern über weniger Abstand: täglich in einen gemeinsamen Stand integrieren, ihn jederzeit auslieferbar halten und das Einschalten eines Features vom Ausrollen des Codes trennen. Das klingt nach Git-Kosmetik, betrifft aber Durchlaufzeiten und Fehlerbehebung. Deploy und Release sind zwei verschiedene Dinge – an dieser Trennung hängt der Rest. Sie ist allerdings nicht kostenlos: Jeder Flag erzeugt zusätzliche Zustände, Testaufwand und eine Aufräumaufgabe.\n\n## Die eigentliche Idee: Integrationsdistanz klein halten\n\nFangen wir bei der Kernidee an, nicht beim Werkzeug. Trunk-Based Development – so wie Paul Hammant es auf trunkbaseddevelopment.com beschreibt – bedeutet im Wesentlichen: Alle Entwickler integrieren ihre Arbeit mindestens einmal täglich in einen einzigen gemeinsamen Branch. Nennen wir ihn `main` oder `trunk`. Dieser Branch bleibt jederzeit releasebar. Branches, falls es sie überhaupt gibt, sind kurzlebig – deutlich unter einem Tag.\n\nDer entscheidende Begriff dahinter ist Integrationsdistanz. Jeder Tag, den ein Branch abseits des Trunks lebt, vergrößert die Distanz zwischen dem, woran ich arbeite, und dem, was der Rest des Teams sieht. Diese Distanz ist keine lineare Größe. Sie wächst überproportional, weil sich Änderungen auf beiden Seiten anhäufen und miteinander in Konflikt geraten können. Ein Merge nach sechs Wochen ist nicht sechsmal so teuer wie einer nach einer Woche, sondern ein Vielfaches davon – und vor allem ist er unvorhersehbar.\n\nMartin Fowler bringt das in seinem Begriff der Continuous Integration auf den Punkt, und zwar wörtlicher, als viele es lesen. „Continuous Integration“ heißt tatsächlich fortlaufend integrieren. Ein langlebiger Feature-Branch ist per Definition das Gegenteil: aufgeschobene Integration, deferred integration. Man kann nicht gleichzeitig Continuous Integration betreiben und tagelang auf eigenen Branches sitzen. Das eine schließt das andere aus. In seinen Patterns for Managing Source Code Branches liefert Fowler die passende Taxonomie: Integrationsfrequenz, der Begriff des „healthy branch“, die Mainline. Wer diese Sprache einmal verinnerlicht hat, sieht den Branch-Friedhof sofort.\n\n## Was die Daten sagen – vorsichtig formuliert\n\nIch bin skeptisch gegenüber Methodik-Versprechen, die sich nur auf Bauchgefühl stützen. Deshalb schätze ich die Arbeit von Nicole Forsgren, Jez Humble und Gene Kim in *Accelerate* und den State-of-DevOps-Reports. Dort wird Trunk-Based Development nicht als Meinung behandelt, sondern als statistisch identifizierte Capability.\n\nIch formuliere das bewusst sauber, weil die Versuchung groß ist, hier zu übertreiben. Die Daten zeigen: Höhere Software-Delivery-Performance korreliert mit wenigen aktiven Branches im Repository – Größenordnung drei oder weniger – und mit Merges in den Trunk mindestens einmal pro Tag. Trunk-Based Development ist eine der Praktiken, die Continuous Delivery statistisch prädiziert. Nicht „verursacht garantiert“, sondern prädiziert und korreliert. Dieser Unterschied ist zu wichtig, um ihn beim Zitieren zu verwischen. Aber die Richtung ist eindeutig, und sie deckt sich mit dem, was ich in Teams beobachte: Wer die Integrationsdistanz klein hält, liefert schneller, seltener kaputt und mit weniger Drama.\n\n## Der Denkfehler: Deploy ist nicht Release\n\nJetzt kommt der Teil, an dem viele Diskussionen kippen. „Wenn alle ständig auf den Trunk mergen – wie soll dann jemals etwas Halbfertiges nicht in Produktion landen?“ Diese Frage ist berechtigt, und ihre Antwort ist der eigentliche Hebel dieses ganzen Ansatzes.\n\nDeploy und Release sind zwei verschiedene Events. Deploy heißt: Der Code liegt auf der Produktionsumgebung. Release heißt: Das Verhalten ist für Nutzer aktiv. Feature Toggles – von Fowler in der Bliki beschrieben und von Pete Hodgson in *Feature Toggles (aka Feature Flags)* ausführlich systematisiert – entkoppeln genau diese beiden Dinge. Der Code wird ausgerollt, aber das Feature ist ausgeschaltet. Das Aktivieren wird zu einer Konfigurations- und Business-Entscheidung, nicht zu einem technischen Deploy-Event mit Nachtschicht und Rollback-Plan.\n\n```mermaid\nflowchart LR\n    subgraph friedhof[\"Branch-Friedhof\"]\n        direction TB\n        M0[\"main\"] --> M1[\"main\"]\n        M0 --> B1[\"feature branch<br/>Tag 1\"]\n        B1 --> B2[\"... Tag 20 ...\"]\n        B2 --> B3[\"divergiert weit\"]\n        M1 --> MG((\"dicker<br/>Merge-Konflikt\"))\n        B3 --> MG\n    end\n    subgraph tbd[\"Trunk-Based\"]\n        direction TB\n        T0[\"trunk\"] --> T1[\"+ commit\"]\n        T1 --> T2[\"+ commit\"]\n        T2 --> T3[\"+ commit\"]\n        T3 --> T4[\"trunk bleibt grün\"]\n        T4 -. \"toggle on<br/>= Release\" .-> R((\"Release<br/>als Schalter\"))\n    end\n```\n\nDas Diagramm zeigt den Kern: Links divergiert ein Branch über zwanzig Tage und mündet in einen schmerzhaften Merge. Rechts fließt ein durchgehender Trunk mit vielen kleinen Commits, und die Aktivierung passiert auf einer eigenen Achse – zeitlich entkoppelt vom Merge und vom Deploy. Release wird zum Schalter.\n\nHodgson unterscheidet vier Kategorien von Toggles, und diese Unterscheidung ist praktisch wertvoll, weil jede einen anderen Lifecycle hat. Release Toggles verstecken unfertige Arbeit und sollen kurzlebig sein. Ops Toggles steuern das Betriebsverhalten, etwa um eine teure Funktion unter Last abzuschalten. Experiment Toggles treiben A/B-Tests und passen gut zum Build-Measure-Learn-Gedanken aus Eric Ries’ *Lean Startup*. Permission Toggles schalten Verhalten für bestimmte Nutzergruppen frei. Wer diese vier nicht auseinanderhält, behandelt am Ende jeden Flag gleich – und das rächt sich.\n\n## Wie unfertige Arbeit sicher auf dem Trunk lebt\n\nEin Release Toggle im einfachsten Fall sieht so aus. Wichtig ist, dass der Flag nicht als loses `if` im Fachcode verstreut liegt, sondern hinter einer sauberen Abstraktion:\n\n```typescript\n// The domain code does not know about flag plumbing.\n// It asks a small, well-named abstraction.\nif (features.isEnabled(\"new-checkout-flow\")) {\n    return newCheckoutService.process(cart);\n}\nreturn legacyCheckoutService.process(cart);\n```\n\nAuf der Konfigurationsseite entscheidet sich, ob ein Deploy zugleich ein Release ist. Ein deaktivierter Flag bedeutet: Der Code ist da, aber niemand sieht ihn. Das ist Deploy ohne Release:\n\n```yaml\nfeatures:\n  new-checkout-flow:\n    enabled: false        # deploy != release\n    strategy: canary      # gradual rollout instead of big-bang\n    percentage: 5         # start with 5% of traffic\n```\n\nFür große Umbauten reicht ein einzelner `if` allerdings nicht. Wenn ich ein zentrales Modul ersetze, hilft mir das Muster Branch by Abstraction, das Fowler beschreibt und Paul Hammant zugeschrieben wird. Die Idee: Ich ziehe ein gemeinsames Interface ein, unter dem alte und neue Implementierung gleichzeitig im Trunk stehen. Die Umschaltung erfolgt über eine Factory oder einen Toggle. Statt eines wochenlangen Branches integriere ich ein großes Refactoring in kleinen, täglich integrierten Schritten:\n\n```java\npublic interface PaymentGateway {\n    PaymentResult charge(Order order);\n}\n\n// Both live in the trunk at the same time.\nfinal class LegacyPaymentGateway implements PaymentGateway { /* ... */ }\nfinal class NewPaymentGateway    implements PaymentGateway { /* ... */ }\n\n// A factory selects the implementation behind a toggle.\nPaymentGateway gateway = features.isEnabled(\"new-payment-gateway\")\n        ? new NewPaymentGateway()\n        : new LegacyPaymentGateway();\n```\n\nErgänzend gibt es Dark Launching und das Keystone Interface: Man baut ein großes Feature Stück für Stück, aber setzt das sichtbare Element – den Schlussstein – erst ganz zuletzt ein. Bis dahin läuft der neue Code vielleicht schon mit, sammelt Daten oder wird gegen Produktionslast getestet, ohne dass ein Nutzer etwas bemerkt. Auch Canary Releases und Blue-Green Deployments spielen hier hinein: Ausrollen und Aktivieren werden zu graduellen, kontrollierbaren Vorgängen statt zum großen Knall.\n\n## Der Kontrast: GitFlow und der Reflex zum langen Branch\n\nIch will fair bleiben. GitFlow, das Vincent Driessen 2010 in „A successful Git branching model“ vorgestellt hat, war eine durchdachte Antwort auf ein reales Problem – für eine bestimmte Art von Software. Driessen selbst hat 2020 den Hinweis ergänzt, dass sein Modell nicht für Continuous-Delivery-Web-Apps gedacht war. Genau da liegt der Punkt. Wer ein Produkt mit versionierten Releases und langen Support-Zyklen baut, kann mit einem Branching-Modell wie GitFlow gut leben. Wer eine kontinuierlich ausgelieferte Anwendung betreibt, importiert sich damit den Branch-Friedhof frei Haus.\n\nAls leichteres Gegenmodell existiert seit 2011 GitHub Flow: ein kurzlebiger Branch, ein Pull Request, schneller Merge zurück in die Mainline. Das ist schon deutlich näher an Trunk-Based Development. Der eigentliche Unterschied liegt nicht im Tooling, sondern in der Frage, wie lange ein Team bereit ist, Integration aufzuschieben. Je länger diese Antwort ausfällt, desto teurer wird die Rechnung.\n\n## Ehrlich über die Fallstricke\n\nDer Ansatz löst nicht alles, und er bringt eigene Probleme mit. Drei Kanten sind es, an denen sich Teams zuverlässig schneiden.\n\nErstens: Toggle-Schulden, der Toggle-Friedhof. Der Witz an der Sache ist bitter. Man führt Feature Flags ein, um den Branch-Friedhof zu vermeiden, und produziert dabei einen neuen Friedhof aus nie entfernten Flags. Jeder Release Toggle, der nach dem Release im Code bleibt, ist technische Schuld. Er verdoppelt Pfade, verwirrt Leser und verrottet still. Hodgson ist hier deutlich: Release Toggles brauchen ein Ablaufdatum und müssen aktiv zurückgebaut werden. In den Teams, bei denen das funktioniert hat, gehörte das Entfernen des Flags fest zur Definition eines fertigen Features – fertig war es erst, wenn sein Release Toggle wieder aus dem Code verschwunden war.\n\n```mermaid\nflowchart LR\n    A[\"create toggle\"] --> B[\"deploy dark\"]\n    B --> C[\"gradual release\"]\n    C --> D[\"fully on\"]\n    D --> E[\"remove toggle\"]\n    E --> F[\"trunk stays clean\"]\n```\n\nZweitens: Trunk-Based Development ohne belastbare Testautomatisierung und ein CI-Gate ist gefährlich. Der ganze Ansatz steht und fällt damit, dass der Trunk grün und releasebar bleibt. Wenn Builds und Tests langsam oder unzuverlässig sind, importiert man Instabilität direkt in die Mainline, statt sie in Branches zu isolieren. Der lange Branch ist in schlecht getesteten Codebasen manchmal ein rationaler Selbstschutz. Die richtige Reihenfolge lautet deshalb: erst schnelle, verlässliche Tests und ein Gate, dann tägliche Integration. Nicht umgekehrt. Wer bei häufigen Merges zusätzlich Integrationsrisiken zwischen Services fürchtet, findet mit Consumer-Driven Contract Testing – etwa über Pact – ein wirksames Sicherheitsnetz.\n\nDrittens: die Testmatrix-Explosion. Jeder Flag verdoppelt kombinatorisch die möglichen Pfade durch den Code. Zwei Flags ergeben vier Zustände, drei ergeben acht. Ungetestete Flag-Kombinationen sind ein realer Risikoraum, kein theoretischer. Die Disziplin dagegen ist unspektakulär, aber wirksam: wenige gleichzeitig aktive Toggles, klare Ownership für jeden einzelnen, und ein bewusstes Auge auf die Kombinationen, die tatsächlich zusammen auftreten können.\n\n## Warum sich der Aufwand rechnet\n\nWenn ich all das zusammenziehe, lande ich nicht bei einer Tool-Empfehlung, sondern bei einer Haltung zur Auslieferung. Kleine Integrationsdistanz, ein jederzeit releasebarer Trunk, und die saubere Trennung von Deploy und Release ergeben zusammen etwas, das sich in Geschäftszahlen niederschlägt.\n\nDie Zyklen werden kürzer, weil niemand mehr Tage in Merge-Konflikten verliert. Die Reibung im Team sinkt, weil alle gegen denselben aktuellen Stand arbeiten und Konflikte klein und häufig statt groß und selten sind. Die Qualität steigt, weil ein Feature graduell und rückholbar ausgerollt wird, statt in einem einzigen riskanten Sprung. Und das Release verliert seinen Schrecken: Es ist kein nächtliches Deploy-Event mehr, sondern eine Entscheidung, die jemand mit einem Schalter trifft – zurücknehmbar, messbar, unaufgeregt.\n\nDas ist am Ende der Reiz des Ansatzes. Er ersetzt Prozess-Overhead durch etwas Einfaches und Elegantes. Statt eines aufwendigen Branching-Modells, das den Merge-Schmerz verwaltet, vermeidet man den Schmerz, indem man ihn gar nicht erst entstehen lässt. Der Branch-Friedhof ist kein Naturgesetz. Er ist eine Folge aufgeschobener Integration – und die kann man abschaffen.\n\n## Weiterführende Quellen\n\n- Paul Hammant u. a.: [trunkbaseddevelopment.com](https://trunkbaseddevelopment.com/)\n- Martin Fowler & Pete Hodgson: [Feature Toggles (aka Feature Flags)](https://martinfowler.com/articles/feature-toggles.html)\n- Martin Fowler: [Patterns for Managing Source Code Branches](https://martinfowler.com/articles/branching-patterns.html)\n- Martin Fowler: [Branch by Abstraction](https://martinfowler.com/bliki/BranchByAbstraction.html)\n- Forsgren, Humble & Kim: *Accelerate* (2018) und die State-of-DevOps-Reports\n- Humble & Farley: *Continuous Delivery* (2010)\n- Vincent Driessen: [A successful Git branching model](https://nvie.com/posts/a-successful-git-branching-model/) (als Kontrast)"},{"locale":"de","translation_key":"wie-react-den-baum-rendert-und-aktualisiert","slug":"wie-react-den-baum-rendert-und-aktualisiert","title":"Wie React den Baum rendert und aktualisiert","summary":"Vom JSX-Element zum sichtbaren Pixel – was zwischen einer State-Änderung und dem neu gezeichneten Bildschirm genau passiert. Render und Commit als getrennte Phasen, der Abgleich zweier Bäume und warum React fast immer nur einen winzigen Teil des DOM anfasst.","tags":["Software","Frontend","React"],"published_at":"2020-10-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/wie-react-den-baum-rendert-und-aktualisiert/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/af0402076991b04ea8f2886840340192c80694feaa994a046bcd480a7e2ea7ab/wie-react-den-baum-rendert-und-aktualisiert-vorlesen.mp3","audio_duration_secs":550,"text":"# Wie React den Baum rendert und aktualisiert\n\n```js\nsetCount(count + 1);\n```\n\nNach dieser Zeile passiert im Browser erst einmal gar nichts. Kein Knoten wird ersetzt, kein Pixel neu gezeichnet. React ruft zunächst nur JavaScript-Funktionen auf – die Komponenten – und sammelt ein, was sie zurückgeben. Ob überhaupt ein DOM-Knoten angefasst werden muss, entscheidet sich erst danach, in einem eigenen Schritt. Dass eine Komponentenfunktion läuft und dass der Browser etwas zu tun bekommt, sind zwei verschiedene Vorgänge – an dieser Trennung lösen sich die meisten Missverständnisse über React-Performance auf.\n\nIm Beitrag [JSX genau: Die Regeln hinter dem Markup](https://www.mikebild.dev/de/blog/jsx-genau-die-regeln-hinter-dem-markup/) ging es darum, dass ein JSX-Element letztlich nur ein Objekt ist – eine Beschreibung dessen, was auf dem Bildschirm stehen soll. Hier geht der Weg weiter: Wie wird aus dieser Beschreibung ein echtes DOM, und was passiert damit, wenn sich der State ändert? Rendern ist dabei eine Berechnung in JavaScript, das Ändern des DOM ein Schreibvorgang im Browser. React hält beides bewusst auseinander.\n\nZwischen einer State-Änderung und einer sichtbaren DOM-Änderung liegen mehrere klar getrennte Stufen.\n\n:::process{title=\"Von der Aktualisierung zum DOM\" role=\"primary\" preferredPattern=\"vertical-journey\"}\n1. Auslösen · State, Props oder Kontext machen Arbeit notwendig\n2. Rendern · React ruft Komponenten auf und erzeugt die nächste Elementstruktur\n3. Abgleichen · alte und neue Struktur werden anhand von Typ und Schlüssel verglichen\n4. Commit · notwendige Änderungen werden auf DOM und Effects angewendet\n:::\n\nDie Trennung erklärt, warum ein erneuter Komponentenaufruf nicht automatisch einen vollständigen DOM-Neuaufbau bedeutet.\n\n## Drei Schritte: Auslösen, Rendern, Anwenden\n\nReact zeigt eine Oberfläche in drei Schritten an. Man kann sie sich wie eine Bestellung in einer Küche vorstellen: Jemand gibt die Bestellung auf, die Küche kocht, der Kellner bringt das Gericht an den Tisch.\n\n```mermaid\nflowchart LR\n  Trigger[\"1. Auslösen<br/>initial oder setState\"] --> Render[\"2. Rendern<br/>Komponenten aufrufen\"]\n  Render --> Commit[\"3. Anwenden<br/>minimale DOM-Änderung\"]\n  Commit --> Paint[\"Browser zeichnet neu\"]\n```\n\nDer erste Schritt ist das Auslösen. Es gibt genau zwei Anlässe. Beim Start der Anwendung passiert es einmalig, wenn man die Wurzel erzeugt und die oberste Komponente übergibt. Danach wird ein erneutes Rendern nur noch durch eine State-Änderung ausgelöst – immer über die Setter-Function aus `useState` oder einen entsprechenden Mechanismus. Ohne State-Änderung rendert React nichts neu. Das ist wichtig: Ein Klick allein bewirkt nichts; erst wenn der Klick den State ändert, kommt die Maschine in Gang.\n\n```jsx\nimport { createRoot } from \"react-dom/client\";\n\nconst root = createRoot(document.getElementById(\"root\"));\nroot.render(<App />);\n```\n\n## Rendern heißt: React ruft deine Funktionen auf\n\nDer zweite Schritt, das Rendern, ist der, der am meisten missverstanden wird. Rendern bedeutet bei React nicht, etwas auf den Bildschirm zu malen. Rendern bedeutet: React ruft deine Komponentenfunktionen auf, um herauszufinden, was angezeigt werden soll. Beim ersten Mal ruft es die Wurzelkomponente auf. Bei einem erneuten Rendern ruft es die Komponente auf, deren State sich geändert hat.\n\nUnd dieser Aufruf ist rekursiv. Gibt eine Komponente andere Komponenten zurück, ruft React auch die auf, und deren Kinder ebenfalls, bis es keine verschachtelten Komponenten mehr gibt. Am Ende dieses Durchlaufs steht kein DOM, sondern ein neuer Baum aus React-Elementen – denselben Beschreibungsobjekten aus dem JSX-Beitrag, nur eben der ganze Baum davon.\n\n```mermaid\nflowchart TB\n  App[\"App()\"] --> Liste[\"Rechnungsliste()\"]\n  App --> Kopf[\"Kopfzeile()\"]\n  Liste --> Z1[\"Zeile() #1\"]\n  Liste --> Z2[\"Zeile() #2\"]\n  Z1 --> Betrag1[\"Betrag()\"]\n  Z2 --> Betrag2[\"Betrag()\"]\n```\n\nDamit dieser Durchlauf verlässlich ist, verlangt React eine Eigenschaft, die ich in den früheren Beiträgen schon betont habe: Das Rendern muss eine reine Berechnung sein. Für dieselben Props und denselben State muss dieselbe Beschreibung herauskommen, und beim Rendern darf nichts verändert werden, was vorher schon existierte. Nur unter dieser Bedingung kann React das Rendern gefahrlos wiederholen, aufschieben oder mit einem späteren Ergebnis verwerfen – alles Dinge, die die moderne, nebenläufige Variante von React tatsächlich tut.\n\n## Der Abgleich: zwei Bäume vergleichen\n\nJetzt kommt der Kern, der erklärt, warum das Ganze schnell ist. Nach einem erneuten Rendern hat React zwei Bäume: den neuen, gerade berechneten, und den vorherigen aus dem letzten Durchlauf. Bevor irgendetwas ins DOM geschrieben wird, vergleicht React die beiden. Diesen Abgleich nennt man Reconciliation, und er folgt ein paar einfachen Regeln.\n\nAn derselben Stelle im Baum entscheidet der Typ des Elements. Ist der Typ gleich – vorher ein `<div>`, jetzt wieder ein `<div>`, oder vorher wie jetzt dieselbe Komponente –, dann behält React den bestehenden Knoten und aktualisiert nur die Eigenschaften, die sich geändert haben. Ist der Typ verschieden – vorher ein `<p>`, jetzt ein `<div>` –, dann gibt es keinen Abgleich im Detail: React reißt den alten Teilbaum ab, wirft dessen State weg und baut den neuen von Grund auf.\n\n```mermaid\nflowchart LR\n  subgraph Vorher\n    A1[\"div\"] --> A2[\"span: 'Hallo'\"]\n  end\n  subgraph Nachher\n    B1[\"div\"] --> B2[\"span: 'Welt'\"]\n  end\n  A1 -. \"gleicher Typ:<br/>Knoten bleibt\" .-> B1\n  A2 -. \"nur Textinhalt<br/>ändert sich\" .-> B2\n```\n\nDiese Regel hat eine praktische Folge, über die Anfänger oft stolpern. Weil ein Typwechsel den ganzen Teilbaum verwirft, verliert man dabei auch dessen State: Ein Eingabefeld, das vorher in einem `<div>` steckte und jetzt in einem `<section>`, wird als neues Element behandelt und ist wieder leer. Wer will, dass State erhalten bleibt, muss dafür sorgen, dass an derselben Stelle derselbe Typ steht.\n\n## Listen sind der Sonderfall – und hier kommen die Keys\n\nBei Kindern in einer Liste reicht die Position nicht aus, denn Listen ändern ihre Reihenfolge. Genau dafür gibt es den Key, über den ich im Beitrag [JSX genau](https://www.mikebild.dev/de/blog/jsx-genau-die-regeln-hinter-dem-markup/) schon gesprochen habe – und hier zeigt sich, warum er so wichtig ist. Beim Abgleich einer Liste vergleicht React nicht Position mit Position, sondern Key mit Key. Ein Element mit demselben Key gilt als dasselbe Element wie vorher, egal an welcher Stelle es jetzt steht. React verschiebt dann den bestehenden DOM-Knoten, statt ihn wegzuwerfen und neu zu bauen.\n\nDeshalb ist der Array-Index als Key so tückisch. Fügt man vorne ein Element ein, verschiebt sich jeder Index um eins. Für React sieht es dann so aus, als hätte sich der Inhalt jeder Zeile geändert – und der State, der eigentlich zur dritten Rechnung gehörte, klebt plötzlich an der vierten. Mit einer stabilen, fachlichen ID als Key erkennt React die Identität korrekt: Das eingefügte Element ist neu, alle anderen sind dieselben wie vorher und wandern einfach eine Position weiter.\n\n## Anwenden: React fasst nur das an, was sich geändert hat\n\nErst nach dem Abgleich kommt der dritte Schritt, der Commit. Jetzt schreibt React ins echte DOM – aber nur das, was der Abgleich als Unterschied ergeben hat. Beim allerersten Rendern muss alles neu erzeugt werden, dafür hängt React die erzeugten Knoten mit den üblichen DOM-Aufrufen in die Seite. Bei jedem weiteren Mal gilt der entscheidende Satz aus der Dokumentation: React verändert einen DOM-Knoten nur, wenn es zwischen zwei Renderdurchläufen einen Unterschied gibt.\n\nDas klingt selbstverständlich, hat aber sichtbare Konsequenzen. Wenn eine Elternkomponente neu rendert, ein Eingabefeld tief darin aber unverändert bleibt, dann fasst React diesen Knoten nicht an – und der Text, den man gerade getippt hat, bleibt stehen, obwohl der ganze Ast neu gerechnet wurde. Genau das ist der Beweis, dass Rendern und DOM-Änderung getrennt sind: Die Komponente wurde neu gerendert (die Funktion lief), aber das DOM wurde nicht angefasst (es gab keinen Unterschied).\n\n```mermaid\nsequenceDiagram\n  participant N as Nutzer\n  participant R as React\n  participant D as DOM\n  N->>R: setState (Zustand ändert sich)\n  R->>R: Komponenten erneut aufrufen (rendern)\n  R->>R: neuen Baum gegen alten abgleichen\n  R->>D: nur die Unterschiede schreiben\n  D->>N: Browser zeichnet das Ergebnis\n```\n\nNach dem Commit ist React fertig. Was danach passiert, gehört dem Browser: Er zeichnet den geänderten Teil der Seite neu. Dieses Neuzeichnen ist ein eigener, von React unabhängiger Schritt – ein weiterer Grund, warum die minimale DOM-Änderung so viel wert ist, denn je weniger sich im DOM ändert, desto weniger muss der Browser neu malen.\n\n## Warum ein erneutes Rendern nicht teuer sein muss\n\nMit diesem Bild löst sich ein verbreitetes Missverständnis auf. Viele glauben, ein erneutes Rendern sei automatisch langsam, und optimieren wild dagegen an. Aber Rendern heißt zunächst nur, dass eine JavaScript-Funktion noch einmal läuft und ein paar Objekte erzeugt. Das ist selten das Problem. Teuer wird erst das Schreiben ins DOM und das anschließende Neuzeichnen – und genau das hält React durch den Abgleich klein.\n\nDas heißt nicht, dass Rendern gratis ist. Rendert eine hoch angesiedelte Komponente neu, ruft React den ganzen Teilbaum darunter erneut auf, auch wenn am Ende kaum DOM-Änderungen herauskommen. Für die allermeisten Anwendungen ist das kein Thema. Wo es doch messbar wird, lässt sich ein Teilbaum von Hand memoisieren, etwa mit `React.memo`: React überspringt das erneute Rendern dann, solange sich dessen Props nicht geändert haben. Die Reihenfolge bleibt aber dieselbe: erst messen, dann prüfen, ob wirklich das Rendern das Problem ist – und meistens ist es das nicht.\n\n## Was man daraus mitnimmt\n\nDie ganze Mechanik lässt sich auf einen Satz eindampfen: React rechnet bei jeder State-Änderung eine neue Beschreibung der Oberfläche aus, vergleicht sie mit der alten und schreibt nur die Unterschiede ins DOM. Die Beschreibung ist billig, der Vergleich ist clever, und die teure DOM-Arbeit bleibt minimal. Der Key ist dabei kein Detail, sondern die Information, mit der der Vergleich Identität von Position unterscheidet – und der Grund, warum eine gute Wahl des Keys über korrekt erhaltenen State entscheidet.\n\nWer das im Kopf hat, trifft im Alltag bessere Entscheidungen: Man erschrickt nicht mehr vor einem erneuten Rendern, man weiß, warum ein Eingabefeld seinen Text behält oder verliert, und man versteht, wann ein Typwechsel oder ein wechselnder Key einen ganzen Teilbaum wegwirft. Zum tieferen Verhalten von State über Rendergrenzen hinweg – warum State an eine Position im Baum gebunden ist und wann er zurückgesetzt wird – gibt es den Folgebeitrag State erhalten und zurücksetzen.\n\n## Weiterführende Quellen\n\n- Repository introduction-react (Beispiele zum Nachvollziehen): https://github.com/mikebild/introduction-react\n- React, Render und Commit: https://react.dev/learn/render-and-commit\n- React, State als Momentaufnahme: https://react.dev/learn/state-as-a-snapshot\n- React, State erhalten und zurücksetzen: https://react.dev/learn/preserving-and-resetting-state\n- React, Listen rendern (Keys): https://react.dev/learn/rendering-lists"},{"locale":"de","translation_key":"team-automatisierung-github-actions","slug":"team-automatisierung-github-actions","title":"Team-Automatisierung mit GitHub Actions","summary":"Warum ich ausgewählte, wiederkehrende Prüfungen als Workflows ausführe – und woran sich zeigt, ob die Automatisierung das Team tatsächlich entlastet.","tags":["Software","Architektur"],"published_at":"2020-10-12T10:00:00+00:00","updated_at":"2026-07-13T08:39:36.579783+00:00","url":"https://www.mikebild.dev/de/blog/team-automatisierung-github-actions/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/2ff98549f5b5e2054cf19f30ee1c7b8ed4671e23a84d96140f73c5576228c896/team-automatisierung-github-actions-vorlesen.mp3","audio_duration_secs":653,"text":"# Team-Automatisierung mit GitHub Actions\n\nEine Datei unter `.github/workflows` ist kein Build-Skript und kein besseres Makefile. Sie ist eine Regel mit Zähnen: etwas, das bei jedem Push und bei jedem Pull Request greift, ohne dass jemand daran erinnern muss. Der Unterschied klingt akademisch, entscheidet aber darüber, was so eine Datei im Alltag eines Teams überhaupt leisten kann.\n\nSichtbar wird er an den Fragen, die dort landen. Wird gemergt, bevor die Tests grün sind? Ist der Code formatiert? Hat die Änderung einen Changelog-Eintrag? Wer darf ein Release auslösen? Solange die Antworten im Kopf einer erfahrenen Person stehen, in einem Wiki oder in einem PR-Kommentar, den man schon dreimal geschrieben hat, halten sie – aber nur, solange alle wach und anwesend sind. Sie brechen an dem Tag, an dem jemand Neues dazukommt, jemand im Urlaub ist oder es einfach spät ist.\n\nIm Repository dagegen steht die Regel neben dem Code, im selben Verlauf, und wird angewendet statt verhandelt. Genau darin liegt der Wert und genau da fangen auch die interessanten Architekturfragen an.\n\n## Automatisierung als ausführbare Vereinbarung\n\nDer erste Denkfehler ist, Automatisierung als Zeitersparnis zu verkaufen. Zeit spart sie auch, aber das ist der kleinere Effekt. Der größere ist, dass eine Entscheidung aufhört, verhandelbar zu sein. Wenn „wir mergen nur mit grünen Tests“ eine Konvention ist, hält sie so lange, bis der Druck steigt. Wenn dieselbe Regel ein Required Check auf dem Branch ist, hält sie auch dann, wenn niemand hinschaut. Die Regel wandert vom sozialen in den technischen Raum, und dort ist sie robust gegen Müdigkeit und Hierarchie.\n\nDamit verschiebt sich meine Design-Frage. Ich frage nicht „welche Schritte kann ich automatisieren“, sondern „welche Entscheidung will ich verlässlich machen“. Das ist eine Architekturentscheidung, keine Skriptübung. Ein guter Workflow kodiert eine Absicht: Diese Klasse von Fehlern soll den Hauptzweig nie erreichen. Diese Nacharbeit soll niemand mehr von Hand machen. Dieser Schritt soll nachvollziehbar sein, auch in einem halben Jahr.\n\n## Wo die Grenze verläuft\n\nBevor ich eine Zeile YAML schreibe, ziehe ich eine Grenze, die viele Pipelines nicht sauber ziehen: die zwischen Prüfen und Verändern. Ein Gate liest nur. Es sagt ja oder nein und fasst nichts an – Lint, Tests, Typecheck, Format-Check. Ein verändernder Schritt greift ein: Er publiziert ein Artefakt, taggt ein Release, deployt, kommentiert, labelt. Diese beiden Klassen haben völlig unterschiedliche Anforderungen an Rechte, Wiederholbarkeit und Fehlerverhalten, und wenn man sie im selben Job vermischt, erbt der harmlose Test-Schritt plötzlich die Rechte des gefährlichen Deploy-Schritts.\n\nPrüfschritte laufen deshalb auf jedem Pull Request, auch auf denen aus Forks, und bekommen keine Geheimnisse. Verändernde Schritte laufen nur auf vertrauenswürdigen Auslösern – ein Merge auf den Hauptzweig, ein Tag, ein bewusst ausgelöster Lauf. Diese Trennung trägt die Sicherheitsarchitektur des ganzen Repositories. GitHub nimmt einen Teil davon ab: Bei einem Pull Request aus einem Fork ist das `GITHUB_TOKEN` read-only und die Secrets sind nicht sichtbar. Das ist die Antwort auf ein reales Angriffsszenario, und ich baue meine Workflows so, dass sie diese Grenze respektieren statt sie zu umgehen.\n\n## Ein konkretes Gate\n\nSo sieht ein Pull-Request-Gate aus, das ich in dieser Form immer wieder aufsetze. Es prüft und verändert nichts:\n\n```yaml\nname: pr-gate\n\non:\n  pull_request:\n    branches: [main]\n\njobs:\n  verify:\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        node-version: [12.x, 14.x]\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v1\n        with:\n          node-version: ${{ matrix.node-version }}\n      - run: npm ci\n      - run: npm run lint\n      - run: npm run typecheck\n      - run: npm test -- --ci\n```\n\nEin paar Entscheidungen darin sind bewusst und tragen mehr Bedeutung, als sie aussehen. `npm ci` statt `npm install`, weil ich reproduzierbare Installationen aus dem Lockfile will und keine schleichende Drift der Abhängigkeiten. Die Matrix über zwei Node-Versionen, weil „läuft bei mir“ die häufigste Lüge in Teams ist und ich die Kompatibilität lieber vom Rechner in die Pipeline verlege. `fail-fast: false`, weil ich bei einem roten Lauf beide Versionen sehen will, nicht nur die erste, die abbricht – ein abgebrochener Report kostet eine ganze Feedback-Runde.\n\nDer eigentliche Hebel ist aber nicht das YAML. Er ist die Branch-Protection-Regel, die diesen Check zur Pflicht macht. Erst dadurch wird aus einer freundlichen Empfehlung eine Grenze, die der Hauptzweig verteidigt. Der Workflow liefert das Signal, die Protection-Regel gibt ihm Zähne.\n\n## Der teure Fehler ist der glückliche Pfad\n\nDer glückliche Pfad ist schnell gebaut: alles grün, Artefakt gebaut, Release raus. Interessant wird es genau da, wo es nicht gut geht, und dort entscheidet sich, ob die Automatisierung ein Werkzeug oder eine neue Fehlerquelle ist.\n\nDer erste Stolperstein ist Idempotenz. Ein verändernder Schritt muss so gebaut sein, dass ein zweiter Lauf keinen Schaden anrichtet. Läufe werden wiederholt – nach einem Netzwerkfehler, per Re-Run-Knopf, weil jemand denselben Tag neu setzt. Wenn mein Publish-Schritt beim zweiten Mal ein doppeltes Artefakt erzeugt oder mit einem harten Fehler abbricht, habe ich die manuelle Nacharbeit nicht abgeschafft, sondern nur verschoben. Ich baue solche Schritte deshalb so, dass sie prüfen, ob die Version schon existiert, und dann sauber nichts tun.\n\nDer zweite Stolperstein ist der Fork. Ein Pull Request von außen soll geprüft, aber nicht mit Vertrauen belohnt werden. Es gibt `pull_request_target`, das mit den Rechten des Zielrepositories läuft und Zugriff auf Secrets hat – gedacht für harmlose Aufgaben wie das Labeln oder Kommentieren eines PR. Wer damit fremden Code aus dem Fork auscheckt und ausführt, öffnet die Tür für genau die Geheimnisse, die er schützen wollte. Auf `pull_request_target` läuft bei mir deshalb nur Code aus dem Zielbranch und niemals der Inhalt des PR. Damit steht die Trennung von Prüfen und Vertrauen genau an der Stelle, an der sie wirklich wehtut.\n\nDer dritte Stolperstein ist der flaky Test. Ein Check, der zufällig rot wird, ist schlimmer als kein Check, weil er dem Team beibringt, das rote Kreuz zu ignorieren. In dem Moment, in dem „einfach nochmal laufen lassen“ zur Gewohnheit wird, ist der Wert des Gates weg. Ein instabiler Test ist für mich kein Randproblem, sondern ein Fehler an der Grenze selbst – er gehört repariert oder isoliert, nicht toleriert.\n\n## Der Weg von Prüfen zu Verändern\n\nDas Bild dahinter ist einfach, und ich zeichne es bewusst als Fluss, weil die Richtung die ganze Aussage trägt:\n\n```mermaid\nflowchart LR\n  PR[Pull Request] --> Gate{Gate<br/>lint, test, types}\n  Gate -- rot --> Stop[Merge blockiert]\n  Gate -- grün --> Merge[Merge auf main]\n  Merge --> Trusted[Vertrauenswürdiger Lauf]\n  Release --> Audit[Nachvollziehbar im Verlauf]\n  Trusted --> Release[Tag, Publish, Deploy]\n```\n\nLinks wird nur gelesen, rechts wird erst nach dem Merge verändert. Zwischen beiden liegt die Vertrauensgrenze. Die Sicherheits- und Betriebsfragen, die in echten Projekten auftauchen, lassen sich fast alle darauf zurückführen, ob ein Schritt auf der richtigen Seite dieses Strichs steht.\n\n## Der bewusste Auslöser\n\nNicht jeder verändernde Schritt soll automatisch feuern. Für ein Release will ich oft einen Menschen im Spiel, aber ohne dass jemand lokal Kommandos abtippt, die keiner mitliest. Genau dafür nutze ich `workflow_dispatch` – einen Auslöser, den man bewusst per Knopfdruck betätigt, mit einer kleinen Eingabemaske:\n\n```yaml\nname: release\n\non:\n  workflow_dispatch:\n    inputs:\n      level:\n        description: \"semver bump level\"\n        required: true\n        default: patch\n\njobs:\n  publish:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v1\n        with:\n          node-version: 14.x\n      - run: npm ci\n      - run: npm run build\n      - run: node ./scripts/release.js --level \"${{ github.event.inputs.level }}\"\n        env:\n          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}\n```\n\nDas ist die manuelle Entscheidung als Formular statt als mündliche Absprache. Die eigentliche Logik liegt bewusst in `release.js`, einem getesteten Skript, das den Workflow nur noch aufruft – das Secret ist auf diesen einen vertrauenswürdigen Pfad begrenzt und taucht im Prüf-Gate nie auf. Der Gewinn liegt in der Nachvollziehbarkeit: Jedes Release steht mit Auslöser, Zeitpunkt und Person im selben Verlauf wie der Code. Aus einem Vorgang, der früher in einem Terminal verschwand, wird ein Eintrag, den man ein halbes Jahr später noch lesen kann.\n\n## Was das messbar bringt\n\nIch mag keine Automatisierung, die sich nur gut anfühlt. Der Nutzen sollte an drei Stellen sichtbar werden, sonst habe ich Aufwand gegen ein Bauchgefühl getauscht.\n\nDer erste ist die Durchlaufzeit eines Pull Requests. Wenn das Gate die üblichen Rückfragen im Review – ist es formatiert, laufen die Tests, ist der Typecheck sauber – schon vor dem menschlichen Blick beantwortet, verkürzt sich die Zeit von „PR offen“ zu „gemergt“ spürbar. Das Review kann sich auf das konzentrieren, was eine Maschine nicht sieht: ob die Lösung die richtige ist.\n\nDer zweite ist die Reibung im Review selbst. Diskussionen über Formatierung und Stil sind teuer, nicht weil sie lange dauern, sondern weil sie den Ton vergiften. Eine Maschine, die Format-Fragen entscheidet, nimmt sie aus der zwischenmenschlichen Ebene heraus. Niemand streitet mehr mit einem Linter.\n\nDer dritte ist die Zeit bis zum ersten sinnvollen Beitrag einer neuen Person. Wenn die Regeln des Teams im Repository stehen und beim ersten PR sichtbar werden, muss niemand sie mündlich weitergeben. Onboarding wird von einer Bringschuld erfahrener Kollegen zu einer Eigenschaft des Projekts. Für mich ist das der unterschätzteste Effekt: Automatisierung ist auch eine Form von Dokumentation, die nie veraltet, weil sie ausgeführt wird.\n\n## Wann ich es bewusst nicht mache\n\nEin Werkzeug ist keine Architektur, und GitHub Actions ist keine Ausnahme. Es gibt Fälle, in denen ich abrate. Wenn eine Automatisierung eine echte Orchestrierung über viele Systeme mit Zustand, Wiederaufsetzpunkten und langen Laufzeiten wäre, ist ein Workflow-Runner das falsche Zuhause – das gehört in einen richtigen Job-Runner oder eine dafür gebaute Plattform, nicht in eine CI-Datei. Und wenn eine Regel noch im Fluss ist, weil das Team selbst nicht weiß, ob sie richtig ist, zementiere ich sie nicht in einem Required Check. Automatisierung ist gut darin, geklärte Entscheidungen durchzusetzen, und schlecht darin, ungeklärte zu ersetzen.\n\nDer teuerste Fehler ist, den Runner zur heimlichen Deployment-Plattform wachsen zu lassen, bis kritische Prozesse in einer YAML-Datei liegen, die niemand mehr versteht. Ein Workflow, der eine Seite füllt, ist ein Gewinn. Ein Workflow, der drei Bildschirme füllt und Sonderfälle mit `if`-Bedingungen abfängt, ist meist ein Programm am falschen Ort – dann gehört die Logik in ein getestetes Skript oder ein kleines CLI, das der Workflow nur aufruft.\n\n## Wie ich anfange\n\nIn der Praxis mache ich daraus keine große Initiative. Ich fange mit genau einem Gate an, das eine echte, wiederkehrende Reibung wegnimmt – meistens Tests plus Format-Check auf jedem PR – und mache es über die Branch-Protection zur Pflicht. Dann warte ich zwei Wochen und schaue, ob es das Team entlastet oder nur nervt. Erst wenn es trägt, kommt der nächste Schritt dazu, und der erste verändernde Schritt kommt bewusst später als der erste prüfende.\n\nDer Maßstab bleibt derselbe wie bei jeder Architektur: Eine Entscheidung ist erst gut, wenn ich ihren Fehlerpfad beschreiben kann. Was passiert bei einem Re-Run? Was, wenn der PR aus einem Fork kommt? Was, wenn ein Test flaky wird? Wer bemerkt es, wenn das Gate stumm ausfällt? Wenn ich diese Fragen beantworten kann, ist aus der Bequemlichkeit ein Stück verlässliche Teaminfrastruktur geworden. Dass dabei auch eine Maschine Arbeit abnimmt, ist der angenehme Side Effect. Der Punkt ist die Entscheidung, die endlich hält."},{"locale":"de","translation_key":"web-apis-mit-flask","slug":"web-apis-mit-flask","title":"Web-APIs mit Flask: von der App zur JSON-API","summary":"Von Hello World zur JSON-API: wie Routing, Request-Verarbeitung und jsonify in Flask 1.1 zusammenspielen – und warum SSR und API dieselbe Mechanik sind.","tags":["Software","Python","Backend"],"published_at":"2020-09-22T10:00:00+00:00","updated_at":"2026-07-13T10:01:21.588381+00:00","url":"https://www.mikebild.dev/de/blog/web-apis-mit-flask/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/f6bb102177a044514e48f62a60d43d84465b31f9ce999c5e755f4e48d94f15bd/web-apis-mit-flask-vorlesen.mp3","audio_duration_secs":672,"text":"Drei Begriffe genügen, um alles zu beschreiben, was Flask tut: Route, Request, Response. Ein Dekorator bindet einen URL-Pfad an eine Python-Funktion, das Objekt `request` beschreibt die eingehende Anfrage, und der Rückgabewert der Funktion wird zur Antwort. Templates, Blueprints, JSON – alles Weitere hängt an diesen drei Punkten.\n\nDamit ist Flask ein guter Ausgangspunkt, wenn aus einem Python-Skript eine Schnittstelle werden soll, die ein anderes Programm über HTTP ansprechen kann. Es ist ein Mikro-Framework: Routing, Request-Objekt und Template-Engine sind dabei, fast alles andere bleibt offen. Es gibt kaum Magie, die man erst wieder auseinandernehmen müsste, um zu verstehen, was zwischen HTTP-Request und eigener Funktion tatsächlich passiert. Dieser Text bezieht sich durchgehend auf Flask 1.1 – die stabile Serie zum Zeitpunkt des Schreibens (1.1.2 erschien im April 2020). Wer schon einmal mit Python-Objekten, Dekoratoren und Dictionaries gearbeitet hat, findet sich schnell zurecht.\n\n**Redaktionelle Einordnung (Juli 2026):** Beim heutigen Flask 3.1 ruft `request.json` intern `get_json()` auf und antwortet bei einem ungeeigneten `Content-Type` standardmäßig mit 415. Nur `request.get_json(silent=True)` liefert in diesem Fall `None`. Diese Änderung betrifft die Error Handling, nicht das Routing-Modell des Artikels.\n\n## Hello World, und was dahinter steckt\n\nDer kleinste sinnvolle Flask-Server passt in sechs Zeilen. An ihm lässt sich das gesamte Modell ablesen.\n\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n    return 'Hello World!'\n\nif __name__ == '__main__':\n    app.run(debug=True, port=8080)\n```\n\n`Flask(__name__)` erzeugt die Anwendung. Der Name des Moduls dient Flask später als Ausgangspunkt, um etwa Templates und statische Dateien relativ zum Projekt zu finden. Der Dekorator `@app.route('/')` verknüpft einen URL-Pfad mit einer Funktion. Wird der Server unter `/` aufgerufen, ruft Flask `hello_world()` auf und schickt den Rückgabewert als Antwort zurück. `app.run()` startet den eingebauten Entwicklungsserver.\n\nDer zentrale Gedanke: Eine Funktion, die einen String zurückgibt, wird zu einer HTTP-Antwort mit `Content-Type: text/html`. Flask nimmt mir die gesamte Übersetzung zwischen HTTP und Python-Funktion ab. Und diese Übersetzung ist flexibler, als der erste Eindruck vermuten lässt. Ein View darf nicht nur einen String zurückgeben, sondern auch ein Tuple aus Rumpf und Statuscode:\n\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n    return 'Hello World!', 202\n```\n\nHier bekommt der Client denselben Text, aber mit dem Status 202 statt der Standard-200. Das Tuple kann sogar drei Elemente haben – Rumpf, Status und ein Dictionary mit zusätzlichen Headern. Diese Rückgabe-Konventionen sind der Kern von Flask, und sie erklären, warum sich dieselbe Route mal als HTML-Seite und mal als JSON-API verhält.\n\n## Routing, Request, Response\n\nBevor die eigentliche API dran ist, lohnen die drei Begriffe eine genauere Betrachtung, weil sie durchgängig wiederkehren:\n\n- Route: Der Dekorator `@app.route(pfad, methods=[...])` bindet einen URL-Pfad an eine Funktion. Pfad-Parameter wie `<int:item_id>` reichen Teile der URL direkt an die Funktion weiter, und `methods` legt fest, welche HTTP-Verben die Route bedient.\n- Request: Das importierte Objekt `request` beschreibt die eingehende Anfrage – `request.args` liest den Query-String, `request.form` die Formularfelder, `request.json` den JSON-Rumpf, `request.method` das verwendete Verb.\n- Response: Der Rückgabewert der Funktion. Ein String wird zu HTML, `jsonify(...)` zu JSON, ein Tuple `(rumpf, status)` steuert den Statuscode.\n\nDiese drei Achsen genügen, um erstaunlich viel zu bauen. Ein Pfad mit Parameter sieht etwa so aus:\n\n```python\n@app.route('/user/<username>')\ndef profile(username):\n    return f'Profile page of {username}'\n```\n\nDer Platzhalter `<username>` wird als Argument an die Funktion übergeben. Braucht man einen numerischen Wert, verlangt der Konverter `<int:item_id>` eine Ganzzahl und liefert sie bereits als `int` – passt der Pfad nicht auf dieses Muster, antwortet Flask von selbst mit 404, bevor meine Funktion überhaupt läuft.\n\nDer Request-Lifecycle lässt sich in einem einfachen Diagramm zusammenfassen. Zwischen der ankommenden Anfrage und der fertigen Antwort stehen nur wenige, klar benannte Schritte.\n\n```mermaid\ngraph LR\n    A[HTTP Request] --> B[\"@app.route<br/>Matching\"]\n    B --> C[View Handler]\n    C --> D[\"jsonify()\"]\n    D --> E[JSON Response]\n```\n\nDer Request trifft ein, Flask sucht die passende Route, ruft die zugehörige Funktion auf, diese baut mit `jsonify` eine Antwort, und die geht an den Client zurück. Kein Schritt davon ist versteckt – man kann an jeder Stelle einen `print` setzen und zusehen.\n\n## Von der Seite zur Schnittstelle\n\nJetzt zum eigentlichen Ziel: eine kleine, REST-artige Schnittstelle. Ich baue dafür einen einzigen Pfad, der zwei Verben bedient – ein `GET` liefert die Liste aller Einträge, ein `POST` legt einen neuen an. Dass eine URL mehrere Methoden bedienen kann, ist genau der Punkt, an dem REST-Denken sichtbar wird: Die Ressource ist dieselbe, nur die Aktion darauf unterscheidet sich.\n\n```python\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\nitems = []  # demo-only in-memory store\n\n@app.route('/items', methods=['GET', 'POST'])\ndef items_collection():\n    if request.method == 'POST':\n        payload = request.get_json()\n        item = {'id': len(items) + 1, 'name': payload['name']}\n        items.append(item)\n        return jsonify(item), 201\n    return jsonify(items)  # GET\n\n@app.route('/items/<int:item_id>')\ndef item_detail(item_id):\n    match = next((i for i in items if i['id'] == item_id), None)\n    return (jsonify(match), 200) if match else ('Not found', 404)\n```\n\nEin paar Dinge sind hier bewusst gesetzt. Beim `POST` lese ich den JSON-Rumpf mit `request.get_json()` und antworte mit Status 201, dem Code für „neu erstellt“. Beim `GET` gebe ich die gesamte Liste zurück. Und die zweite Route zeigt den Pfad-Parameter im Einsatz: `/items/3` sucht den Eintrag mit dieser ID und liefert entweder ihn oder eine 404-Antwort.\n\n`jsonify` ist dabei mehr als ein hübscheres `json.dumps`. Es serialisiert das Dictionary oder die Liste, setzt den `Content-Type` korrekt auf `application/json` und baut ein fertiges Response-Objekt. Der handgemachte Weg – `json.dumps(...)` in einen String verwandeln und den Header manuell setzen – funktioniert zwar, ist aber fehleranfälliger und dupliziert genau die Arbeit, die Flask ohnehin sauber erledigt.\n\n## Der historische Dreh: dict direkt zurückgeben\n\nHier lohnt eine Notiz, die in älteren Beispielen für Verwirrung sorgt. Seit Flask 1.1 darf ein View ein `dict` direkt zurückgeben – Flask ruft dann intern automatisch `jsonify()` darauf auf:\n\n```python\n@app.route('/status')\ndef status():\n    return {'ok': True, 'items': len(items)}  # Flask >= 1.1 -> JSON\n```\n\nDas ist bequem, aber es ist eine relativ junge Erleichterung. In Flask 1.0 und davor war genau diese Zeile ein Fehler: Ein Dictionary war kein gültiger Rückgabetyp, und man bekam einen `TypeError`. Wer damals JSON ausliefern wollte, musste `return jsonify({...})` explizit schreiben. In Tutorials und Stack-Overflow-Antworten stehen beide Varianten nebeneinander, ohne dass die Version dabeisteht – so geraten Version und Verhalten leicht durcheinander. Solange nicht sicher ist, welche Flask-Version läuft, schreibe ich `jsonify` explizit hin. Es funktioniert in jeder Version und macht die Absicht deutlich.\n\n## SSR und API sind dieselbe Mechanik\n\nServerseitiges Rendern (SSR) und eine JSON-API gelten oft als zwei verschiedene Welten. In Flask sind sie es nicht: derselbe Routing-Mechanismus, dieselbe Funktion, nur ein anderer Rückgabetyp. Statt `jsonify` verwende ich `render_template`, das eine HTML-Datei aus dem Ordner `templates/` mit Jinja2 füllt.\n\n```python\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n    return render_template('index.html', items=items)\n\n@app.route('/forms', methods=['POST'])\ndef forms():\n    return 'You said: ' + request.form['text']\n```\n\nDas zugehörige Template ist gewöhnliches HTML mit Platzhaltern. Der übergebene Kontext – hier `items` – steht in der Vorlage als Variable zur Verfügung:\n\n```html\n<form action=\"/forms\" method=\"POST\">\n  <input name=\"text\">\n  <input type=\"submit\" value=\"Submit\">\n</form>\n\n<ul>\n  {% for item in items %}\n    <li>{{ item.name }}</li>\n  {% endfor %}\n</ul>\n```\n\nDer Unterschied zwischen der API und der gerenderten Seite ist allein die Repräsentation: einmal JSON für Maschinen, einmal HTML für den Browser. Das Framework darunter bleibt gleich. Als Diagramm ist die Verzweigung schnell erzählt.\n\n```mermaid\ngraph LR\n    A[View Handler] --> B{Repräsentation?}\n    B -->|render_template| C[HTML]\n    B -->|jsonify| D[JSON]\n```\n\nDamit lösen sich „API-Framework“ und „Web-Framework“ als getrennte Kategorien auf. Es ist eine Entscheidung pro Route, kein Architekturbruch.\n\n## Struktur mit Blueprints\n\nSobald mehr als eine Handvoll Routen zusammenkommt, wird die eine große `app.py` unübersichtlich. Flask bietet dafür Blueprints – eine Möglichkeit, Routen thematisch zu gruppieren und mit einem gemeinsamen Präfix an die App zu hängen.\n\n```python\nfrom flask import Blueprint, jsonify\n\napi = Blueprint('api', __name__, url_prefix='/api')\n\n@api.route('/items')\ndef list_items():\n    return jsonify(items)\n\n# in the main app:\n# app.register_blueprint(api)\n```\n\nAlle Routen dieses Blueprints liegen dann unter `/api` – die Route oben ist also unter `/api/items` erreichbar. Wichtig zu verstehen: Ein Blueprint ist ein reines Strukturmittel. Er ändert nichts am Laufzeitverhalten und bringt keine eigene Magie mit, sondern hilft nur, den Code in nachvollziehbare Einheiten zu schneiden. Ich trenne damit gern die JSON-API von den gerenderten Seiten – zwei Blueprints, ein Projekt.\n\n## Drei Fallstricke\n\nZum Schluss die Stellen, an denen es in der Praxis regelmäßig klemmt. Keiner dieser Punkte ist ein Bug in Flask – es sind Eigenheiten, die man kennen muss.\n\nDer erste betrifft `request.json`. Im hier verwendeten Flask 1.1 war der Wert ohne `Content-Type: application/json` schlicht `None`, und ein direkter Zugriff wie `payload['name']` lief in einen Fehler. Aktuelle Flask-Versionen antworten bei diesem Zugriff standardmäßig mit 415. Wer bewusst selbst behandeln will, nutzt `request.get_json(silent=True)` und prüft das mögliche `None`.\n\n```python\n@app.route('/echo', methods=['POST'])\ndef echo():\n    data = request.get_json(silent=True)\n    if not data:\n        return jsonify({'error': 'expected JSON body'}), 400\n    return jsonify(data)\n```\n\nDer zweite ist `debug=True`. Im Entwicklungsserver ist der Debug-Modus praktisch – er lädt bei Änderungen neu und zeigt bei Fehlern einen interaktiven Traceback. Genau dieser interaktive Traceback ist aber eine ausführbare Konsole im Browser. In einer öffentlich erreichbaren Umgebung ist das eine offene Tür für das Ausführen beliebigen Codes. `debug=True` gehört ausschließlich in die lokale Entwicklung. Und `app.run()` selbst ist ohnehin nur der Entwicklungsserver – für den produktiven Betrieb setzt man einen WSGI-Server wie gunicorn oder uWSGI davor.\n\nDer dritte betrifft den globalen Zustand. Meine `items = []`-Liste ist eine Demo-Abkürzung und keine Datenbank. Sie steht im Speicher des Prozesses, geht bei jedem Neustart verloren und verhält sich unzuverlässig, sobald mehrere Worker parallel laufen – dann sieht jeder Worker seine eigene Liste. Für ein Beispiel wie dieses ist das völlig in Ordnung, für echte Daten braucht es Persistenz, etwa eine Datenbank hinter der Route.\n\n## Fazit\n\nDer Weg von einem Python-Skript zu einer Web-Schnittstelle ist mit Flask kürzer, als viele erwarten, und – wichtiger – er ist nachvollziehbar. Eine Funktion wird über einen Dekorator an einen Pfad gebunden, das `request`-Objekt beschreibt die Anfrage, der Rückgabewert wird zur Antwort. Ob daraus eine HTML-Seite über `render_template` oder eine JSON-API über `jsonify` wird, ist eine Entscheidung pro Route und kein Systemwechsel. Blueprints geben dem Ganzen Struktur, sobald es wächst, ohne neue Konzepte einzuführen.\n\nWichtiger als die Liste der Funktionen ist mir dabei, dass sich jederzeit sagen lässt, was zwischen dem HTTP-Request und der eigenen Funktion geschieht. Flask hält diese Kette sichtbar. Wer sie einmal durchgegangen ist, liest auch komfortablere Frameworks gelassener – darunter steht überall dasselbe Modell aus Route, Request und Response.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-python.html\n- Repository `introduction-python`, Verzeichnis `web/examples/` – die lauffähigen Flask-Beispiele (`1-app.py`, `2-html.py`, `3-json.py`, `app.py`), auf denen dieser Artikel aufbaut.\n- Flask 1.1 Quickstart – Routing, Methoden und Pfad-Parameter: https://flask.palletsprojects.com/en/1.1.x/quickstart/\n- Flask 1.1 API-Referenz – Request-Objekt und `jsonify`: https://flask.palletsprojects.com/en/1.1.x/api/\n- Flask 1.1 Blueprints: https://flask.palletsprojects.com/en/1.1.x/blueprints/\n- Flask 1.1 Deployment – warum der Entwicklungsserver nicht in Produktion gehört: https://flask.palletsprojects.com/en/1.1.x/deploying/\n- [Flask 3.1: eingehende Request-Daten und `get_json()`](https://flask.palletsprojects.com/en/stable/api/#flask.Request.get_json)"},{"locale":"de","translation_key":"read-models-sind-projektionen","slug":"read-models-sind-projektionen","title":"Read Models aus Events: Projections statt zufälliger Caches","summary":"Ein aus Events aufgebautes Read Model ist eine bewusst gepflegte Projection für konkrete Queries. Herkunft und Rebuild unterscheiden es von einem zufällig gewachsenen Cache, auch wenn die technische Sicht cacheähnlich wirken kann.","tags":["Software","Architektur"],"published_at":"2020-09-15T10:00:00+00:00","updated_at":"2026-07-13T07:56:13.215191+00:00","url":"https://www.mikebild.dev/de/blog/read-models-sind-projektionen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/9d0ee765f965aeedcb5c67ddc831ab56b6c1883afb8741f00619c2bc01d77034/read-models-sind-projektionen-vorlesen.mp3","audio_duration_secs":706,"text":"# Read Models aus Events: Projections statt zufälliger Caches\n\nDieser Beitrag betrachtet den Event-Sourcing-Fall: Hinter der Lese-View liegt ein Event-Strom, aus dem sie sich erneut ableiten lässt. Das Read Model ist damit die für Queries vorgesehene Sicht und keine zufällige Beschleunigungsschicht. Technisch darf sie trotzdem cacheähnlich aussehen, etwa als denormalisierte Tabelle mit schneller Ersetzung. Entscheidend sind Herkunft und Rebuild, nicht das Speicherprodukt.\n\nDer Vergleich mit dem Cache liegt trotzdem nahe: eine denormalisierte, schnelle Sicht, die neben der eigentlichen Datenbank steht, sieht nun einmal aus wie einer. Teuer wird er in dem Moment, in dem das erste Schema auf der Leseseite wandern soll. Eine Leseseite, die als Cache gebaut wurde, lässt sich dann nicht mehr sauber wiederherstellen. Eine, die als Projection gebaut wurde, hat den Neuaufbau von Anfang an im Design – und dieser Unterschied zieht sich durch Betrieb, Migration und Fehlerbehebung.\n\n## Woher der Cache-Reflex kommt\n\nDer Reflex hat einen wahren Kern. Ein Read Model und ein Cache lösen oberflächlich dasselbe Problem: Queries sollen schnell sein, ohne das teure Schreibmodell bei jeder Anzeige zu befragen. Beide sind denormalisiert, beide liegen dem Nutzer näher als die Wahrheitsquelle, beide sind potenziell veraltet.\n\nDer Bruch liegt eine Ebene tiefer, bei der Frage: Wer ist die Wahrheitsquelle, und wie entsteht die schnelle Sicht daraus? Ein Cache hat eine autoritative Datenbank *hinter* sich. Fällt der Cache-Eintrag weg, zieht man den Datensatz erneut aus dieser Quelle und legt ihn wieder ab. Die Invalidierung ist ein Side Effect von TTL oder Verdrängung, der Kaltstart ist ein Betriebsdetail. Ein Read Model dagegen hat keine \"eigentliche\" Lese-Datenbank hinter sich, aus der man es bei Bedarf nachlädt. Es *ist* die autoritative Lese-View. Was dahinter liegt, ist der Event Store oder das Write Model – und daraus wird das Read Model nicht \"nachgeladen\", sondern *berechnet*.\n\nDiese Berechnung ist die Projection. Und sie ist der Grund, warum ich auf der Unterscheidung bestehe.\n\n## Was eine Projection ausmacht\n\nVor dem Code stehen drei Begriffe. Martin Fowler beschreibt CQRS als bewusste Trennung: Man nutzt ein anderes Modell zum Schreiben als zum Lesen. Das Read Model ist dabei kein Blick durch das Domänenmodell hindurch, sondern ein eigenständiges Modell, das ausschließlich Queries bedient. Greg Young und Vaughn Vernon liefern das Bindeglied: die Projection – der Prozess, der aus den Änderungen der Schreibseite, konkret aus den Domain Events, das Read Model ableitet und fortschreibt.\n\nDie entscheidende Eigenschaft der hier behandelten Projection ist ihre Herkunft aus einem immutable Event-Strom. Wenn Events, Reihenfolge, Projektionscode und sonstige Eingaben feststehen, entsteht beim Wiederholen dasselbe Read Model. Daraus folgt die zweite Eigenschaft: Man kann die Sicht wegwerfen und aus den Events vollständig neu berechnen. Der Rebuild ist kein Notfallplan, sondern ein reguläres Werkzeug.\n\nGenau hier trennt sich die Projection vom Cache. Ein Cache kann man auch neu füllen, aber der Neuaufbau ist ein Kaltstart-Side-Effect, dessen Ergebnis von der Quelle im *aktuellen* Moment abhängt. Ein Rebuild einer Projection ist deterministisch und zeitunabhängig, weil er auf der Historie fußt, nicht auf einem Momentanzustand.\n\nEin Vorbehalt gehört hierher: Dieser freie Rebuild setzt voraus, dass die Events dauerhaft und vollständig vorliegen – also einen Schreibweg mit Event Sourcing, bei dem der Event Store die Wahrheitsquelle ist. CQRS und Event Sourcing sind zwei getrennte Entscheidungen, die man oft zusammen trifft, aber nicht muss; Fowler beschreibt CQRS ausdrücklich unabhängig von der Persistenzform. Wer CQRS ohne persistente Event-Historie betreibt und die Leseseite nur aus flüchtigen Benachrichtigungen fortschreibt, hat eine Projection im Betrieb, aber nicht den deterministischen Neuaufbau aus der Historie. Die Beispiele hier setzen den Event Store voraus – und mit ihm die Eigenschaft, die das Read Model vom Cache trennt.\n\n## Die Projection als Faltung\n\nAm klarsten wird das im Code. Eine Projection ist im Kern eine Faltung – ein `reduce` über die Events, das mit einem leeren Zustand beginnt und jedes Event auf den bisherigen Zustand anwendet. Illustrativ, in TypeScript:\n\n```ts\ntype OrderPlaced = { type: \"OrderPlaced\"; orderId: string; total: number }\ntype OrderShipped = { type: \"OrderShipped\"; orderId: string }\ntype OrderCancelled = { type: \"OrderCancelled\"; orderId: string }\n\ntype OrderEvent = OrderPlaced | OrderShipped | OrderCancelled\n\ntype OrderSummary = {\n  orderId: string\n  total: number\n  status: \"placed\" | \"shipped\" | \"cancelled\"\n}\n\n// pure reducer: (state, event) => state\nfunction apply(state: OrderSummary, event: OrderEvent): OrderSummary {\n  switch (event.type) {\n    case \"OrderPlaced\":\n      return { orderId: event.orderId, total: event.total, status: \"placed\" }\n    case \"OrderShipped\":\n      return { ...state, status: \"shipped\" }\n    case \"OrderCancelled\":\n      return { ...state, status: \"cancelled\" }\n  }\n}\n\n// the projection is a fold over the event stream\nfunction project(events: OrderEvent[]): OrderSummary {\n  return events.reduce(apply, {} as OrderSummary)\n}\n```\n\n`apply` ist eine Pure Function `(state, event) => state`. Kein Zugriff auf die Uhr, kein Netzwerk, keine Zufälligkeit. Das ist keine stilistische Vorliebe. Ohne diese Reinheit bleibt der Rebuild nicht deterministisch. Sobald in `apply` ein `Date.now()` oder ein externer Lookup steckt, ist die schöne Eigenschaft \"gleiche Events, gleiches Read Model\" verloren – und man hat sich unbemerkt einen Cache gebaut, dessen Neuaufbau vom Zeitpunkt abhängt.\n\n## Ein Read Model pro Sicht\n\nDer zweite Kernpunkt: Es gibt nicht *das* eine Read Model. Es gibt eines pro Query, jeweils denormalisiert und exakt auf die Sicht zugeschnitten, die es bedient. Vernon weist darauf hin, dass Read Models besonders dort nützlich sind, wo die angezeigten Daten quer über mehrere Aggregates schneiden. Das Read Model zieht diese Daten vorberechnet zusammen, sodass die Query flach und billig bleibt.\n\nEine Sicht für eine Bestellliste zieht andere Felder als eine Detailsicht. Statt zur Laufzeit zu joinen und zu rechnen, legt die Projection die fertigen Werte ab:\n\n```ts\ntype CustomerOrderListItem = {\n  orderId: string\n  customerName: string   // denormalized from the customer aggregate\n  itemCount: number      // precomputed, no join at read time\n  totalAmount: number\n  statusLabel: string    // display-ready, e.g. \"Versandt\"\n}\n\n// this projection cuts across order and customer to build one flat view\nfunction toListItem(\n  order: OrderSummary,\n  customerName: string,\n  itemCount: number,\n): CustomerOrderListItem {\n  return {\n    orderId: order.orderId,\n    customerName,\n    itemCount,\n    totalAmount: order.total,\n    statusLabel: order.status === \"shipped\" ? \"Versandt\" : \"Offen\",\n  }\n}\n```\n\nWichtig ist die Denkrichtung: Das Read Model wird für die Query gebaut, nicht die Query für das Read Model. Das ist genau das, was ich in [CQRS ist eine fachliche Grenze](https://www.mikebild.dev/de/blog/cqrs-fachliche-grenze-kein-framework/) meine, wenn ich sage, dass die Trennung von Lesen und Schreiben eine Aussage über Verantwortlichkeit ist, nicht über zwei Datenbanken. Die Leseseite darf ihre eigene Form haben, weil sie eine eigene Aufgabe hat.\n\n## Der Rebuild gehört zum Design\n\nWeil die Projection deterministisch aus den Events entsteht, ist der Neuaufbau trivial zu formulieren – man leert die Read-Seite und spielt die Events erneut ein:\n\n```ts\ninterface ReadStore {\n  clear(): void\n  save(view: OrderSummary): void\n}\n\ninterface EventStore {\n  allEvents(): Iterable<OrderEvent>\n}\n\nfunction rebuild(events: EventStore, read: ReadStore): void {\n  read.clear()\n  const views = new Map<string, OrderSummary>()\n  for (const event of events.allEvents()) {\n    const current = views.get(event.orderId) ?? ({} as OrderSummary)\n    views.set(event.orderId, apply(current, event))\n  }\n  for (const view of views.values()) read.save(view)\n}\n```\n\nDieser `rebuild` ist der praktische Lackmustest. Wenn er sich sauber schreiben lässt, hat man eine Projection. Wenn er sich *nicht* sauber schreiben lässt – weil Zustand von außen einfließt, weil Events verworfen wurden, weil das `apply` nicht rein ist –, dann hat man einen Cache und sollte aufhören, ihn Read Model zu nennen.\n\nDer Rebuild ist auch die Antwort auf eine Frage, die in Projekten früher oder später kommt: Was passiert bei einer Schema-Änderung auf der Leseseite? Bei einem Cache ist das ein Migrationsproblem mit Datenübernahme. Bei einer Projection ist es ein neuer Projector, den man über die vorhandenen Events laufen lässt. Die neue Sicht entsteht aus derselben Quelle wie die alte. Das ist der Moment, in dem sich die anfängliche Disziplin auszahlt.\n\n## Der Datenfluss im Bild\n\nEine Quelle, mehrere sichtenspezifische Projections – so sieht der Fluss aus:\n\n```mermaid\nflowchart LR\n  C[Command] --> W[Write Model /<br/>Event Store]\n  W -->|Events| P[Projektor]\n  P -->|async · eventual| A[Read Model A<br/>Liste]\n  P -->|async · eventual| B[Read Model B<br/>Detail]\n  P -->|async · eventual| R[Read Model C<br/>Report]\n```\n\nDer Command läuft gegen das Write Model und erzeugt Events. Der Projector abonniert diese Events und schreibt daraus so viele Read Models fort, wie es Sichten gibt. Die Kanten zu den Read Models sind bewusst mit \"async · eventual\" beschriftet, denn hier steckt der dritte Kernpunkt: die Konsistenz.\n\n## Eventual Consistency ist ein bewusster Handel\n\nDie Projection läuft asynchron, nachdem der Schreibvorgang erfolgreich war. Fowler formuliert die Konsequenz nüchtern: Man kann nicht exakt garantieren, *wann* das Read Model konsistent ist. Kurz nach dem Schreiben ist es potenziell veraltet. Das ist kein Bug, kein Datenverlust und keine Korruption – es ist ein begrenzter, bekannter Verzug, den man in Kauf nimmt, um Lese- und Schreibseite zu entkoppeln.\n\nDer Verzug selbst macht selten Ärger. Der Umgang damit schon. Wer eine synchrone Read-after-write-Konsistenz erwartet, baut die UI so, dass sie sofort nach dem Command aus dem Read Model liest und sich wundert, dass der neue Datensatz \"fehlt\". Er ist nicht weg, die Projection ist nur noch nicht durch. Das gehört ins Design der Oberfläche, nicht in einen Bugreport.\n\nGefährlicher ist die zweite Variante: aus dem Read Model heraus Command-seitige Invarianten prüfen. Greg Young ist hier deutlich – das Read Model darf keine Geschäftsentscheidung tragen, die auf aktuellem, konsistentem Zustand beruhen muss. Weil es veraltet sein kann, würde man auf veralteten Daten entscheiden. Die Prüfung, ob ein Konto gedeckt ist oder eine Bestellung noch storniert werden darf, gehört auf die Schreibseite, gegen das Aggregate, nicht gegen die Leseansicht. Diese Arbeitsteilung habe ich in [Commands, Events und Queries trennen](https://www.mikebild.dev/de/blog/commands-events-queries-trennen/) genauer aufgeschrieben: Eine Query stellt eine Frage und ändert nichts; sie darf deshalb auch keine Entscheidung erzwingen.\n\n## Projection oder Cache – die Unterscheidung in fünf Punkten\n\nOb eine konkrete Leseseite eine Projection oder ein Cache ist, klärt sich an fünf Fragen:\n\n- Wer ist die Wahrheitsquelle? Bei der Projection ist der Event Store die Quelle, das Read Model ist die autoritative Lese-View. Beim Cache liegt die autoritative Quelle in der Datenbank dahinter.\n- Wie wird invalidiert? Die Projection wird eventgetrieben fortgeschrieben, der Cache über TTL oder Verdrängung.\n- Wie läuft der Neuaufbau? Die Projection ist by design deterministisch aus der Historie neu berechenbar; der Cache-Neuaufbau ist ein Kaltstart-Side-Effect, abhängig vom aktuellen Quellzustand.\n- Welche Form hat die Sicht? Die Projection ist pro Sicht denormalisiert und aggregatübergreifend zusammengezogen, der Cache meist eine Kopie des Quell-Datensatzes.\n- Wie steht es um die Konsistenz? Die Projection ist bewusst eventual consistent mit begrenztem Verzug, der Cache best-effort.\n\nEin oder zwei dieser Punkte kann man diskutieren. Aber wenn die Antworten überwiegend in der Cache-Spalte landen, dann sollte man das Ding auch so nennen und nicht die Erwartungen an ein Read Model daran hängen.\n\n## Die drei Fallstricke, konkret\n\nZum Schluss die Muster, die den Ärger verursachen, jeweils in einem Satz benannt und mit der Gegenmaßnahme.\n\nDer erste ist das Cache-Denken selbst: Das Read Model als optionalen Beschleuniger behandeln, den man bei einem Fehltreffer aus der \"eigentlichen\" Datenbank neu zieht. Es gibt diese eigentliche Datenbank nicht. Die Fortschreibung erfolgt eventgetrieben, und der Rebuild kommt aus den Events. Wer das ernst nimmt, hört auf, nach der Quelle *hinter* dem Read Model zu suchen.\n\nDer zweite ist das Read Model als Wahrheitsquelle: Aus einer potenziell veralteten Lese-View heraus über Command-Invarianten entscheiden. Die Konsequenz sind Entscheidungen auf altem Stand. Die Gegenmaßnahme ist Disziplin über die Seitengrenze – Entscheidungen auf die Schreibseite, gegen das Aggregate.\n\nDer dritte ist der vergessene Neuaufbau: Eine Projection bauen, die sich nicht replayen lässt, weil das `apply` nicht rein ist oder Events verworfen wurden. Dann wird die erste Schema-Migration zur Sackgasse. Die Gegenmaßnahme steht oben im Code – halte den Projector als reine Faltung über den Events, und schreibe den `rebuild` früh, nicht erst wenn er brennt.\n\n## Fazit\n\nEin Read Model verdient einen besseren Namen als \"Cache\", weil der Name die Erwartungen setzt. Nennt man es Cache, baut man einen optionalen Beschleuniger mit einer vermeintlichen Quelle dahinter, TTL-Invalidierung und einem Neuaufbau, der Side Effect bleibt. Nennt man es Projection, baut man eine reine Faltung über einem immutable Event-Strom, pro Sicht zugeschnitten, eventgetrieben fortgeschrieben und jederzeit deterministisch neu berechenbar. Die drei Eigenschaften, an denen ich das festmache, sind immer dieselben: deterministisch abgeleitet, jederzeit neu aufbaubar, bewusst eventual consistent. Wer diese drei ins Design zieht, hat eine Leseseite, die man betreiben und migrieren kann, ohne bei jeder Änderung ins Schwitzen zu geraten.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html\n- Martin Fowler, [CQRS](https://martinfowler.com/bliki/CQRS.html) – der konzeptuelle Modellsplit und die Warnung, ihn nur kontextlokal einzusetzen.\n- Martin Fowler, [Reporting Database](https://martinfowler.com/bliki/ReportingDatabase.html) – die verwandte, aber engere Idee einer separaten Lese-Datenbank.\n- Martin Fowler, [Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html) – die Persistenzform, die Projections so natürlich macht.\n- Greg Young, [CQRS Documents (2010, PDF)](https://cqrs.files.wordpress.com/2010/11/cqrs_documents.pdf) – die Grundlagen zu Read Models, Eventual Consistency und Rebuild.\n- Vaughn Vernon, *Implementing Domain-Driven Design* (2013), Kapitel zu Architektur und CQRS; Beispielcode in den [IDDD Samples](https://github.com/VaughnVernon/IDDD_Samples).\n- Mein eigenes Vortragsmaterial \"CQRS + Event Sourcing\" auf SlideShare – die Folien, aus denen ich in Schulungen den Kern herleite: Lesen und Schreiben sind unterschiedliche Verantwortlichkeiten."},{"locale":"de","translation_key":"cloud-guardrails","slug":"cloud-guardrails","title":"Cloud Guardrails statt Cloud Gatekeeping","summary":"Warum zentrale Freigabeprozesse in der Cloud Schatten-Infrastruktur züchten und wie technisch durchgesetzte Leitplanken – SCPs, Permission Boundaries, Config Rules, Budgets – Teams Bewegungsfreiheit zurückgeben.","tags":["Software","Architektur"],"published_at":"2020-09-12T10:00:00+00:00","updated_at":"2026-07-14T17:13:13.975247+00:00","url":"https://www.mikebild.dev/de/blog/cloud-guardrails/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/5e6213d2b8014cf05d733ee7148f711e54bd87f328be608851b42877af4362e0/cloud-guardrails-vorlesen.mp3","audio_duration_secs":663,"text":"# Cloud Guardrails statt Cloud Gatekeeping\n\nEin Freigabeprozess mit drei Tagen Wartezeit erzeugt keine Kontrolle. Er erzeugt Schatten-Infrastruktur. Das Team, das auf die Freigabe für eine DynamoDB-Tabelle wartet, wartet nicht wirklich – es weicht aus: auf den privaten AWS-Account eines Kollegen, auf die Kreditkarte des Projektleiters, auf den „temporären\" Bucket im Sandbox-Account, der zwei Jahre später immer noch produktive Daten enthält. Der Prozess, der Risiken verhindern sollte, verschiebt sie genau dorthin, wo niemand mehr hinschaut: kein Review, kein zentrales Logging, keine Kostenkontrolle, keine Backups.\n\nIn einem Projekt im letzten Jahr habe ich das aus der Nähe gesehen. Ein zentrales Cloud-Team, ein Jira-Board, jede neue Ressource ein Ticket. Offizielle Durchlaufzeit: drei Tage. Tatsächliche Durchlaufzeit bei Rückfragen: eine Woche und mehr. Das Cloud-Team war weder böswillig noch faul – es war schlicht zu klein für zwölf Produktteams, und jedes Ticket brauchte Kontext, den nur das anfragende Team hatte. Mir ist dabei aufgefallen, dass die eigentliche Diskussion nie „erlauben oder verbieten\" war. Sie war fast immer: „In welcher Region? Mit welchem Tagging? Wer zahlt das?\" Also Fragen, die sich als Regel formulieren lassen. Und was sich als Regel formulieren lässt, kann eine Maschine durchsetzen – ohne Wartezeit.\n\n## Was der Ticket-Prozess eigentlich schützt\n\nBevor man den Prozess abschafft, lohnt der Blick darauf, welche berechtigten Sorgen er trägt. In dem Projekt waren es im Kern vier:\n\n- Kosten: Niemand soll versehentlich einen teuren Cluster in einer exotischen Instanzgröße starten.\n- Datenhoheit: Daten bleiben in europäischen Regionen, Punkt.\n- Sicherheitsgrundlinien: Kein öffentlicher S3-Bucket, kein abgeschaltetes CloudTrail, keine weit offenen Security Groups.\n- Rechte-Eskalation: Wer Rollen anlegen darf, darf sich sonst beliebig weitreichende Rechte selbst ausstellen.\n\nAlle vier Sorgen sind real. Aber keine davon braucht einen Menschen, der drei Tage später ein Ticket liest. Sie brauchen Grenzen, die zum Zeitpunkt des API-Aufrufs gelten – nicht zum Zeitpunkt der Freigabe. Der Ticket-Prozess prüft eine Absichtserklärung; was danach wirklich passiert, prüft er nie wieder. Die Leitplanke prüft jede einzelne Aktion, jedes Mal.\n\nAWS selbst hat für dieses Denken inzwischen einen Namen: Control Tower, seit Sommer 2019 allgemein verfügbar, nennt seine vorkonfigurierten Regeln wörtlich „Guardrails\". Der Begriff ist also kein Schlagwort von Konferenzfolien, sondern kommt aus der Produktpraxis der Plattform. Interessanter als der Name ist die Unterscheidung, die Control Tower dabei trifft: preventive Guardrails verhindern eine Aktion, detective Guardrails erkennen eine Abweichung. Diese Unterscheidung trägt die gesamte Architektur.\n\n```mermaid\nflowchart LR\n  A[Team ändert<br/>Infrastruktur] --> B{Präventiv:<br/>SCP / Boundary}\n  B -->|verstößt| C[API-Aufruf sofort<br/>abgelehnt]\n  B -->|erlaubt| D[Ressource<br/>entsteht]\n  D --> E{Detektivisch:<br/>AWS Config}\n  E -->|konform| F[Nichts passiert]\n  E -->|Abweichung| G[Alarm oder<br/>Auto-Korrektur]\n```\n\n## Harte Grenzen: Service Control Policies\n\nDie äußerste Leitplanke sind Service Control Policies in AWS Organizations. Eine SCP gilt für ganze Accounts oder Organizational Units und schlägt jede IAM-Policy im Account – selbst der Account-Administrator kommt nicht daran vorbei. Genau deshalb gehören hier nur die Regeln hinein, die wirklich nie verhandelbar sind. In dem Projekt waren das zwei: erlaubte Regionen und eine kurze Liste verbotener Services.\n\n```json\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"DenyOutsideAllowedRegions\",\n      \"Effect\": \"Deny\",\n      \"NotAction\": [\n        \"iam:*\",\n        \"organizations:*\",\n        \"route53:*\",\n        \"cloudfront:*\",\n        \"support:*\"\n      ],\n      \"Resource\": \"*\",\n      \"Condition\": {\n        \"StringNotEquals\": {\n          \"aws:RequestedRegion\": [\"eu-central-1\", \"eu-west-1\"]\n        }\n      }\n    },\n    {\n      \"Sid\": \"DenyUnapprovedServices\",\n      \"Effect\": \"Deny\",\n      \"Action\": [\"gamelift:*\", \"robomaker:*\", \"chime:*\"],\n      \"Resource\": \"*\"\n    }\n  ]\n}\n```\n\nZwei Details daran sind mir wichtig. Erstens die `NotAction`-Ausnahmen: IAM, CloudFront oder Route 53 sind globale Services, ihre API-Aufrufe laufen technisch über us-east-1 – wer sie in der Regionssperre vergisst, sperrt sich selbst aus. Das haben wir auf die harte Tour gelernt, zum Glück in einem Test-Account. Zweitens der Charakter der Liste verbotener Services: Sie ist kurz und begründet, keine Positivliste von hundert Einträgen. Eine SCP, die alles verbietet außer dem, was jemand einmal beantragt hat, ist nur das alte Gatekeeping in JSON-Form. Die Leitplanke markiert den Rand der Straße, nicht die einzige erlaubte Spur.\n\nWichtig für das Verständnis: Eine SCP vergibt selbst keine Rechte. Sie definiert die Obergrenze dessen, was IAM-Policies im Account überhaupt wirksam erlauben können. Innerhalb dieser Grenze bewegen sich die Teams frei – und genau das ist der Punkt.\n\n## Selbstbedienung bei IAM: Permission Boundaries\n\nDie unbequemste Frage kam in dem Projekt vom Sicherheitsverantwortlichen: „Wenn Entwickler eigene IAM-Rollen anlegen dürfen, können sie sich dann nicht beliebige Rechte geben?\" Ohne Gegenmaßnahme: ja. Wer `iam:CreateRole` und `iam:AttachRolePolicy` hat, kann eine Rolle mit Administratorrechten bauen und sie übernehmen. Deshalb war IAM historisch das letzte Revier des zentralen Teams – und der häufigste Grund für Wartezeit, denn jede Lambda-Function, jede Pipeline braucht eine Rolle.\n\nSeit 2018 gibt es dafür Permission Boundaries: eine Managed Policy, die als Obergrenze an eine Rolle geheftet wird. Die effektiven Rechte sind der Schnitt aus Boundary und angehefteten Policies. Der Trick liegt in der Selbstverstärkung – die Boundary erlaubt das Anlegen neuer Rollen nur dann, wenn die neue Rolle wieder dieselbe Boundary trägt:\n\n```json\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"AllowWorkloadServices\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\n        \"s3:*\", \"dynamodb:*\", \"lambda:*\", \"sqs:*\",\n        \"logs:*\", \"cloudwatch:*\", \"apigateway:*\"\n      ],\n      \"Resource\": \"*\"\n    },\n    {\n      \"Sid\": \"DenyCreateWithoutBoundary\",\n      \"Effect\": \"Deny\",\n      \"Action\": [\"iam:CreateRole\", \"iam:CreateUser\"],\n      \"Resource\": \"*\",\n      \"Condition\": {\n        \"StringNotEquals\": {\n          \"iam:PermissionsBoundary\": \"arn:aws:iam::111122223333:policy/workload-boundary\"\n        }\n      }\n    },\n    {\n      \"Sid\": \"DenyBoundaryTampering\",\n      \"Effect\": \"Deny\",\n      \"Action\": [\n        \"iam:DeleteRolePermissionsBoundary\",\n        \"iam:DeletePolicy\",\n        \"iam:CreatePolicyVersion\"\n      ],\n      \"Resource\": \"arn:aws:iam::111122223333:policy/workload-boundary\"\n    }\n  ]\n}\n```\n\nDamit konnten die Teams Rollen für ihre Services anlegen, ohne dass jemand freigeben musste – aber keine Rolle konnte je mehr als die `workload-boundary` erlaubt. Im CDK, mit dem wir die Infrastruktur ohnehin beschrieben haben, ist das eine Zeile pro Rolle:\n\n```ts\nimport * as iam from '@aws-cdk/aws-iam';\n\nconst boundary = iam.ManagedPolicy.fromManagedPolicyName(\n  this,\n  'WorkloadBoundary',\n  'workload-boundary'\n);\n\nconst serviceRole = new iam.Role(this, 'OrderServiceRole', {\n  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),\n  permissionsBoundary: boundary,\n});\n```\n\nDie drei Tage Wartezeit für „bitte eine Rolle für den Order-Service\" waren damit weg. Nicht, weil jemand schneller freigab, sondern weil es nichts mehr freizugeben gab: Die Grenze war schon gezogen, bevor die Anfrage entstand.\n\n## Erkennen statt nur verhindern: AWS Config\n\nPräventive Regeln haben eine Lücke: Sie können nur verbieten, was sich als IAM-Bedingung ausdrücken lässt. „Kein S3-Bucket ohne Verschlüsselung\" oder „keine Security Group mit 0.0.0.0/0 auf Port 22\" sind Eigenschaften einer Ressource, keine API-Aktionen – dafür braucht es die zweite Sorte Leitplanke. AWS Config zeichnet den Zustand aller Ressourcen auf und prüft ihn laufend gegen Regeln. Bei Abweichung: Alarm, und wo es gefahrlos möglich ist, automatische Korrektur.\n\n```ts\nimport * as config from '@aws-cdk/aws-config';\nimport * as budgets from '@aws-cdk/aws-budgets';\n\nnew config.ManagedRule(this, 'BucketsNotPublic', {\n  identifier: 'S3_BUCKET_PUBLIC_READ_PROHIBITED',\n});\n\nnew config.ManagedRule(this, 'VolumesEncrypted', {\n  identifier: 'ENCRYPTED_VOLUMES',\n});\n\nnew budgets.CfnBudget(this, 'TeamMonthlyBudget', {\n  budget: {\n    budgetType: 'COST',\n    timeUnit: 'MONTHLY',\n    budgetLimit: { amount: 500, unit: 'USD' },\n  },\n  notificationsWithSubscribers: [\n    {\n      notification: {\n        notificationType: 'ACTUAL',\n        comparisonOperator: 'GREATER_THAN',\n        threshold: 80,\n      },\n      subscribers: [\n        { subscriptionType: 'EMAIL', address: 'team-orders@example.com' },\n      ],\n    },\n  ],\n});\n```\n\nDas Budget gehört für mich in dieselbe Kategorie, auch wenn es technisch ein anderer Service ist. Die Kostenangst war der emotionale Kern des alten Freigabeprozesses – und ein Budget-Alarm bei 80 Prozent beantwortet sie besser als jedes Ticket, weil er auf tatsächliche Ausgaben reagiert statt auf geschätzte. In dem Projekt bekam jedes Team sein eigenes Budget mit eigener Benachrichtigung. Die Diskussionen über Kosten wurden dadurch nicht weniger, aber sie fanden mit Zahlen statt mit Vermutungen statt, und sie fanden im Team statt – nicht zwischen Team und Torwächter.\n\nDer zweite Gewinn von Config ist unscheinbarer: die Historie. Wenn eine Security Group heute anders aussieht als gestern, zeigt Config, wann sich was geändert hat – das hat uns bei mehr als einer Fehlersuche Stunden gespart, ganz unabhängig von den Regeln. Ein Freigabeprozess weiß nur, was beantragt wurde; Config weiß, was tatsächlich passiert ist.\n\nBei der Auto-Korrektur bin ich zurückhaltender geworden. Eine Regel, die eine öffentliche Bucket-Policy sofort wieder entfernt, ist ein Sicherheitsgewinn. Eine Regel, die nachts Ressourcen löscht, deren Tags nicht stimmen, hat uns einmal einen Morgen Fehlersuche gekostet, weil ein legitimer Prototyp verschwunden war. Erkennen und melden ist fast immer richtig; automatisch eingreifen nur dort, wo die Korrektur garantiert nichts zerstört.\n\n## Leitplanken sind Code, keine Klick-Konfiguration\n\nDer Punkt, an dem solche Setups in meiner Erfahrung kippen, ist nicht die Technik, sondern die Pflege. Eine SCP, die jemand vor einem Jahr in der Konsole zusammengeklickt hat, ist genauso undurchsichtig wie der alte Freigabeprozess – nur dass jetzt niemand mehr weiß, warum Port 22 gesperrt ist und wer das ändern darf. Leitplanken sind Infrastruktur, und für Infrastruktur gilt, was ich schon [beim Review von Infrastruktur-Code](https://www.mikebild.dev/de/blog/infrastructure-as-code-code-reviews/) beschrieben habe: Sie gehört versioniert, reviewt und nachvollziehbar geändert.\n\nKonkret heißt das bei uns: SCPs, Boundary-Policies und Config-Rules stehen als Code im Repository, Änderungen laufen als Pull Request, und im Review sitzt neben dem Plattform-Team auch jemand aus einem Produktteam. Der Pull Request ersetzt das Ticket – mit einem entscheidenden Unterschied: Diskutiert wird eine dauerhafte Regel für alle, nicht eine Einzelfreigabe für einen. Die Diskussion lohnt sich also, ihr Ergebnis wirkt weiter. Wie sich solche Regeln zusätzlich schon beim Synthetisieren der eigenen Stacks prüfen lassen, habe ich in [Policy as Code für CDK](https://www.mikebild.dev/de/blog/policy-as-code-fuer-cdk/) beschrieben – beides zusammen ergibt zwei Prüfpunkte: einen früh im Build, einen unumgehbar an der Konto-Grenze.\n\nNebenbei: Das Muster ist nicht AWS-spezifisch. Im Kubernetes-Umfeld passiert gerade dasselbe mit Open Policy Agent und Gatekeeper – Regeln als Code, durchgesetzt am Admission Controller statt im Meeting. Wer beide Welten betreibt, erkennt die Denkfigur sofort wieder.\n\n```mermaid\nflowchart TD\n  Root[Organization Root] --> Sec[OU Security<br/>Logging, Audit]\n  Root --> Work[OU Workloads]\n  Root --> Sand[OU Sandbox]\n  Work --> A1[Account Team Orders]\n  Work --> A2[Account Team Billing]\n  SCP1[SCP: EU-Regionen,<br/>Service-Sperrliste] -.gilt für.-> Work\n  SCP2[SCP: zusätzlich<br/>Kostengrenzen eng] -.gilt für.-> Sand\n```\n\nDie Organisationsstruktur selbst ist Teil der Leitplanken: Eine Sandbox-OU mit engen Grenzen und einer Aufräum-Regel nimmt dem Experimentieren das Risiko, eine Workload-OU trägt die verbindlichen Regeln. Wer heute mit einer Multi-Account-Struktur anfängt, bekommt mit Control Tower genau dieses Gerüst vorkonfiguriert – die Guardrails dahinter sind dieselben SCPs und Config-Rules, nur fertig verdrahtet.\n\n## Was am Ende anders ist\n\nNach einem halben Jahr mit diesem Setup war das Jira-Board des Cloud-Teams fast leer – nicht weil weniger passierte, sondern weil das meiste keine Freigabe mehr brauchte. Die Tickets, die blieben, waren die interessanten: Anträge, eine Leitplanke zu ändern. Genau da gehört menschliche Aufmerksamkeit hin. Und das Plattform-Team hatte plötzlich Zeit für die Arbeit, die vorher liegen blieb: bessere Vorlagen, schärfere Regeln, ein neuer Account in einer Stunde statt in einer Woche.\n\nEin paar Beobachtungen nehme ich mit. Der Freigabeprozess und die Leitplanke beantworten dieselbe Frage – „was darf hier passieren?\" – aber zu verschiedenen Zeitpunkten: der Prozess einmal vorher auf Basis einer Beschreibung, die Leitplanke bei jeder Aktion auf Basis der Wirklichkeit. Das macht Leitplanken nicht nur schneller, sondern ehrlicher. Zweitens: Die Trennung in präventiv und detektivisch ist keine Feinheit, sondern die zentrale Entwurfsentscheidung. Alles, was hart verboten ist, gehört in SCPs und Boundaries; alles, was Eigenschaften von Ressourcen betrifft, in Config-Rules mit Alarm. Wer versucht, alles präventiv zu erzwingen, baut das Gatekeeping in JSON nach. Und drittens: Schatten-Infrastruktur ist kein Disziplinproblem der Teams, sondern ein Symptom. Sie verschwindet nicht durch strengere Prozesse, sondern durch einen offiziellen Weg, der schneller ist als der Umweg.\n\n## Weiterführende Quellen\n\n- [Service Control Policies – AWS Organizations User Guide](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html)\n- [Permissions Boundaries for IAM Entities – AWS IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)\n- [What Is AWS Config? – AWS Config Developer Guide](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)\n- [AWS Control Tower – Set up & Govern a Multi-Account AWS Environment (AWS News Blog, 2019)](https://aws.amazon.com/blogs/aws/aws-control-tower-set-up-govern-a-multi-account-aws-environment/)"},{"locale":"de","translation_key":"cdk-constructs-abstraktion-mit-haftung","slug":"cdk-constructs-abstraktion-mit-haftung","title":"CDK Constructs: Abstraktion mit Haftung","summary":"Wer ein CDK Construct veröffentlicht, verschickt keine Hilfsfunktion, sondern Betriebsentscheidungen – über Defaults, Upgrade-Pfade und das, was beim Konsumenten im CloudFormation-Template landet.","tags":["Software","AWS","Cloud"],"published_at":"2020-08-12T10:00:00+00:00","updated_at":"2026-07-14T17:10:58.285909+00:00","url":"https://www.mikebild.dev/de/blog/cdk-constructs-abstraktion-mit-haftung/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0044b69bc7a126d6fb3d3fa51af4f11d0392452c29e9d70533846aed3203aa8a/cdk-constructs-abstraktion-mit-haftung-vorlesen.mp3","audio_duration_secs":709,"text":"# CDK Constructs: Abstraktion mit Haftung\n\nEine Abstraktion, die man importiert, ist Verantwortung, die man abgibt – so lautet die stillschweigende Annahme, wenn ein Team das erste fertige CDK Construct in sein Projekt zieht. Drei Zeilen Code, ein `cdk deploy`, und S3-Bucket, CloudFront-Distribution und Bucket-Policy stehen. Die Details hat ja jemand anderes durchdacht.\n\nGenau diese Annahme halte ich für falsch, und zwar in beide Richtungen. Wer ein Construct benutzt, gibt keine Verantwortung ab – er importiert fremde Entscheidungen in sein eigenes CloudFormation-Template, auf seine eigene AWS-Rechnung und in seine eigene Angriffsfläche. Und wer ein Construct veröffentlicht, hat nicht einfach Code geteilt – er haftet ab jetzt für Defaults, für Upgrade-Pfade und für alles, was bei fremden Leuten in Produktion entsteht. Ein Construct ist Abstraktion mit Haftung. Das unterscheidet es von fast allem, was ich sonst über npm beziehe.\n\n## Drei Ebenen, drei verschiedene Versprechen\n\nDas CDK sortiert seine Bausteine in drei Ebenen, und die Haftungsfrage stellt sich auf jeder anders. L1-Constructs (`CfnBucket`, `CfnDistribution`) sind generierte Eins-zu-eins-Abbildungen der CloudFormation-Ressourcen. Sie versprechen nichts außer Vollständigkeit: jede Property, kein Default, keine Meinung. L2-Constructs (`s3.Bucket`, `lambda.Function`) sind handgeschriebene Kapseln mit Meinung – sinnvolle Defaults, Komfortmethoden wie `grantRead`, automatisch verdrahtete IAM-Policies. L3-Constructs schließlich, im CDK-Sprachgebrauch auch Patterns, verdrahten mehrere Dienste zu einem fachlichen Baustein: „statische Website mit CDN\", „API mit Lambda und DynamoDB\".\n\nJe höher die Ebene, desto größer das Versprechen – und desto größer die Haftung. Ein L1-Construct kann mich kaum überraschen, weil es nichts entscheidet. Ein L3-Construct entscheidet fast alles, und ich sehe es dem Code nicht an. Genau deshalb sind L3-Constructs so verführerisch: Sie lesen sich wie Fachlichkeit („eine Website\", „eine API\") und verstecken, dass darunter ein Bündel sehr konkreter Betriebsentscheidungen liegt. Was dabei wirklich passiert, zeigt erst die Synthese:\n\n```mermaid\nflowchart LR\n  L3[L3: StaticSite<br/>eigenes Pattern] --> L2[L2: s3.Bucket<br/>CloudFrontWebDistribution]\n  L2 --> L1[L1: CfnBucket<br/>CfnDistribution]\n  L1 --> SYNTH[cdk synth]\n  SYNTH --> TPL[CloudFormation-Template<br/>mehrere hundert Zeilen]\n  TPL --> DEPLOY[cdk deploy]\n  DEPLOY --> RES[echte Ressourcen:<br/>Kosten, Rechte, Angriffsfläche]\n```\n\nDer Pfeil ganz rechts ist der Punkt, an dem sich ein Construct von einer Bibliotheksfunktion unterscheidet. Eine Funktion aus lodash erzeugt zur Laufzeit ein Array. Ein Construct erzeugt eine CloudFront-Distribution, die Geld kostet, einen Bucket, der öffentlich sein kann oder nicht, und IAM-Statements, die jemandem etwas erlauben. Wenn `map` einen Fehler hat, schlägt ein Test fehl. Wenn ein Construct einen Fehler hat, liegt ein Bucket offen im Internet oder eine Removal Policy löscht beim Stack-Abbau Produktionsdaten. Das ist kein Grund, auf Abstraktion zu verzichten – aber ein Grund, sie anders zu behandeln.\n\n## Ein eigenes Construct und seine unbequemen Entscheidungen\n\nMir wurde das richtig klar, als ich selbst ein kleines Construct gebaut habe: statische Website in S3, ausgeliefert über CloudFront. Der dritte oder vierte handgeschriebene Stack dieser Art im Umfeld, immer dieselben sechzig Zeilen, also lag die Extraktion nahe. Der erste Wurf war schnell fertig. Interessant wurde es bei den Fragen, die der erste Wurf offen ließ.\n\n```typescript\nimport { Construct, RemovalPolicy } from '@aws-cdk/core';\nimport * as s3 from '@aws-cdk/aws-s3';\nimport * as cloudfront from '@aws-cdk/aws-cloudfront';\nimport * as deployment from '@aws-cdk/aws-s3-deployment';\n\nexport interface StaticSiteProps {\n  readonly sourcePath: string;\n  readonly retainBucket?: boolean;\n}\n\nexport class StaticSite extends Construct {\n  public readonly siteBucket: s3.Bucket;\n  public readonly distribution: cloudfront.CloudFrontWebDistribution;\n\n  constructor(scope: Construct, id: string, props: StaticSiteProps) {\n    super(scope, id);\n\n    const originAccessIdentity = new cloudfront.OriginAccessIdentity(\n      this,\n      'OriginAccessIdentity'\n    );\n\n    this.siteBucket = new s3.Bucket(this, 'SiteBucket', {\n      encryption: s3.BucketEncryption.S3_MANAGED,\n      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,\n      removalPolicy: props.retainBucket\n        ? RemovalPolicy.RETAIN\n        : RemovalPolicy.DESTROY,\n    });\n    this.siteBucket.grantRead(originAccessIdentity);\n\n    this.distribution = new cloudfront.CloudFrontWebDistribution(this, 'Distribution', {\n      originConfigs: [\n        {\n          s3OriginSource: {\n            s3BucketSource: this.siteBucket,\n            originAccessIdentity,\n          },\n          behaviors: [{ isDefaultBehavior: true }],\n        },\n      ],\n    });\n\n    new deployment.BucketDeployment(this, 'DeploySite', {\n      sources: [deployment.Source.asset(props.sourcePath)],\n      destinationBucket: this.siteBucket,\n      distribution: this.distribution,\n    });\n  }\n}\n```\n\nJede dieser Zeilen ist eine Betriebsentscheidung, die ich für alle künftigen Nutzer treffe. Der Bucket ist nicht öffentlich, sondern nur über die Origin Access Identity erreichbar – das ist die richtige Entscheidung, aber sie ist nicht selbstverständlich: das nackte `s3.Bucket` aus dem CDK setzt bis heute keinen Public-Access-Block, wenn man nichts angibt. Die Verschlüsselung ist eingeschaltet, obwohl der Inhalt einer öffentlichen Website sie streng genommen nicht braucht – weil niemand später diskutieren soll, warum ausgerechnet dieser Bucket unverschlüsselt ist. Und die Removal Policy steht per Default auf `DESTROY`.\n\nÜber diesen letzten Default habe ich am längsten nachgedacht. Das CDK selbst behält Buckets beim Stack-Abbau (`RETAIN`), weil ein Bucket mit Inhalt nicht ohne Weiteres gelöscht werden kann und weil Datenverlust der teuerste aller Fehler ist. Für ein Website-Construct, dessen Bucket-Inhalt bei jedem Deployment neu aus dem Build entsteht, ist `RETAIN` aber der falsche Schutz: Er hinterlässt bei jedem abgerissenen Test-Stack einen Waisen-Bucket, und nach drei Monaten weiß niemand mehr, welche davon weg können. Also `DESTROY` als Default und `retainBucket` als Ausweg für die Fälle, in denen der Bucket doch mehr enthält als Build-Artefakte. Vielleicht ist das die falsche Abwägung – aber sie steht jetzt in einer Zeile Interface-Definition und ist damit diskutierbar. Vorher steckte sie unausgesprochen in sechzig Zeilen kopiertem Stack-Code.\n\nGenauso bewusst sind die beiden `public readonly`-Felder. Ein Construct, das seine inneren Ressourcen versteckt, zwingt seine Nutzer beim ersten Sonderfall zum Fork. Wer an die `CfnDistribution` heran muss, kommt über `this.distribution.node.defaultChild` dran und kann per `addPropertyOverride` alles übersteuern, was meine Abstraktion nicht vorgesehen hat:\n\n```typescript\nconst cfnDistribution = site.distribution.node\n  .defaultChild as cloudfront.CfnDistribution;\n\ncfnDistribution.addPropertyOverride(\n  'DistributionConfig.ViewerCertificate.MinimumProtocolVersion',\n  'TLSv1.2_2019'\n);\n```\n\nDiese Escape Hatches sind kein Schönheitsfehler der Abstraktion, sondern Teil des Vertrags. Eine Abstraktion ohne Ausweg ist in der Infrastruktur eine Sackgasse, und Sackgassen fallen immer erst auf, wenn man schon drinsteht.\n\n## cdk synth ist der Wahrheitstest\n\nFür die andere Seite der Haftung – die des Konsumenten – gibt es ein Werkzeug, das ich für wichtiger halte als jede Dokumentation: die Synthese. `cdk synth` schreibt das CloudFormation-Template heraus, das aus dem ganzen Construct-Baum entsteht. Das Template lügt nicht. Es enthält jede Ressource, jede Policy, jeden Default, den irgendein Construct irgendwo gesetzt hat.\n\n```bash\nnpm install @aws-cdk/aws-s3@1.57.0 @aws-cdk/aws-cloudfront@1.57.0\n\ncdk synth StaticSiteStack > synthesized.yaml\n\n# what did the abstraction actually decide for me?\ngrep -A 6 'PublicAccessBlockConfiguration' synthesized.yaml\ngrep -B 2 'DeletionPolicy' synthesized.yaml\n\n# and before every deployment: what changes against reality?\ncdk diff StaticSiteStack\n```\n\nBevor ich ein fremdes Construct einsetze, baue ich ein Minimalbeispiel, synthetisiere und lese. Nicht das ganze Template Zeile für Zeile – aber gezielt die Stellen, an denen fremde Defaults teuer oder gefährlich werden. Das kostet eine halbe Stunde und hat sich bisher jedes Mal bezahlt gemacht: Einmal fand ich auf diesem Weg eine CloudFront-Price-Class, die weltweit auslieferte, wo Europa gereicht hätte; ein anderes Mal eine Log-Konfiguration, die schlicht fehlte, was erst beim ersten Vorfall aufgefallen wäre. Bei einem Pattern aus drei Zeilen Anwendungscode kommen gern mehrere hundert Zeilen Template heraus, und irgendwo darin stehen die Antworten auf die Fragen, die das README nicht beantwortet:\n\n- Welche IAM-Statements entstehen, und stehen darin Wildcards, die ich nicht bestellt habe?\n- Welche Ressourcen kosten laufend Geld, auch wenn niemand das System benutzt?\n- Was ist öffentlich erreichbar, was ist verschlüsselt, was hat welche `DeletionPolicy`?\n- Welche Properties kann ich über das Interface ändern – und für welche brauche ich schon am ersten Tag den Escape Hatch?\n\nAWS hat in diesem Frühjahr mit den Solutions Constructs eine eigene Bibliothek solcher Patterns gestartet: geprüfte Zwei-Dienst-Kombinationen wie CloudFront vor API Gateway vor Lambda, mit Defaults entlang des Well-Architected Framework. Ich habe einige davon gelesen, teils benutzt, und finde vor allem den Quellcode lehrreich – dort sieht man, wie viele Zeilen Default-Logik nötig sind, damit „CloudFront plus S3\" wirklich vernünftig verdrahtet ist, inklusive der Details, die in handgeschriebenen Stacks regelmäßig fehlen. Genau das ist der Wert einer fremden L3-Abstraktion: nicht, dass ich nichts mehr wissen muss, sondern dass jemand die Entscheidungen schon einmal getroffen und aufgeschrieben hat, gegen die ich meine eigenen halten kann. Wie sich solche Prüfungen automatisieren lassen, statt an Disziplin zu hängen, habe ich mir in [Policy as Code für CDK](https://www.mikebild.dev/de/blog/policy-as-code-fuer-cdk/) schon einmal angesehen – Synthese und Regelprüfung gehören für mich inzwischen zusammen.\n\n## Was der Autor schuldet\n\nBleibt die Frage, was man sich einhandelt, wenn man selbst veröffentlicht. Nach einem halben Jahr mit dem eigenen Construct und etlichen gelesenen fremden habe ich dafür eine vorläufige Liste, und sie ist länger, als mir beim Extrahieren der ersten sechzig Zeilen klar war.\n\nDa sind zuerst die Defaults, über die oben schon alles steht – mit dem Zusatz, dass ein veröffentlichter Default praktisch nicht mehr zu ändern ist. Wer ihn verschärft, bricht bestehende Deployments; wer ihn lockert, macht bestehende Nutzer unbemerkt unsicherer. Ein Default ist ein Versprechen mit sehr langer Laufzeit.\n\nDann die Upgrade-Pfade. Das CDK erscheint derzeit fast wöchentlich in neuer Version, wir stehen bei 1.5x, und Module wie CloudFront tragen noch den Experimental-Stempel, dürfen sich also in Minor-Releases ändern. Ein Construct, das ich veröffentliche, spannt sich über diese Bewegung: Meine Nutzer heben ihre CDK-Version an und erwarten, dass mein Construct mitkommt. Peer Dependencies auf die richtigen `@aws-cdk`-Pakete, zeitnahe Releases nach Upstream-Änderungen, ein Changelog, das Template-Änderungen erwähnt – das ist keine Kür, das ist die Hälfte der Arbeit. Und weil das CDK über jsii auch Python-, Java- und .NET-Bindings erzeugt, entscheidet schon die API-Form (keine TypeScript-Spezialitäten, die jsii nicht abbilden kann) darüber, wen ich als Nutzer überhaupt erreichen kann.\n\nDazu kommen Tests, und zwar auf der richtigen Ebene. Unit-Tests gegen die eigene TypeScript-Logik prüfen nur die halbe Wahrheit; haftbar bin ich für das Template. Mit `@aws-cdk/assert` lässt sich beides festnageln – einzelne Zusicherungen (`expect(stack).to(haveResource('AWS::S3::Bucket', { PublicAccessBlockConfiguration: … }))`) für die Entscheidungen, die nie kippen dürfen, und ein Snapshot des ganzen synthetisierten Templates, damit jede Änderung der Ausgabe im Review sichtbar wird statt erst beim Nutzer. Seit ich das so halte, sind mir zwei Upstream-Änderungen aufgefallen, bevor sie ein Release erreicht haben – beide hätten das Template verändert, ohne dass sich eine Zeile meines Codes geändert hätte.\n\nUnd schließlich die Template-Ausgabe selbst. Logische IDs im Template entstehen aus dem Construct-Pfad; wer beim Refactoring seines Constructs Kinder umbenennt oder umhängt, ändert die IDs – und CloudFormation ersetzt daraufhin Ressourcen, statt sie zu ändern. Bei einer CloudFront-Distribution ist das eine halbe Stunde Wartezeit, bei einem Bucket mit Daten ein Zwischenfall. `cdk diff` gegen einen ausgerollten Beispiel-Stack gehört deshalb bei mir vor jedes Release des Constructs, aus demselben Grund, aus dem es vor jedes Deployment gehört. Seit Juli gibt es mit CDK Pipelines (Developer Preview) einen Baustein, der solche Prüfungen in eine selbst-mutierende Deployment-Pipeline zieht – noch frisch, aber die Richtung stimmt: Auch die Auslieferung eines Constructs ist Infrastruktur und will als solche behandelt werden.\n\n## Unterm Strich\n\nVor gut einem Jahr habe ich [darüber geschrieben, was sich ändert, wenn Infrastruktur zur Programmiersprache wird](https://www.mikebild.dev/de/blog/cdk-infrastruktur-als-programmiersprache/). Constructs sind die Fortsetzung davon: Wenn Infrastruktur Code ist, bekommt sie auch die Eigenschaften von Code – Wiederverwendung, Paketierung, Versionierung. Nur die Fehlerkosten bleiben die von Infrastruktur.\n\nDeshalb halte ich beide bequemen Haltungen für falsch. „Ich schreibe alles selbst, dann weiß ich, was drin ist\" skaliert nicht und reproduziert in jedem Stack dieselben vergessenen Details. „Ich nehme das fertige Pattern, dann muss ich es nicht verstehen\" verwechselt Abstraktion mit Absolution. Was für mich trägt, liegt dazwischen: L3-Abstraktionen ja, gern auch eigene – aber gelesen vor dem Einsatz, synthetisiert vor dem Vertrauen, und beim Veröffentlichen mit dem Bewusstsein, dass man ab jetzt für fremde Produktionsumgebungen mitentscheidet. Ein Construct ist kein Snippet. Es ist ein Vertrag über Defaults, Auswege und Upgrade-Pfade, und `cdk synth` ist das Dokument, in dem dieser Vertrag schwarz auf weiß steht.\n\n## Weiterführende Quellen\n\n- AWS Solutions Constructs auf GitHub: https://github.com/awslabs/aws-solutions-constructs\n- AWS CDK auf GitHub: https://github.com/aws/aws-cdk\n- Constructs im CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n- Ankündigung der AWS Solutions Constructs (AWS-Blog): https://aws.amazon.com/blogs/aws/aws-solutions-constructs-a-library-of-architecture-patterns-for-the-aws-cdk/\n- CDK Pipelines Developer Preview (AWS-Blog): https://aws.amazon.com/blogs/developer/cdk-pipelines-continuous-delivery-for-aws-cdk-applications/"},{"locale":"de","translation_key":"bounded-contexts-grenze-vor-microservice","slug":"bounded-contexts-grenze-vor-microservice","title":"Bounded Contexts vor dem Serviceschnitt","summary":"Bevor ich Services schneide, kläre ich fachliche Grenzen. Ein Bounded Context ist eine Sprachgrenze und ein möglicher, aber nicht zwingender Serviceschnitt.","tags":["Software","Architektur"],"published_at":"2020-07-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/bounded-contexts-grenze-vor-microservice/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/df651ec6cd30243a1c3aeef51a70ecebb5d29d9abe4aa9b8292292caa8b8cede/bounded-contexts-grenze-vor-microservice-vorlesen.mp3","audio_duration_secs":738,"text":"# Bounded Contexts vor dem Serviceschnitt\n\nWer die Zahl der Services festlegt, bevor die fachlichen Grenzen stehen, löst keine Kopplung auf – er verteilt sie übers Netzwerk. Der Schnitt trennt dann Code, aber keine Zuständigkeiten: Eine Änderung an einem einzigen Begriff läuft weiterhin durch drei Systeme, jetzt nur mit HTTP dazwischen und drei Teams, die sich abstimmen müssen.\n\nDie Grenze, die vorher fehlt, ist keine technische. Sie verläuft dort, wo ein Wort aufhört, dasselbe zu bedeuten.\n\nDie Architektur entsteht an den sprachlichen Grenzen und an den Übersetzungen zwischen ihnen.\n\n:::relationship{title=\"Fachliche Grenzen vor technischen Schnitten\" role=\"primary\" preferredPattern=\"architecture-map\"}\n- Subdomain · beschreibt einen fachlichen Problemraum\n- Bounded Context · gibt Begriffen und Regeln einen eindeutigen Geltungsbereich\n- Modell · implementiert die Sprache innerhalb dieser Grenze\n- Context Map · benennt Abhängigkeiten und Einfluss zwischen Kontexten\n- Anti-Corruption Layer · übersetzt ein fremdes Modell in die eigene Sprache\n- Service · kann eine Grenze ausführen, definiert sie aber nicht automatisch\n:::\n\nDamit werden Kästen nicht zum Selbstzweck. Entscheidend bleibt, wo Bedeutung wechselt und wer diese Übersetzung verantwortet.\n\n## Warum die Reihenfolge über das Ergebnis entscheidet\n\nDie Frage, mit der Monolithen-Migrationen üblicherweise beginnen, lautet: \"In wie viele Microservices zerlegen wir den Monolithen?\" Sie ist schon falsch gestellt. Die Zahl ist ein Ergebnis und keine Vorgabe. Zu klären ist, wo die fachlichen Grenzen liegen – und ob sich für jede Grenze eine eigene, in sich konsistente Sprache benennen lässt. Wie viele Services daraus werden, zeigt sich danach.\n\nDer Grund dafür ist ökonomisch. Ein Serviceschnitt ist billig zu zeichnen und teuer zu korrigieren, sobald Teams, Deployments und Datenbanken daran hängen. Eine fachliche Grenze dagegen lässt sich am Whiteboard verschieben, solange sie noch Modell ist und keine Infrastruktur. Deshalb investiere ich die erste Woche eines solchen Projekts in Sprache und noch nicht in Infrastruktur- und Deployment-Diagramme. Das Business-Ergebnis ist messbar: kürzere Änderungszyklen, weil eine Änderung in einem Kontext bleibt; weniger Reibung zwischen Teams, weil niemand über geteilte Tabellen stolpert; höhere Qualität, weil das Modell die Fachlichkeit abbildet statt einer technischen Zufallsstruktur.\n\n## Der Bounded Context ist eine Sprachgrenze\n\nEric Evans hat den Begriff 2003 in *Domain-Driven Design* geprägt, Martin Fowler hat ihn in seinem Bliki auf den Punkt gebracht: Ein Bounded Context ist der Bereich, in dem genau ein Modell und genau eine Ubiquitous Language gelten. Innerhalb dieser Grenze bedeutet jedes Wort exakt eine Sache. Über die Grenze hinweg darf dasselbe Wort etwas anderes heißen – darin liegt der eigentliche Gewinn.\n\nEin Beispiel aus dem Handel: das Wort \"Product\". Im Verkauf ist ein Product ein Ding mit Preis, Beschreibung und Verfügbarkeit. Im Lager ist dasselbe Product eine SKU mit Bestand, Lagerort und Nachbestellpunkt. In der Buchhaltung ist es eine Position mit Steuersatz und Erlöskonto. Drei Kontexte, drei legitime Bedeutungen. Der klassische Fehler ist, daraus ein einziges kanonisches `Product`-Objekt bauen zu wollen, das allen dreien gerecht wird. Das Resultat ist eine Klasse mit vierzig Feldern, von denen jeder Kontext zehn ignoriert – und jede Änderung betrifft alle drei Teams.\n\nFowler nennt als dominanten Faktor beim Ziehen dieser Grenzen nicht die Technik, sondern \"human culture\" – Sprache und Organisation. Hier greift Conway's Law: Kontextgrenzen und Teamgrenzen beeinflussen sich gegenseitig. Wenn ich eine saubere Grenze ziehe, an der aber zwei Teams gemeinsam arbeiten müssen, ziehe ich sie am falschen Ort.\n\nPraktisch teste ich eine vermutete Grenze mit zwei Fragen. Erstens: Kann ich in diesem Kontext einen Satz sagen, den ein Domänenexperte des Nachbarkontexts ohne Übersetzung nicht mehr eindeutig versteht? Wenn ja, sind es zwei Sprachen und damit zwei Kontexte. Zweitens: Gibt es eine Regel, die genau hier gilt und nebenan nicht – etwa \"ein Product ohne Bestand ist im Verkauf trotzdem sichtbar, im Lager aber inexistent\"? Solche Regelbrüche sind die verlässlichsten Grenzmarken, die ich kenne. Sie stehen im Fachgespräch, nicht im Klassendiagramm, und genau deshalb finde ich sie nur, wenn ich zuerst zuhöre statt zu modellieren.\n\n## Subdomains ordnen, Bounded Contexts implementieren\n\nBevor ich Grenzen ziehe, sortiere ich den Problemraum. Strategisches DDD trennt Problem Space und Solution Space. Im Problemraum liegen die Subdomains, und die kategorisiere ich in drei Klassen:\n\nDie Core Domain ist das, was ein Unternehmen besser kann als der Wettbewerb – dorthin gehören das beste Team und die meiste Modellierungsarbeit. Supporting Subdomains sind notwendig, aber kein Differenzierungsmerkmal; hier reicht solide Standardarbeit. Generic Subdomains sind gelöste Probleme wie Authentifizierung, Buchhaltung oder Benachrichtigung; die kaufe oder standardisiere ich, statt sie selbst zu bauen.\n\nDiese Einordnung ist eine Geschäftsentscheidung, keine technische. Sie beantwortet die Frage, wo Aufwand einen Return bringt. Bounded Contexts sind dann die Antwort im Lösungsraum: Idealerweise entspricht eine Subdomain genau einem Bounded Context. In der Realität ist das selten deckungsgleich – ein historisch gewachsenes System schneidet oft quer. Aber die Zuordnung Core/Supporting/Generic sagt mir, an welcher Grenze ich Präzision brauche und wo Pragmatismus genügt.\n\n## Die Kanten sind die Architektur, nicht die Kästen\n\nIsolierte Modelle sind noch kein System. Das System entsteht an den Beziehungen zwischen den Kontexten, und diese Beziehungen zu benennen ist der Kern der Arbeit – das Context Mapping. Ohne Context Map entsteht genau das, was Evans einen \"distributed Big Ball of Mud\" nennt: viele Services, die alle voneinander abhängen, ohne dass jemand die Übersetzung kontrolliert.\n\nEine Context Map zeichne ich als Kästen mit Kanten. Die Kästen sind die Kontexte, jeder mit seiner eigenen Sprache. Interessant sind die Kanten: Wer ist upstream (bestimmt das Modell), wer downstream (muss sich anpassen)? Wer übersetzt, wer publiziert?\n\n```mermaid\ngraph LR\n  subgraph U[\"Upstream\"]\n    INV[\"Inventory<br/>Product = SKU + stock\"]\n  end\n  subgraph D[\"Downstream\"]\n    SAL[\"Sales<br/>Product = price + description\"]\n    BIL[\"Billing<br/>Product = tax + revenue account\"]\n  end\n  INV -->|\"OHS / PL\"| SAL\n  SAL -->|\"ACL\"| BIL\n  INV -.->|\"SK shared kernel\"| SAL\n```\n\nDie Beschriftungen tragen die Aussage. Ein Open Host Service mit Published Language (OHS/PL) auf der Upstream-Seite heißt: Inventory bietet eine stabile, dokumentierte Schnittstelle an, an die sich viele andocken können. Ein Anti-Corruption Layer (ACL) auf der Downstream-Seite heißt: Billing schützt sein Modell aktiv vor fremden Begriffen. Ein Shared Kernel (SK) heißt: Zwei Kontexte teilen sich bewusst ein kleines gemeinsames Modell – und damit Kopplung.\n\nDer entscheidende Punkt: Der spätere Serviceschnitt legt sich *auf* diese Context Map. Erst existiert sie, dann entscheide ich, welcher Kontext ein Service wird, welcher zwei, welche zusammen deployt bleiben. Der Bounded Context ist die Modellgrenze, der Service die Deployment-Einheit. Vladik Khononov hat 2018 treffend formuliert: Bounded Contexts sind nicht Microservices. Ein Service kann Teil eines Kontexts sein, ein Kontext kann mehrere Services umfassen.\n\n## Das Muster, das die meiste Reibung spart: der Anti-Corruption Layer\n\nVon allen Context-Mapping-Patterns ist der Anti-Corruption Layer das, dessen Fehlen ich am häufigsten teuer bezahlt sehe. Sobald ein sauber modellierter Kontext an ein Legacy- oder Fremdsystem grenzt, braucht er eine Übersetzungsschicht. Ohne sie sickert das fremde Modell – oft ein schlechtes – in meinen Kern. Was als \"wir passen uns kurz an\" (Conformist) beginnt, wird stillschweigend zur Dauerlösung.\n\nKonkret: Mein Sales-Kontext kennt ein sauberes `Product`. Das Inventory-System spricht in `LegacyInventoryResponse` mit `sku` und `price_cents`. Ich lasse diese Fremd-DTOs nie in mein Domänenmodell. Ein Adapter übersetzt an genau einer Stelle:\n\n```java\n// Downstream context: Sales\ninterface CatalogPort {\n    Product findById(ProductId id);\n}\n\n// ACL: isolates the upstream \"Inventory\" model.\n// Only this class knows the foreign DTOs; the domain never does.\nclass InventoryAntiCorruptionLayer implements CatalogPort {\n\n    private final LegacyInventoryClient legacyClient;\n\n    @Override\n    public Product findById(ProductId id) {\n        LegacyInventoryResponse raw = legacyClient.get(id.value());\n        return new Product(\n            new ProductId(raw.sku),\n            Money.of(raw.price_cents) // translate cents into the domain type\n        );\n    }\n}\n```\n\nDer Gewinn ist nicht kosmetisch. Wenn das Inventory-Team sein Format ändert, ändert sich genau eine Klasse. Mein Kern bleibt stabil, meine Tests bleiben grün, und die Übersetzung ist dokumentiert statt über den Code verstreut. Das ist der Unterschied zwischen einer Grenze, die hält, und einer, die leckt.\n\nDie Kehrseite gilt für den Shared Kernel: Ich setze ihn nur ein, wenn zwei Teams in echter Partnership arbeiten und die Kopplung bewusst wollen. Geteiltes Modell heißt geteilte Änderung – jede Anpassung zwingt beide Teams zur Koordination. Als Default missbraucht wird der Shared Kernel zur Bremse. Im Zweifel gebe ich jedem Kontext sein eigenes Modell und verbinde sie über eine Published Language.\n\nZwischen Conformist und ACL liegt eine Kostenabwägung, und die gehört ausgesprochen. Conformist heißt: Wir übernehmen das fremde Modell eins zu eins und sparen uns die Übersetzung. Das ist legitim, wenn der Upstream stabil ist und sein Modell zum eigenen passt – etwa bei einer Generic Subdomain, die ohnehin nur eingebunden wird. Sobald aber der eigene Kern betroffen ist oder der Upstream ein schwaches Modell hat, wird die eingesparte Übersetzungsschicht zur gestundeten Schuld. Der ACL kostet einmal Aufbau und zahlt bei jeder Fremdänderung zurück. Diese Rechnung mache ich explizit, statt die Entscheidung dem Zufall des ersten Integrationssprints zu überlassen. In der Praxis notiere ich sie als kurze Entscheidung: Welches Fremdmodell koppeln wir, wie stabil ist es, was kostet uns ein Wechsel? Wer diese Frage einmal bewusst beantwortet, trifft sie nicht mehr versehentlich unter Zeitdruck.\n\n## Grenzen deklarativ festhalten\n\nDamit die Context Map nicht als Foto vom Whiteboard verrottet, halte ich sie versionierbar fest. Mit dem Context Mapper und seiner DSL formuliere ich die Beziehungen als Text, der im Repository neben dem Code liegt und bei jeder Änderung mitversioniert wird:\n\n```text\nContextMap ShopMap {\n    contains Sales, Inventory, Billing\n\n    Inventory -> Sales : Customer-Supplier {\n        implementationTechnology = \"REST\"\n        downstreamRights = INFLUENCER\n        exposedAggregates = Product\n    }\n\n    Sales -> Billing : Conformist {\n        implementationTechnology = \"Messaging\"\n    }\n}\n```\n\nDas ist kein Selbstzweck. Der Wert liegt darin, dass die Beziehung – Customer-Supplier, wer upstream ist, welches Aggregat exponiert wird – überprüfbar dokumentiert ist. Ein neuer Entwickler liest an einer Stelle ab, wie die Kontexte zusammenhängen, statt es aus Aufrufketten zu rekonstruieren. Diskussionen über Grenzen führe ich am Diff dieser Datei, nicht am nächsten abgewischten Whiteboard.\n\n## Wie ich in der Praxis vorgehe\n\nMein Ablauf ist bewusst unspektakulär und braucht keine Werkzeugkette. Ich hole die Domänenexperten und ein bis zwei Entwickler in einen Raum und lasse sie den fachlichen Ablauf erzählen – bei größeren Domänen nutze ich EventStorming als Discovery-Technik, um die Events an die Wand zu bringen. Dabei höre ich auf Sprachbrüche: Sobald dasselbe Wort zweimal Verschiedenes meint, habe ich vermutlich eine Kontextgrenze gefunden. Dann benenne ich die Kontexte, ordne sie in Core, Supporting und Generic ein und zeichne die Kanten mit ihren Mustern. Jede vermutete Grenze spiegele ich sofort an den Domänenexperten zurück: Ich erzähle den Ablauf in ihrer Sprache nach und beobachte, wo sie mich korrigieren. Diese Korrekturen sind Gold wert, denn sie zeigen mir die Stellen, an denen mein Modell und die gelebte Fachlichkeit noch auseinanderlaufen. Erst danach – und oft erst Wochen später – reden wir über Services, Repositories und Deployment.\n\nDieses Vorgehen fühlt sich für technikgetriebene Teams zunächst langsam an. Es ist das Gegenteil. Die Wochen, die ich vorne in Sprache investiere, spare ich hinten dreifach, weil ich Grenzen nicht mehr durch produktives System hindurch korrigieren muss. Einfach und elegant heißt hier: wenige, gut begründete Grenzen statt vieler zufälliger.\n\n## Fazit\n\nDer rote Faden ist eine Reihenfolge. Zuerst die Sprache: Wo gilt welches Modell, wo bricht ein Begriff? Das ist der Bounded Context. Dann die Beziehungen: Wer ist upstream, wer übersetzt, wo schütze ich meinen Kern mit einem Anti-Corruption Layer, wo koppele ich bewusst über einen Shared Kernel? Das ist die Context Map. Und erst ganz zuletzt die Deployment-Einheit: Welcher Kontext wird ein Microservice?\n\nWer diese Reihenfolge einhält, kann Services an fachlichen Grenzen ausrichten, statt sie nach technischen Schichten zu schneiden. Wer sie umdreht und Services zählt, bevor er die Sprache versteht, riskiert einen verteilten Big Ball of Mud mit mehr Netzwerk dazwischen. Erst kommt die Modellgrenze, dann die Entscheidung über den Betrieb. Nicht jeder Bounded Context muss ein eigener Service werden.\n\n## Weiterführende Quellen\n\n- [Martin Fowler – BoundedContext](https://martinfowler.com/bliki/BoundedContext.html)\n- [Martin Fowler – UbiquitousLanguage](https://martinfowler.com/bliki/UbiquitousLanguage.html)\n- [Martin Fowler – Conway's Law](https://martinfowler.com/bliki/ConwaysLaw.html)\n- [Vladik Khononov – Bounded Contexts are NOT Microservices](https://vladikk.com/2018/01/21/bounded-contexts-vs-microservices/)\n- [Context Mapper – Context Map](https://contextmapper.org/docs/context-map/)"},{"locale":"de","translation_key":"funktionale-muster-in-python","slug":"funktionale-muster-in-python","title":"Funktionale Muster in Python: Comprehensions, itertools und functools","summary":"Comprehensions, functools und itertools im Zusammenspiel: Wie ich in Projekten zeige, wann eine Comprehension die bessere Wahl ist als map/filter, wo lru_cache und groupby glänzen und welche Fallstricke lauern.","tags":["Software","Python","Backend"],"published_at":"2020-07-15T10:00:00+00:00","updated_at":"2026-07-13T13:19:52.630074+00:00","url":"https://www.mikebild.dev/de/blog/funktionale-muster-in-python/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/c173aa70bef9c91aa9f80aaa651103293c143bdc6bb7ef525b7b27c18be9f259/funktionale-muster-in-python-vorlesen.mp3","audio_duration_secs":828,"text":"```python\nfrom itertools import groupby\nfrom operator import itemgetter\n\nrecords = [\n    {\"team\": \"a\", \"pts\": 3},\n    {\"team\": \"b\", \"pts\": 5},\n    {\"team\": \"a\", \"pts\": 2},\n]\n\ntotals = {\n    team: sum(r[\"pts\"] for r in group)\n    for team, group in groupby(records, key=itemgetter(\"team\"))\n}\n# {\"a\": 2, \"b\": 5} – erwartet war {\"a\": 5, \"b\": 5}\n```\n\nKein Traceback, keine Warnung, nur ein falsches Ergebnis. `groupby` fasst ausschließlich *aufeinanderfolgende* gleiche Schlüssel zusammen. Ohne Vorsortierung zerfällt Team `a` in zwei Gruppen, und die zweite überschreibt im Dictionary die erste. Wer `GROUP BY` aus SQL kennt, erwartet an dieser Stelle das Gegenteil.\n\nGenau so verhalten sich die funktionalen Werkzeuge in Python insgesamt: Sie tragen vertraute Namen aus Java, C# oder SQL, folgen aber eigenen Regeln. Wer funktional in Python arbeiten will, greift seltener zu `map` und `filter` und häufiger zu Comprehensions, `functools` und `itertools`. Diese drei decken zusammen fast alles ab, was aus der funktionalen Programmierung vertraut ist – in einer Schreibweise, die für Python typisch ist.\n\nIch gehe der Reihe nach durch: erst Comprehensions als idiomatischer Ersatz für `map`/`filter`, dann die lazy Kombinatoren aus `itertools`, danach die Helfer aus `functools` – allen voran `lru_cache` – und zum Schluss die Neigung zur Immutability. An mehreren Stellen zeige ich nicht nur, wie es geht, sondern wo ich in der Praxis regelmäßig Fehler sehe. Wer sich vorher mit [Fortgeschrittenem Python](https://www.mikebild.dev/de/blog/python-advanced-decorators-generatoren/) beschäftigt hat, kennt Generatoren und Dekoratoren schon – hier bauen wir darauf auf.\n\n## Comprehensions statt map und filter\n\nFangen wir mit dem konkreten Beispiel an. Ich will die Quadrate aller geraden Zahlen von 0 bis 9. In der `map`/`filter`-Variante liest sich das so:\n\n```python\nnums = range(10)\n\n# map/filter with lambdas – works, but reads inside out\nsquares_even = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, nums)))\n```\n\nDas funktioniert, aber man liest es von innen nach außen: erst `filter`, dann `map`, und die beiden `lambda`-Ausdrücke stehen zwischen den Argumenten. Die Comprehension dreht das um und stellt die Transformation nach vorn, die Bedingung nach hinten:\n\n```python\nnums = range(10)\n\n# comprehension – transform first, condition last, one line\nsquares_even = [n * n for n in nums if n % 2 == 0]\n```\n\nDas ist die Form, die in Python-Code überwiegt, und der Grund ist schlicht Lesbarkeit. Idiomatischer Python-Code bevorzugt meist eine Comprehension gegenüber `map` oder `filter` mit `lambda`; PEP 8 schreibt diese konkrete Wahl allerdings nicht vor. Comprehensions gibt es in drei Ausprägungen – für Listen, Dictionaries und Sets:\n\n```python\nwords = [\"alpha\", \"beta\", \"gamma\"]\n\n# list, dict and set comprehensions\nlengths = [len(w) for w in words]\nby_length = {w: len(w) for w in words}\ninitials = {w[0] for w in words}\n```\n\nEin Detail geht dabei leicht unter: Seit Python 3 hat die Comprehension einen eigenen Namensraum. Die Laufvariable `w` bleibt innerhalb der Comprehension und leckt nicht mehr in den umgebenden Code – ein alter Stolperstein aus Python-2-Zeiten, den man heute nicht mehr fürchten muss.\n\nBedeutet das, dass `map` und `filter` überflüssig sind? Nein. Sie sind weiterhin idiomatisch, wenn bereits eine benannte Funktion existiert. `map(str.upper, words)` ist klarer als `[w.upper() for w in words]` – hier steht kein `lambda`, sondern eine fertige Funktion, und der Ausdruck bleibt knapp:\n\n```python\nwords = [\"alpha\", \"beta\", \"gamma\"]\n\n# map shines with an existing named function – no lambda noise\nshouted = list(map(str.upper, words))\n```\n\nDas `lambda` taugt damit als Signal: Steht eines in `map` oder `filter`, wäre eine Comprehension die bessere Wahl. Eine benannte Funktion in `map` dagegen ist völlig in Ordnung.\n\nEin verwandtes Detail sorgt regelmäßig für Verwirrung: der Unterschied zwischen dem Filter am Ende und einem bedingten Ausdruck vorn. Beide benutzen das Schlüsselwort `if`, tun aber Gegensätzliches:\n\n```python\nnums = range(10)\n\n# if at the end filters elements out – only evens survive\nevens = [n for n in nums if n % 2 == 0]\n\n# if ... else at the front transforms – all elements stay\nmasked = [n if n % 2 == 0 else 0 for n in nums]\n```\n\nDas `if` am Ende wählt aus und lässt die ungeraden Zahlen weg; das `if ... else` vorn behält jedes Element und ersetzt nur die ungeraden durch `0`. Zwei Konstrukte, die sich leicht verwechseln lassen und völlig unterschiedliche Ergebnisse liefern – im Code-Review stolpere ich regelmäßig darüber.\n\n## Lazy rechnen mit map, filter und Generator-Expressions\n\nEin Punkt wird oft übersehen: In Python 3 geben `map` und `filter` keine Listen mehr zurück, sondern Iteratoren. Sie rechnen bedarfsgesteuert – erst wenn man Werte anfordert, werden sie erzeugt. Genau deshalb steht in den Beispielen oben ein `list(...)` drumherum, sonst bekäme man nur das Iterator-Objekt.\n\nDie Comprehension dagegen materialisiert sofort: Sie baut die komplette Liste im Speicher auf. Für kleine Datenmengen ist das egal, für große kann es teuer werden. Hier kommt die Generator-Expression ins Spiel – syntaktisch fast identisch zur List-Comprehension, nur mit runden statt eckigen Klammern:\n\n```python\n# list comprehension: builds the whole list in memory\ntotal_eager = sum([n * n for n in range(1_000_000)])\n\n# generator expression: yields one value at a time, constant memory\ntotal_lazy = sum(n * n for n in range(1_000_000))\n```\n\nBeide liefern dasselbe Ergebnis, aber die zweite Variante materialisiert keine vollständige Ergebnisliste. Sie erzeugt ihre Werte nach Bedarf; vorgelagerte Datenquellen oder einzelne Operationen können natürlich trotzdem Speicher belegen. Wenn ich einen Ausdruck ohnehin nur einmal durchlaufe – etwa als Argument für `sum`, `any` oder `max` –, ist die Generator-Expression meist die passende Wahl.\n\nEin Wort der Vorsicht: Ein Generator ist nach einem Durchlauf erschöpft. Wer denselben Generator zweimal durchgehen will, bekommt beim zweiten Mal ein leeres Ergebnis. Für mehrfachen Zugriff braucht man eine materialisierte Liste – oder man denkt die Pipeline so, dass ein Durchlauf reicht.\n\nDamit haben wir drei Wege, eine Sequenz zu verarbeiten, und jeder hat seinen Platz:\n\n- Comprehension – lesbar, materialisiert sofort, eigener Namensraum, Filter und Transformation in einem Ausdruck.\n- `map`/`filter` – lazy, ideal in Kombination mit einer vorhandenen benannten Funktion, mit `lambda` weniger lesbar.\n- `itertools` – lazy Kombinatoren für lange oder unendliche Ströme, konstanter Speicher, gut komponierbar.\n\nDen dritten Punkt schauen wir uns jetzt genauer an.\n\n## itertools: lazy Kombinatoren für Ströme\n\n`itertools` ist eine Sammlung von Bausteinen, die alle lazy arbeiten. Sie erzeugen Iteratoren, keine Listen, und lassen sich zu Pipelines zusammenstecken, ohne dass Zwischenergebnisse im Speicher auflaufen. Ein paar, die ich fast täglich verwende:\n\n```python\nfrom itertools import chain, islice, count\n\n# count: infinite counter, here 1, 3, 5, 7, 9\nfirst_five_odds = list(islice(count(1, 2), 5))\n\n# chain.from_iterable: flatten a list of lists lazily\nflat = list(chain.from_iterable([[1, 2], [3, 4], [5, 6]]))\n```\n\nNeben `chain`, `islice` und `count` greife ich oft zu `takewhile` und `dropwhile`. Beide nehmen ein Prädikat und einen Strom: `takewhile` liefert Werte, solange die Bedingung hält, und bricht beim ersten `False` endgültig ab; `dropwhile` überspringt den führenden Block, für den das Prädikat wahr ist, und gibt ab da alles zurück. Auf einem sortierten Strom lässt sich damit ein Bereich herausschneiden, ohne den ganzen Rest noch zu prüfen.\n\n`count(1, 2)` ist ein unendlicher Zähler – ohne `islice` würde er nie aufhören. `islice` schneidet die ersten fünf Werte heraus und stoppt die Auswertung genau dort. Das ist das Muster hinter lazy Pipelines: Man beschreibt eine potenziell unendliche Quelle und begrenzt sie erst am Ende. `chain.from_iterable` wiederum flacht verschachtelte Sequenzen ab, ohne die Teillisten vorher zusammenzukopieren.\n\nDer Baustein, der die meisten Aha-Momente auslöst, ist `groupby`. Damit lassen sich Datensätze nach einem Schlüssel gruppieren und aggregieren:\n\n```python\nfrom itertools import groupby\nfrom operator import itemgetter\n\nrecords = [\n    {\"team\": \"a\", \"pts\": 3},\n    {\"team\": \"a\", \"pts\": 2},\n    {\"team\": \"b\", \"pts\": 5},\n]\n\n# IMPORTANT: sort by the same key before grouping\nrecords.sort(key=itemgetter(\"team\"))\n\ntotals = {\n    team: sum(r[\"pts\"] for r in group)\n    for team, group in groupby(records, key=itemgetter(\"team\"))\n}\n# {\"a\": 5, \"b\": 5}\n```\n\nDamit sind wir zurück beim Beispiel vom Anfang: Ist die Eingabe nicht nach demselben Schlüssel vorsortiert, entstehen mehrere Gruppen für denselben Schlüssel, und das Ergebnis ist stillschweigend falsch. Das `records.sort(...)` vor dem `groupby` ist keine Kür, sondern Pflicht – es ist die eine Zeile, die den Unterschied zwischen `{\"a\": 5, \"b\": 5}` und `{\"a\": 2, \"b\": 5}` ausmacht.\n\nEin zweiter Punkt: Die Gruppen, die `groupby` liefert, sind flüchtige Iteratoren. Sobald man in der äußeren Schleife weiterrückt, wird die vorige Gruppe ungültig. Wer eine Gruppe über die Iteration hinaus behalten will, muss sie mit `list(group)` materialisieren, bevor er weitergeht. Im Beispiel oben ist das kein Problem, weil `sum(...)` die Gruppe direkt im selben Schritt auswertet.\n\nBevor wir zu `functools` kommen, ein Blick auf das Gesamtbild. Die folgende Skizze zeigt, wie sich Rohdaten durch eine solche Pipeline bewegen – von der eager materialisierenden Comprehension über lazy Generator-Expressions und `itertools`-Kombinatoren bis zur finalen Faltung auf einen Wert.\n\n```mermaid\ngraph LR\n    A[Raw data] --> B[Comprehension<br/>eager, materialised]\n    B --> C[Generator expr<br/>lazy, constant memory]\n    C --> D[itertools<br/>chain / islice / groupby]\n    D --> E[reduce / sum / prod<br/>fold to a value]\n    E --> F[Result]\n```\n\n## functools: partial, reduce und lru_cache\n\n`functools` bündelt Werkzeuge, die auf Funktionen selbst wirken. Drei davon sind für funktionale Muster zentral.\n\n`partial` bindet Argumente einer Funktion vorab und gibt eine neue, aufrufbare Funktion zurück. Das ist praktisch, um allgemeine Funktionen zu spezialisieren:\n\n```python\nfrom functools import partial\n\ndef power(base, exponent):\n    return base ** exponent\n\n# fix the exponent, get a specialised function\nsquare = partial(power, exponent=2)\ncube = partial(power, exponent=3)\n\nprint(square(5))  # 25\nprint(cube(5))    # 125\n```\n\n`reduce` faltet eine Sequenz auf einen einzigen Wert – der Klassiker der funktionalen Programmierung. In Python 3 ist `reduce` bewusst kein Builtin mehr, sondern in `functools` verschoben. Das ist ein deutliches Signal: sparsam einsetzen.\n\n```python\nfrom functools import reduce\n\nflat = [1, 2, 3, 4]\n\n# reduce works, but a built-in is almost always clearer\ntotal = reduce(lambda acc, x: acc + x, flat, 0)  # 10\nbetter = sum(flat)                                # same result, obvious intent\n```\n\nEin Detail an `reduce` ist leicht zu übersehen: das dritte Argument. Es ist der Startwert der Faltung und entscheidet zugleich, was bei einer leeren Sequenz passiert. Mit Startwert `0` liefert `reduce` bei leerer Eingabe genau diese `0`; ohne Startwert wirft `reduce` bei leerer Sequenz stattdessen einen `TypeError`. Wer den Startwert weglässt, handelt sich also einen Sonderfall ein, den man in Tests leicht vergisst – und der dann ausgerechnet im Randfall zuschlägt.\n\nHier zeigt sich der häufigste `functools`-Fehler, den ich sehe: `reduce` wird überstrapaziert. Verschachtelte `reduce`-Lambdas sind schwer zu lesen, und für die meisten Fälle gibt es klarere Alternativen – `sum` für Summen, `math.prod` für Produkte (seit Python 3.8), eine Comprehension oder schlicht eine Schleife. `reduce` ist gerechtfertigt, wenn die Faltung wirklich nicht-trivial ist und keine spezialisierte Funktion existiert. In allen anderen Fällen gilt: Der ausdrücklichere Weg gewinnt.\n\nDer Star von `functools` ist für mich `lru_cache`. Der Dekorator memoisiert die Ergebnisse einer Funktion – gleiche Argumente liefern das gespeicherte Ergebnis, statt neu zu rechnen. Das klassische Lehrbeispiel ist die naive rekursive Fibonacci-Funktion, deren Laufzeit ohne Memoisierung exponentiell explodiert:\n\n```python\nfrom functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fib(n: int) -> int:\n    return n if n < 2 else fib(n - 1) + fib(n - 2)\n\nprint(fib(50))          # 12586269025 – instant instead of minutes\nprint(fib.cache_info())  # CacheInfo(hits=48, misses=51, maxsize=None, currsize=51)\n```\n\nMit `lru_cache` wird jeder Fibonacci-Wert genau einmal berechnet – die Komplexität sinkt von exponentiell auf linear. `cache_info()` gibt Einblick in Treffer und Fehlschläge, `cache_clear()` leert den Speicher. Ein Hinweis zur Schreibweise: Ich schreibe konsequent `@lru_cache(maxsize=None)` mit Klammern. Das ist über alle Versionen hinweg eindeutig und erspart Diskussionen darüber, ab welcher Python-Version der Aufruf ohne Klammern erlaubt ist.\n\nZwei Bedingungen muss man kennen. Erstens: Die Argumente müssen hashbar sein – Listen oder Dictionaries als Parameter funktionieren nicht, Tupel nur dann, wenn auch ihre Elemente hashbar sind. Zweitens: `lru_cache` passt, wenn das Ergebnis ausschließlich von diesen Argumenten abhängt und das zurückgegebene Objekt gefahrlos wiederverwendet werden kann. Bei Side Effects oder veränderlichem externem Zustand liefert der Cache leicht falsche Ergebnisse. Und `maxsize=None` bedeutet einen unbeschränkten Cache – bei sehr vielen verschiedenen Argumenten kann der Speicherverbrauch ungebremst wachsen. Für solche Fälle setzt man ein konkretes `maxsize`.\n\n`functools` hält noch mehr bereit, als in einen Artikel passt – etwa `singledispatch`, das eine Funktion je nach Typ ihres ersten Arguments unterschiedlich auflösen lässt, oder `cmp_to_key`, das eine alte Vergleichsfunktion in einen `key` für `sorted` übersetzt. Für funktionale Muster im engeren Sinn sind `partial`, `reduce` und `lru_cache` aber die drei, zu denen ich in der Praxis am häufigsten greife.\n\n## Der Hang zur Immutability\n\nFunktionales Arbeiten und Immutability gehören zusammen. Python bietet zwei immutable Container, die dabei helfen: `tuple` für geordnete Sequenzen und `frozenset` für Mengen. Beide sind hashbar, sofern ihre Elemente hashbar sind, und lassen sich dann als Dictionary-Schlüssel oder als Elemente eines Sets verwenden – etwas, das mit `list` oder `set` nicht geht:\n\n```python\n# immutable, hashable – usable as dict keys or set members\npoint = (3, 4)\nallowed = frozenset({\"read\", \"write\"})\n\npermissions = {\n    frozenset({\"read\"}): \"viewer\",\n    frozenset({\"read\", \"write\"}): \"editor\",\n}\nprint(permissions[allowed])  # editor\n```\n\nDer Vorteil liegt nicht nur in der Hashbarkeit. immutable Daten können sich nicht unbemerkt ändern, während man sie durch eine Pipeline schickt. Genau das ist die Grundlage seiteneffektfreien Arbeitens: Eine Funktion bekommt Daten herein, gibt neue Daten heraus und lässt die Eingabe unangetastet. Gerade in größeren Systemen macht diese Trennung Übergänge nachvollziehbar.\n\nDas führt direkt zum letzten Fallstrick, den ich häufig sehe: Side Effects in Comprehensions. Eine Comprehension soll Werte erzeugen, nicht `print` aufrufen, an eine Liste anhängen oder Zustand verändern:\n\n```python\n# don't do this: a comprehension used only for side effects\n[print(w) for w in words]  # builds a useless list of None values\n\n# do this instead\nfor w in words:\n    print(w)\n```\n\nDie erste Variante baut nebenbei eine Liste aus lauter `None`-Werten, die niemand braucht. Sie missbraucht die Comprehension für etwas, wofür die normale Schleife da ist. Comprehensions sind für Transformationen gedacht – wenn kein Wert entsteht, gehört der Code in eine Schleife.\n\n## Die passende Wahl treffen\n\nEntscheidend ist weniger, jedes Werkzeug zu kennen, als im richtigen Moment das passende zu greifen. Der folgende Entscheidungsbaum fasst zusammen, wie ich in der Praxis abwäge.\n\n```mermaid\ngraph TD\n    A[Sequence to process] --> B{Build a new container?}\n    B -->|Yes| C[Comprehension<br/>list / dict / set]\n    B -->|No| D{Transform with a<br/>named function?}\n    D -->|Yes| E[map]\n    D -->|No| F{Large or infinite,<br/>save memory?}\n    F -->|Yes| G[Generator expr<br/>or itertools]\n    F -->|No| H{Fold to one value?}\n    H -->|Yes| I[sum / prod / reduce]\n```\n\nDie Linie, die sich durch all das zieht: Python stellt die funktionalen Werkzeuge bereit, verlangt aber, dass man sie in seiner eigenen Ausdrucksform nutzt. Comprehensions kommen vor `map`/`filter` mit `lambda`, weil sie sich besser lesen. Generator-Expressions und `itertools` treten an, wenn Datenmengen groß werden oder Ströme unendlich sind – lazy und speicherschonend. `functools` steuert `partial` für Spezialisierung, `reduce` für die seltenen echten Faltungen und `lru_cache` für Memoisierung Pure Functions bei. Und die immutable Container `tuple` und `frozenset` halten das Ganze seiteneffektfrei zusammen.\n\nDie Fallstricke, die ich gezeigt habe, sind alle vom selben Typ: `reduce`, wo `sum` gereicht hätte; `groupby` ohne Vorsortierung; Side Effects in einer Comprehension. Sie entstehen nicht aus fehlendem Wissen, sondern aus der Gewohnheit, ein Werkzeug über seinen Zweck hinaus einzusetzen. Wer diese drei Werkzeuggruppen kennt und diszipliniert einsetzt, schreibt Python, das kompakt bleibt und trotzdem gut lesbar ist – und genau das ist der Anspruch, den die Sprache an funktionalen Code stellt.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-python.html\n- Repository `introduction-python` – die Beispiele aus diesem Artikel zum Ausprobieren.\n- [functools – Higher-order functions (Python 3.8)](https://docs.python.org/3.8/library/functools.html)\n- [itertools – Functions creating iterators (Python 3.8)](https://docs.python.org/3.8/library/itertools.html)\n- [List Comprehensions – Python Tutorial (3.8)](https://docs.python.org/3.8/tutorial/datastructures.html#list-comprehensions)\n- [map und filter – Built-in Functions (Python 3.8)](https://docs.python.org/3.8/library/functions.html#map)"},{"locale":"de","translation_key":"jsx-genau-die-regeln-hinter-dem-markup","slug":"jsx-genau-die-regeln-hinter-dem-markup","title":"JSX genau: Die Regeln hinter dem Markup","summary":"Ein präziser Blick auf JSX – was der Compiler daraus macht, warum in geschweiften Klammern Ausdrücke statt Anweisungen stehen, wie Attribute, Kinder, Bedingungen und Listen funktionieren und an welchen Stellen Anfänger stolpern.","tags":["Software","Frontend","React"],"published_at":"2020-06-24T10:00:00+00:00","updated_at":"2026-07-13T07:28:41.146176+00:00","url":"https://www.mikebild.dev/de/blog/jsx-genau-die-regeln-hinter-dem-markup/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/614df915c5e8ef680648f25d6349bd1fafb83a79f3f25699ae792fab84ac2e49/jsx-genau-die-regeln-hinter-dem-markup-vorlesen.mp3","audio_duration_secs":645,"text":"# JSX genau: Die Regeln hinter dem Markup\n\nJSX ist keine Template-Sprache und keine HTML-Variante, die JavaScript irgendwie duldet. Es ist eine Schreibweise für Funktionsaufrufe: Jedes Element, das man notiert, wird vor der Ausführung in einen Aufruf übersetzt, und dieser Aufruf gibt ein gewöhnliches JavaScript-Objekt zurück.\n\n**Redaktionelle Einordnung (Juli 2026):** Der Haupttext erklärt den klassischen JSX-Transform, der im Juni 2020 der veröffentlichte Stand war. Seit React 17 kann der automatische Transform Funktionen aus `react/jsx-runtime` verwenden; am mentalen Modell ändert das nichts. Wie React die entstehenden Elemente später abgleicht, behandelt der nachträglich erschienene Beitrag [Wie React den Baum rendert und aktualisiert](https://www.mikebild.dev/de/blog/wie-react-den-baum-rendert-und-aktualisiert/).\n\nIm React-Überblick stand dazu ein einziger Satz – sieht aus wie HTML, ist aber JavaScript. Der Satz stimmt und verhindert trotzdem keinen der Fehler, die im Alltag entstehen: reservierte Attributnamen, Anweisungen in geschweiften Klammern, eine einsame `0` in der Oberfläche, Keys aus Array-Indizes. Also die Regeln der Reihe nach, jede mit einem winzigen Beispiel und, wo es zählt, mit dem Fehler, den man macht, wenn man die Regel nicht kennt.\n\n## Was der Compiler wirklich daraus macht\n\nJSX ist keine Sprachfunktion von JavaScript. Kein Browser versteht es. Bevor der Code läuft, übersetzt ein Build-Schritt wie Babel jedes JSX-Element in einen normalen Funktionsaufruf. Diese eine Tatsache erklärt fast alle Regeln, die danach kommen.\n\nStand Juni 2020 ist das Ziel dieser Übersetzung `React.createElement`. Aus dem Markup wird ein Aufruf, und aus dem Aufruf ein einfaches Objekt.\n\n```jsx\nconst el = <button className=\"primary\" onClick={handleClick}>Save</button>;\n```\n\nwird sinngemäß zu:\n\n```js\nconst el = React.createElement(\n  \"button\",\n  { className: \"primary\", onClick: handleClick },\n  \"Save\",\n);\n```\n\nDas zurückgegebene Objekt beschreibt nur, was gerendert werden soll – es ist kein DOM-Knoten, es passiert noch nichts im Browser. React nimmt dieses Objekt später und erzeugt oder aktualisiert daraus das echte DOM. Man nennt so ein Beschreibungsobjekt ein React-Element. Wenn man das im Kopf hat, wird verständlich, warum ein Tippfehler im JSX oft als ganz normaler JavaScript-Fehler erscheint: Es ist ja am Ende ein Funktionsaufruf.\n\n## Ausdruck, nicht Anweisung\n\nDie wichtigste Regel für den geschweiften Klammerinhalt lautet: Zwischen `{` und `}` steht ein **Ausdruck**, keine **Anweisung**. Ein Ausdruck ist etwas, das einen Wert ergibt – `user.name`, `a + b`, `price > 0 ? \"ok\" : \"no\"`, ein Funktionsaufruf. Eine Anweisung ist etwas, das etwas tut, aber keinen Wert liefert – `if`, `for`, `while`, `switch`. Anweisungen sind in den Klammern nicht erlaubt.\n\n```jsx\n// works – an expression\n<p>{user ? user.name : \"Guest\"}</p>\n\n// does not work – if is a statement\n<p>{if (user) { user.name }}</p>\n```\n\nDeshalb greift man in JSX so oft zum ternären Operator `? :` und zum logischen `&&`: Sie sind die Ausdrucks-Varianten von `if`. Wer eine echte Verzweigung mit mehreren Zweigen braucht, zieht sie vor das `return` und arbeitet dort mit ganz normalem `if`:\n\n```jsx\nfunction Status({ status }) {\n  let text;\n  if (status === \"open\") text = \"Open\";\n  else if (status === \"paid\") text = \"Paid\";\n  else text = \"Unknown\";\n\n  return <span>{text}</span>;\n}\n```\n\nDas ist kein Umweg. Das ist die saubere Trennung: Logik oben, Darstellung unten. Ein häufiger Anfängerreflex ist, immer komplexere Ternäroperatoren ineinander zu schachteln, bis niemand sie mehr liest. Sobald zwei Ebenen erreicht sind, gehört die Entscheidung nach oben.\n\n## Attribute sind Props, und sie heißen anders als in HTML\n\nJSX-Attribute sehen aus wie HTML-Attribute, sind aber die Eigenschaften des erzeugten Objekts – also Props. Weil die Zielsprache JavaScript ist und nicht HTML, folgen sie den Regeln von JavaScript, und an ein paar Stellen weicht das sichtbar von HTML ab.\n\nZwei Namen sind reserviert, weil `class` und `for` in JavaScript Schlüsselwörter sind. Deshalb heißt das Klassenattribut `className` und das Label-Attribut `htmlFor`:\n\n```jsx\n<label htmlFor=\"email\" className=\"field-label\">Email</label>\n<input id=\"email\" />\n```\n\nAlle mehrteiligen HTML-Attribute werden in camelCase geschrieben: `tabindex` wird zu `tabIndex`, `readonly` zu `readOnly`, `maxlength` zu `maxLength`. Event-Handler heißen `onClick`, `onChange`, `onSubmit` – großes Binnen-C – und bekommen eine Funktion, keinen String:\n\n```jsx\n// correct – a function reference\n<button onClick={handleSave}>Save</button>\n\n// wrong – calls handleSave IMMEDIATELY on render and passes the return value\n<button onClick={handleSave()}>Save</button>\n```\n\nDer zweite Fall ist einer der häufigsten Einsteigerfehler. `onClick={handleSave()}` führt `handleSave` beim Rendern aus und hängt dessen Ergebnis an den Handler. Wenn man Argumente übergeben will, wickelt man den Aufruf in eine Pfeilfunktion: `onClick={() => handleSave(id)}`.\n\nWerte gibt man in geschweiften Klammern, feste Strings in Anführungszeichen. Ein Attribut ohne Wert ist implizit `true`:\n\n```jsx\n<input type=\"text\" value={value} disabled />\n// disabled is equivalent to disabled={true}\n```\n\n## Wie Werte im Inhalt gerendert werden – und was verschwindet\n\nWas React aus einem Ausdruck im Inhalt macht, hängt vom Typ des Werts ab, und hier lauert eine ganze Reihe kleiner Überraschungen. Strings und Zahlen werden als Text ausgegeben. Arrays werden Element für Element gerendert. Aber `null`, `undefined`, `true` und `false` rendern **nichts** – sie verschwinden spurlos. Genau das macht bedingtes Rendern erst möglich.\n\n```jsx\n<div>\n  {message}          {/* string or number -> gets displayed */}\n  {null}             {/* nothing */}\n  {isAdmin && <Panel/>} {/* Panel only when isAdmin is true */}\n</div>\n```\n\nEin klassischer Fehler steckt im `&&`. Es rendert das rechte Element nur, wenn die linke Seite wahr ist – aber es gibt die linke Seite zurück, wenn sie falsch ist. Bei Booleans ist das harmlos, weil `false` verschwindet. Bei einer Zahl nicht:\n\n```jsx\n// pitfall: if count is 0, a 0 appears in the UI, not nothing\n{count && <List />}\n\n// correct: convert to a boolean first\n{count > 0 && <List />}\n```\n\nDie `0` ist eben keine `false`, sondern eine Zahl, und Zahlen werden gerendert. Wer schon einmal eine einsame `0` in seiner Oberfläche gesucht hat, kennt diesen Fehler. Die Regel dahinter ist einfach: Vor einem `&&` steht am besten ein echter Wahrheitswert, kein Wert, der zufällig falsy ist.\n\n## Ein Element, ein Wurzelknoten – und Fragmente\n\nWeil ein JSX-Ausdruck am Ende ein einzelnes Objekt ergibt, muss eine Komponente genau ein Wurzelelement zurückgeben. Zwei Elemente nebeneinander ohne Klammerung sind ein Syntaxfehler. Man könnte alles in ein `<div>` wickeln, aber das erzeugt einen zusätzlichen, oft unerwünschten Knoten im DOM. Dafür gibt es das Fragment – eine Klammer, die im DOM nichts hinterlässt:\n\n```jsx\nfunction Row() {\n  return (\n    <>\n      <td>Name</td>\n      <td>Amount</td>\n    </>\n  );\n}\n```\n\nDie Kurzschreibweise `<>...</>` reicht fast immer. Nur wenn das Fragment selbst ein `key` braucht – etwa als direktes Kind einer Liste – muss man die lange Form `<Fragment key={id}>...</Fragment>` verwenden, weil die Kurzform keine Attribute annimmt.\n\nDie runden Klammern um mehrzeiliges JSX nach `return` sind übrigens keine Kosmetik gegen Einrückung, sondern ein Schutz vor einer JavaScript-Falle: Steht das erste Element in einer neuen Zeile direkt nach `return`, fügt JavaScript automatisch ein Semikolon ein, und die Funktion gibt `undefined` zurück. Die Klammer verhindert das.\n\n## Listen und Keys: die am meisten unterschätzte Regel\n\nEine Liste rendert man, indem man ein Array mit `map` in ein Array von Elementen verwandelt. Jedes dieser Elemente braucht ein `key`-Attribut. Der Key ist kein Deko-Detail – er ist die Information, an der React beim nächsten Rendern erkennt, welches alte Element welchem neuen entspricht.\n\n```jsx\n<ul>\n  {invoices.map((i) => (\n    <li key={i.id}>{i.number}</li>\n  ))}\n</ul>\n```\n\nDer Key muss zwei Eigenschaften haben: Er muss unter den Geschwistern eindeutig sein, und er muss stabil sein, also bei denselben Daten immer gleich. Deshalb nimmt man eine fachliche ID, keinen zufälligen Wert und – das ist der wunde Punkt – möglichst nicht den Array-Index.\n\nDer Index als Key funktioniert scheinbar, solange sich die Liste nie ändert. Sobald man aber vorne etwas einfügt, löscht oder sortiert, verschieben sich die Indizes, und React ordnet den alten States die falschen Elemente zu. Das äußert sich in gespenstischen Fehlern: Ein Eingabefeld behält seinen Text, obwohl die Zeile eine ganz andere sein sollte; eine Checkbox bleibt angehakt, obwohl das zugehörige Element gelöscht wurde. Der Index beschreibt eine Position, der Key soll aber eine Identität beschreiben – und Position und Identität sind zwei verschiedene Dinge. Nur wenn eine Liste garantiert statisch ist und nie umsortiert wird, ist der Index als Key vertretbar. Wie React diesen Vergleich beim erneuten Rendern im Detail durchführt, ist ein eigenes Thema.\n\n## Spread, Kinder und die kleinen Fallstricke am Rand\n\nProps kann man einzeln setzen oder mit dem Spread-Operator aus einem Objekt durchreichen. Das ist bequem, verdient aber Vorsicht:\n\n```jsx\nconst props = { type: \"text\", value: value, onChange: handleChange };\n<input {...props} />\n```\n\nSauber ist das, wenn man genau weiß, was im Objekt steckt. Unsauber wird es, wenn man ein ganzes fremdes Objekt blind durchreicht und damit unbemerkt Attribute setzt, die man gar nicht wollte. Kommt nach dem Spread noch ein einzelnes Attribut, gewinnt das letzte – `<input {...props} value={otherValue} />` überschreibt das `value` aus dem Objekt.\n\nDer Inhalt zwischen öffnendem und schließendem Tag landet in der besonderen Prop `children`. Eine Komponente, die `children` rendert, weiß nichts über ihren Inhalt und ist gerade deshalb überall einsetzbar. Man kann `children` auch explizit als Attribut übergeben, was aber selten schöner ist als die natürliche Schachtelung.\n\nEin paar weitere Details, die immer wieder auffallen: Inline-Styles sind in JSX ein Objekt, keine CSS-Zeichenkette, und ihre Schlüssel stehen in camelCase – `<div style={{ backgroundColor: \"red\", fontSize: 14 }} />`, mit doppelten Klammern, weil das äußere Paar den Ausdruck einleitet und das innere das Objekt ist. Kommentare innerhalb von JSX schreibt man als Ausdruck: `{/* so */}`. Und rohes HTML aus einem String setzt man nur über `dangerouslySetInnerHTML` ein – der sperrige Name ist Absicht, denn genau hier entstehen Cross-Site-Scripting-Lücken, wenn der String aus einer fremden Quelle stammt. Normaler Text in JSX wird von React automatisch escaped und ist deshalb sicher; dieser eine Weg umgeht diesen Schutz bewusst.\n\n## Warum sich die Genauigkeit lohnt\n\nAll diese Regeln folgen aus einem einzigen Gedanken: JSX ist eine Schreibweise für Funktionsaufrufe, die ein Beschreibungsobjekt erzeugen. Die reservierten Namen, die Ausdrucksregel, das Verschwinden von `null` und `false`, die `0`-Falle, der Zwang zu einem Wurzelknoten, die Bedeutung des Keys – nichts davon ist Willkür, alles ergibt sich daraus, dass am Ende JavaScript läuft und nicht HTML.\n\nWer JSX so liest, hört auf, gegen die Sprache zu arbeiten. Man setzt `className` nicht mehr aus Versehen als `class`, man macht aus einer Zahl vor dem `&&` einen echten Vergleich, man vergibt Keys aus fachlichen IDs statt aus Indizes – nicht weil ein Linter meckert, sondern weil man versteht, was der Compiler daraus macht. Zu den einzelnen Bausteinen, die hier nur gestreift wurden – der Datenfluss über Props, die Frage nach dem State-Besitz, das Rendern auf dem Server –, gibt es eigene Beiträge. JSX ist der Anfang von allem, und genau deshalb lohnt es sich, hier genau zu sein.\n\n## Weiterführende Quellen\n\n- Repository introduction-react (JSX-Kapitel und Beispiele): https://github.com/mikebild/introduction-react\n- React, JSX-Markup schreiben: https://react.dev/learn/writing-markup-with-jsx\n- React, JavaScript in JSX mit geschweiften Klammern: https://react.dev/learn/javascript-in-jsx-with-curly-braces\n- React, Listen rendern und Keys: https://react.dev/learn/rendering-lists"},{"locale":"de","translation_key":"aws-deployment-pipelines-architektur","slug":"aws-deployment-pipelines-architektur","title":"AWS Deployment Pipelines sind Architektur","summary":"Deployment Pipelines sind Architektur, weil sie bestimmen, wie häufig, sicher und reversibel ein System verändert wird.","tags":["Software","AWS","Cloud"],"published_at":"2020-05-12T10:00:00+00:00","updated_at":"2026-07-13T08:38:49.427291+00:00","url":"https://www.mikebild.dev/de/blog/aws-deployment-pipelines-architektur/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/34350b2e9e16ceefa74bad2b01d9163467d4c18dc23fe7d64ea87b5039ff5a4f/aws-deployment-pipelines-architektur-vorlesen.mp3","audio_duration_secs":655,"text":"# AWS Deployment Pipelines sind Architektur\n\nDie Zeit von einem gemergten Commit bis zu dem Moment, in dem die Änderung in Produktion wirkt, liegt bei manchen Teams unter einer Viertelstunde und bei anderen bei einem Quartal – häufig bei vergleichbarem Anwendungscode. Diese Spanne steht in keinem Architekturdiagramm. Sie entsteht dort, wo eine Änderung ihren Weg nimmt: in den Schritten zwischen Commit und Runtime, in den Kontrollen, die sie passieren muss, und in dem, was übrig bleibt, wenn sie zurückgenommen werden soll. Der Weg dorthin gehört damit in dieselbe Entwurfsdiskussion wie die Wahl einer Datenbank – und braucht dieselbe Begründung.\n\nDer konkrete Anlass für diesen Text ist eine kleine GitHub Action, die nichts weiter tut, als ein AWS-CDK-Projekt zu deployen. Ein paar Zeilen YAML. Und trotzdem legt genau dieser Baustein fest, welcher Fehler früh auffällt, welcher erst in der Produktion – und wer eine Änderung an der Infrastruktur überhaupt auslösen darf.\n\n## Die Pipeline legt die Änderbarkeit fest\n\nArchitektur beantwortet die Frage, was sich unabhängig voneinander ändern lässt. Genau das ist auch die Kernfrage einer Pipeline. Ein System, das nur im Quartals-Release deploybar ist, hat eine andere Architektur als eines, das dieselbe Codebasis zwanzigmal am Tag ausrollt – selbst wenn beide identischen Anwendungscode enthalten. Die Änderbarkeit steckt nicht allein im Modul-Schnitt, sondern im Weg von einem Commit bis in die Runtime.\n\nAuf AWS wird dieser Weg besonders sichtbar, seit Infrastruktur selbst Code ist. Mit dem CDK beschreibe ich Lambda-Functions, API-Gateways, Tabellen und Rechte in TypeScript. `cdk synth` übersetzt das in ein CloudFormation-Template, `cdk deploy` bringt es in ein Konto. Damit verschiebt sich etwas Grundlegendes: Die Frage „wie sieht meine Infrastruktur aus?“ und die Frage „wie kommt eine Änderung dorthin?“ fallen zusammen. Beide liegen im selben Repository, durchlaufen denselben Review und dieselbe Pipeline. Das habe ich in [Infrastruktur als Programmiersprache](https://www.mikebild.dev/de/blog/cdk-infrastruktur-als-programmiersprache/) ausführlicher aufgeschrieben; hier interessiert mich der Schritt danach – was passiert, wenn dieser Code automatisch ausgerollt wird.\n\nEin minimaler Stack sieht so aus:\n\n```ts\nimport * as cdk from \"@aws-cdk/core\";\nimport * as lambda from \"@aws-cdk/aws-lambda\";\nimport * as apigw from \"@aws-cdk/aws-apigateway\";\n\nexport class ApiStack extends cdk.Stack {\n  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {\n    super(scope, id, props);\n\n    const handler = new lambda.Function(this, \"ApiHandler\", {\n      runtime: lambda.Runtime.NODEJS_12_X,\n      handler: \"index.handler\",\n      code: lambda.Code.fromAsset(\"dist/api\"),\n    });\n\n    new apigw.LambdaRestApi(this, \"Api\", { handler });\n  }\n}\n```\n\nDas Beispiel ist bewusst klein. Es soll keine vollständige Anwendung zeigen, sondern die Grenze markieren: Alles, was hier steht, ist ab jetzt Teil des deploybaren Artefakts. Wenn ich die Runtime ändere, ein Recht erweitere oder das API umbaue, geht das denselben Weg wie eine Codeänderung. Die spannende Entscheidung ist nicht, wie viele Constructs ich schreibe, sondern welche Kontrolle zwischen diesem Code und der Produktion steht.\n\n## Die „CDK Action“ als kleinster ehrlicher Baustein\n\nDer einfachste Weg, dieses Deployment zu automatisieren, ist eine GitHub Action, die auf jeden Push nach `main` reagiert:\n\n```yaml\nname: deploy\non:\n  push:\n    branches: [main]\n\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v1\n        with:\n          node-version: 12\n      - run: npm ci\n      - run: npm test\n      - run: npx cdk deploy --require-approval never\n        env:\n          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}\n          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n          AWS_DEFAULT_REGION: eu-central-1\n```\n\nDas sieht harmlos aus, trifft aber lauter Architekturentscheidungen. `on: push` heißt: Jeder Merge nach `main` ist ein Deployment – der Trunk ist die Auslieferung, nicht bloß ein Zwischenstand. Der Schritt `npm test` vor `cdk deploy` zieht eine Qualitätsgrenze: Was rot ist, geht nicht raus. `--require-approval never` verzichtet auf die interaktive Rückfrage des CDK bei sicherheitsrelevanten Änderungen – bequem, aber es verschiebt die Verantwortung für IAM-Änderungen vollständig in den Review davor. Und die zwei Secrets legen fest, mit welchen Rechten diese Pipeline im Konto agiert; in der Praxis ist das der Punkt, an dem die meiste unausgesprochene Macht steckt.\n\nGenau deshalb ist dieser kleine Baustein aufschlussreicher als jede große Referenzpipeline. Man kann ihn in fünf Minuten im Team durchgehen, und jede Zeile steht für eine bewusste oder unbewusste Entscheidung über Häufigkeit, Sicherheit und Zuständigkeit.\n\n## Der Review-Punkt liegt vor dem Deploy, nicht danach\n\nBei Anwendungscode reviewen wir den Diff. Bei Infrastruktur tun das viele nicht – und wundern sich, dass ein Merge nebenbei eine Security Group öffnet oder eine Tabelle ersetzt. Das CDK hat dafür ein gutes Werkzeug, das in einer Pipeline zum eigentlichen Review-Artefakt wird:\n\n```bash\n# what will actually change in the account\ncdk diff ApiStack\n```\n\n`cdk diff` zeigt nicht meinen TypeScript-Diff, sondern den Unterschied zwischen dem, was im Konto steht, und dem, was ich deployen will – inklusive der IAM-Statements, die CloudFormation daraus ableitet. In einer sauberen Pipeline läuft dieser Schritt automatisch und hängt das Ergebnis an den Pull Request. Damit entscheidet ein Mensch über die Wirkung, nicht über den Quelltext. Das ist ein methodischer Unterschied mit direkter Betriebswirkung: Ein Reviewer, der sieht „diese Änderung fügt `iam:PassRole` hinzu“, stoppt sie, bevor sie im Konto liegt. Ein Reviewer, der nur `stack.ts` liest, übersieht sie oft.\n\nSo sieht der Weg als Ganzes aus:\n\n```mermaid\nflowchart LR\n  Commit --> Build[\"Build & Test\"]\n  Build --> Synth[\"cdk synth<br/>CloudFormation-Template\"]\n  Synth --> Diff[\"cdk diff<br/>Review-Artefakt\"]\n  Diff --> Approve{\"Freigabe?\"}\n  Approve -->|ja| Deploy[\"cdk deploy\"]\n  Approve -->|nein| Stop[\"Halt\"]\n  Deploy --> Observe[\"Metriken &<br/>Alarme\"]\n  Observe -->|Fehler| Rollback[\"Rollback auf<br/>vorherige Revision\"]\n```\n\nJeder Knoten in dieser Skizze ist eine Stellschraube. Wo die Freigabe sitzt, entscheidet über Tempo gegen Kontrolle. Ob nach `Deploy` überhaupt beobachtet wird, entscheidet, ob ein schlechtes Release auffällt, bevor der Kunde es meldet. Und ob es einen echten `Rollback`-Pfad gibt, entscheidet darüber, ob eine Änderung reversibel ist – oder nur hoffentlich richtig.\n\n## Dasselbe Artefakt durch mehrere Umgebungen\n\nSobald mehr als eine Umgebung im Spiel ist – Staging und Produktion, oft in getrennten AWS-Konten – wird die Pipeline zur eigentlichen Definition dessen, was „promoten“ heißt. Tragfähig ist das nur unter einer Bedingung: Dasselbe geprüfte Artefakt wandert durch die Stufen, nicht ein zweiter Build mit leicht anderen Zutaten. Beim CDK bedeutet das, dieselbe App mit unterschiedlichem Kontext zu synthetisieren.\n\n```ts\nconst app = new cdk.App();\n\nnew ApiStack(app, \"ApiStack-staging\", {\n  env: { account: \"111111111111\", region: \"eu-central-1\" },\n});\n\nnew ApiStack(app, \"ApiStack-prod\", {\n  env: { account: \"222222222222\", region: \"eu-central-1\" },\n});\n```\n\nDamit steht die Umgebungs-Topologie im selben Repository wie der Code und durchläuft denselben Review. Der methodische Gewinn ist Vertrauen: Wenn Staging und Produktion aus einer Quelle synthetisiert werden, testet Staging tatsächlich das, was später in Produktion läuft – und nicht eine plausible Kopie, die an drei Stellen abweicht. Genau diese Abweichungen sind es, die sonst erst im teuersten Konto auffallen. Die Trennung in eigene Konten ist dabei kein Betriebsdetail, sondern eine Architekturgrenze: Ein Deploy nach Staging kann Produktion nicht versehentlich berühren, weil ihm schlicht die Rechte im anderen Konto fehlen.\n\n## Trade-offs, die man benennen muss\n\nDie interessante Arbeit an einer Pipeline besteht nicht darin, sie zum Laufen zu bringen, sondern darin, ihre Kompromisse offenzulegen. Drei davon tauchen regelmäßig auf:\n\n- Auto-Deploy auf `main` gegen manuelles Gate. Der automatische Weg verkürzt die Durchlaufzeit drastisch, verlangt aber ein belastbares Testnetz und gute Alarme. Das Gate gibt ein Sicherheitsgefühl, sammelt in der Praxis aber Änderungen zu großen, riskanten Batches an – der häufigste Grund für seltene, angstbesetzte Releases.\n- Ein Stack gegen viele Stacks. Ein großer Stack ist einfach zu deployen, aber jede Änderung berührt alles. Getrennte Stacks für API, Daten und statisches Frontend erlauben es, das Risiko klein zu halten und Teile unabhängig auszurollen – auf Kosten von mehr Koordination an den Schnittstellen.\n- Rollback per Redeploy gegen Vorwärts-Fix. CloudFormation kann bei einem fehlgeschlagenen Deploy automatisch zurückrollen. Das trägt aber nur, solange die Änderung nicht bereits Daten migriert oder ein Schema erweitert hat. Ab da ist „einfach zurück“ eine Illusion, und man braucht additive, rückwärtskompatible Schritte statt eines Undo-Knopfs.\n\nKeine dieser Entscheidungen ist universell richtig. Aber sie gehören in ein Architektur-Gespräch und in ein kurzes ADR, nicht in eine YAML-Datei, die jemand vor einem Jahr committet hat und die seither niemand mehr hinterfragt.\n\n## Warum das ein CTO interessieren sollte\n\nFür die technische Leitung übersetzt sich das alles in Zahlen, die seit „Accelerate“ ein etabliertes Vokabular haben. Vier Kennzahlen beschreiben die Leistungsfähigkeit einer Auslieferung ziemlich vollständig, und alle vier werden von der Pipeline bestimmt, nicht vom Anwendungscode:\n\n- Deployment-Häufigkeit – wie oft geht überhaupt etwas live. Ein Auto-Deploy auf `main` hebt sie um Größenordnungen gegenüber einem manuellen Quartals-Gate.\n- Lead Time – wie lange von „Code fertig“ bis „in Produktion“. `cdk diff` im PR plus automatischer Deploy drückt das von Tagen auf Minuten.\n- Change Failure Rate – welcher Anteil der Releases erzeugt einen Fehler. Der Test-Schritt und das Diff-Review vor dem Deploy senken sie, ohne die Häufigkeit zu opfern.\n- Time to Restore – wie schnell ist der Normalzustand wieder da. Ein echter, geübter Rollback-Pfad ist hier der Unterschied zwischen Minuten und einem verlorenen Nachmittag.\n\nDas Wichtige an diesen vier: Sie machen unterschiedliche Seiten der Lieferfähigkeit sichtbar. Kleine Änderungen begrenzen den Umfang einer Prüfung und eines möglichen Fehlers; automatisierte Checks verkürzen die Rückmeldung; ein geübter Wiederherstellungsweg senkt die Zeit bis zur Reparatur. Ob eine Pipeline diese Wirkung tatsächlich hat, zeigen erst Lead Time for Changes, Change Failure Rate und Time to Restore Service im eigenen System. Sie ist damit keine Zugabe für die Betriebsseite, sondern Teil der Architektur.\n\n## Woran ich eine Pipeline prüfe\n\nBelastbar ist ein Pipeline-Entwurf erst, wenn auch der Fehlerpfad beschrieben ist. Die Fragen, die dabei am meisten aufdecken, zielen genau dorthin. Was passiert, wenn `cdk deploy` mitten im Umbau abbricht – bleibt ein halber Zustand zurück? Ist der Deploy idempotent genug, dass ein zweiter Lauf ihn heilt? Wo liegt die Grenze, ab der ein Rollback nicht mehr genügt, weil bereits Daten migriert wurden? Und ganz banal: Wer darf diese Pipeline auslösen, und ist das nachvollziehbar protokolliert?\n\nAm häufigsten begegnet mir dabei die Überbewertung des glücklichen Pfades. Im Demo-Konto läuft alles sauber. Interessant wird es bei Teilfehlern, Rechten, die knapp nicht ausreichen, Ressourcen, die CloudFormation ersetzen statt ändern will, und bei dem einen Deploy, der um 17 Uhr am Freitag hängenbleibt. Genau dort zeigt sich, ob das Pipeline-Modell trägt – und ob „reversibel“ ein echtes Versprechen ist oder nur ein Wort in einer Präsentation.\n\n## Fazit\n\nDie Verlockung ist, eine Pipeline als Werkzeugfrage zu behandeln: welche Action, welcher Runner, welcher Provider. Der eigentliche Gehalt liegt woanders. Eine Pipeline kodiert, wie oft ein Team seine Meinung ändern darf, wie sicher es das tut und wie leicht es einen Fehler zurücknimmt. Das sind Architektureigenschaften, und sie entstehen nicht im Toolnamen, sondern in den paar bewussten Entscheidungen dahinter – Auto-Deploy oder Gate, ein Stack oder viele, Undo oder Vorwärts-Fix. Wer diese Entscheidungen benennt und ihre Wirkung misst, kann Engpässe gezielt verändern. Wer sie einer alten YAML-Datei überlässt, trifft sie trotzdem – nur unbewusst und meist zum ungünstigsten Zeitpunkt.\n\n## Weiterführende Quellen\n\n- AWS CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/home.html\n- AWS CDK Constructs: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n- AWS CloudFormation – wie Deployments und Rollbacks intern ablaufen: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html\n- Nicole Forsgren, Jez Humble, Gene Kim: „Accelerate“ – die vier Delivery-Kennzahlen im Detail."},{"locale":"de","translation_key":"python-advanced-decorators-generatoren","slug":"python-advanced-decorators-generatoren","title":"Fortgeschrittenes Python: Decorators, Magic Methods und Generatoren","summary":"Drei Bausteine, die pythonischen Code ausmachen: Decorators umschließen Funktionen, Magic Methods binden eigene Objekte an Pythons Protokolle, Generatoren erzeugen lazy Sequenzen.","tags":["Software","Python","Backend"],"published_at":"2020-04-08T10:00:00+00:00","updated_at":"2026-07-13T10:00:30.74463+00:00","url":"https://www.mikebild.dev/de/blog/python-advanced-decorators-generatoren/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/3137291c3f9908c8a2f11ba497f69558d1af30b33839b6be786f0ac02cbbd328/python-advanced-decorators-generatoren-vorlesen.mp3","audio_duration_secs":615,"text":"Python-Code, den man Zeile für Zeile genauso in Java oder C# hätte schreiben können, ist selten falsch – er nutzt die Sprache nur nicht. Drei Mechanismen machen den Unterschied, und keiner davon ist Zauberei: der `@`-Decorator, die Dunder-Methode und `yield`. Alle drei sind im Sprachkern dokumentiert, jeder ist in wenigen Zeilen selbst nachbaubar, und jeder löst ein Problem, das man sonst mit Copy-Paste oder mit zu viel Arbeitsspeicher löst.\n\nDer Stand hier ist Anfang 2020, also Python 3.8. Alle Beispiele laufen dort ohne Zusatzpakete – nur mit `functools`, `time` und der Standardbibliothek. Vorausgesetzt sind Python-Objekte, Funktionen und die üblichen eingebauten Datentypen.\n\n## Decorators: Funktionen, die Funktionen umschließen\n\nDer Einstieg in Decorators ist einfacher, als der `@`-Zucker vermuten lässt. In Python sind Funktionen ganz normale Objekte. Man kann sie einer Variablen zuweisen, als Argument übergeben und aus einer anderen Funktion zurückgeben. Ein Decorator ist nichts weiter als eine Funktion höherer Ordnung: Sie nimmt eine Funktion entgegen und gibt eine – meist umschließende – Funktion zurück.\n\n```python\nimport functools\nimport time\n\n\ndef timer(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.perf_counter()\n        result = func(*args, **kwargs)\n        elapsed = time.perf_counter() - start\n        print(f\"{func.__name__} took {elapsed:.4f}s\")\n        return result\n    return wrapper\n\n\n@timer\ndef slow_sum(n):\n    return sum(range(n))\n```\n\nDie Schreibweise `@timer` über `def slow_sum` ist exakt Syntaxzucker für `slow_sum = timer(slow_sum)`. Nichts anderes passiert. Nach dem Dekorieren zeigt der Name `slow_sum` nicht mehr auf die ursprüngliche Funktion, sondern auf `wrapper`. Bei jedem Aufruf startet zuerst die Zeitmessung, dann läuft die echte Funktion, danach wird die verstrichene Zeit gedruckt. Das `*args, **kwargs` sorgt dafür, dass der Wrapper beliebige Signaturen durchreicht, ohne selbst etwas über die Argumente wissen zu müssen.\n\nDer Ablauf beim Aufruf einer dekorierten Funktion, aufgezeichnet – der Wrapper klammert die eigentliche Arbeit ein:\n\n```mermaid\nflowchart LR\n    Call[\"call slow_sum()\"] --> W[\"wrapper()\"]\n    W -->|\"before:<br/>start timer\"| F[\"original func()\"]\n    F -->|\"return value\"| W\n    W -->|\"after:<br/>print elapsed\"| Ret[\"return result\"]\n```\n\n### functools.wraps ist keine Kür\n\nEin Detail fehlt in selbstgeschriebenen Decorators mit schöner Regelmäßigkeit: die Zeile `@functools.wraps(func)`. Ohne sie funktioniert der Decorator zwar, aber der Wrapper übernimmt nicht die Identität der ursprünglichen Funktion. `slow_sum.__name__` liefert dann `\"wrapper\"` statt `\"slow_sum\"`, `slow_sum.__doc__` ist der Docstring des Wrappers, und `help(slow_sum)` zeigt die falsche Signatur.\n\n```python\ndef timer_broken(func):\n    def wrapper(*args, **kwargs):\n        return func(*args, **kwargs)\n    return wrapper\n\n\n@timer_broken\ndef greet(name):\n    \"\"\"Say hello to someone.\"\"\"\n    return f\"Hello, {name}\"\n\n\nprint(greet.__name__)   # -> \"wrapper\"\nprint(greet.__doc__)    # -> None\n```\n\n`functools.wraps` ist ein Convenience-Wrapper um `functools.update_wrapper`. Er kopiert `__module__`, `__name__`, `__qualname__`, `__annotations__` und `__doc__` von der Originalfunktion auf den Wrapper und setzt zusätzlich `__wrapped__`, sodass man im Zweifel wieder an die undekorierte Funktion herankommt. Für Debugging, Introspektion und Werkzeuge, die auf Metadaten schauen, ist das der Unterschied zwischen brauchbar und verwirrend. Die Zeile gehört deshalb in jeden Decorator, den ich schreibe.\n\n### Decorators mit Argumenten\n\nHäufig will man einen Decorator konfigurieren, etwa: „Führe die Funktion dreimal aus.“ Dafür braucht man eine Ebene mehr. Ein Decorator mit Argumenten ist eine Funktion, die einen Decorator zurückgibt, der wiederum den Wrapper zurückgibt – drei ineinander geschachtelte Funktionen.\n\n```python\ndef repeat(times):\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            result = None\n            for _ in range(times):\n                result = func(*args, **kwargs)\n            return result\n        return wrapper\n    return decorator\n\n\n@repeat(times=3)\ndef ping():\n    print(\"ping\")\n```\n\n`@repeat(times=3)` wird zuerst ausgewertet: Der Aufruf `repeat(times=3)` liefert `decorator` zurück, und dieses `decorator` wird dann auf `ping` angewandt. Wer den Aufbau einmal von innen nach außen gelesen hat, dem erschließt sich das Muster – und es taucht in vielen Bibliotheken genau so auf, etwa bei Routing-Decorators in Web-Frameworks.\n\n## Magic Methods: eigene Objekte, die sich wie eingebaute verhalten\n\nDer zweite Baustein greift tiefer in die Sprache hinein. Magic Methods – auch Dunder-Methoden genannt, wegen der doppelten Unterstriche – sind der Weg, über den eigene Klassen an Pythons Protokolle andocken. Man ruft diese Methoden nie direkt auf. Stattdessen ruft der Interpreter sie auf, wenn man ein Objekt in einen bekannten Kontext stellt: `len(obj)` löst `__len__` aus, `==` löst `__eq__` aus, ein `for`-Loop löst `__iter__` aus, ein `with`-Block löst `__enter__` und `__exit__` aus.\n\nEin paar der gängigsten Dunder-Methoden und was sie auslösen:\n\n- `__init__` – die Konstruktion beim Erzeugen einer Instanz\n- `__repr__` – `repr()` und die Anzeige im REPL, idealerweise eindeutig und im besten Fall `eval`-fähig\n- `__str__` – `str()` und `print()`; fehlt sie, springt `__repr__` ein\n- `__eq__` – der Vergleich mit `==`\n- `__len__` – der Aufruf `len(obj)`, der auch für die Wahrheitsprüfung herangezogen wird, wenn `__bool__` fehlt\n- `__iter__` und `__next__` – die Iteration in `for`-Loops und beim Entpacken\n- `__enter__` und `__exit__` – der Ein- und Ausstieg eines `with`-Blocks\n- `__call__` – der Aufruf einer Instanz wie eine Funktion, `obj()`\n\nDamit das konkret wird, baue ich eine Klasse, die Zeilen aus einer Datei bereitstellt. Sie soll ein ordentliches `__repr__` haben, sich mit `==` vergleichen lassen, als Context Manager funktionieren und iterierbar sein.\n\n```python\nclass LineStore:\n    def __init__(self, path):\n        self.path = path\n\n    def __repr__(self):\n        return f\"LineStore({self.path!r})\"\n\n    def __eq__(self, other):\n        return isinstance(other, LineStore) and self.path == other.path\n\n    def __enter__(self):\n        self._file = open(self.path, encoding=\"utf-8\")\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self._file.close()\n        return False   # do not swallow exceptions\n\n    def __iter__(self):\n        return (line.rstrip(\"\\n\") for line in self._file)\n```\n\nEin `LineStore` verhält sich jetzt wie ein eingebautes Objekt. Im REPL zeigt er `LineStore('access.log')` statt einer nichtssagenden Speicheradresse. Zwei Instanzen mit gleichem Pfad sind gleich. Und der eigentliche Clou steckt im `with`-Block:\n\n```python\nwith LineStore(\"access.log\") as store:\n    for line in store:\n        if \"ERROR\" in line:\n            print(line)\n```\n\nDas `with` ruft `__enter__` auf, bindet den Rückgabewert an `store`, führt den Body aus und ruft danach – garantiert, auch bei einer Exception – `__exit__` auf. Dort wird die Datei geschlossen. Genau das ist der Sinn eines Context Managers: Aufräumen, das man nicht vergessen kann. Der Rückgabewert von `__exit__` entscheidet über den Umgang mit Fehlern. Gibt die Methode `True` zurück, wird eine im Block aufgetretene Exception unterdrückt; ein falsy Wert wie `False` reicht sie weiter. Ich gebe hier bewusst `False` zurück, weil ein Fehler beim Lesen der Datei nicht stillschweigend verschwinden soll.\n\nFür einfache Fälle muss man das Protokoll übrigens nicht von Hand implementieren. `contextlib.contextmanager` verwandelt eine Generatorfunktion in einen Context Manager, wobei das `yield` Setup und Teardown trennt. Das führt uns direkt zum dritten Baustein.\n\n## Generatoren: lazy Sequenzen mit yield\n\nDer `LineStore` schleppt eine Eigenheit mit sich: Sein `__iter__` gibt bereits eine Generator-Expression zurück. Generatoren sind der dritte Pfeiler, und für mich der praktisch wichtigste, sobald Daten größer werden als der Arbeitsspeicher.\n\nSobald in einer Funktion das Schlüsselwort `yield` auftaucht, ist sie kein normales Callable mehr, sondern eine Generatorfunktion. Ihr Aufruf führt den Rumpf nicht aus, sondern gibt sofort ein Generator-Objekt zurück. Der Code läuft erst, wenn man über das Objekt iteriert – und er hält an jedem `yield` an, merkt sich seinen Zustand und macht beim nächsten Schritt genau dort weiter.\n\n```python\ndef stream_lines(path):\n    with open(path, encoding=\"utf-8\") as fh:\n        for line in fh:          # a file object is itself an iterator\n            yield line.rstrip(\"\\n\")\n\n\nfor line in stream_lines(\"big.log\"):\n    if line.startswith(\"2020\"):\n        print(line)\n```\n\nHier steht immer nur eine Zeile gleichzeitig im Speicher. Egal, ob die Datei zehn Kilobyte oder zehn Gigabyte groß ist – der Speicherbedarf bleibt konstant. Genau das ist der Unterschied zu einer Liste. Würde ich `fh.readlines()` schreiben, hielte Python alle Zeilen auf einmal. Der Generator erzeugt sie einzeln, auf Abruf.\n\nDasselbe Prinzip gibt es kompakt als Generator-Expression – syntaktisch wie eine List Comprehension, nur mit runden statt eckigen Klammern:\n\n```python\n# list comprehension: builds the whole list in memory\nlengths_list = [len(line) for line in stream_lines(\"big.log\")]\n\n# generator expression: yields one length at a time\ntotal = sum(len(line) for line in stream_lines(\"big.log\"))\n```\n\nDie zweite Variante summiert die Zeilenlängen, ohne je eine vollständige Liste anzulegen. Für Aggregationen über große Datenmengen ist das der Standardweg. Und wenn man Generatoren verketten will, hilft `yield from`, um an einen anderen iterierbaren Wert zu delegieren, ohne selbst eine Schleife zu schreiben:\n\n```python\ndef chained(*paths):\n    for path in paths:\n        yield from stream_lines(path)\n```\n\n## Drei Fallstricke\n\nSo klar die drei Bausteine sind, so zuverlässig treten in der Praxis dieselben Stolperstellen auf. Diese drei kosten die meiste Zeit.\n\nDer Klassiker sind veränderliche Default-Argumente. Wer eine leere Liste als Default schreibt, bekommt nicht bei jedem Aufruf eine frische Liste, sondern immer dieselbe.\n\n```python\ndef append_item(item, acc=[]):   # trap: shared across calls\n    acc.append(item)\n    return acc\n\n\nprint(append_item(1))   # [1]\nprint(append_item(2))   # [1, 2]  – surprise\n```\n\nDer Default wird genau einmal ausgewertet, nämlich beim `def`. Danach teilen sich alle Aufrufe dasselbe Objekt. Die Lösung ist ein Wächter über `None`:\n\n```python\ndef append_item(item, acc=None):\n    if acc is None:\n        acc = []\n    acc.append(item)\n    return acc\n```\n\nDie zweite Stolperstelle ist das vergessene `functools.wraps`, der oben gezeigte Fall. Ein Decorator ohne diese Zeile funktioniert, aber er verschluckt Name, Docstring und Signatur der dekorierten Funktion. In kleinen Skripten fällt das nicht auf; sobald jemand die Funktion introspektiert oder ein Framework auf die Metadaten schaut, wird es zum Rätsel.\n\nDie dritte trifft Generatoren: Nach einem Durchlauf sind sie erschöpft, und das ist die Kehrseite der Lazy-Auswertung. Ein Generator merkt sich seinen Fortschritt und setzt ihn nicht zurück. Wer ihn zweimal durchläuft, bekommt beim zweiten Mal nichts.\n\n```python\ngen = stream_lines(\"big.log\")\nfirst = list(gen)    # reads all lines\nsecond = list(gen)   # empty – the generator is exhausted\n```\n\nEine Liste kann man beliebig oft durchlaufen, einen Generator nur einmal. Wer die Daten mehrfach braucht, materialisiert sie bewusst in eine Liste – oder ruft die Generatorfunktion erneut auf, um ein frisches Objekt zu erhalten. Verwandt dazu: `len()` funktioniert nicht auf einem Generator, weil dessen Länge ohne vollständigen Durchlauf gar nicht bekannt ist.\n\n## Fazit\n\nDecorators, Magic Methods und Generatoren wirken beim ersten Kontakt wie fortgeschrittene Kür, sind aber im Alltag Grundwerkzeug. Decorators trennen wiederkehrendes Verhalten – Zeitmessung, Logging, Wiederholung – sauber von der eigentlichen Logik, solange man `functools.wraps` nicht vergisst. Magic Methods schließen eigene Objekte an die Sprache an, sodass `len()`, `==`, `for` und `with` einfach funktionieren, ohne dass der aufrufende Code etwas über die Interna wissen muss. Und Generatoren machen aus einer Funktion eine lazy Sequenz, die große Datenmengen Element für Element liefert, statt alles gleichzeitig zu halten.\n\nWas diese drei Bausteine verbindet, ist ein gemeinsamer Gedanke: Python stellt klar definierte Protokolle bereit, und der eigene Code klinkt sich dort ein. Man schreibt nicht gegen die Sprache, sondern mit ihr. Wer das einmal verinnerlicht hat, erkennt die Muster überall in der Standardbibliothek wieder – und schreibt Code, der sich nicht nur ausführen, sondern lesen lässt.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-python.html\n- Repository `introduction-python` – Kapitel `13-decorators.md`, `14-magic-methods.md`, `15-iter.md` mit den zugehörigen Beispielen unter `examples/` (`decorators.py`, `classes.py`, `functional.py`)\n- Python Data Model / Special Methods: https://docs.python.org/3.8/reference/datamodel.html\n- Das `with`-Statement und das Context-Manager-Protokoll: https://docs.python.org/3.8/reference/compound_stmts.html#the-with-statement\n- `functools` mit `wraps` und `update_wrapper`: https://docs.python.org/3.8/library/functools.html\n- `contextlib.contextmanager`: https://docs.python.org/3.8/library/contextlib.html\n- Yield-Ausdrücke und Generatoren: https://docs.python.org/3.8/reference/expressions.html#yield-expressions\n- Tutorial zu Generators und Generator Expressions: https://docs.python.org/3.8/tutorial/classes.html#generators\n- PEP 318 – Decorators for Functions and Methods: https://www.python.org/dev/peps/pep-0318/"},{"locale":"de","translation_key":"policy-as-code-fuer-cdk","slug":"policy-as-code-fuer-cdk","title":"Policy as Code für CDK","summary":"Policy as Code macht einen prüfbaren Teil der Architekturregeln ausführbar und versionierbar.","tags":["Software","AWS","Cloud"],"published_at":"2020-03-12T10:00:00+00:00","updated_at":"2026-07-13T08:38:35.328116+00:00","url":"https://www.mikebild.dev/de/blog/policy-as-code-fuer-cdk/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/57dd96d6e8acc21a0c10bf31614e5e3ada3c5951ce79b742b4327842cf5036c4/policy-as-code-fuer-cdk-vorlesen.mp3","audio_duration_secs":678,"text":"# Policy as Code für CDK\n\nWer eine Architekturregel nur aufschreibt, bekommt sie irgendwann als Vorfall zurück. Kein öffentlich lesbarer Bucket, jede Tabelle verschlüsselt, keine Instanz größer als nötig, alles getaggt: Diese Liste steht selten vollständig an einem Ort. Sie existiert in ein paar Köpfen, in einem Wiki, das niemand mehr öffnet, und in Review-Kommentaren, die davon abhängen, wer gerade schaut und wie viel Zeit er hat. Ein unauffälliger Default genügt, und aus dem guten Vorsatz wird ein offener Bucket in Produktion. Genau um dieses Problem geht es hier – und `cloudpatrol` ist mein Versuch, es zu lösen.\n\nIn meinem [Beitrag über die CDK-Anfänge](https://www.mikebild.dev/de/blog/cdk-infrastruktur-als-programmiersprache/) endet der Text mit einem Nebensatz: Für Regeln, die nicht verhandelbar sind, lohnt sich eine maschinelle Prüfung der synthetisierten Vorlage, eine Art Policy as Code für den eigenen CDK-Output. Diesen Nebensatz löse ich hier ein. Es geht dabei weniger um ein weiteres Werkzeug als darum, begründete Guardrails als automatisierte Checks auszuführen. Abwägungen bleiben Architekturarbeit.\n\n## Warum Regeln aus dem Review herausfallen\n\nEin Review ist ein Mensch mit begrenzter Aufmerksamkeit. Er sieht heute, dass ein Bucket keine Verschlüsselung hat, und übersieht es nächste Woche, weil der Pull Request groß ist, es Freitagnachmittag ist oder die interessante Diskussion woanders lief. Das ist kein Vorwurf. So funktioniert Aufmerksamkeit. Wissen, das nur im Review existiert, ist so verlässlich wie die Tagesform des Reviewers.\n\nDaraus folgt: Eine Regel, die man nicht ausführen kann, ist keine Regel. Sie ist eine Hoffnung. Solange „kein öffentlicher Bucket“ ein Satz im Onboarding-Dokument ist, wird er irgendwann gebrochen, und zwar nicht aus bösem Willen, sondern weil ein Default unauffällig durchrutscht. Der Punkt von Policy as Code ist deshalb weniger technisch als kulturell. Er verschiebt die Regel von einem Ort, an dem sie erinnert werden muss, an einen Ort, an dem sie geprüft wird.\n\nDas CDK macht diese Verschiebung erst möglich. Weil Infrastruktur hier Code ist, der zu einer CloudFormation-Vorlage synthetisiert wird, gibt es einen Zwischenschritt, den man inspizieren kann, bevor irgendetwas in der Cloud entsteht. Genau dieser Zwischenschritt ist der richtige Ort für eine Prüfung.\n\n## Der Prüfpunkt liegt zwischen Synthese und Deployment\n\nMan kann Cloud-Ressourcen an vielen Stellen prüfen. Zur Laufzeit über einen Dienst, der Konten scannt, findet Verstöße erst, wenn sie schon existieren. Ein Wochenreport ist besser als nichts, kommt aber immer zu spät für den, der den Fehler gemacht hat. Interessant wird es, wenn die Prüfung dorthin wandert, wo die Entscheidung fällt: in den Moment, in dem der Code die Vorlage erzeugt.\n\n```mermaid\nflowchart LR\n  Source[\"CDK-Code (TypeScript)\"] --> Synth[\"cdk synth\"]\n  Synth --> Policy[\"Policy-Check\"]\n  Policy -->|verstoss| Fail[\"Feedback im PR\"]\n  Policy -->|ok| Deploy[\"Deployment\"]\n```\n\n`cloudpatrol` setzt genau an dieser Stelle an. Es hängt sich in die Synthese ein und bewertet die Constructs, während sie entstehen. Das ist ein architektonisch anderer Ansatz als ein nachgelagerter Scanner. Die Prüfung sieht nicht die rohe JSON-Vorlage, sondern die typisierten Constructs mit ihren Eigenschaften. Damit lässt sich eine Regel gegen `s3.CfnBucket` schreiben, statt gegen einen String-Pfad in einem YAML-Baum zu matchen. Die Grenze, an der geprüft wird, ist dieselbe Grenze, an der auch der Entwickler denkt.\n\nDer Effekt auf den Zyklus ist konkret. Ein Verstoß, der früher als Incident sichtbar wurde – jemand meldet einen offenen Bucket, es gibt eine Untersuchung, ein Fix, ein Postmortem – wird jetzt als roter Testlauf sichtbar, bevor der Pull Request gemergt ist. Die Zeit zwischen Fehler und Erkennung schrumpft von Tagen auf Sekunden, und die Kosten der Korrektur sinken entsprechend.\n\n## Eine Policy ist Code, kein Config-Eintrag\n\nDer entscheidende Entwurf in `cloudpatrol` ist, dass eine Regel keine Zeile in einer YAML-Datei ist, sondern eine Klasse. Sie deklariert, für welchen Construct-Typ sie gilt, und sie enthält eine Validator-Methode, die den konkreten Knoten prüft und Befunde an einen Reporter meldet.\n\n```ts\nimport { Policy, PolicyInterface, Reportable } from \"cloudpatrol\";\nimport * as s3 from \"@aws-cdk/aws-s3\";\n\nexport class BucketEncryptionPolicy extends Policy implements PolicyInterface {\n  public policyName = \"Bucket Encryption\";\n  public description = \"S3 buckets must be encrypted at rest.\";\n  public scope = s3.CfnBucket;\n\n  public validator(node: s3.CfnBucket, reporter: Reportable): void {\n    if (!node.bucketEncryption) {\n      reporter.addError(node, this, \"Bucket has no server-side encryption configured.\");\n    }\n  }\n}\n```\n\nDer `scope` ist der Selektor: Der Validator läuft nur für Buckets, nicht für jeden Knoten im Baum. Innerhalb des Validators habe ich die volle Ausdruckskraft von TypeScript. Ich kann Bedingungen verschachteln, Ausnahmen für bestimmte Umgebungen zulassen, mehrere Eigenschaften zusammen bewerten. Eine deklarative Regelsprache stößt genau hier an ihre Grenze – die interessanten Regeln lauten selten „Feld X muss Y sein“, sondern „Feld X muss Y sein, außer wenn Z, und dann bitte mit dieser Begründung“.\n\nAngewandt wird das Ganze über eine Patrol, die einen Stack durchläuft:\n\n```ts\nconst patrol = new AwsCdkPatrol(awsDefaults);\npatrol.check(stack);\n```\n\n`cloudpatrol` bringt eine Handvoll eingebauter Policies mit – Verschlüsselung, Versionierung, Instanztypen –, aber die eingebauten sind nur der Startpunkt. Der eigentliche Wert entsteht, wenn ein Team seine eigene ungeschriebene Liste in solche Klassen übersetzt. Ab dann ist die Liste nicht mehr ungeschrieben. Sie liegt im Repository, sie ist versioniert, sie hat einen Autor und eine Historie, und man kann über sie in einem Pull Request diskutieren wie über jeden anderen Code.\n\n## warn oder block ist eine Entwurfsentscheidung\n\nNicht jede Regel hat dasselbe Gewicht. Ein fehlendes Kostenstellen-Tag ist ärgerlich, ein öffentlich lesbarer Bucket mit Kundendaten ist ein Vorfall. Deshalb ist die Schwere einer Regel kein Detail, sondern die zentrale Entwurfsentscheidung. Eine Warnung meldet und lässt durch. Ein Fehler blockiert. Wer alles blockiert, erzieht sein Team dazu, die Prüfung zu umgehen. Wer nichts blockiert, hat am Ende nur eine schön formatierte Log-Ausgabe.\n\nIch unterscheide dabei bewusst zwischen Guardrails und Architekturpolizei. Guardrails definieren die wenigen Leitplanken, die wirklich nicht verhandelbar sind: Verschlüsselung, minimale Rechte, keine offenen Netze, harte Kostenlimits. Innerhalb dieser Leitplanken bleibt das Team handlungsfähig und schnell. Architekturpolizei dagegen versucht, jede Entscheidung zu zentralisieren, und verlagert damit Verantwortung von den Teams weg. Das Erste beschleunigt sicheres Arbeiten, das Zweite bremst und frustriert. Der Unterschied liegt nicht im Werkzeug, sondern in der Frage, wie viele Regeln man auf `block` setzt und wie gut man diese wenigen begründet.\n\n```ts\ntype Severity = \"warn\" | \"block\";\n\ntype RuleMeta = {\n  policyName: string;\n  severity: Severity;\n  reason: string;\n  suggestion: string;\n};\n```\n\n## Jede Regel braucht einen Grund und einen Ausweg\n\nEine Prüfung, die nur „verboten“ sagt, ist eine Wand. Der Entwickler steht davor, versteht nicht, warum, und sucht den kürzesten Weg drumherum. Eine Prüfung, die den Grund und eine Alternative liefert, ist Lernfeedback. Sie erklärt die Entscheidung an genau der Stelle, an der sie relevant wird, und macht den nächsten Entwickler ein Stück selbständiger.\n\n```json\n{\n  \"policy\": \"lambda-timeout-max\",\n  \"severity\": \"block\",\n  \"reason\": \"A timeout above 30s usually hides a synchronous call that should be async.\",\n  \"suggestion\": \"Move the work behind a queue or a Step Function and return early.\"\n}\n```\n\nDiese drei Felder – Grund, Schwere, Ausweg – sind der Unterschied zwischen einer Regel, die Reibung erzeugt, und einer, die Reibung abbaut. Der Grund verhindert, dass die Regel als Willkür gelesen wird. Der Ausweg verwandelt das Blockieren in eine Empfehlung. Genau deshalb gehört zu jeder Policy in `cloudpatrol` ein `description`- und ein `link`-Feld: Die Regel trägt ihre eigene Begründung mit sich, statt sie in einem Wiki zu parken, das vom Code entkoppelt ist.\n\n## Der Pull Request ist der richtige Ort\n\nGuardrails wirken am besten vor dem Deployment, und der Pull Request ist der natürliche Ort dafür, weil dort Code, Kontext und Diskussion zusammenkommen. Praktisch heißt das: Der Policy-Check läuft in derselben Pipeline, die den Code baut und die Infrastruktur ausliefert. Ein roter Check ist dann kein Bürokratie-Schritt, sondern dieselbe Art von Signal wie ein fehlgeschlagener Unit-Test.\n\nDer Nutzen ist an dieser Stelle messbar, und zwar auf drei Ebenen. Erstens die Zykluszeit: Ein Verstoß wird beim Öffnen des Pull Requests sichtbar, nicht Tage später im Betrieb. Zweitens die Konsistenz: Die Prüfung ist immer gleich streng, unabhängig davon, wer reviewt und wie voll der Kalender ist. Drittens die Review-Last: Menschen müssen nicht mehr mechanisch nach denselben zehn Dingen suchen, sondern können sich auf die Fragen konzentrieren, die eine Maschine nicht beantwortet – ist der Zuschnitt des Stacks sinnvoll, passt die Abstraktion, stimmt das Kostenprofil.\n\nDas ist der eigentliche Produktivitätsgewinn: Die immer gleiche, langweilige Prüfarbeit übernimmt eine Maschine, und die Köpfe im Team werden für die interessante Arbeit frei.\n\n## Kosten sind ein Architektursignal\n\nEin Side Effect lohnt die Erwähnung, weil er oft übersehen wird. Cloud-Kosten sind nicht nur ein Thema für die Buchhaltung, sie sind ein Verhaltenssignal der Architektur. Eine Funktion, die zu oft startet, eine Ressource, die zu großzügig dimensioniert ist, ein Deployment, das unnötig Artefakte erzeugt – all das hinterlässt eine Kostenspur, bevor es als Architekturproblem benannt wird.\n\n```mermaid\nflowchart LR\n  Usage[\"Nutzung\"] --> Cost[\"Kostenspur\"]\n  Cost --> Signal[\"Signal\"]\n  Signal --> Rule[\"Policy als Leitplanke\"]\n```\n\nEine Policy, die einen zu großzügigen Instanztyp oder eine fehlende Lifecycle-Regel markiert, ist deshalb nicht nur eine technische Prüfung. Sie fängt eine Kostenentscheidung ab, bevor sie im nächsten Monat als Rechnung auftaucht. Kosten ersetzen kein Design, aber sie sind ein ehrlicher Prüfstein dafür, ob die Architektur sich so verhält, wie man es beim Entwerfen angenommen hat.\n\n## Wo Policy as Code an ihre Grenze kommt\n\nEs wäre ein Fehler, alles in eine Regel gießen zu wollen. Manche Entscheidungen sind keine Prüfung, sondern eine Abwägung, und die gehört zu einem Menschen. Ein Timeout über dreißig Sekunden kann falsch sein oder genau richtig, je nach Kontext. Solche Fälle gehören in ein Architekturgespräch oder einen kurzen ADR, nicht in einen stumpfen Blocker. Die Policy sagt dann nicht „verboten“, sondern „das braucht eine Begründung“.\n\nDamit hat Policy as Code eine klare Zuständigkeit. Sie eignet sich für die kleine Menge nicht verhandelbarer Leitplanken, deren Verletzung objektiv erkennbar ist. Sie eignet sich nicht für Geschmacksfragen und nicht für Abwägungen, bei denen die richtige Antwort vom Projekt abhängt. Wer diese Grenze respektiert, bekommt ein Werkzeug, das Vertrauen schafft. Wer sie ignoriert und jede Meinung zur blockierenden Regel macht, bekommt ein Werkzeug, das umgangen wird.\n\nEin zweiter Vorbehalt betrifft die Abstraktion. `cloudpatrol` prüft, was die Synthese erzeugt. Ein selbst geschriebenes Construct, das ein Dutzend Ressourcen kapselt, kann eine Regel unbeabsichtigt aushebeln, wenn es die geprüfte Eigenschaft anders setzt, als man denkt. Die Prüfung ist also nur so ehrlich wie die Sichtbarkeit der Constructs. Das ist kein Argument gegen Abstraktion, aber eine Erinnerung daran, dass eine Regel und die Bausteine, gegen die sie läuft, zusammen entworfen werden müssen.\n\n## Was ich nach ein paar Wochen mitnehme\n\n`cloudpatrol` ist Alpha, die API bewegt sich, und ich würde heute keine große Initiative darauf aufbauen. Aber die Richtung überzeugt mich, und sie ist unabhängig vom konkreten Tool. Sobald Infrastruktur Code ist, gehören ihre Regeln in denselben Kreislauf wie der Code: versioniert, geprüft, im Pull Request diskutierbar. Der Gewinn ist nicht, dass eine Maschine Fehler findet. Der Gewinn ist, dass eine Architekturentscheidung nicht mehr im Kopf einer einzelnen Person liegt, sondern als ausführbare, begründete Regel im Repository steht, an der ein anderer Entwickler morgen sinnvoll widersprechen kann.\n\nOb sich eine Regel lohnt, entscheidet sich an drei Punkten. Sie muss einen echten Fehlerfall verhindern, den ich benennen kann, sie muss ihren Grund mitliefern, und sie muss einen Ausweg zeigen. Erfüllt sie das, hängt die Regel nicht mehr an der Tagesform des Reviewers, sondern an einer Prüfung, die immer gleich streng ist. Alles andere bleibt Gesprächsstoff für Menschen – und das ist gut so.\n\n## Weiterführende Quellen\n\n- AWS CDK, Einführung und Konzepte: https://docs.aws.amazon.com/cdk/latest/guide/home.html\n- Constructs als Bausteine: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n- Policy as Code fürs CDK (cloudpatrol): https://github.com/MikeBild/cloudpatrol"},{"locale":"de","translation_key":"aggregat-als-konsistenzgrenze","slug":"aggregat-als-konsistenzgrenze","title":"Das Aggregat als Konsistenzgrenze","summary":"Ein Aggregat ist keine ORM-Entity und keine Tabelle, sondern eine Konsistenz- und Transaktionsgrenze: ein Verbund von Objekten, den eine Aggregate Root als Einheit schützt. Warum eine Transaktion genau ein Aggregat ändert und andere Aggregate nur per ID referenziert werden.","tags":["Software","Architektur"],"published_at":"2020-02-19T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/aggregat-als-konsistenzgrenze/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0af23d3aa0f673eb11cd6200616017ee64a2a16d67ab4f6941af6802d8a20f06/aggregat-als-konsistenzgrenze-vorlesen.mp3","audio_duration_secs":851,"text":"```typescript\n@Entity()\nclass Order {\n  @PrimaryGeneratedColumn() id: number;\n  @ManyToOne(() => Customer) customer: Customer;\n  @OneToMany(() => LineItem, (li) => li.order) lineItems: LineItem[];\n  @Column() status: string;\n}\n```\n\nDiese Klasse trägt vier Annotationen und keine einzige Regel. Nichts hindert Code an irgendeiner Stelle daran, `order.lineItems.push(...)` aufzurufen, obwohl `status` längst auf `'CONFIRMED'` steht. Und über `order.customer.updateAddress(...)` verändert derselbe Aufrufer in derselben Transaktion nebenbei ein zweites Modell. Was hier steht, ist ein Objektgraph: Datenklassen mit Gettern und Settern, die über Fremdschlüssel zusammenhängen. Trotzdem wird genau so eine Klasse regelmäßig als Aggregat bezeichnet.\n\nEin Aggregat entsteht früher. Es beginnt mit der Frage, welche Regeln im selben Augenblick gelten müssen, und wird erst danach zu Klassen und Tabellen. Wer den Begriff so liest, trifft andere Entscheidungen: über Transaktionen, über Referenzen zwischen Objekten, über die Größe seiner Modelle und darüber, wo eventual consistency anfängt. Das ist die Fortsetzung eines Gedankens, den ich schon an anderer Stelle verfolgt habe – dass [CQRS eine fachliche Grenze ist](https://www.mikebild.dev/de/blog/cqrs-fachliche-grenze-kein-framework/) und kein Framework. Das Aggregat ist die nächste, kleinere Grenze im selben Denkgebäude.\n\n## Was ein Aggregat wirklich ist\n\nMartin Fowler formuliert es knapp: Ein Aggregat ist „a cluster of domain objects that can be treated as a single unit“ – ein Verbund von Domänenobjekten, den man als eine Einheit behandelt. Das klassische Beispiel ist eine `Order` mit ihren `LineItems`. Das sind getrennte Objekte, aber sie werden nie einzeln geladen, geändert oder gespeichert. Sie kommen als Ganzes aus dem Repository und gehen als Ganzes zurück. Das Aggregat ist die Grundeinheit für den Speicher-Transfer.\n\nInnerhalb dieses Verbunds gibt es genau eine ausgezeichnete Komponente: die Aggregate Root. Sie ist die einzige Entity, auf die von außen referenziert werden darf. Niemand außerhalb des Aggregats hält jemals direkt ein `LineItem` in der Hand – man geht immer über die `Order`. Das klingt nach einer lästigen Kapselungsregel, hat aber einen tiefen Grund: Nur wenn aller Zugriff über die Root läuft, kann die Root garantieren, dass der Zustand des gesamten Aggregats stimmt.\n\nUnd damit sind wir beim Kern. Eric Evans, Vaughn Vernon und Fowler meinen alle dasselbe, wenn sie vom Aggregat sprechen: Es ist die Konsistenzgrenze. Die Invarianten – die Geschäftsregeln, die immer gelten müssen – sind nach jeder abgeschlossenen Änderung erfüllt. Nicht „irgendwann“, nicht „nach dem nächsten Batch-Lauf“, sondern unmittelbar, transaktional. Vernon nennt das treffend „must always be transactionally consistent“. Eine Invariante ist zum Beispiel: „Nach der Bestätigung dürfen keine Positionen mehr hinzukommen.“ Oder: „Die Summe der Positionen entspricht der Bestellsumme.“ Solche Regeln gehören nicht in einen Service irgendwo weiter oben, sie gehören in die Root selbst.\n\nDas ist der entscheidende Perspektivwechsel: Den Zuschnitt eines Aggregats bestimmen die Invarianten, die gemeinsam geschützt werden müssen. Welche Objekte fachlich zusammengehören, ergibt sich daraus – und nicht umgekehrt.\n\n## Die Root schützt ihre Invarianten\n\nSehen wir uns das im Code an. Das folgende Beispiel ist illustrativ – es geht mir um die Struktur, nicht um ein lauffähiges System. Wichtig ist, was fehlt: öffentliche Setter. Die `lineItems`-Liste ist privat, und der einzige Weg, sie zu verändern, führt über Methoden, die die Invarianten kennen.\n\n```typescript\ntype OrderStatus = 'DRAFT' | 'CONFIRMED';\n\nclass Order {\n  private status: OrderStatus = 'DRAFT';\n  private readonly lineItems: LineItem[] = [];\n\n  constructor(\n    readonly id: OrderId,\n    private readonly customerId: CustomerId,\n  ) {}\n\n  addLineItem(product: ProductId, quantity: number): void {\n    if (this.status === 'CONFIRMED') {\n      throw new Error('Cannot modify a confirmed order');\n    }\n    if (quantity <= 0) {\n      throw new Error('Quantity must be positive');\n    }\n    this.lineItems.push(new LineItem(product, quantity));\n  }\n\n  confirm(): void {\n    if (this.lineItems.length === 0) {\n      throw new Error('Cannot confirm an order without line items');\n    }\n    this.status = 'CONFIRMED';\n  }\n}\n```\n\nZwei Invarianten stehen hier: Eine bestätigte Bestellung nimmt keine Positionen mehr an, und eine leere Bestellung lässt sich nicht bestätigen. Beide sind an genau einer Stelle durchgesetzt, in der Root. Es gibt keinen Weg, an dieser Prüfung vorbei ein `LineItem` in die Liste zu schmuggeln – denn niemand außerhalb der `Order` kommt an die Liste heran. Genau das meint „die Root sichert die Integrität des gesamten Aggregats“. Der Zustand kann gar nicht erst ungültig werden.\n\nMan vergleiche das mit der annotierten Datenklasse vom Anfang, deren `lineItems` und `status` offen liegen. Dort kann jeder Code an jeder Stelle die Liste manipulieren oder den Status setzen. Die Regel „keine Positionen nach Bestätigung“ existiert dann bestenfalls als Konvention, verstreut über die Codebasis, und wird früher oder später verletzt. Das Aggregat verlegt sie an eine einzige, unumgehbare Stelle.\n\n## Eine Transaktion ändert genau ein Aggregat\n\nAus der Konsistenzgrenze folgt unmittelbar die Transaktionsgrenze. Evans und Vernon sind hier deutlich: Transaktionen dürfen Aggregatgrenzen nicht überschreiten. Die Faustregel lautet – eine Transaktion ändert genau eine Aggregat-Instanz. Was darüber hinausgeht, wird nicht im selben atomaren Commit erledigt, sondern in getrennten Transaktionen, verbunden über eventual consistency.\n\nDiese Regel stößt zuverlässig auf Widerstand, und der Einwand klingt immer ähnlich: „Wenn eine Bestellung bestätigt wird, muss doch auch der Lagerbestand reserviert werden – das gehört in eine Transaktion.“ Gehört es nicht. `Order` und `Inventory` sind zwei Aggregate mit je eigenen Invarianten. Sie in einen gemeinsamen Commit zu zwingen, koppelt sie technisch, erzeugt Lock-Contention und macht das System schwerer skalierbar. Stattdessen bestätigt die Transaktion T1 die Bestellung und schreibt ein `OrderConfirmed`-Event. Eine separate Transaktion T2 verarbeitet dieses Event und reserviert im `Inventory` den Bestand.\n\n```mermaid\ngraph LR\n  subgraph T1[\"Transaction T1\"]\n    O[\"Order<br/>confirm()\"]\n  end\n  subgraph T2[\"Transaction T2\"]\n    I[\"Inventory<br/>reserve()\"]\n  end\n  O -- \"OrderConfirmed (event)\" --> I\n```\n\nWichtig gegen ein verbreitetes Missverständnis: Eventual consistency heißt nicht „keine Konsistenz“. Innerhalb eines Aggregats ist alles strikt und transaktional konsistent – die `Order` ist nach T1 in jedem Fall ein gültiger Zustand. Zwischen den Aggregaten ist es eventual: Es vergeht eine kurze, aber endliche Zeit, bis das `Inventory` nachgezogen hat. Diese Grenze bewusst zu setzen, ist eine fachliche Entscheidung. Die Frage lautet immer: Muss diese Regel im selben Augenblick gelten, oder darf sie ein paar Millisekunden später gelten? Nur wenn die Antwort „im selben Augenblick“ ist, gehören die Daten ins selbe Aggregat.\n\nWer diese Trennung von schreibenden Absichten und den daraus folgenden Fakten sauber halten will, landet ohnehin schnell bei der Frage, wie man [Commands, Events und Queries trennt](https://www.mikebild.dev/de/blog/commands-events-queries-trennen/). Das Event zwischen T1 und T2 ist genau so ein Fakt: etwas, das passiert ist und andere Aggregate reagieren lässt.\n\n## Andere Aggregate nur per Identity referenzieren\n\nDamit die Transaktionsgrenze überhaupt hält, braucht es eine zweite Regel, und sie ist die, gegen die am häufigsten verstoßen wird: Ein Aggregat referenziert ein anderes Aggregat nur über dessen Identität, über die ID, niemals über einen direkten Objekt-Pointer. Vernon führt das als eigene Design-Regel: „Reference Other Aggregates by Identity“.\n\nIn der `Order` oben sieht man das bereits. Die Root hält `customerId: CustomerId`, nicht `customer: Customer`. Der Unterschied ist keine Kleinigkeit.\n\n```typescript\n// Wrong: the customer is pulled inside the order\nclass Order {\n  private customer: Customer; // pulls another aggregate inside the boundary\n}\n\n// Right: only the identity crosses the boundary\nclass Order {\n  private readonly customerId: CustomerId; // reference by identity\n}\n```\n\nSobald `Order` ein echtes `Customer`-Objekt hält, verschwimmt die Grenze. Der Entwickler, der die `Customer`-Referenz sieht, wird sie früher oder später benutzen – `order.customer.updateAddress(...)` – und schon werden in einer Transaktion zwei Aggregate geändert. Die Referenz per ID verhindert das strukturell: Man kann eine `CustomerId` nicht versehentlich mutieren. Braucht man wirklich das Kunden-Aggregat, lädt man es vorher über sein eigenes Repository und übergibt gezielt, was gebraucht wird – die ID-Referenz erzwingt also die bewusste Entscheidung.\n\nDer Side Effect ist ebenfalls wertvoll: Aggregate bleiben klein. Es gibt kein Eager-Loading ganzer Objektgraphen, kein „Bestellung laden zieht den Kunden zieht dessen Adressen zieht deren Länder“. Es wird geladen, was in der Grenze liegt, und sonst nichts.\n\nDamit die Regeln zusammen im Bild bleiben, hier die Konsistenzgrenze als Diagramm. Innerhalb des umrandeten Blocks liegt das `Order`-Aggregat mit Root und inneren Objekten; `Customer` liegt außerhalb, als eigenes Aggregat, und ist nur über die Identität verbunden.\n\n```mermaid\ngraph TB\n  ext[\"Client code\"]\n  subgraph agg[\"Aggregate: Order (consistency boundary)\"]\n    root[\"Order (Aggregate Root)\"]\n    li[\"LineItem\"]\n    money[\"Money (Value Object)\"]\n    root --> li\n    li --> money\n  end\n  cust[\"Customer<br/>(separate aggregate)\"]\n  ext -->|\"references the root only\"| root\n  root -. \"customerId (by identity)\" .-> cust\n```\n\nMan beachte die Pfeile: Der externe Zugriff zeigt ausschließlich auf die Root, nie auf `LineItem` oder `Money`. Und die Verbindung zum `Customer` ist gestrichelt und mit `customerId` beschriftet – eine Referenz, kein Enthaltensein.\n\n## Aggregate klein halten\n\nDas führt zu Vernons vielleicht praktischster Regel: „Design Small Aggregates“. Die Versuchung, Aggregate groß werden zu lassen, ist enorm, und sie hat sogar einen Namen – „object graph greed“. Aus Bequemlichkeit schließt man alles ein, was man beim Navigieren gern zur Hand hätte. Ein `Customer`, der alle seine `Orders` als Liste hält, ist das Standardbeispiel. Fachlich klingt das plausibel, technisch ist es ein Problem: Jede Änderung an einer einzelnen Bestellung müsste das gesamte Kunden-Aggregat mitsamt aller Bestellungen laden und sperren. Bei einem Kunden mit tausend Bestellungen wird jede kleine Operation teuer, und gleichzeitige Zugriffe blockieren sich gegenseitig.\n\nDie Heuristik dagegen ist einfach: Modelliert wird entlang echter Invarianten, nicht entlang von Navigationswünschen. Die Frage ist nicht „will ich von A zu B navigieren können“, sondern „muss A ungültig werden, wenn B sich ändert, und zwar sofort“. Nur wenn zwischen zwei Objekten eine echte, augenblickliche Konsistenzregel besteht, gehören sie ins selbe Aggregat. Für alles andere gibt es Referenzen per ID und, wenn man lesend navigieren will, ein Read Model. Das Aggregat ist ein Schreibmodell; wer Navigationskomfort für die Anzeige sucht, baut sich dafür eine Projection, statt das Aggregat aufzublähen.\n\nFassen wir die Regeln zusammen, an denen ich ein Aggregat im Entwurf prüfe:\n\n- Aller Zugriff von außen läuft über die Aggregate Root; innere Objekte sind gekapselt.\n- Die Root setzt die Invarianten durch, und zwar transaktional konsistent nach jeder Änderung.\n- Eine Transaktion ändert genau eine Aggregat-Instanz; alles Weitere läuft über eventual consistency und Domain Events.\n- Andere Aggregate werden nur über ihre Identität referenziert, nie als eingebettetes Objekt.\n- Aggregate bleiben klein und werden entlang echter Invarianten geschnitten, nicht entlang von Navigationswünschen.\n\n## Die drei Fallstricke\n\nDrei Verwechslungen begegnen mir dabei immer wieder, und es lohnt sich, sie beim Namen zu nennen.\n\nDer erste und häufigste: das Aggregat mit einer Datenbanktabelle oder einer ORM-Entity gleichzusetzen. Das ist falsch. Das Aggregat ist ein Modellierungs- und Konsistenzkonzept; wie es auf Tabellen abgebildet wird, ist eine völlig getrennte Frage. Ein Aggregat kann über mehrere Tabellen persistiert werden, und eine Tabelle kann mehrere Value Objects enthalten. Die Persistenz ist orthogonal zum Modell. Eine `@Entity`-annotierte Klasse mit lauter Gettern und Settern ist noch lange kein Aggregat – ihr fehlt das Entscheidende, die durchgesetzte Invariante.\n\nDer zweite: die Aggregate Root als „God Object“ misszuverstehen. Weil die Root der einzige Entry Point ist, landet bei unerfahrenen Teams gern alles in ihr. Das ist das Gegenteil der Absicht. Die Root ist klein und invariantengetrieben. Sie hält genau das, was sie zur Durchsetzung ihrer Regeln braucht – nicht mehr. Eine Root, die alles hält, ist meist ein Zeichen dafür, dass mehrere Aggregate fälschlich zu einem verschmolzen wurden.\n\nDer dritte: direkte Objekt-Referenzen zwischen Aggregaten, den Fehler vom Anfang. Er ist deshalb so tückisch, weil er sich harmlos anfühlt und weil ORMs ihn geradezu einladen – eine `@ManyToOne`-Beziehung ist schnell annotiert. Aber jede solche Referenz ist eine Einladung, in einer Transaktion mehrere Aggregate zu ändern und die Grenze aufzuweichen. Die Disziplin lautet: per ID referenzieren, und wenn man das fremde Aggregat wirklich braucht, es vorher über sein Repository laden – vor dem Aufruf der Aggregat-Methode, nicht mittendrin.\n\n## Eine kurze Abgrenzung\n\nWeil im DDD-Umfeld ständig durcheinandergerät, was zusammengehört und was nicht, eine kurze Klarstellung am Rande. CQRS und Event Sourcing sind nicht dasselbe und beide sind nicht das Aggregat. CQRS trennt Schreib- und Lesemodell, Command von Query. Event Sourcing persistiert den Zustand als Sequenz von Events statt als aktuellen Snapshot. Beide sind unabhängig voneinander einsetzbar – man kann jedes ohne das andere nutzen, wie Fowler und Greg Young betonen. Das Aggregat wiederum ist ein Baustein, der in all diesen Welten vorkommt: Es ist die Konsistenzgrenze, gegen die ein Command validiert und aus der Events entstehen. Wer diese Begriffe sauber auseinanderhält, spart sich viele fruchtlose Architekturdiskussionen.\n\nUnd noch eine feine, aber wichtige Unterscheidung: Die Konsistenzgrenze ist nicht die Transaktionsgrenze der Datenbank. Es ist umgekehrt. Das Aggregat definiert die logische Grenze, innerhalb derer alles konsistent sein muss – und die Datenbanktransaktion hat sich daran zu halten. Nicht die verfügbaren Transaktionsmechanismen bestimmen den Zuschnitt der Modelle, sondern die fachlichen Invarianten bestimmen, wie weit eine Transaktion reichen darf. Wer das umdreht und seine Aggregate an den technischen Möglichkeiten des ORM ausrichtet, hat die Grenze am falschen Ende gezogen.\n\n## Fazit\n\nDas Aggregat verdient seinen zentralen Platz in DDD, weil es eine der schwierigsten Fragen der Softwareentwicklung beantwortet: Wo endet Konsistenz und wo beginnt Koordination? Es ist kein Datencontainer und kein Persistenzartefakt, sondern eine bewusst gezogene Konsistenz- und Transaktionsgrenze mit einer Root, die ihre Invarianten unerbittlich durchsetzt. Aus dieser einen Idee folgt alles Weitere fast von selbst: eine Transaktion pro Aggregat, Referenzen zwischen Aggregaten nur über Identität, kleine Modelle entlang echter Regeln, und eventual consistency dort, wo augenblickliche Konsistenz weder nötig noch bezahlbar ist.\n\nDie erste Frage vor einem Domänenmodell lautet also nicht „welche Objekte gehören zusammen“, sondern „welche Regeln müssen im selben Augenblick gelten“. Die Antwort schneidet die Aggregate – und mit ihnen die halbe Architektur.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html\n- Martin Fowler: [DDD_Aggregate](https://martinfowler.com/bliki/DDD_Aggregate.html) – die kompakte Definition von Aggregat und Aggregate Root.\n- Vaughn Vernon: [Effective Aggregate Design](https://www.dddcommunity.org/library/vernon_2011/) (2011), Teil I–III – die Regeln „Design Small Aggregates“ und „Reference Other Aggregates by Identity“.\n- Eric Evans: *Domain-Driven Design* (2003), Kapitel 6 – die Primärquelle für Aggregate und Aggregate Roots.\n- Greg Young / Martin Fowler zur Abgrenzung von CQRS und Event Sourcing – nützlich, um das Aggregat sauber davon zu trennen.\n- Aus meinem eigenen Vortragsmaterial: das Deck „CQRS + Event Sourcing“ (SlideShare), in dem ich diese Grenzziehung an konkreten Beispielen durchspiele."},{"locale":"de","translation_key":"ssmenv-cli-kleine-clis","slug":"ssmenv-cli-kleine-clis","title":"`ssmenv-cli`: kleine CLIs für große Ordnung","summary":"Eine kleine CLI über AWS SSM zeigt, wie Konfiguration aus einer benannten, zugriffskontrollierten Quelle in lokale Prozesse und CI gelangt – einschließlich Versions- und Ausfallfragen.","tags":["Software","Daten","Tools"],"published_at":"2020-02-12T10:00:00+00:00","updated_at":"2026-07-20T13:27:22.94021+00:00","url":"https://www.mikebild.dev/de/blog/ssmenv-cli-kleine-clis/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/eadf9601e030708ec8293eb2cd52f9afe50e6650584a307334dc20fe68fd3123/ssmenv-cli-kleine-clis-vorlesen.mp3","audio_duration_secs":695,"text":"# `ssmenv-cli`: kleine CLIs für große Ordnung\n\nKonfiguration ist kein Dateiformat. Sie ist ein Datenbestand mit Zugriffsrechten, Versionen und einer Historie – die `.env`-Datei ist nur eine Kopie davon, und selten die einzige.\n\nUnd Kopien vermehren sich: ein `.env` auf dem Laptop, ein zweites im CI, ein drittes im Onboarding-Wiki, ein viertes als Screenshot in einem Chat, ein fünftes „nur bei mir lokal“. Welcher Wert führt, weiß irgendwann niemand mehr. Dort entstehen die Bugs, die sich nicht reproduzieren lassen, und die Onboarding-Tage, die man nicht zurückbekommt. `ssmenv-cli` zieht daraus eine Konsequenz: Der AWS Systems Manager Parameter Store führt die Werte, und das Werkzeug übersetzt sie nur noch in die Umgebung eines Prozesses.\n\n## Das Problem hinter dem Werkzeug\n\nDas klassische Muster ist der geteilte `.env`-Zettel. Er funktioniert am ersten Tag und zerfällt danach langsam. Die typischen Symptome kenne ich auswendig: Ein Secret liegt versehentlich im Git-Verlauf. Ein neuer Kollege bekommt eine veraltete Kopie und verliert einen halben Tag mit „bei mir läuft es nicht“. Ein Wert wird in Produktion geändert, aber nirgends nachvollziehbar dokumentiert. Und niemand kann auf Anhieb sagen, wer eigentlich das Recht hat, ein Produktions-Secret zu lesen.\n\nDas ist im Kern kein Tooling-Problem, sondern ein Grenzproblem. Es fehlt eine klare Antwort auf drei Fragen: Welche Daten sind führend? Wer darf sie lesen und ändern? Wo wird eine Änderung nachvollziehbar? Solange diese Grenzen unscharf bleiben, hilft auch das schönste Skript nicht. Die drei Fragen kommen also vor dem Werkzeug.\n\n## Die Entscheidung: SSM als einzige Quelle\n\nDie tragende Entscheidung lautet: Der AWS Systems Manager Parameter Store wird zur einzigen Quelle für Konfiguration und Secrets. Nicht Git, nicht der Laptop, nicht der Chat – ein hierarchischer Namensraum in AWS, der ohnehin schon da ist, wenn man dort deployt.\n\nDas ist eine bewusste Wahl gegen ein eigenes System und gegen ein großes zusätzliches Produkt. Der Parameter Store bringt genau das mit, was ich für diese Grenze brauche: eine Hierarchie über Pfade wie `/myapp/prod/DATABASE_URL`, Verschlüsselung sensibler Werte über KMS als `SecureString`, Zugriffskontrolle über IAM und eine lückenlose Aufzeichnung über CloudTrail. Damit sind die drei offenen Fragen von oben beantwortet, ohne dass ich eine einzige Zeile Infrastruktur selbst betreibe.\n\nWas jetzt noch fehlt, ist nur die letzte Meile: der Weg vom Parameter Store in die Umgebungsvariablen eines Prozesses. Genau das – und nichts mehr – ist die Aufgabe der CLI.\n\n## Architektur: ein dünner Adapter, keine Plattform\n\nDie wichtigste Architekturentscheidung an `ssmenv-cli` ist, was das Tool bewusst *nicht* tut. Es speichert nichts, es entscheidet über keine Rechte, es hält keinen Zustand. Es ist ein dünner Adapter zwischen einer führenden Datenquelle und dem 12-Factor-Prinzip „config in the environment“.\n\nDiese Trennung ist die eigentliche Grenze. Der Parameter Store ist der Wahrheitsspeicher. IAM ist die Berechtigungsgrenze. KMS ist die Vertraulichkeitsgrenze. Die CLI ist reine Übersetzung: Sie liest einen Pfad-Präfix, löst `SecureString`-Werte auf und stellt sie einem Prozess als Umgebung bereit. Weil das Tool selbst keine Autorität hat, kann ich es jederzeit austauschen, ohne dass sich am Sicherheits- oder Datenmodell irgendetwas ändert. Das ist der Wert einer sauber gezogenen Grenze: Sie macht das Werkzeug ersetzbar.\n\n## Kleines Beispiel\n\nDer praktische Kern passt in wenige Zeilen. Werte setzt man einmal – idealerweise über Automatisierung, hier zur Anschauung von Hand:\n\n```bash\n# Store a secret as an encrypted SecureString under a namespaced path\nssmenv set --path /myapp/prod DATABASE_URL \"postgres://db.internal:5432/app\"\n\n# List everything under a prefix (values masked by default)\nssmenv list --path /myapp/prod\n```\n\nDer eigentliche Gewinn zeigt sich beim Laden. Statt eine Datei zu verteilen, löst man die Umgebung zur Laufzeit auf:\n\n```bash\n# Run a process with the resolved environment, nothing written to disk\nssmenv exec --path /myapp/prod -- node server.js\n\n# Or export into the current shell for a quick local session\neval \"$(ssmenv export --path /myapp/staging)\"\n```\n\nUnd weil zwei Umgebungen selten identisch sind, ist der Vergleich ein vollwertiger Befehl und keine Nebensache:\n\n```bash\n# Show which keys differ between staging and prod\nssmenv diff --path /myapp/staging --path /myapp/prod\n```\n\nDas Beispiel ist bewusst klein. Es simuliert keine vollständige Plattform, es zeigt die Grenze: Die CLI berührt nur die letzte Meile zwischen Speicher und Prozess. Ein gutes Beispiel ist nicht das mit den meisten Optionen, sondern das, bei dem man die Entscheidung nach fünf Minuten diskutieren kann.\n\n## Skizze\n\n```mermaid\nflowchart LR\n  Store[\"SSM Parameter Store<br/>/myapp/prod/*\"] --> CLI[\"ssmenv-cli<br/>thin adapter\"]\n  IAM[\"IAM<br/>permission boundary\"] --> CLI\n  KMS[\"KMS<br/>SecureString decrypt\"] --> CLI\n  CLI --> Env[\"process env\"]\n  Env --> App[\"node server.js\"]\n```\n\nDie Skizze macht die Verantwortlichkeiten sichtbar: Der Store hält die Wahrheit, IAM und KMS ziehen die Grenzen, die CLI übersetzt. Kein Kasten in diesem Bild ist auf einen Toolnamen angewiesen – das ist Absicht.\n\n## Trade-offs: warum klein, warum nicht mehr\n\nDie naheliegende Gegenfrage lautet: Warum nicht gleich ein vollwertiges Secret-Management-Produkt? Das ist eine Abwägung, kein Dogma. Ein großes System bringt Rotation, dynamische Credentials und feingranulare Policies mit – und dazu Betrieb, Lernkurve und eine weitere Abhängigkeit. Für viele Teams, die ohnehin auf AWS deployen, ist das mehr Maschine, als das Problem verlangt.\n\nIch baue die kleinste Lösung, die die drei Grenzfragen sauber beantwortet, und lasse Raum für den Wechsel. Weil `ssmenv-cli` nur ein Adapter ist, ist dieser Wechsel billig. Wenn ein Team später Rotation im großen Stil braucht, tausche ich den Backend-Speicher aus, nicht das mentale Modell. Die teure Entscheidung – Konfiguration ist zentral, zugriffskontrolliert und auditierbar – bleibt dieselbe. Genau so sollte ein Trade-off aussehen: klein anfangen, ohne sich den Ausbau zu verbauen.\n\nDer zweite Trade-off betrifft Netzabhängigkeit. Werte zur Laufzeit aus dem Store zu lösen heißt, dass ein Prozessstart eine AWS-Erreichbarkeit voraussetzt. Das ist bewusst gewählt: Ich tausche einen kurzen Netzaufruf beim Start gegen die dauerhafte Gefahr veralteter lokaler Kopien. Für lokale Offline-Arbeit gibt es weiterhin einen expliziten Export – eine sichtbare Ausnahme, die jemand bewusst auslösen muss.\n\n## Betriebliche Konsequenz\n\nDie Konsequenz einer Architektur zeigt sich nicht in der Demo, sondern bei Fehlern, Last, Rollback und Review. Hier trägt das Modell, weil die schweren Aufgaben dort liegen, wo sie hingehören.\n\nZugriff ist eine IAM-Frage. Wer `/myapp/prod/*` lesen darf, steht in einer Policy und nicht in einem Chatverlauf – und lässt sich damit prüfen und entziehen. Vertraulichkeit ist eine KMS-Frage: Sensible Werte liegen als `SecureString` verschlüsselt, und die CLI entschlüsselt nur, wenn der Aufrufer das Recht dazu hat. Nachvollziehbarkeit ist eine CloudTrail-Frage: Jeder Lese- und Schreibzugriff ist aufgezeichnet. Wenn jemand fragt „wer hat dieses Secret wann gelesen?“, gibt es eine Antwort statt eines Schulterzuckens.\n\nRückbaubarkeit ist der stärkste Punkt. Weil der Parameter Store Versionen hält, ist ein fehlerhaft gesetzter Wert kein Notfall, sondern ein Rollback auf die vorige Version. Eine Änderung an Konfiguration wird damit so behandelbar wie eine Änderung an Code.\n\n## Fehlerfälle\n\nEine Idee ist erst belastbar, wenn der Fehlerpfad beschrieben ist. Drei Fälle gehören dazu.\n\nFehlende Berechtigung: Wenn der Aufrufer den Pfad nicht lesen darf, muss die CLI hart und deutlich abbrechen. Ein leerer Wert, der stillschweigend als leerer String durchrutscht, ist der gefährlichste Bug – die Anwendung startet mit halber Konfiguration und fällt erst tief im Betrieb um. Ein `exec` muss deshalb bei fehlenden oder unlesbaren Schlüsseln scheitern, bevor der Zielprozess überhaupt startet.\n\nTeilweise aufgelöste Umgebung: Wenn von zehn erwarteten Schlüsseln nur neun da sind, ist das kein „fast richtig“, sondern falsch. Ich behandle das als Fehler mit klarer Meldung, welcher Schlüssel fehlt.\n\nNetz- und Regionsfehler: Ein nicht erreichbarer Store oder eine falsche Region darf keine kryptische SDK-Ausnahme durchreichen, sondern eine Meldung, die den Pfad und die Ursache benennt. Der Unterschied zwischen Demo und Betrieb liegt fast immer in genau diesen unaufgeregten Fehlermeldungen.\n\n## Dieselbe Grenze im CI\n\nDer wahre Test einer Konfigurationsgrenze ist die Pipeline. Im CI läuft kein Mensch mit persönlichen Rechten, sondern eine Rolle – und genau das macht das Modell sauber. Statt Secrets als CI-Variablen zu duplizieren, bekommt der Build-Job eine IAM-Rolle, die exakt den Pfad lesen darf, den er braucht, und keinen anderen. Ein Staging-Deploy sieht `/myapp/staging/*`, ein Produktions-Deploy `/myapp/prod/*`, und die Trennung ist keine Konvention, sondern eine Berechtigung.\n\n```bash\n# In CI: the job's role grants read on /myapp/staging/* only\nssmenv exec --path /myapp/staging -- npm run deploy\n```\n\nDamit verschwindet die Klasse der „Secret liegt jetzt auch im CI“-Kopien. Es gibt keine zweite Quelle, die veralten kann, und das Prinzip der geringsten Rechte gilt für Maschinen genauso wie für Menschen. Wenn ein CI-Token kompromittiert wird, ist der Schaden auf genau den Pfad begrenzt, den dieser Job lesen durfte – nachlesbar in CloudTrail, entziehbar in einer Policy. Dass lokal, im CI und in Produktion buchstäblich derselbe Befehl mit einem anderen Pfad läuft, ist der Kern der Reproduzierbarkeit.\n\n## Business-Outcome: kürzere Zyklen, weniger Reibung\n\nDer Nutzen ist messbar, auch wenn das Werkzeug klein ist. Onboarding, das früher „hol dir das aktuelle `.env` von irgendwem“ hieß, wird zu einem einzigen Befehl gegen einen Pfad – aus einem halben Tag Reibung werden Minuten. Die ganze Klasse „bei mir läuft es, bei dir nicht“-Fehler verschwindet, weil dev, CI und Produktion dieselbe führende Quelle nutzen und sich nur im Pfad-Präfix unterscheiden. Und das Risiko, ein Secret im Git-Verlauf zu hinterlassen, sinkt strukturell, weil es keinen Grund mehr gibt, Secrets in Dateien abzulegen, die versioniert werden.\n\nDas sind die drei Hebel, die für technische Entscheider zählen: kürzere Zyklen beim Aufsetzen und Wechseln von Umgebungen, weniger Reibung im Alltag und höhere Qualität durch reproduzierbare Konfiguration. Der Gewinn steckt nicht im Toolnamen, sondern in der Entscheidung, Konfiguration wie ein prüfbares Datensystem zu behandeln.\n\n## Das Muster für kleine CLIs\n\n`ssmenv-cli` bleibt absichtlich ein Adapter. Ob der Parameter Store wirklich die führende Quelle sein kann, entscheiden Schreibrechte, der Umgang mit Versionen und das Verhalten bei Nichterreichbarkeit. Die CLI löst keine dieser Fragen; sie macht die getroffene Antwort nur für lokale Prozesse und CI nutzbar.\n\nDeshalb baue ich lieber viele kleine, scharf umrissene CLIs als ein großes, unscharfes Framework. Jede erledigt eine Aufgabe, hat eine sichtbare Grenze und mindestens einen ehrlichen Fehlerfall. Dieselbe Denkweise steckt in `ssmenv-cli`: klein im Umfang, klar in der Verantwortung, ersetzbar im Detail. Große Ordnung entsteht nicht aus großen Werkzeugen, sondern aus vielen kleinen mit klaren Zuständigkeiten.\n\n## Schluss\n\nWichtiger als die Funktionsweise von `ssmenv-cli` ist der Verlauf der Grenze: Konfiguration zentral und auditierbar, das Werkzeug bewusst dünn und austauschbar. Diese Entscheidung trägt auch dann noch, wenn das Tool längst durch ein anderes ersetzt ist – und genau deshalb lässt sie sich im nächsten Teamgespräch wiederverwenden.\n\n## Weiterführende Quellen\n\n- Repository ssmenv-cli: https://github.com/MikeBild/ssmenv-cli\n\nDie Quelle hilft beim Gegenprüfen der konkreten Umsetzung."},{"locale":"de","translation_key":"github-actions-mit-aws-cdk","slug":"github-actions-mit-aws-cdk","title":"GitHub Actions mit AWS CDK","summary":"GitHub Actions und AWS CDK verbinden Codeänderung, Infrastruktur und Deployment zu einer reviewbaren Pipeline – und machen die Architekturentscheidung im Pull Request sichtbar.","tags":["Software","AWS","Cloud"],"published_at":"2020-01-12T10:00:00+00:00","updated_at":"2026-07-13T07:55:50.690283+00:00","url":"https://www.mikebild.dev/de/blog/github-actions-mit-aws-cdk/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/7d9d27403d8521f29de31772a17da923b333891bb39d9b2cf6a8bcbfdd227dff/github-actions-mit-aws-cdk-vorlesen.mp3","audio_duration_secs":686,"text":"# GitHub Actions mit AWS CDK\n\nZwei Befehle tragen diese Konstruktion: `cdk diff` im Pull Request und `cdk deploy` auf `main`. Der erste ändert nichts und zeigt alles – neue Ressourcen, geänderte Rechte, gelöschte Tabellen. Der zweite ändert alles und zeigt nichts, was nicht vorher schon im Review stand.\n\n**Redaktionelle Einordnung (Juli 2026):** Workflow und CDK-Code zeigen den Stand von Januar 2020: Actions v1, Node 12, CDK v1 und dauerhaft hinterlegte AWS-Schlüssel. Für einen heutigen Aufbau gehören aktuelle Action-Versionen, CDK v2 und kurzlebige AWS-Zugangsdaten per OpenID Connect in den Workflow. Der Review-Gedanke um `cdk diff` bleibt davon unberührt.\n\nIn dieser Reihenfolge steckt der Unterschied zwischen Automatisierung und Architektur. Wie man GitHub Actions und AWS CDK miteinander verbindet, ist in einer Stunde erledigt. Spannender ist, welche Entscheidung dadurch früher auf den Tisch kommt.\n\n## Warum diese Kombination mehr ist als Automatisierung\n\nGitHub Actions ist seit wenigen Wochen allgemein verfügbar, und die naheliegende Reaktion ist, damit den bekannten Ablauf nachzubauen: Test bauen, Artefakt schnüren, per Skript deployen. Das funktioniert, verschenkt aber den eigentlichen Hebel. Denn mit AWS CDK beschreibe ich meine Infrastruktur im selben TypeScript-Repository wie meine Anwendung – Lambda, API Gateway, IAM-Rollen, Tabellen. Damit wird Infrastruktur zu Code, der reviewt, versioniert und getestet werden kann wie jeder andere.\n\nDer Punkt, um den es mir geht, entsteht erst im Zusammenspiel. Wenn Anwendungscode und Infrastrukturcode im selben Pull Request liegen und dieselbe Pipeline durchlaufen, dann ist eine Änderung nicht mehr „neuer Handler“ plus „jemand klickt später eine Rolle in der Konsole zusammen“. Sie ist eine einzige, nachvollziehbare Einheit. Die Codeänderung und ihre Betriebsfolge stehen nebeneinander, bevor irgendetwas produktiv wird. Genau das ist der architektonische Gewinn – nicht die Ersparnis an Klicks.\n\nDiese Grenze wird häufig woanders gezogen. Infrastruktur steckt dann in einem Wiki, in Terminalbefehlen, in den Köpfen von zwei Leuten. Die Pipeline deployt den Code, aber niemand kann im Review sagen, welche Rechte, welche Ressourcen und welche Kosten eine Änderung nach sich zieht. CDK plus GitHub Actions macht diese Frage zu einem Artefakt, über das man diskutieren kann.\n\n## Vor dem Workflow steht die Freigabe\n\nBevor ich YAML schreibe, kläre ich drei konkrete Punkte: Wer darf ein Deployment auslösen? Welche Änderungen müssen im Pull Request sichtbar sein? Und was ist der Rückweg, wenn der neue Stack nicht trägt? GitHub Actions beantwortet keine dieser Fragen. Der Workflow setzt die Antworten nur durch. Fehlt etwa eine geschützte Umgebung mit Freigabe, wird aus `cdk deploy` auf `main` schnell ein Automatismus, der schneller ist als die Kontrolle dahinter.\n\n## Der `cdk diff` als Review-Artefakt\n\nDer methodische Kern dieser Kombination ist für mich ein einziger Befehl: `cdk diff`. Er vergleicht den synthetisierten CloudFormation-Stand mit dem, was in AWS tatsächlich läuft, und zeigt die Differenz – neue Ressourcen, geänderte Rechte, gelöschte Tabellen. Wenn ich diesen Befehl in den Pull-Request-Lauf ziehe, bekommt jeder Review eine ehrliche Vorschau auf die Betriebsfolge.\n\nDas ändert die Qualität eines Reviews spürbar. Ein Reviewer sieht nicht nur, dass ein Handler dazukommt, sondern dass dieser Handler eine neue IAM-Policy mit `dynamodb:*` mitbringt. Diese Zeile im Diff ist der Moment, in dem eine schlechte Entscheidung auffällt – vor dem Merge, nicht im nächsten Security-Audit. Ich verschiebe damit einen Fehler von „teuer und spät“ nach „billig und früh“, und das ist die konkrete Wirkung, um die es geht.\n\nDer Diff deckt außerdem eine Klasse von Problemen auf, die sonst unsichtbar bleibt: Drift. Wenn jemand in der Konsole eine Ressource von Hand ändert, weicht der reale Stand vom Code ab. Ohne Diff merkt das niemand, bis ein Deployment die manuelle Änderung stillschweigend überschreibt und irgendetwas kaputtgeht, das „gestern noch lief“. Mit dem Diff im Pull Request wird diese Abweichung zum sichtbaren Signal – und zur Gelegenheit, die eigentliche Frage zu stellen: Warum wurde an der Konsole gearbeitet, und wie bringe ich diese Änderung zurück in den Code, wo sie hingehört. Der Diff ist damit nicht nur ein Review-Werkzeug, sondern eine leise Disziplinierung des ganzen Teams in Richtung „der Code ist die Wahrheit“.\n\n## Ein kleiner Stack\n\nAls Grundlage dient ein bewusst kleiner Stack – eine Lambda hinter einem API Gateway. Er soll keine vollständige Anwendung simulieren, sondern die Grenze zeigen.\n\n```ts\nimport * as cdk from \"@aws-cdk/core\";\nimport * as lambda from \"@aws-cdk/aws-lambda\";\nimport * as apigw from \"@aws-cdk/aws-apigateway\";\n\nexport class ApiStack extends cdk.Stack {\n  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {\n    super(scope, id, props);\n\n    const handler = new lambda.Function(this, \"ApiHandler\", {\n      runtime: lambda.Runtime.NODEJS_12_X,\n      handler: \"index.handler\",\n      code: lambda.Code.fromAsset(\"dist/api\"),\n      timeout: cdk.Duration.seconds(10)\n    });\n\n    new apigw.LambdaRestApi(this, \"Api\", { handler });\n  }\n}\n```\n\nInteressant ist weniger, was hier steht, als was hier nicht steht. `LambdaRestApi` ist ein Construct, das im Hintergrund eine API, eine Integration und die passende Ausführungsrolle erzeugt. Das ist der Wert einer guten Abstraktion: Sie reduziert Wiederholung und kapselt vernünftige Defaults. Und das ist zugleich ihr Risiko – sie darf nicht verstecken, welche Ressourcen, Rechte und Kosten real entstehen. Der `cdk diff` ist genau die Kontrollinstanz, die das Versteckte wieder sichtbar macht.\n\nEin gutes Beispiel hat wenige Features und einen Punkt, über den man nach fünf Minuten streiten kann. Der `timeout` ist so ein Punkt: zehn Sekunden sind eine Betriebsentscheidung, kein Detail, und sie gehört in den Code, nicht in eine mündliche Absprache.\n\n## Die Pipeline\n\nDie Pipeline hat zwei Aufgaben, die ich sauber trenne. Im Pull Request zeigt sie den Diff, ohne etwas zu verändern. Auf `main` deployt sie. Diese Trennung ist keine Kosmetik – sie stellt sicher, dass die Vorschau folgenlos ist und das Deployment einen klaren Auslöser hat.\n\n```yaml\nname: deploy\n\non:\n  push:\n    branches: [main]\n  pull_request:\n\njobs:\n  diff:\n    if: github.event_name == 'pull_request'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v1\n      - uses: actions/setup-node@v1\n        with:\n          node-version: \"12\"\n      - run: npm ci\n      - run: npm run build\n      - run: npx cdk diff\n        env:\n          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}\n          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n          AWS_DEFAULT_REGION: eu-central-1\n\n  deploy:\n    if: github.ref == 'refs/heads/main'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v1\n      - uses: actions/setup-node@v1\n        with:\n          node-version: \"12\"\n      - run: npm ci\n      - run: npm run build\n      - run: npx cdk deploy --require-approval never\n        env:\n          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}\n          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n          AWS_DEFAULT_REGION: eu-central-1\n```\n\nDie Credentials liegen als GitHub Secrets im Repository und werden über Umgebungsvariablen an die CDK-CLI gereicht. Das ist der pragmatische Weg, den ich heute gehe – und zugleich die Stelle mit der größten Verantwortung, dazu gleich mehr.\n\nDer Ablauf als Skizze:\n\n```mermaid\nflowchart LR\n  PR[Pull Request] --> Diff[cdk diff<br/>im Review sichtbar]\n  Diff --> Merge[Merge nach main]\n  Merge --> Build[Build + synth]\n  Build --> Deploy[cdk deploy]\n  Deploy --> CFN[CloudFormation<br/>Change Set]\n  CFN --> Observe[Logs + Metriken]\n```\n\n## Eine Umgebung, die sich reproduzieren lässt\n\nSobald der erste Stack läuft, kommt die Frage nach Staging und Produktion. Und hier zeigt sich, warum Infrastruktur als Code mehr ist als ein bequemeres Deployment. Weil mein Stack eine TypeScript-Klasse ist, kann ich ihn parametrisieren und zweimal instanziieren – dieselbe Definition, unterschiedliche Namen, unterschiedliche Konten. Staging ist dann per Konstruktion eine exakte Kopie von Produktion, nicht eine Umgebung, die sich über Monate langsam auseinanderentwickelt, bis niemand mehr weiß, welcher Unterschied Absicht war und welcher Zufall.\n\nDas ist eine der methodischen Konsequenzen, die ich am höchsten schätze. Der klassische Bruch zwischen „funktioniert bei mir“ und „funktioniert in Produktion“ entsteht fast immer aus Umgebungsunterschieden, die niemand dokumentiert hat. Wenn die Umgebung selbst versioniert ist, verschwindet dieser Bruch nicht vollständig, aber er wird zu einer Frage, die ich im Repository beantworten kann, statt zu einem Rätsel, das ich unter Zeitdruck im Produktivsystem löse. Genau deshalb gehört CDK für mich zum Thema Reproduzierbarkeit. Die gesparten Deployment-Handgriffe sind nur der sichtbare Side Effect.\n\n## Rechte, die nicht mit jeder Bequemlichkeit mitwachsen\n\nDie verlockendste Abkürzung ist eine Deploy-Identität mit `AdministratorAccess`. Sie funktioniert immer, sie erklärt nie einen Fehler, und sie ist der Grund, warum ein kompromittiertes Repository zum kompromittierten Account wird. Der Trade-off ist real: Eine eng geschnittene Rolle bedeutet, dass ein Deployment gelegentlich an einer fehlenden Berechtigung scheitert und ich nachschärfen muss. Aber dieses Scheitern ist billig und lehrreich, während der stille Vollzugriff nur ein einziges Mal teuer wird.\n\nServerless verschiebt Betriebsarbeit, es entfernt sie nicht. Rechte, Logs, Kaltstarts, Timeouts, Kosten und Rollback-Fähigkeit müssen weiterhin explizit entworfen werden. Der Unterschied ist, dass ich sie mit CDK im selben Review entwerfe, in dem ich auch den Handler schreibe – statt sie auf „machen wir später“ zu vertagen. „Später“ ist in der Praxis der Name für „gar nicht“.\n\n## Rollback und der Irrtum des glücklichen Pfades\n\nBleibt die Überbewertung des glücklichen Pfades. Viele Pipelines sehen sauber aus, solange jedes Deployment gelingt. Interessant wird es bei Teilfehlern: Eine Ressource wird erstellt, die nächste scheitert, und der Stack steht auf halber Strecke.\n\nHier hilft, dass CDK auf CloudFormation aufsetzt. Ein fehlgeschlagenes Deployment rollt auf den letzten konsistenten Stand zurück, und dieses Verhalten ist Teil der Plattform, nicht meines Skripts. Das ist ein starker Grund, unter CDK zu bleiben, statt einzelne Ressourcen mit imperativen CLI-Aufrufen aneinanderzureihen: Ich bekomme eine definierte Transaktionsgrenze geschenkt. Trotzdem muss ich sie kennen. Ein Deployment, das Daten migriert, ist nicht automatisch rückbaubar, nur weil der Stack es ist – die Frage nach Idempotenz und Wiederholbarkeit bleibt meine.\n\n## Was sich dadurch messbar ändert\n\nWenn diese Teile zusammenspielen, ändert sich die Arbeit spürbar, und zwar in einer Richtung, die ich einem technischen Entscheider erklären kann. Der Zyklus von „Idee“ zu „läuft produktiv“ wird kürzer, weil kein manueller Übergabeschritt mehr zwischen Code und Infrastruktur liegt. Die Reibung im Team sinkt, weil niemand mehr Deployment-Wissen als persönliches Herrschaftswissen hält – es steht im Repository. Und die Qualität steigt, weil der `cdk diff` einen Fehler dorthin verschiebt, wo er billig ist: in den Pull Request.\n\nKonkret sieht das so aus: In einem Team ohne diese Konstruktion dauert eine Infrastrukturänderung so lange, wie die verfügbare Person mit AWS-Zugang braucht – plus die Zeit, bis jemand merkt, dass die Änderung in Staging und Produktion unterschiedlich ausgefallen ist. Mit der Pipeline ist dieselbe Änderung ein Pull Request, den zwei Kolleg:innen lesen können, ohne selbst Konsolenzugriff zu haben. Der Engpass „eine Person mit Rechten“ verschwindet, und mit ihm die stille Queue, die niemand je auf einem Board sieht. Das ist Developer Productivity im wörtlichen Sinn: nicht schneller tippen, sondern weniger Übergaben, weniger Rückfragen, weniger Zustände, in denen jemand auf jemand anderen wartet.\n\nDas ist der Bogen von der Mechanik zur Wirkung. GitHub Actions und CDK sind austauschbare Werkzeuge. Die wiederverwendbare Entscheidung dahinter – Infrastruktur als reviewbaren Teil jeder Änderung zu behandeln – ist es nicht.\n\n## Worauf ich im Review prüfe\n\nFür den Review dieser Konstruktion stelle ich drei Fragen. Zeigt der Pull Request die Betriebsfolge, also den Diff, oder nur den Anwendungscode? Ist die Deploy-Identität so eng geschnitten, dass ich einen Rechtefehler erklären kann, statt ihn wegzukonfigurieren? Und ist klar, was bei einem halb durchgelaufenen Deployment passiert?\n\nWenn eine dieser Fragen offen bleibt, fehlt der Pipeline noch etwas – ein sichtbarer Diff, eine schärfere Rolle oder ein geklärter Rollback-Pfad. Ein Construct sollte Wiederholung reduzieren und gute Defaults kapseln, aber nie verschleiern, welche Ressourcen, Rechte und Kosten entstehen. Genau an dieser Kante zwischen bequemer Abstraktion und ehrlicher Sichtbarkeit entscheidet sich, ob die Kombination trägt.\n\n## Weiterführende Quellen\n\n- AWS CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/home.html\n- AWS CDK Constructs: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n- [GitHub Actions: OpenID Connect mit AWS](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws)\n- Repository aws-cdk-js-github-action: https://github.com/MikeBild/aws-cdk-js-github-action\n\nDie Quellen helfen beim Gegenprüfen von Plattformverhalten. Die eigentliche Aussage bleibt die Architekturentscheidung im konkreten Beispiel.\n\n## Schluss\n\nGitHub Actions und CDK zusammenzubringen, ist schnell erledigt. Der Ertrag liegt darin, dass die Grenze zwischen Anwendung und Plattform in den Pull Request wandert. Dort entsteht der Nutzen für Entwickler, Architekten und technische Entscheider. Er hängt an einer wiederverwendbaren Entscheidung: Infrastruktur so ernst zu nehmen wie den Code, der auf ihr läuft. Der Toolname ist austauschbar."},{"locale":"de","translation_key":"pouchdb-offline-first","slug":"pouchdb-offline-first","title":"PouchDB und Offline-First","summary":"Wer offline Schreibzugriffe erlaubt, wechselt von Request/Response zur Replikation – und der Revisionsbaum von PouchDB und CouchDB macht Konflikte zur Aufgabe des Fachmodells.","tags":["Software","Architektur"],"published_at":"2019-11-12T10:00:00+00:00","updated_at":"2026-07-14T17:08:56.769898+00:00","url":"https://www.mikebild.dev/de/blog/pouchdb-offline-first/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/9c5035a7e2bec2a23cb2df548e43879133e5580807a1540324b9d41fd12efc44/pouchdb-offline-first-vorlesen.mp3","audio_duration_secs":721,"text":"# PouchDB und Offline-First\n\nOffline gilt als Sonderfall: erst die Anwendung fertig bauen, dann kurz vor dem Release einen Cache davorschalten, fehlgeschlagene Requests abfangen, ein Banner „Du bist offline\" anzeigen. Diese Annahme hält genau bis zum ersten Schreibzugriff ohne Netz. Lesen lässt sich zwischenspeichern – Schreiben nicht. Sobald ein Nutzer im Zug einen Datensatz ändern darf, lautet die Frage nicht mehr, wie man Antworten cached, sondern: Wo steht die Wahrheit, solange die Verbindung fehlt? Und was passiert, wenn zwei Geräte in der Zwischenzeit denselben Datensatz geändert haben?\n\nDamit ist Offline-First keine Feature-Checkbox, die man am Ende abhakt. Es ist eine Architekturentscheidung, die das Kommunikationsmodell der Anwendung austauscht: Replikation statt Request/Response. Die Offline-First-Bewegung sagt das seit Jahren – der Begriff stammt aus dem Umfeld von hood.ie und offlinefirst.org, lange bevor Progressive Web Apps das Thema in die Breite getragen haben. Trotzdem wird er im Alltag gern auf „Service Worker plus Cache\" verkürzt. Der Service Worker löst aber nur die halbe Aufgabe: Er liefert die Anwendung selbst ohne Netz aus – HTML, JavaScript, CSS. Die Daten sind das eigentliche Problem, und für die braucht es ein anderes Werkzeug.\n\n## Replikation statt Request/Response\n\nIm Request/Response-Modell ist der Server die einzige Quelle der Wahrheit. Der Client fragt, der Server antwortet, und ohne Verbindung gibt es schlicht keinen Zustand. Jede Offline-Funktion ist in diesem Modell ein Umweg: eine Queue für ausstehende POSTs, ein Cache für veraltete Antworten, Retry-Logik, lauter Spezialfälle, die quer zur eigentlichen Anwendung liegen.\n\nIm Replikationsmodell dreht sich das um. Die Anwendung liest und schreibt ausschließlich lokal, gegen eine Datenbank im Browser. Synchronisation ist ein eigenständiger Prozess, der im Hintergrund läuft, wenn eine Verbindung da ist – und der pausiert, wenn nicht. Die UI bekommt vom Netz zunächst gar nichts mit.\n\n```mermaid\nflowchart LR\n  subgraph rr[\"Request/Response\"]\n    UI1[\"UI\"] -->|\"HTTP-Request<br/>blockiert ohne Netz\"| API[\"API-Server\"]\n    API --> DB1[(\"zentrale<br/>Datenbank\")]\n  end\n  subgraph repl[\"Replikation\"]\n    UI2[\"UI\"] -->|\"lokal lesen<br/>und schreiben\"| LOCAL[(\"PouchDB<br/>IndexedDB\")]\n    LOCAL <-->|\"Sync, wenn<br/>Netz da ist\"| REMOTE[(\"CouchDB\")]\n  end\n```\n\nDer Unterschied zeigt sich zuerst in der gefühlten Geschwindigkeit: Lokale Lese- und Schreiboperationen liegen im Millisekundenbereich, unabhängig von Funkloch, Latenz oder Serverlast. Der eigentliche Gewinn und der eigentliche Preis stecken aber woanders. Das Replikationsmodell akzeptiert, dass es zeitweise mehrere gültige Sichten auf dieselben Daten gibt. Konflikte sind darin kein Betriebsunfall, sondern eine erwartbare Folge der Architektur – und genau deshalb gehören sie ins Fachmodell, nicht in einen Fehler-Handler.\n\n## PouchDB im Browser, CouchDB am anderen Ende\n\nPouchDB ist eine JavaScript-Datenbank, die im Browser auf IndexedDB aufsetzt und die HTTP-API von CouchDB nachbildet – inklusive des CouchDB-Replikationsprotokolls. Dieses Protokoll ist offen dokumentiert und beschreibt, wie zwei Peers ihre Änderungen austauschen: Changes-Feed lesen, fehlende Revisionen ermitteln, Dokumente übertragen, Checkpoint schreiben. Bricht die Verbindung ab, setzt der nächste Lauf am letzten Checkpoint auf, nicht am Anfang.\n\nDass sich damit bidirektionale Synchronisation in wenigen Zeilen aufsetzen lässt, wirkt beim ersten Kontakt fast verdächtig:\n\n```js\nconst localNotes = new PouchDB('notes');\nconst remoteNotes = new PouchDB('https://couch.example.com/notes');\n\nlocalNotes.sync(remoteNotes, { live: true, retry: true })\n  .on('change', info => renderChange(info))\n  .on('paused', () => setSyncStatus('idle'))\n  .on('active', () => setSyncStatus('syncing'))\n  .on('error', err => reportSyncError(err));\n```\n\n`sync` ist dabei nichts Magisches, sondern zwei einseitige Replikationen, eine in jede Richtung. `live` hält den Changes-Feed offen, `retry` überbrückt Verbindungsabbrüche mit Backoff. Die Events `paused` und `active` taugen als ehrliche Statusanzeige: `paused` heißt „alles übertragen oder gerade kein Netz\", `active` heißt „es fließen Änderungen\". Mehr Sync-Code habe ich in kleinen Anwendungen tatsächlich nie gebraucht – der Rest ist Konfliktbehandlung, dazu gleich.\n\nWichtig für die Einordnung, Stand heute mit PouchDB 7 und CouchDB 2.x: Das Replikationsprotokoll ist kein internes Detail, sondern eine Schnittstelle. Alles, was es spricht, kann teilnehmen – ein CouchDB-Cluster, ein zweiter Browser-Tab, ein Node-Prozess mit express-pouchdb davor. Die Synchronisationslogik wird damit zu Infrastruktur. Was in der Anwendung verbleibt, ist die fachliche Frage, die keine Bibliothek beantworten kann: Was bedeutet es, wenn zwei Stände auseinanderlaufen?\n\n## Der Revisionsbaum\n\nDer Kern des Modells ist die Versionierung jedes einzelnen Dokuments. Jede Änderung erzeugt eine neue Revision, und jede Schreiboperation muss die Revision nennen, die sie fortschreiben will. Passt die nicht, lehnt die Datenbank sofort ab:\n\n```js\nasync function saveNote(note) {\n  try {\n    await localNotes.put(note);\n  } catch (err) {\n    if (err.status !== 409) throw err;\n    // optimistic locking: fetch the current revision and retry once\n    const current = await localNotes.get(note._id);\n    await localNotes.put({ ...note, _rev: current._rev });\n  }\n}\n```\n\nDieser 409 ist der unmittelbare Konflikt: zwei Schreiber auf derselben Datenbank, klassisches Optimistic Locking, gut zu behandeln. Interessanter ist der zweite Fall. Zwei Geräte ändern offline dasselbe Dokument, beide Schreiboperationen sind lokal völlig gültig, und erst die Replikation führt die Stände zusammen. Dann entsteht im Dokument ein Revisionsbaum mit zwei Zweigen:\n\n```mermaid\ngraph TD\n  R1[\"Rev 1-a4f<br/>gemeinsamer Ausgangsstand\"] --> R2A[\"Rev 2-c91<br/>geändert auf Gerät A\"]\n  R1 --> R2B[\"Rev 2-b07<br/>geändert auf Gerät B\"]\n  R2A --> R3[\"Rev 3-e12<br/>Zusammenführung<br/>durch die Anwendung\"]\n  R2B -. \"Verlierer-Zweig<br/>bleibt erhalten\" .-> R3\n```\n\nCouchDB und PouchDB wählen in dieser Lage deterministisch einen Gewinner: der längere Revisionspfad gewinnt, bei Gleichstand der lexikografisch höhere Revisions-Hash. Deterministisch heißt, jeder Knoten kommt ohne Abstimmung zum selben Ergebnis – ein Cluster braucht dafür keinen Konsens-Algorithmus. Es heißt ausdrücklich nicht: fachlich richtig. Der Verlierer-Zweig wird auch nicht gelöscht, sondern bleibt als `_conflicts` am Dokument hängen. Die Datenbank hebt beide Stände auf und wartet darauf, dass jemand entscheidet. Dieses „jemand\" ist die Anwendung.\n\n## Konflikte sind der Normalfall\n\nAn dieser Stelle trennt sich die Cache-Denke endgültig vom Replikationsmodell. Wer Offline-Fähigkeit nachrüstet, behandelt Konflikte als Fehler, die möglichst nicht auftreten sollen. Wer repliziert, behandelt sie als gewöhnliches Event mit einer fachlichen Antwort. Die Datenbank kann diese Antwort nicht geben, weil sie die Bedeutung der Daten nicht kennt. Ob bei einer Notiz der längere Text gewinnt, ob sich zwei Einkaufslisten mengenweise vereinigen lassen oder ob ein Mensch entscheiden muss – das steht im Fachmodell, nirgendwo sonst.\n\nDie Auflösung selbst ist mechanisch unspektakulär: Konfliktrevisionen abholen, zusammenführen, Ergebnis schreiben, Verlierer entfernen.\n\n```js\nasync function resolveConflicts(id) {\n  const winner = await localNotes.get(id, { conflicts: true });\n  if (!winner._conflicts) return winner;\n\n  const losers = await Promise.all(\n    winner._conflicts.map(rev => localNotes.get(id, { rev }))\n  );\n\n  const merged = mergeNotes(winner, losers); // domain-specific merge\n  await localNotes.put(merged);\n  await Promise.all(\n    losers.map(loser => localNotes.remove(loser._id, loser._rev))\n  );\n  return merged;\n}\n```\n\nEntscheidend ist `mergeNotes` – und dass es diese Funktion überhaupt gibt. Mir ist in Code-Reviews aufgefallen, dass genau sie fast immer fehlt: Sync eingebaut, Demo läuft, und der Konfliktfall wird auf später verschoben, weil er in der Entwicklung schlicht nicht auftritt. Ein einzelner Entwickler mit einem Gerät und stabilem WLAN produziert keine Konflikte. Zwei Außendienstler mit Tablets im Funkloch produzieren sie am ersten Tag. Fehlt dann die Auflösung, gewinnt stillschweigend der deterministische Algorithmus, und die Änderungen des Verlierers sind aus Nutzersicht verschwunden – nicht gelöscht, aber unsichtbar. Das ist die teuerste Sorte Fehler: kein Absturz, kein Log-Eintrag, nur leiser Datenverlust aus Sicht des Menschen vor dem Bildschirm.\n\nDeshalb gehört zur Konfliktstrategie auch eine Sichtbarkeitsstrategie. Eine kleine Anzeige „drei Änderungen warten auf Sync\" kostet wenig und verändert das Vertrauen in die Anwendung spürbar. Nutzer verzeihen Wartezeiten, wenn sie sehen, woran sie sind.\n\n## Was das mit dem Datenmodell macht\n\nReplikation und Konflikte wirken auf den Dokumentenschnitt zurück. Ein Dokument ist die Einheit, in der repliziert und in der gestritten wird – also lohnt es sich, Dokumente so zu schneiden, dass Konflikte selten und, wenn sie auftreten, auflösbar sind. Ein paar Regeln haben sich bei mir bewährt:\n\n- Ein Dokument pro fachlicher Einheit, die ein Nutzer in einem Zug bearbeitet – kein Sammeldokument für den halben Anwendungszustand.\n- Sprechende IDs wie `note:2019-11-12` statt reiner Zufalls-UUIDs, wo die Fachlichkeit es hergibt; das macht Direktzugriffe planbar und erspart manchen Index.\n- Anfügen statt Überschreiben, wo es geht: Wer Events als neue Dokumente schreibt, statt ein bestehendes zu ändern, bekommt strukturell weniger Konflikte.\n- Löschungen als Teil des Modells begreifen: Gelöschte Dokumente bleiben als `_deleted`-Revisionen erhalten, damit die Löschung selbst repliziert werden kann.\n\nFür Queries jenseits des Schlüsselzugriffs gibt es Mango-Queries über pouchdb-find, inzwischen Teil des Standard-Builds:\n\n```js\nawait localNotes.createIndex({ index: { fields: ['updatedAt'] } });\n\nconst recent = await localNotes.find({\n  selector: { updatedAt: { $gte: '2019-11-01' } },\n  sort: [{ updatedAt: 'desc' }],\n  limit: 20\n});\n```\n\nDazu kommt eine Browser-Realität, die man kennen sollte: IndexedDB-Speicher ist nicht garantiert. Der Browser darf unter Druck aufräumen, und Speicherkontingente unterscheiden sich je nach Plattform deutlich. Über `navigator.storage.persist()` lässt sich beständiger Speicher anfragen, aber verlassen würde ich mich darauf nicht – die Kopie auf dem Server bleibt die Lebensversicherung, die lokale Datenbank ist der Arbeitsstand.\n\n## Zwei eigene Erfahrungen\n\n2016 habe ich mit graphql-pouch ausprobiert, wie weit sich die Idee treiben lässt: eine GraphQL-Runtime direkt auf PouchDB, Schemas in GraphQL-Shorthand-Notation, als eigenständiger Dienst mit CouchDB-Synchronisation und Master/Master-Replikation. Der Prototyp hat mir zwei Dinge gezeigt. Erstens, wie viel Backend das Replikationsprotokoll ersetzt: Sync-Endpoints, Retry-Logik, Delta-Berechnung – alles Code, den ich nie geschrieben habe, weil das Protokoll ihn mitbringt. Zweitens, dass einen die Konfliktfrage auch serverseitig einholt. Sobald zwei Instanzen gegeneinander replizieren, trägt der „Server\" dieselben Revisionsbäume wie der Browser. Die Architekturentscheidung verschwindet also nicht, wenn man sie auf die Serverseite schiebt; sie wechselt nur den Ort.\n\nNebenbei pflege ich seit einigen Jahren die Liste awesome-pouchdb, in der ich Werkzeuge, Plugins und Artikel rund um PouchDB sammle. Der Blick auf das Ökosystem ist selbst ein Datenpunkt: Auffällig viele Einträge drehen sich um genau die Stellen, an denen das Modell drückt – pouchdb-find für Queries, express-pouchdb für eigene Sync-Endpoints, pouchdb-authentication für die Anmeldung gegen CouchDB. Wo eine Community viele Werkzeuge baut, liegt selten Zufall vor, sondern ein wiederkehrendes Problem.\n\n## Wo ich es nicht einsetzen würde\n\nSo überzeugend das Modell für Notizen, Formulare und Außendienst-Szenarien ist – es hat klare Grenzen, und die sollte man vor der Entscheidung kennen, nicht danach:\n\n- Feingranulare Zugriffsrechte: CouchDB autorisiert pro Datenbank, nicht pro Dokument. Das übliche Gegenmittel ist eine Datenbank pro Nutzer, was Betrieb und serverseitige Auswertung merklich verkompliziert.\n- Große, zentral auszuwertende Datenmengen: Was der Browser hält, muss dorthin repliziert werden. Für Dashboards über Millionen Zeilen ist der Ansatz das falsche Werkzeug.\n- Streng konsistente Abläufe: Kontostände, Lagerbestände, Buchungen mit harten Invarianten brauchen zentrale Koordination. Eventual Consistency lässt sich nicht wegkonfigurieren.\n- Daten, die das Endgerät nicht verlassen dürfen es aber täten – oder umgekehrt gar nicht erst darauf liegen dürfen. Replikation verteilt Kopien, das ist ihr Zweck.\n\nGefilterte Replikation kann die Datenmenge pro Client eingrenzen, hat aber ihren eigenen Preis: Der Filter läuft über den kompletten Changes-Feed, und nachträgliche Filteränderungen sind mühsam. Wer nur einen Teilbestand synchronisieren will, sollte das früh im Dokumentenschnitt berücksichtigen, etwa über getrennte Datenbanken je Mandant oder Projekt.\n\n## Unterm Strich\n\nOffline-First entscheidet man am Anfang eines Projekts, nicht am Ende – weil Dokumentenschnitt, Konfliktverhalten und Berechtigungsmodell daran hängen. PouchDB und CouchDB nehmen einem die Mechanik vollständig ab: Replikationsprotokoll, Revisionsbäume, Checkpoints, Wiederaufnahme nach Abbruch. Was sie einem nicht abnehmen, ist die fachliche Antwort auf die eine Frage, an der alles hängt: Was soll passieren, wenn zwei Geräte dasselbe geändert haben? Wer darauf eine Antwort hat, bekommt mit erstaunlich wenig Code eine Anwendung, die im Funkloch genauso funktioniert wie im Büro. Wer keine hat, bekommt sie trotzdem – nur entscheidet dann ein Hash-Vergleich über die Daten seiner Nutzer.\n\n## Weiterführende Quellen\n\n- [awesome-pouchdb – kuratierte Liste von PouchDB-Werkzeugen und Plugins](https://github.com/MikeBild/awesome-pouchdb)\n- [graphql-pouch – GraphQL-Runtime auf PouchDB mit CouchDB-Sync](https://github.com/MikeBild/graphql-pouch)\n- [PouchDB Guide: Replication](https://pouchdb.com/guides/replication.html)\n- [PouchDB Guide: Conflicts](https://pouchdb.com/guides/conflicts.html)\n- [CouchDB Replication Protocol (offizielle Spezifikation)](https://docs.couchdb.org/en/stable/replication/protocol.html)\n- [Offline First – offlinefirst.org](http://offlinefirst.org/)"},{"locale":"de","translation_key":"commands-events-queries-trennen","slug":"commands-events-queries-trennen","title":"Commands, Events und Queries sauber trennen","summary":"Command, Event und Query sind drei Nachrichtenarten mit klarer Semantik: ein Wunsch, der abgelehnt werden kann, eine geschehene Tatsache und eine seiteneffektfreie Query. Wer sie sauber benennt und trennt, gewinnt Klarheit im Modell – ganz ohne großes CQRS-Setup.","tags":["Software","Architektur"],"published_at":"2019-10-08T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/de/blog/commands-events-queries-trennen/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/dd741934ab970fc6cfeb6198dca95a8c3f4dc1bf2d9d4620d0a0e1a140087d21/commands-events-queries-trennen-vorlesen.mp3","audio_duration_secs":802,"text":"`updateOrder(...)` ist keine fachliche Message. Der Name sagt nicht, ob jemand etwas möchte oder ob bereits etwas passiert ist – er beschreibt nur, dass Felder anders werden. Solche Methodennamen sind der Grund, warum Modelle verwaschen: Bitte, Tatsache und Frage laufen unter derselben Bezeichnung durch dieselben Klassen, und niemand kann an der Signatur ablesen, welche davon gerade unterwegs ist.\n\nCommand, Event und Query räumen das auf. Die drei unterscheiden sich in drei Punkten, die man an jeder einzelnen Message prüfen kann: in der Zeitform, in der Frage, ob sie abgelehnt werden darf, und in der Zahl der Empfänger. Die folgenden Abschnitte gehen diese Punkte durch – erst begrifflich, dann in TypeScript, dann entlang der Fehler, die dabei regelmäßig entstehen.\n\nDie Form einer Message folgt ihrer Bedeutung. Gleich aussehende JSON-Objekte können dennoch völlig unterschiedliche Verträge tragen.\n\n::::comparison{title=\"Messages nach ihrer Aussage unterscheiden\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Command\"}\n- Bedeutung · Bitte, eine Zustandsänderung zu versuchen\n- Zeitbezug · auf eine beabsichtigte Zukunft gerichtet\n- Ergebnis · kann abgelehnt werden oder scheitern\n:::\n:::side{label=\"Event\"}\n- Bedeutung · eine bereits eingetretene Tatsache\n- Zeitbezug · immutable Vergangenheit\n- Ergebnis · wird nicht nachträglich abgelehnt\n:::\n:::side{label=\"Query\"}\n- Bedeutung · Anfrage nach vorhandener Information\n- Zeitbezug · Sicht auf den aktuellen oder angegebenen Stand\n- Ergebnis · verändert den fachlichen Zustand nicht\n:::\n::::\n\nDiese Unterscheidung macht Namen, Fehlerpfade und Verantwortlichkeiten präziser, bevor ein Framework ins Spiel kommt.\n\n## Drei Messages, drei Bedeutungen\n\nFangen wir mit dem Kern an, denn hier entscheidet sich alles. Ein Command, ein Event und eine Query sind grundverschiedene Dinge, auch wenn sie im Code oberflächlich ähnlich aussehen – am Ende ist jedes davon ein Objekt mit ein paar Feldern. Der Unterschied steckt nicht in der Struktur, sondern in der Bedeutung.\n\nEin **Command** ist ein imperativer Wunsch. „Tu X.“ `CreateOrder`, `ShipProduct`, `CancelReservation`. Ein Command drückt eine Absicht aus, die noch nicht eingetreten ist. Und das ist entscheidend: Ein Command ist eine Bitte, die abgelehnt werden kann. Er durchläuft Validierung und Geschäftsregeln, und wenn etwas nicht stimmt, scheitert er. Genau ein Handler ist zuständig, ein Command ist gerichtet – er hat einen intendierten Empfänger.\n\nEin **Event** ist das genaue Gegenteil in der Zeitachse. Es ist eine Tatsache, die bereits eingetreten ist. `OrderCreated`, `ProductShipped`, `ItemOrdered` – benannt in der Vergangenheit. Ein Event ist immutable, denn man kann die Vergangenheit nicht mehr ändern. Und ein Event ist nicht ablehnbar: Man kann zu etwas Geschehenem nicht „nein“ sagen. Es ist das Ergebnis eines erfolgreich verarbeiteten Commands. Während ein Command genau einen Handler hat, kann ein Event keinen, einen oder viele Konsumenten haben – es ist eine Benachrichtigung an potenziell viele.\n\nEine **Query** schließlich fragt Daten ab, ohne etwas zu verändern. `GetOrderSummary`. Sie gibt ein Ergebnis zurück und lässt den beobachtbaren Zustand des Systems unangetastet – sie ist frei von Side Effects. Eine Query liest, idealerweise aus einer für das Lesen optimierten Sicht, und darf harmlos beliebig oft wiederholt werden.\n\nDiese semantische Trennung ist der ganze Punkt. Bertrand Meyer hat sie vor Jahrzehnten als Command-Query Separation formuliert: Jede Methode ist entweder ein Command, der den Zustand ändert, aber nichts zurückgibt, oder eine Query, die etwas zurückgibt, aber den Zustand nicht ändert – nie beides. Das Event kommt als dritte Art hinzu, wenn wir über Zustandsänderungen nicht nur befehlen, sondern auch berichten wollen.\n\n## Der Name transportiert die Semantik\n\nWenn ich in Reviews auf verwaschene Modelle stoße, liegt es fast immer an der Benennung. Der Name einer Message ist kein Beiwerk – er ist die Semantik, sichtbar gemacht. Ein Command im Imperativ, ein Event in der Vergangenheit. Diese Disziplin klingt banal, aber sie ist der billigste und wirksamste Hebel, den ich kenne.\n\nVergleichen wir die drei Arten direkt:\n\n- Ein Command steht im Imperativ und in der Gegenwart (`CreateOrder`): eine Absicht, gerichtet an genau einen Handler, die abgelehnt werden und scheitern kann.\n- Ein Event steht in der Vergangenheit (`OrderCreated`): eine Tatsache, immutable und nicht ablehnbar, gerichtet an null bis viele Konsumenten.\n- Eine Query beginnt meist mit `Get` oder `Find` (`GetOrderSummary`): eine Frage, seiteneffektfrei, sie liefert Daten und verändert nichts.\n\nSobald ein Team diese Namenskonvention verinnerlicht hat, liest sich der Code fast von selbst. Man sieht `CreateOrder` und weiß: Hier will jemand etwas, das schiefgehen kann. Man sieht `OrderCreated` und weiß: Das ist bereits geschehen, damit kann ich rechnen. Der Name ersetzt die halbe Dokumentation.\n\n## Der Fluss: vom Wunsch zur Tatsache zur Antwort\n\nWie hängen die drei nun zusammen? Der typische Fluss ist erstaunlich geradlinig. Ein Command trifft ein und wird von seinem Handler geprüft. Der Handler validiert und wendet Geschäftsregeln an. Wenn alles stimmt, emittiert er ein oder mehrere Events – die Tatsachen, die aus dem erfolgreichen Command folgen. Diese Events aktualisieren dann das Read Model, also die Lesesicht. Und eine Query liest schließlich aus genau diesem Read Model, ohne den Schreibpfad überhaupt zu berühren.\n\nMartin Fowler beschreibt das als zwei getrennte Wege: Der geänderte Zustand wird über das Command-Modell geroutet, die Anzeige kommt aus dem Query-Modell. Schreiben läuft über Command zu Event, Lesen geht direkt ans Read Model.\n\n```mermaid\nflowchart LR\n  C[Command: CreateOrder] --> H[Command Handler]\n  H -->|validate / business rules| E[Event: OrderCreated]\n  E --> RM[(Read Model)]\n  Q[Query: GetOrderSummary] --> RM\n```\n\nMan erkennt in diesem Bild die Asymmetrie, die den ganzen Ansatz ausmacht. Der Schreibpfad ist ein Prozess mit Prüfung: Command, Validierung, dann erst die Tatsache. Der Lesepfad ist eine direkte Query ohne Umweg. Beide teilen sich das Read Model, aber sie nähern sich ihm von entgegengesetzten Seiten – der eine schreibend über Events, der andere lesend über Queries.\n\n## In Code gegossen\n\nGenug Theorie – schauen wir uns an, wie das in TypeScript aussieht. Der folgende Code ist illustrativ, kein lauffähiges Repository; er soll die Semantik zeigen, nicht ein Framework ersetzen. Beginnen wir mit den Nachrichtentypen selbst, modelliert als discriminated unions:\n\n```ts\ntype LineItem = { sku: string; quantity: number };\n\ntype Command =\n  | { type: 'CreateOrder'; orderId: string; customerId: string; items: LineItem[] };\n\ntype DomainEvent =\n  | { type: 'OrderCreated'; orderId: string; customerId: string; occurredAt: Date };\n\ntype Query =\n  | { type: 'GetOrderSummary'; orderId: string };\n```\n\nSchon an den Typen lässt sich die Semantik ablesen. Der Command steht im Imperativ. Das Event steht in der Vergangenheit und trägt ein `occurredAt` – den Zeitpunkt, zu dem die Tatsache eingetreten ist, denn ein Event lebt von seiner zeitlichen Verortung. Die Query beginnt mit `Get` und liefert erkennbar nur eine Frage.\n\nJetzt der Command-Handler. Er ist das Herzstück des Schreibpfads: Er prüft, entscheidet und emittiert. Wichtig ist, dass ein Command abgelehnt werden kann – und dass die Rückgabe eine Liste von Events ist, denn ein Command kann durchaus mehrere Tatsachen nach sich ziehen:\n\n```ts\nclass RejectedCommand extends Error {}\n\nfunction handleCreateOrder(cmd: Extract<Command, { type: 'CreateOrder' }>): DomainEvent[] {\n  if (cmd.items.length === 0) {\n    throw new RejectedCommand('order needs at least one item');\n  }\n\n  return [\n    {\n      type: 'OrderCreated',\n      orderId: cmd.orderId,\n      customerId: cmd.customerId,\n      occurredAt: new Date(),\n    },\n  ];\n}\n```\n\nHier wird die Semantik konkret. Der Handler validiert, und wenn die Bitte nicht erfüllbar ist, lehnt er sie ab – der Command scheitert, bevor irgendeine Tatsache entsteht. Erst wenn die Prüfung durchgeht, wird das Event geboren. Kein Event ohne bestandene Validierung; das ist die Ordnung, die wir wollen.\n\nAuf der anderen Seite steht der Query-Handler. Er tut genau eine Sache: lesen. Keine Mutation, kein emittiertes Event, kein Side Effect:\n\n```ts\ninterface OrderReadModel {\n  findSummary(orderId: string): OrderSummary;\n}\n\ntype OrderSummary = { orderId: string; itemCount: number; status: string };\n\nfunction handleGetOrderSummary(\n  q: Extract<Query, { type: 'GetOrderSummary' }>,\n  readModel: OrderReadModel,\n): OrderSummary {\n  return readModel.findSummary(q.orderId); // read only, no mutation, no events\n}\n```\n\nUnd damit der Kreis sich schließt: Wie kommt das Read Model überhaupt zu seinen Daten? Über eine Projection, die auf Events reagiert. Die Projection nimmt ein `OrderCreated` entgegen und aktualisiert die Lesesicht – so fließt die Tatsache aus dem Schreibpfad in die Sicht, die später von Queries gelesen wird:\n\n```ts\nfunction applyOrderCreated(\n  event: Extract<DomainEvent, { type: 'OrderCreated' }>,\n  store: Map<string, OrderSummary>,\n): void {\n  store.set(event.orderId, {\n    orderId: event.orderId,\n    itemCount: 0,\n    status: 'created',\n  });\n}\n```\n\nWer diese vier Bausteine nebeneinanderlegt – Command-Typ, Command-Handler, Projection, Query-Handler –, sieht den gesamten Fluss auf einen Blick. Der Command ist der Wunsch, der Handler prüft ihn, das Event ist die Tatsache, die Projection trägt sie ins Read Model, und die Query liest von dort. Jede Message hat ihren Platz und ihre Bedeutung.\n\n## Die Fallstricke, die ich immer wieder sehe\n\nSo klar die Theorie ist, so hartnäckig sind die Fehler in der Praxis. Vier davon begegnen mir immer wieder.\n\nDer häufigste ist die **verdrehte Benennung**. Ein `OrderCreated`, das eigentlich ein Command ist, oder ein `CreateOrder`, das als Event durch die Gegend fliegt. Sobald das passiert, verliert das Team die Unterscheidung zwischen „Absicht, die scheitern kann“ und „Fakt, der bereits eingetreten ist“. Der Name lügt, und mit ihm das Modell. Wenn ich in einem Review ein Event im Imperativ finde, ist das für mich das erste Alarmsignal.\n\nDer zweite Fallstrick ist die **Query mit Side Effect**. Eine vermeintliche Query, die nebenbei schreibt, einen Zähler hochsetzt oder ein Event feuert. Das bricht die Freiheit von Side Effects, die Meyer für Queries fordert. Eine Query muss harmlos wiederholbar sein – wenn ich sie zweimal aufrufe, darf sich am System nichts ändern. Sobald eine Query Zustand mutiert, ist sie keine Query mehr, sondern ein verkleideter Command.\n\nDer dritte Fehler ist begrifflicher Natur: **CQRS mit Event Sourcing verwechseln**. Die Trennung von Command, Event und Query braucht kein Event Sourcing. Sie braucht auch nicht zwingend zwei Datenbanken oder einen asynchronen Message Bus. Man kann die drei Nachrichtenarten in einem ganz gewöhnlichen Service mit einer einzigen Datenbank sauber trennen. Greg Young bringt das Verhältnis auf einen Merksatz: Man kann CQRS ohne Event Sourcing nutzen; nutzt man Event Sourcing, braucht man praktisch CQRS. Nicht umkehren.\n\nDer vierte Fallstrick ist der **anämische Command als Setter**. Ein `UpdateOrder(status = 'shipped')` verrät nichts über die fachliche Absicht. Warum wird der Status geändert? Weil das Produkt versandt wurde. Dann heißt der Command `ShipProduct`, nicht `UpdateOrder`. Ein Command soll eine fachliche Absicht ausdrücken, keine generische Datenmanipulation. Der Unterschied zwischen `UpdateOrder` und `ShipProduct` ist der Unterschied zwischen einem Formular und einer Geschichte.\n\n## Ein kurzer Blick über den Tellerrand: CQS, CQRS und die Kosten\n\nDamit die Begriffe nicht durcheinandergeraten, lohnt eine saubere Abgrenzung. **CQS** – Command-Query Separation nach Meyer – ist ein Prinzip auf Methodenebene: Jede Methode ist entweder Command oder Query. **CQRS** – von Greg Young geprägt und von Fowler popularisiert – hebt dasselbe Prinzip auf die Objekt- beziehungsweise Serviceebene: ein getrenntes Modell zum Schreiben und ein getrenntes Modell zum Lesen. Fowler formuliert es so, dass man ein anderes Modell zum Aktualisieren von Informationen nutzen kann als das Modell zum Lesen.\n\nUnd dazu gehört ein Satz, der gern untergeht: CQRS ist kein Default. Fowler warnt ausdrücklich, dass CQRS riskante Komplexität hinzufügt und nur bei klarem Nutzen gerechtfertigt ist. Getrennte Modelle, eventuell getrennte Speicher, asynchrone Konsistenz – das will man nicht überall. Wer CQRS reflexartig überall einführt, handelt sich mehr Probleme ein, als er löst. Ich habe an anderer Stelle ausführlicher beschrieben, warum [CQRS eine fachliche Grenze ist, kein Framework](https://www.mikebild.dev/de/blog/cqrs-fachliche-grenze-kein-framework/) – die Entscheidung für getrennte Modelle gehört an die fachliche Konsistenzgrenze, nicht in jeden Service.\n\nDie gute Nachricht ist: Die reine semantische Trennung von Command, Event und Query kostet fast nichts und lohnt sich fast immer. Sie ist nicht CQRS. Sie ist die begriffliche Hygiene, auf der CQRS später aufsetzen kann, falls man es überhaupt braucht. Man kann Commands imperativ benennen, Events in der Vergangenheit, Queries seiteneffektfrei halten – und dabei in einem völlig konventionellen Service bleiben. Diese Klarheit im Kleinen ist der eigentliche Gewinn.\n\n## Roter Faden\n\nDie Frage vom Anfang – möchte jemand etwas, oder ist etwas passiert? – lässt sich an jeder Message beantworten, sobald sie einen ehrlichen Namen trägt. Ein Command ist der Wunsch, der geprüft wird und scheitern kann. Ein Event ist die Tatsache, die daraus folgt, immutable und nicht verhandelbar. Eine Query ist die Frage, die liest, ohne zu berühren. Drei Messages, drei Bedeutungen, drei Namen – und der Name trägt die Bedeutung nach außen.\n\nDiese Trennung ist kein großes Architekturprojekt. Sie beginnt mit Disziplin bei der Benennung und mit der Weigerung, eine Query heimlich schreiben zu lassen. Man muss weder Event Sourcing einführen noch zwei Datenbanken aufsetzen, um den Nutzen einzufahren. Wer im nächsten Modell konsequent zwischen `CreateOrder`, `OrderCreated` und `GetOrderSummary` unterscheidet, hat schon den größten Teil der Arbeit getan. Alles Weitere – CQRS, Projections, getrennte Speicher – ist eine Frage, die man später und nur bei echtem Bedarf stellt. Die semantische Trennung selbst kostet nichts außer Aufmerksamkeit, und genau die zahlt sich in jedem Modell aus.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html\n- Martin Fowler, [CQRS](https://martinfowler.com/bliki/CQRS.html) – die kompakte Definition samt Warnung vor der Komplexität.\n- Martin Fowler, [CommandQuerySeparation](https://martinfowler.com/bliki/CommandQuerySeparation.html) – Meyers ursprüngliches Prinzip auf Methodenebene.\n- Martin Fowler, [What do you mean by „Event-Driven“?](https://martinfowler.com/articles/201701-event-driven.html) – zur Einordnung von Events als Messages und Tatsachen.\n- Greg Young, [CQRS](https://gregfyoung.wordpress.com/2012/03/02/cqrs/) – der Ursprung der Objekt-/Serviceebene und das Verhältnis zu Event Sourcing.\n- Vaughn Vernon, *Implementing Domain-Driven Design* (2013), Kapitel zu Domain Events – zur Benennung und Bedeutung von Events in der Domäne.\n- Mein eigenes Vortragsmaterial „CQRS + Event Sourcing“ (SlideShare) – die Folien, auf denen ich diese Trennung ausführlicher durchgehe."},{"locale":"de","translation_key":"infrastructure-as-code-code-reviews","slug":"infrastructure-as-code-code-reviews","title":"Infrastructure as Code braucht Code-Reviews","summary":"Sobald Infrastruktur Code ist, entscheidet ein kleiner Diff über Sicherheit, Kosten und Ausfallrisiko – deshalb gehört sie in denselben Review-Prozess wie Anwendungscode.","tags":["Software","AWS","Cloud"],"published_at":"2019-09-24T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/infrastructure-as-code-code-reviews/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/34344369eee3450fdca8c99df6b92ee0deb82c64d7b4b91ac411f54459dc14d5/infrastructure-as-code-code-reviews-vorlesen.mp3","audio_duration_secs":661,"text":"# Infrastructure as Code braucht Code-Reviews\n\nWer eine Wildcard-Berechtigung durchwinkt, hat sie erteilt. Der Merge ist der Moment der Entscheidung, nicht das Audit ein Jahr später, in dem dieselbe Zeile rot markiert wird. Und dieser Moment sieht harmlos aus: ein paar geänderte Zeilen, ein grüner Build, ein Daumen hoch.\n\nAuslöser ist das AWS CDK, das diesen Sommer stabil wurde. Damit beschreibe ich Cloud-Infrastruktur nicht mehr in tausend Zeilen YAML, sondern in TypeScript – mit Typen, Funktionen und Abstraktionen. Das ist spürbar produktiver, und genau da liegt der Haken.\n\nDenn eine Änderung an der Infrastruktur sieht jetzt aus wie jede andere Pull Request. Was in diesem unauffälligen Diff steckt, ist aber kein Feature-Flag. Es ist eine IAM-Policy, eine Security-Group oder die Speicherzuweisung einer Funktion, die pro Aufruf abgerechnet wird. Die Reibung beim Ändern ist gesunken – das Risiko pro Änderung nicht. Diese Schere ist das eigentliche Thema.\n\n## Was sich mit Infrastructure as Code wirklich ändert\n\nVorher steckte Infrastruktur in Klick-Sessions in der Konsole und in den Köpfen von zwei, drei Leuten. Niemand konnte eine Änderung reviewen, weil es keinen Diff gab. Wer eine Regel in einer Security-Group aufmachte, hinterließ keine nachvollziehbare Spur. Ausfälle wurden zu archäologischen Ausgrabungen: Wer hat wann was verstellt, und warum?\n\nInfrastructure as Code dreht das um. Jede Änderung wird zu einem Commit, jeder Commit ist versioniert, jede Version ist überprüfbar. Der eigentliche Gewinn liegt dabei nicht in der schöneren Syntax. Er liegt darin, dass Infrastruktur endlich denselben Kontrollmechanismen unterliegt wie der Rest des Systems. Rollback wird ein `git revert`, Nachvollziehbarkeit wird ein `git blame`, Wissen wird ein lesbares Repository statt eines Stammtisch-Gesprächs.\n\nNur: Die Review-Disziplin ist mit dieser Verschiebung nicht automatisch mitgewachsen. Wir reviewen Anwendungscode seit Jahren mit einem klaren Blick für Nebenwirkungen, Grenzfälle und Sicherheit. Bei Infrastruktur-Code lesen viele Teams denselben Diff mit halber Aufmerksamkeit, weil er kurz aussieht und der Build grün ist. Ein grüner Build heißt bei IaC aber nur, dass die Synthese durchlief – nicht, dass die entstehende Infrastruktur sicher, bezahlbar und zurückbaubar ist.\n\n## Der Diff, den ich wirklich reviewen muss\n\nCDK arbeitet mit Constructs: Bausteinen, die eine oder mehrere CloudFormation-Ressourcen samt sinnvoller Defaults kapseln. Das ist die Stärke und zugleich die Falle. Ein High-Level-Construct kann aus drei Zeilen TypeScript ein Dutzend Ressourcen erzeugen – eine Funktion, eine Log-Gruppe, eine Execution-Rolle, ein paar Berechtigungen. Der TypeScript-Diff zeigt mir die Absicht. Was tatsächlich provisioniert wird, zeigt er nicht.\n\nDas eigentliche Review-Artefakt ist deshalb der `cdk diff`, nicht der Code allein: die Gegenüberstellung von aktuellem und geplantem CloudFormation-Zustand. Erst da wird sichtbar, dass eine unscheinbare Zeile eine Rolle mit einer Wildcard-Berechtigung anlegt oder eine Security-Group öffnet.\n\n```ts\nconst handler = new lambda.Function(this, \"ApiHandler\", {\n  runtime: lambda.Runtime.NODEJS_10_X,\n  handler: \"index.handler\",\n  code: lambda.Code.fromAsset(\"dist/api\")\n});\n```\n\nDiese vier Zeilen sind bewusst klein. Sie erzeugen aber mehr als eine Funktion: eine Log-Gruppe, eine Execution-Rolle mit Basisrechten und die Verknüpfungen dazwischen. Die Review-Frage lautet nicht „läuft der Handler?“, sondern „welche Rechte bekommt diese Rolle, wie lange bleiben die Logs liegen, und was kostet ein Aufruf?“. Ein gutes Construct reduziert Wiederholung und kapselt gute Defaults – es darf aber nicht verstecken, welche Ressourcen, Rechte und Kosten entstehen. Genau diese Grenze prüfe ich im Review.\n\n## Die teuerste Zeile ist oft eine Berechtigung\n\nDer klassische Fehler ist die bequeme Berechtigung. Es funktioniert sofort, wenn ich einer Funktion breiten Zugriff gebe, und niemand merkt im Demo, dass die Grenze zu weit gezogen ist.\n\n```ts\n// convenient, and wrong\nbucket.grantReadWrite(handler);\ntable.grant(handler, \"dynamodb:*\");\n```\n\nDas läuft. Es ist auch die Art von Zeile, die ein Jahr später in einem Security-Audit rot markiert wird. Least Privilege ist keine Fleißaufgabe für später. Die Entscheidung darüber fällt im Review, im Moment des Merges – danach ist die Rolle in Betrieb, und aus einem „mach ich noch enger“ wird selten etwas. Im Review frage ich deshalb konkret: Braucht diese Funktion wirklich Schreibrechte, oder nur Lesen? Braucht sie den ganzen Table oder eine Aktion? Jede Wildcard ist eine Behauptung, die belegt werden muss.\n\nDas Muster wiederholt sich bei öffentlichen Buckets, offenen Security-Groups und geteilten Secrets. Keiner dieser Fehler ist technisch schwierig. Alle sind billig zu verhindern, wenn jemand den Diff mit der richtigen Frage liest – und teuer, wenn niemand es tut.\n\n## Kosten gehören in den Review\n\nBei serverloser Infrastruktur ist die Rechnung ein direktes Ergebnis von Codezeilen. Die Speichergröße einer Funktion, provisionierte Concurrency, ein NAT-Gateway, ein zu groß gewählter Instanztyp, eine Retention-Einstellung, die Logs für immer aufhebt – all das sind einzeilige Änderungen mit einer laufenden monatlichen Konsequenz.\n\nIch habe erlebt, wie eine einzige geänderte Zeile die Cloud-Rechnung eines Teams verdoppelt hat, weil ein Default unbedacht übernommen wurde. Der Diff war unauffällig, der Build grün, der Review eine Formsache. Kostentransparenz im Review heißt nicht, jede Rechnung vorherzusagen. Es heißt, die Frage überhaupt zu stellen: Was ändert diese Zeile an den laufenden Kosten – einmalig, pro Aufruf, oder pro Monat? Serverless verschiebt Betriebsarbeit, es entfernt sie nicht. Rechte, Logs, Kaltstarts, Timeouts, Kosten und Rollback-Fähigkeit müssen weiterhin explizit entworfen werden.\n\n## Wonach ich im Infrastruktur-Review sehe\n\nÜber die einzelnen Beispiele hinweg prüfe ich immer dieselben Grenzen. Ist die Berechtigung so eng wie möglich, oder öffnet der Diff mehr, als die Aufgabe braucht? Wie groß ist der Blast Radius, wenn diese Ressource falsch konfiguriert ist – trifft es einen Service oder das ganze Konto? Ist die Änderung idempotent und rückbaubar, oder erzeugt ein zweites Deployment einen anderen Zustand als das erste? Was passiert bei einem fehlerhaften Deployment – gibt es einen sauberen Weg zurück, oder muss jemand nachts von Hand reparieren? Und produziert der Betrieb genug Signale – Logs, Metrics, Alarme –, um einen Fehler später überhaupt zu erklären?\n\nDiese Fragen wirken trocken. Sie sind aber der Unterschied zwischen einem System, das im Demo sauber aussieht, und einem, das unter Wiederholung, Teilausfällen, alten Daten und falschen Berechtigungen trägt. Der glückliche Pfad ist nie das Problem. Interessant wird Infrastruktur genau dort, wo etwas schiefgeht.\n\n## Der Trade-off der Abstraktion\n\nCDK bietet Constructs auf mehreren Ebenen: dünne Hüllen um einzelne CloudFormation-Ressourcen, komfortable Bausteine mit guten Defaults und ganze Muster aus mehreren Ressourcen. Je höher die Ebene, desto weniger Code schreibe ich – und desto mehr Entscheidungen delegiere ich an Defaults, die ich nicht sehe.\n\nDas ist kein Argument gegen Abstraktion. Es ist ein Argument dafür, die Abstraktionsebene bewusst zu wählen und im Review sichtbar zu machen. Ein High-Level-Construct ist ein guter Tausch, wenn seine Defaults zu meinen Anforderungen an Sicherheit und Kosten passen. Er ist ein schlechter Tausch, wenn ich seine Defaults nie geprüft habe und sie in Produktion überrascht kennenlerne. Die methodische Konsequenz ist einfach: Der `cdk diff` gehört in jede Pull Request, damit die Ebene, auf der ich delegiere, nicht implizit bleibt.\n\n## Wo der Review in die Pipeline gehört\n\n```mermaid\nflowchart LR\n  Source --> Synth\n  Synth --> Diff[\"cdk diff\"]\n  Diff --> Review[\"Review<br/>Rechte · Kosten · Rollback\"]\n  Review --> Deploy\n  Deploy --> Observe\n```\n\nDer Diff ist keine Formalie am Schluss. Er ist der Ort, an dem der Review greift: vor dem Deployment, als sichtbares Artefakt in der Pull Request. Das verschiebt den Fehler aus dem Betrieb in die Review-Phase – und das ist der ganze Sinn. Ein Konfigurationsfehler, der im Diff auffällt, kostet zehn Minuten Diskussion. Derselbe Fehler in Produktion kostet einen Incident, eine Nachtschicht und Vertrauen.\n\n## Was die Maschine prüft, was der Mensch prüft\n\nEin guter Review-Prozess verschwendet keine menschliche Aufmerksamkeit an Dinge, die eine Regel erledigen kann. Vieles am Infrastruktur-Review ist mechanisch und lässt sich automatisieren: offene Security-Groups, unverschlüsselte Buckets, Wildcard-Policies, fehlende Log-Retention. Statische Analyse auf dem synthetisierten CloudFormation-Template – etwa mit cfn_nag – fängt diese Klasse von Fehlern in der Pipeline ab, bevor überhaupt ein Mensch draufschaut.\n\nWeil die Infrastruktur jetzt Code ist, kann ich außerdem Annahmen als Test festschreiben. CDK erlaubt Assertions gegen das synthetisierte Template: „diese Rolle darf keine Wildcard-Action enthalten“, „dieser Bucket ist nicht öffentlich“. Ein solcher Test schlägt fehl, sobald jemand die Grenze aufweicht – nicht erst im Audit ein Jahr später. Das ist derselbe Reflex, den ich von Anwendungscode kenne: Was einmal richtig war und richtig bleiben muss, wird ein Test, kein Merksatz.\n\nDie Automatisierung nimmt dem menschlichen Review nicht die Arbeit ab, sie fokussiert sie. Wenn die Maschine die immer gleichen Regeln durchsetzt, kann der Mensch sich auf das konzentrieren, was keine Regel entscheiden kann: Ist diese Abstraktionsebene die richtige? Ist der Blast Radius vertretbar? Passt die Kostenkonsequenz zur Aufgabe? Genau diese Fragen sind der Grund, warum es den Review überhaupt gibt.\n\n## Der Fehler, das Werkzeug für die Lösung zu halten\n\nEin Werkzeug erzeugt keine gute Architektur, es kann sie nur ausdrücken. CDK ist kein Sicherheitskonzept. CloudFormation ist kein Berechtigungsmodell. Serverless ist keine Betriebsstrategie. Diese Werkzeuge machen es leichter, gute Grenzen zu ziehen – sie ziehen sie nicht von selbst. Wer glaubt, mit dem Umstieg auf Infrastructure as Code sei die Sicherheits- und Kostenfrage erledigt, hat nur das Medium gewechselt, in dem dieselben Entscheidungen jetzt schneller und unauffälliger getroffen werden.\n\nGenau deshalb braucht Infrastructure as Code den Review mehr, nicht weniger. Die niedrige Reibung, die den ganzen Ansatz so attraktiv macht, ist gleichzeitig ihr größtes Risiko. Ändern ist billig geworden – Verstehen muss es bleiben.\n\n## Was das dem Team bringt\n\nDer Nutzen ist messbar, auch wenn er sich als Abwesenheit zeigt. Fehler, die früher als Incident auftraten, tauchen jetzt als Kommentar in einer Pull Request auf. Die Cloud-Rechnung bleibt vorhersehbar, weil Kostenänderungen benannt statt entdeckt werden. Onboarding wird kürzer, weil neue Leute die Infrastruktur lesen statt raten. Und die Durchlaufzeit sinkt sogar: Es wird nicht weniger geprüft, es muss weniger repariert werden.\n\nEin Review kostet Minuten. Ein offener Bucket, eine Wildcard-Rolle oder ein verdoppeltes NAT-Gateway kostet Tage und im schlimmsten Fall Kundendaten. Infrastructure as Code hat die Infrastruktur endlich in ein Format gebracht, in dem sich dieser Handel lohnt. Es wäre schade, den Review als einzigen Schritt auszulassen, der aus einem Diff eine Entscheidung macht.\n\n## Weiterführende Quellen\n\n- AWS CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/home.html\n- AWS CDK Constructs: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n\nDie Quellen helfen beim Gegenprüfen von Plattformverhalten und Defaults. Die eigentliche Entscheidung steht aber nicht in der Doku. Sie steht im konkreten Diff – und hängt daran, dass jemand ihn liest, bevor er live geht."},{"locale":"de","translation_key":"secrets-im-build","slug":"secrets-im-build","title":"Secrets im Build sind Produktentscheidungen","summary":"Secrets im Build sind ein Vertrauensproblem: Wer darf was wann sehen, speichern und deployen?","tags":["Software","DevOps","Architektur"],"published_at":"2019-09-12T10:00:00+00:00","updated_at":"2026-07-13T08:38:07.947838+00:00","url":"https://www.mikebild.dev/de/blog/secrets-im-build/","audio_url":"https://media.mikebild.dev/site/mikebild/audio/4aca0cc499b8c90f1d0138de2f9e562ee4c383bcdf2da5a8dc0e841367bfc9f8.mp3","audio_duration_secs":647,"text":"# Secrets im Build sind Produktentscheidungen\n\n```console\n$ docker history --no-trunc myapp:staging\nIMAGE      CREATED BY\n<missing>  /bin/sh -c #(nop) COPY file:3f2a… in /app/.env\n<missing>  /bin/sh -c #(nop) ENV DATABASE_URL=postgres://app:S3cr3t@db.prod.internal:5432/app\n```\n\nZwei Zeilen Layer-Metadaten, lesbar für jeden mit Pull-Rechten auf die Registry. In einem Projekt lag die halbe Konfiguration in einer `.env`, die per `COPY` ins Image wanderte. Das lief monatelang gut, bis jemand das Image aus der Registry zog, `docker history` aufrief und die Datenbank-URL samt Passwort im Klartext las. Kein Angriff, kein exotischer Bug – nur ein Artefakt, das mehr wusste, als es durfte.\n\nDer Fehler war nicht die vergessene Verschlüsselung. Der Fehler war eine unausgesprochene Grenze: Das Team hatte nie entschieden, ob ein Build-Artefakt Secrets kennen darf. Es hatte nur ein Tutorial kopiert. Und genau da hört die Sache auf, eine Betriebsfrage zu sein. Wo ein Token, ein Passwort oder ein Zertifikat entsteht, gespeichert und in ein Artefakt injiziert wird, legt fest, wer ohne Rücksprache liefern darf und wer warten muss. Das entscheidet über Tempo, Reibung und Fehlerrate eines Teams – lange bevor irgendein Tool ausgewählt ist.\n\n## Die eigentliche Frage ist Vertrauen, nicht Verschlüsselung\n\nVerschlüsselung löst ein enges Problem: Daten at rest und in transit schützen. Sie beantwortet nicht die Frage, die im Alltag teuer wird – wer im Prozess das Secret überhaupt in die Hand bekommt. Ein KMS-verschlüsselter Wert, den jeder CI-Job entschlüsseln darf, ist bequem und trotzdem eine offene Grenze.\n\nBevor ich ein Werkzeug wähle, kläre ich vier Fragen. Welche Komponente ist führend für den Wert? Wer darf ihn lesen, und in welcher Umgebung? Wann wird er gelesen – zur Build-Zeit oder zur Laufzeit? Und was muss später nachvollziehbar sein, wenn er kompromittiert ist? Diese Antworten entscheiden über Rotation und Schadensradius. Verschlüsselung allein beantwortet keine davon.\n\n## Build-Zeit und Laufzeit sind zwei verschiedene Vertrauenszonen\n\nDie wichtigste Grenze verläuft zwischen Build und Runtime. Ein Build erzeugt ein Artefakt, das durch mehrere Umgebungen wandert und in einer Registry landet, auf die oft mehr Menschen Zugriff haben, als man denkt. Alles, was in dieses Artefakt eingebacken wird, ist damit so vertraulich wie die Registry – und nicht vertraulicher.\n\nDas klassische Anti-Pattern sieht harmlos aus:\n\n```dockerfile\n# ANTI-PATTERN: the secret becomes part of a shared, promotable artifact\nCOPY .env /app/.env\n```\n\n```dockerfile\n# ANTI-PATTERN: build args stay recoverable via `docker history`\nARG NPM_TOKEN\nRUN echo \"//registry.npmjs.org/:_authToken=${NPM_TOKEN}\" > .npmrc \\\n  && npm ci \\\n  && rm .npmrc\n```\n\nDas `rm` täuscht Sicherheit vor. Der Token bleibt in den Layer-Metadaten sichtbar, und die `.env` reist als eigener Layer mit. Beides überlebt jedes spätere `docker run` in jeder Umgebung. Das eigentliche Problem ist nicht der Befehl, sondern die vermischte Vertrauenszone: Ein Artefakt, das in Staging und Production identisch sein soll, trägt plötzlich Production-Secrets.\n\nDie architektonische Antwort ist eine saubere Trennung. Der Build produziert ein umgebungsneutrales Artefakt ohne Secrets. Die Konfiguration kommt erst zur Laufzeit dazu, injiziert aus einer Quelle, die pro Umgebung getrennt ist. Ein Multi-Stage-Build macht diese Absicht im Code sichtbar:\n\n```dockerfile\n# build stage produces an artifact that knows nothing about any environment\nFROM node:12 AS build\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci\nCOPY . .\nRUN npm run build\n\n# runtime stage receives config from the environment, never from the image\nFROM node:12-slim\nWORKDIR /app\nCOPY --from=build /app/dist ./dist\nCMD [\"node\", \"dist/server.js\"]\n```\n\nDieselbe Denkweise gilt für Build-Secrets, die der Build wirklich braucht – etwa ein privater Registry-Token. Die kommen über einen Secret-Mount, der im finalen Image nicht persistiert, statt über einen `ARG`, der in der History bleibt. Der Grundsatz bleibt: Ein Secret, das nur der Build braucht, darf das Runtime-Artefakt nicht erreichen.\n\n## Parameter Store als Interface, nicht als Datenbank\n\nSobald die Trennung steht, wird Parameter Store interessant. Seinen Wert bezieht er aus der Struktur, die er erzwingt, und nicht daraus, dass er Werte aufbewahrt. Der hierarchische Pfad ist der eigentliche Hebel: Er kodiert die Umgebung, und die Umgebung ist die Grenze, an der Berechtigungen ansetzen.\n\n```bash\n# resolve runtime config just-in-time, scoped by environment path\naws ssm get-parameters-by-path \\\n  --path \"/myapp/production/\" \\\n  --with-decryption \\\n  --query \"Parameters[].{Name:Name,Value:Value}\"\n```\n\nDer Pfad `/myapp/production/` ist mehr als Kosmetik. Er erlaubt es, Least-Privilege sauber auszudrücken: Ein Deploy-Job für Staging bekommt eine IAM-Policy, die genau auf `staging/*` zeigt und Production nicht einmal lesen kann.\n\n```json\n{\n  \"Effect\": \"Allow\",\n  \"Action\": \"ssm:GetParametersByPath\",\n  \"Resource\": \"arn:aws:ssm:eu-central-1:123456789012:parameter/myapp/staging/*\"\n}\n```\n\nDamit ist die fachliche Absicht in der Infrastruktur verankert statt in einem Wiki-Satz. Der Wert wird zur Laufzeit aufgelöst und nie in Repo oder Image geschrieben:\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# inject secrets at container start, keep them out of the image and the repo\nexport DATABASE_URL=\"$(aws ssm get-parameter \\\n  --name \"/myapp/production/database-url\" \\\n  --with-decryption --query \"Parameter.Value\" --output text)\"\nexec node dist/server.js\n```\n\nOb dahinter Parameter Store, Secrets Manager oder ein Vault steht, ist die kleinere Frage. Die größere ist, dass der Zugriff pro Umgebung getrennt, auditierbar und rotierbar ist. Das Werkzeug drückt die Grenze aus – es erzeugt sie nicht.\n\n## Skizze\n\n```mermaid\nflowchart LR\n  Repo[Code<br/>ohne Secrets] --> Build[Build<br/>reproduzierbares Artefakt]\n  Build --> Registry[Artefakt<br/>je Umgebung gleich]\n  Store[Parameter Store<br/>je Umgebung getrennt] --> Runtime\n  Registry --> Runtime[Runtime<br/>injiziert Config just-in-time]\n```\n\nDie Skizze zeigt die eine Aussage, auf die es ankommt: Der linke Pfad ist überall identisch, der Secret-Pfad kommt getrennt und erst ganz rechts hinzu. Genau an dieser Kreuzung entscheidet sich, ob ein Team schnell und sicher liefern kann oder beides gegeneinander eintauscht.\n\n## Die Trade-offs, die man wirklich abwägt\n\nKein Ansatz ist umsonst. Ein umgebungsneutrales Artefakt plus Laufzeit-Injektion braucht eine funktionierende Secret-Quelle in jeder Umgebung und macht den Container-Start abhängig von einem weiteren Dienst. Fällt Parameter Store aus, startet der Service nicht – das ist ein bewusster Preis für die Grenze, kein Versehen. Man federt ihn mit Caching und klaren Fehlermeldungen ab, nicht damit, dass man Secrets doch wieder einbäckt.\n\nUmgekehrt ist die Bequemlichkeit der `.env`-im-Image real: ein Artefakt, keine Abhängigkeit zur Startzeit, lokal leicht zu reproduzieren. Der Preis dafür fällt nur später an – bei Rotation, bei einem Leak, bei der Frage, wer das Staging-Image mit Production-Zugängen in der Hand hatte. Architektur heißt hier, den Preis an die Stelle zu verschieben, an der man ihn kontrollieren kann, statt ihn in einen späteren Incident zu verlagern.\n\nDer zweite Trade-off betrifft Zentralisierung. Eine zentrale Secret-Quelle vereinfacht Rotation und Audit, wird aber selbst zum kritischen Pfad und zur begehrten Grenze. Deshalb ist die Pfad- und IAM-Struktur keine Formalie: Sie ist der Unterschied zwischen „ein Dienst kennt alles“ und „jeder Dienst kennt genau seins“. Zwischen beidem liegt die eigentliche Produktentscheidung.\n\n## Der Fehlerpfad entscheidet, nicht der Happy Path\n\nEine Secret-Architektur ist erst belastbar, wenn der Fehlerpfad beschrieben ist. Im Demo-Modus sieht jeder Ansatz sauber aus. Interessant wird es genau dort, wo Systeme normalerweise brechen.\n\nRotation ist der ehrlichste Test. Kann ich einen kompromittierten Wert ändern, ohne ein Image neu zu bauen und durch alle Umgebungen zu promoten? Bei Laufzeit-Injektion ist das ein Parameter-Update plus Neustart. Beim eingebackenen Secret ist es ein voller Release-Zyklus unter Zeitdruck – der schlechteste Moment für einen langen Weg.\n\nRollback ist der zweite Test. Ein zurückgerolltes Image bringt bei sauberer Trennung nur alten Code mit, nicht alte Secrets. Vermischt man beides, rollt man mit dem Code auch stillschweigend abgelaufene oder rotierte Zugangsdaten zurück. Und drittens der Audit: Wenn ein Wert leakt, will ich rekonstruieren, welcher Job ihn wann gelesen hat. Ein zentraler Store mit Zugriffs-Logs beantwortet das; eine Datei in einem Layer beantwortet es nicht. Diese Fragen wirken trocken, sind aber der Unterschied zwischen Demo und Betrieb.\n\n## Der Business-Outcome ist Tempo bei kontrolliertem Risiko\n\nDer Grund, warum ich Secrets als Produktentscheidung behandle, ist messbar. Wenn ein Team Secrets nicht mehr manuell durchreichen muss, verschwindet eine ganze Klasse von Wartezeit. Ein Entwickler deployt nach Staging, ohne dass jemand aus dem Ops-Team ein Passwort per Chat kopiert – die IAM-Policy erlaubt genau diesen Pfad und nichts darüber hinaus. Das verkürzt den Zyklus von Idee zu laufender Änderung und senkt gleichzeitig das Risiko, weil der Zugriff eng geschnitten ist. Tempo und Sicherheit stehen hier nicht im Widerspruch; die richtige Grenze liefert beides.\n\nWeniger Reibung entsteht auch dadurch, dass die Grenze im Code steht und nicht im Kopf einer Person. Neue Teammitglieder lesen aus Pfadstruktur und Policy ab, was erlaubt ist, statt es zu erfragen. Und die Qualität steigt, weil der teuerste Fehler – ein Secret im geteilten Artefakt – strukturell nicht mehr passieren kann, statt nur durch Disziplin verhindert zu werden. Genau das meine ich mit Developer Productivity: nicht schneller tippen, sondern seltener warten und seltener aufräumen.\n\nDer Effekt ist kein weiches Versprechen, sondern lässt sich beobachten. Ich messe ihn an drei Zahlen: an der Zeit von „Passwort muss getauscht werden“ bis „getauscht und im Betrieb“, an der Zahl der manuellen Übergaben pro Release und daran, wie viele Umgebungen ein einzelner Zugang lesen kann. Jede dieser Zahlen sinkt, wenn die Build-Runtime-Grenze steht – und jede ist im Zweifel überzeugender als die Behauptung, es sei jetzt sicherer.\n\n## Typische Fehler\n\nDer erste Fehler ist, das Werkzeug mit der Lösung zu verwechseln. Ein Secret-Store ist keine Architektur, KMS ist keine Zugriffsgrenze, und ein `--build-arg` ist keine Vertraulichkeit. Diese Werkzeuge können gute Grenzen ausdrücken, aber sie erzeugen sie nicht automatisch. Wer den Store einführt, ohne die Build-Runtime-Grenze zu ziehen, hat die Datei nur an einen anderen Ort verschoben.\n\nDer zweite Fehler ist, den Happy Path zu überschätzen. Viele Setups sehen im ersten Deploy sauber aus und zeigen ihre Schwäche erst bei der ersten dringenden Rotation. Der dritte ist, alles gleich vertraulich zu behandeln. Eine Feature-Flag-Konfiguration und ein Datenbank-Passwort brauchen unterschiedliche Grenzen; wer beides in denselben Topf wirft, macht den harmlosen Fall teuer und den kritischen Fall bequem.\n\n## Worauf ich prüfe\n\nDrei Checks reichen mir meistens. Erstens: Ist ein Build-Artefakt umgebungsneutral, oder kennt es Secrets? Ein `docker history` und ein Blick in die Layer beantworten das in einer Minute. Zweitens: Ist der Zugriff pro Umgebung getrennt, sodass ein Staging-Job Production nicht lesen kann? Drittens: Kann ich ein Secret rotieren, ohne neu zu bauen, und den Zugriff im Nachhinein nachvollziehen?\n\nWenn eine dieser Fragen mit Nein endet, fehlt noch ein Teil der Architektur – kein weiteres Tool, sondern eine bewusst gezogene Grenze. Ich würde daraus keine große Initiative machen, sondern mit einem kleinen, überprüfbaren Ergebnis beginnen: ein Multi-Stage-Dockerfile, eine IAM-Policy mit Pfad-Scope, ein Startskript, das den Wert just-in-time auflöst. Konkret genug, dass ein anderer Entwickler sinnvoll widersprechen kann. Zustimmung ist gut, aber Widerspruch zeigt oft die versteckte Annahme.\n\n## Schluss\n\nEin Secret sicher abzulegen ist die kleinere Hälfte der Arbeit. Die größere ist die Begründung, warum die Grenze zwischen Build und Runtime genau dort verläuft. Entscheidend sind das konkrete Risiko, die erlaubten Zugriffe und die Frage, ob sich ein kompromittierter Wert unabhängig vom Artefakt rotieren lässt. Der Name des Secret-Stores kommt danach."},{"locale":"de","translation_key":"product-discovery-vor-der-ersten-zeile","slug":"product-discovery-vor-der-ersten-zeile","title":"Product Discovery vor der ersten Zeile Code","summary":"Discovery senkt das Risiko, effizient das Falsche zu bauen. Ich zeige eine kontinuierliche Spur, die Annahmen prüft, bevor sie teure Delivery bindet – nicht eine Phase vor der Entwicklung.","tags":["Software","Produkt"],"published_at":"2019-06-26T10:00:00+00:00","updated_at":"2026-07-14T20:59:37.10998+00:00","url":"https://www.mikebild.dev/de/blog/product-discovery-vor-der-ersten-zeile/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/4d60ac3c1a16425e7e0ae58c5bca777dc004e8352ef94796a728c77b3c003965/product-discovery-vor-der-ersten-zeile-vorlesen.mp3","audio_duration_secs":669,"text":"Die teuersten Zeilen Code, die ich in Projekten gesehen habe, waren technisch tadellos. Sauber getestet, elegant strukturiert, in einer Continuous-Delivery-Pipeline mehrmals am Tag ausgeliefert. Nur: Sie lösten ein Problem, das niemand hatte. Ein halbes Jahr Entwicklungskapazität, ein makelloses Feature, und beim ersten echten Nutzerkontakt kippte die Grundannahme. Sauberes Handwerk sagt eben nichts darüber aus, ob am Ende jemand etwas davon hat. Diese Frage stellt keine Pipeline.\n\nGenau hier setzt Product Discovery an. Und ich meine damit nicht eine vorgeschaltete Analysephase, in der sechs Wochen lang Dokumente entstehen, bevor irgendjemand Code anfassen darf. Ich meine eine parallele, kontinuierliche Spur. Eine Annahme wird mit dem billigsten sinnvollen Versuch konfrontiert, bevor das Team sie als Feature ausbaut. Darum geht es in diesem Artikel.\n\n## Discovery und Delivery sind zwei Spuren, keine Phasen\n\nDer häufigste Denkfehler ist, Discovery als Vorstufe zu begreifen. Erst denken, dann bauen. Das ist Wasserfall im neuen Gewand. Der Ansatz, den Marty Cagan und Jeff Patton unter dem Begriff Dual-Track Agile popularisiert haben, meint etwas anderes: zwei Spuren, die dauerhaft nebeneinanderlaufen. Die Discovery-Spur klärt, *was* gebaut werden sollte. Die Delivery-Spur baut es solide. Beide laufen in jedem Sprint, nicht nacheinander.\n\nDer Trick liegt in der Größe der Übergabe. Bevor ein Team ein großes oder schwer umkehrbares Vorhaben in Delivery bindet, sollte die riskanteste Annahme dahinter geprüft sein. Kleine technische Spikes und dünne, reversible Schnitte dürfen früher in Delivery laufen und selbst Evidenz erzeugen. Dual Track ist keine harte Schleuse zwischen Denken und Bauen.\n\n```mermaid\nflowchart LR\n  subgraph Discovery\n    A[Idea] --> B[Assumption]\n    B --> C[Experiment]\n    C --> D[Validated item]\n  end\n  subgraph Delivery\n    E[Build] --> F[Test]\n    F --> G[Release]\n  end\n  D -->|only validated work<br/>enters delivery| E\n```\n\nDer Pfeil in der Mitte ist die eigentliche Botschaft. Er ist ein Filter. Alles, was ihn passiert, hat eine Prüfung bestanden. Alles, was in der Discovery-Spur scheitert, hat nie ein Entwicklerteam belastet. Das ist der Hebel: Ein verworfenes Experiment kostet Stunden, ein verworfenes Feature kostet Monate.\n\nEbenso wichtig ist, wer Discovery betreibt. Es ist keine Aufgabe, die eine vorgelagerte Analyseabteilung erledigt und dann als fertige Spezifikation weiterreicht. Teams, die das gut machen, setzen Produktverantwortung, Design und Engineering gemeinsam an die Discovery-Spur – das Trio, das Marty Cagan beschreibt. Der Entwickler, der die Machbarkeit einschätzt, hört im selben Nutzergespräch, warum ein Feature überhaupt gewünscht ist. Die Designerin, die einen Prototyp baut, versteht die technischen Grenzen aus erster Hand. Diese geteilte Verantwortung ist der Grund, warum Discovery schnell bleibt: Entscheidungen fallen dort, wo das Wissen sitzt, ohne den Umweg über Übergabedokumente. Wer Discovery an eine einzelne Rolle delegiert, holt sich die Wasserfall-Dynamik zurück, die der Dual-Track-Ansatz gerade vermeiden will.\n\n## Die vier großen Risiken, die Discovery adressiert\n\nAuf die Frage, *warum* ein bestimmtes Feature gebaut werden soll, kommt in Diskussionen meist eine Antwort, die nur eine einzige Dimension abdeckt. Cagan hat in der zweiten Auflage von *INSPIRED* vier Risikoklassen benannt, die jede ernsthafte Discovery abklopfen muss:\n\nValue-Risiko fragt, ob Nutzer das überhaupt wollen und ob sie dafür wechseln oder zahlen. Usability-Risiko fragt, ob sie es bedienen können. Feasibility-Risiko fragt, ob wir es mit unserer Zeit, unseren Daten und unserer Technik bauen können. Und Viability-Risiko fragt, ob es zum Geschäft passt – rechtlich, wirtschaftlich, strategisch.\n\nFeasibility zieht die Aufmerksamkeit an, weil es die Frage ist, die Entwickler am liebsten beantworten. \"Können wir das bauen?\" ist fast immer mit \"ja\" zu beantworten. Die teuren Fehlschläge sitzen aber im Value- und im Viability-Risiko. Discovery zwingt dazu, alle vier zu betrachten, bevor die erste Story geschnitten wird.\n\n## Annahmen sichtbar und priorisierbar machen\n\nDer praktischste Schritt ist banal und wirkungsvoll zugleich: Annahmen aufschreiben. Jede Produktidee ist ein Stapel unausgesprochener Wetten. \"Nutzer wollen ihre Reports selbst konfigurieren.\" \"Die Bezahl-API hält unsere Latenz-Anforderung.\" \"Der Vertrieb kann das ohne Schulung verkaufen.\" Solange diese Sätze im Kopf bleiben, kann man sie nicht testen und nicht priorisieren.\n\nDavid J. Bland hat mit dem Assumptions Mapping ein einfaches Werkzeug etabliert: eine Matrix aus zwei Achsen. Die eine Achse misst, wie wichtig eine Annahme ist – fällt das ganze Vorhaben, wenn sie falsch ist? Die andere misst, wie viel Evidenz wir schon haben. Der Quadrant oben rechts, wichtig und kaum belegt, wird zuerst getestet. Das ist die riskanteste Annahme, und sie verdient den ersten Test.\n\n```mermaid\nquadrantChart\n  title Assumptions Map\n  x-axis Low evidence --> High evidence\n  y-axis Low importance --> High importance\n  quadrant-1 Test first\n  quadrant-2 Keep as leap of faith\n  quadrant-3 Ignore for now\n  quadrant-4 Already known\n  Users self-configure reports: [0.2, 0.9]\n  Payment API meets latency SLA: [0.35, 0.85]\n  Sales can sell without training: [0.6, 0.4]\n  Login flow is usable: [0.8, 0.3]\n```\n\nDiesen Zustand lege ich versioniert im Repository ab, statt ihn an ein Whiteboard zu heften. Ein Assumption-Register neben dem Code macht die Wetten Teil des Projekts und nicht Teil eines vergessenen Workshops:\n\n```yaml\n# assumptions.yaml — reviewed before any story enters delivery\nassumptions:\n  - id: A-1\n    statement: \"Users will self-configure their reports instead of asking support\"\n    type: desirability\n    importance: high\n    evidence: low\n    test: landing-page\n    kill_criterion: \"signup-to-config rate below 20% after 200 visitors\"\n  - id: A-2\n    statement: \"The payment API stays under our latency budget at peak load\"\n    type: feasibility\n    importance: high\n    evidence: low\n    test: spike\n    kill_criterion: \"p95 response time above 200ms in a load test\"\n  - id: A-3\n    statement: \"Sales can close the feature without extra training\"\n    type: viability\n    importance: medium\n    evidence: low\n    test: interview\n    kill_criterion: \"3 of 5 reps ask for a dedicated enablement session\"\n```\n\nFür einen bestätigenden Test ist `kill_criterion` das entscheidende Feld. Wer erst nach dem Test entscheidet, was ein gutes Ergebnis gewesen wäre, findet leicht eine Erklärung, warum die Lieblingsidee doch gewonnen hat. Explorative Discovery darf offener beginnen; sobald eine konkrete Hypothese entschieden werden soll, gehört das Kriterium vorher festgeschrieben.\n\n## Fortschritt heißt validiertes Lernen, nicht ausgelieferte Features\n\nEric Ries hat in *The Lean Startup* den Begriff geprägt, an dem ich mich bis heute ausrichte: validated learning. Fortschritt misst sich an Annahmen, die wir belastbar geklärt haben, und nicht an Features im Release. Der Build-Measure-Learn-Kreis dreht sich um genau diese Frage: Was ist der schnellste Weg, um eine Wette zu prüfen?\n\nHier lauert das größte Missverständnis rund um das MVP. Ein Minimum Viable Product ist kein billiges, halbfertiges Produkt. Es ist das Experiment mit dem größten Lernertrag pro Aufwand. Sehr oft enthält es gar keinen Code. Eine Landingpage, die ein noch nicht existierendes Feature bewirbt und Anmeldungen zählt. Ein Concierge-Ansatz, bei dem ein Mensch manuell tut, was später Software tun soll. Ein Demo-Video, das die Reaktion misst. Für die Annahme A-1 oben ist die Landingpage schneller und ehrlicher als jede Implementierung. Sie beantwortet die Value-Frage in Tagen statt in Monaten.\n\nWenn das Ergebnis eindeutig gegen die Annahme spricht, ist die richtige Reaktion nicht, trotzdem zu bauen. Es ist der Pivot – die Richtung ändern und eine andere Wette angehen. Das fällt Teams schwer, weil verworfene Ideen sich wie Scheitern anfühlen. Sie sind das Gegenteil. Jede früh gekippte Annahme ist eingespartes Kapital.\n\n## Auch technische Annahmen gehören getestet\n\nDiscovery ist kein reines Produkt- oder UX-Thema. Das Feasibility-Risiko ist oft die stillste und teuerste Wette. \"Die Bezahl-API hält unsere Latenz\" ist eine technische Annahme, die man greifbar machen kann, bevor ein Feature darauf aufbaut. Ich formuliere solche Annahmen als ausführbaren Test – eine Fitness Function im Sinne von *Building Evolutionary Architectures*. Sie macht ein Qualitätsziel messbar und wiederholbar:\n\n```typescript\n// fitness function — runs the riskiest technical assumption as a test\nimport { measureP95 } from \"./load-harness\";\n\nconst SLA_MS = 200;\n\ntest(\"checkout endpoint stays under the latency budget at peak load\", async () => {\n  const p95 = await measureP95({\n    endpoint: \"/api/checkout\",\n    concurrentUsers: 500,\n    durationSeconds: 60,\n  });\n\n  expect(p95).toBeLessThan(SLA_MS);\n});\n```\n\nDer Wert dieses Tests zeigt sich in dem Moment, in dem er rot wird, bevor ein Feature live geht. Dann wissen wir: Die technische Annahme trägt nicht. Besser jetzt als in der Produktion. Dieselbe Denkweise gilt für Ausfallverhalten. Wenn ein Feature von einem externen Dienst abhängt, ist die Annahme \"der Dienst ist verfügbar\" eine Wette, die man mit Stabilitätsmustern wie einem Circuit Breaker aus Michael Nygards *Release It!* entschärft – und mit Consumer-Driven Contract Tests, die prüfen, ob zwei Dienste sich noch verstehen, bevor der Bruch in Produktion auffällt.\n\n## Warum Effizienz allein nicht schützt\n\nDer naheliegende Einwand lautet: \"Wir liefern doch schon schnell und stabil aus.\" Und ja, das ist wertvoll. Das Buch *Accelerate* von Nicole Forsgren, Jez Humble und Gene Kim hat mit vier Kennzahlen gezeigt, wie sich Auslieferungsqualität messen lässt: Deployment Frequency, Lead Time for Changes, Change Failure Rate und Mean Time to Restore. Teams, die hier stark sind, liefern häufig, schnell und mit wenig Fehlern.\n\nNur misst keine dieser Kennzahlen, ob das Richtige gebaut wird. Sie messen, wie gut die Delivery-Spur läuft. Ein Team mit Bestwerten kann mit hoher Frequenz Features ausliefern, die niemand braucht. Tempo beim Bauen des Falschen ist immer noch Verschwendung – nur schnellere. Deshalb gehören beide Spuren zusammen: Discovery sorgt dafür, dass wir am Richtigen arbeiten, Delivery-Exzellenz sorgt dafür, dass wir es gut bauen. Wer nur die zweite Hälfte optimiert, baut sich am Ende die effizienteste Art, Geld zu verbrennen.\n\nGenau das ist der ökonomische Kern. Discovery ist keine zusätzliche Prozessschicht, die Zyklen verlangsamt. Sie verkürzt den Zyklus, der wirklich zählt: von der Idee bis zur validierten Erkenntnis. Ein Landingpage-Test dauert Tage. Ein fehlgeleitetes Feature dauert Monate und fällt trotzdem. Discovery tauscht die teure, späte Rückmeldung des Marktes gegen eine billige, frühe Rückmeldung im Experiment.\n\n## Wie das im Alltag konkret aussieht\n\nIch fasse die Methodik in wenige Gewohnheiten, die ohne schweres Framework auskommen. Vor jedem größeren Vorhaben werden die Annahmen aufgeschrieben und auf der Zwei-Achsen-Matrix eingeordnet. Die riskanteste Annahme bekommt einen passenden Versuch; ein bestätigender Test erhält ein vorab definiertes Entscheidungskriterium. Technische Wetten werden als Fitness Function oder Spike geprüft, nicht als Bauchgefühl abgenickt. Solange die größte Unsicherheit offen ist, bleibt die Delivery-Investition klein und umkehrbar.\n\nDas klingt nach mehr Arbeit vorne. In der Praxis kann es große Umwege verkürzen, garantiert sie aber nicht. Die Teams, mit denen ich so arbeite, streiten weniger über Meinungen und mehr über Evidenz. Eine Landingpage mit zweihundert Besuchern kann ein Signal liefern, wenn Zielgruppe, Traffic-Quelle und erwarteter Effekt dazu passen; sie ersetzt weder sauberes Stichprobendesign noch qualitative Rückfragen. Was dabei verschwindet, ist ein Teil der unproduktiven Reibung zwischen Meinungen ohne Daten. Die produktive Reibung am Problem bleibt.\n\n## Fazit\n\nDie erste Zeile Produktionscode erhöht die Investition, ist aber kein unumkehrbarer Grenzübertritt. Product Discovery hält die riskantesten Entscheidungen so lange klein, bis es genug Evidenz für den nächsten Einsatz gibt. Discovery und Delivery laufen dabei parallel: Die eine Spur klärt, was zu bauen ist, die andere liefert kleine, belastbare Schritte und kann selbst Teil des Experiments sein.\n\nDer rote Faden ist einfach: Man kann alles technisch richtig machen und trotzdem das Falsche liefern. Effizienz in der Auslieferung ist notwendig, aber sie ist kein Ersatz für die Frage, ob wir am Richtigen arbeiten. Wer Annahmen sichtbar macht, die riskanteste zuerst prüft und für bestätigende Tests ein Entscheidungskriterium festlegt, verbessert die Chance auf kürzere Lernzyklen und begründete Entscheidungen. Discovery bleibt Arbeit; ihr Wert liegt darin, teure Gewissheit nicht mit unbelegter Zuversicht zu verwechseln.\n\n## Weiterführende Quellen\n\n- Marty Cagan: *INSPIRED* (2. Auflage, 2017) und die \"four big risks\" auf svpg.com/four-big-risks\n- Jeff Patton und Marty Cagan zu Dual-Track Agile, jpattonassociates.com und svpg.com\n- Eric Ries: *The Lean Startup* (2011), Build-Measure-Learn und MVP, theleanstartup.com\n- David J. Bland: Assumptions Mapping, precoil.com und strategyzer.com\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate* (2018)\n- Neal Ford, Rebecca Parsons, Patrick Kua: *Building Evolutionary Architectures* (2017)\n- Michael Nygard: *Release It!* zu Circuit Breaker und Stability Patterns"},{"locale":"de","translation_key":"cqrs-fachliche-grenze-kein-framework","slug":"cqrs-fachliche-grenze-kein-framework","title":"CQRS ist eine fachliche Grenze, kein Framework","summary":"CQRS trennt das Modell zum Schreiben vom Modell zum Lesen – eine fachliche Entscheidung, kein installierbares Framework. Wann sich die Grenze lohnt, wie man klein anfängt und welche Verwechslungen teuer werden.","tags":["Software","Architektur"],"published_at":"2019-06-25T10:00:00+00:00","updated_at":"2026-07-13T08:37:17.581144+00:00","url":"https://www.mikebild.dev/de/blog/cqrs-fachliche-grenze-kein-framework/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ae168475354eb8f05b2bddb88a78a0dbcba066b36d081702aea7bb81285337c4/cqrs-fachliche-grenze-kein-framework-vorlesen.mp3","audio_duration_secs":723,"text":"Zwei Fragen stellt jede Anwendung an ihre Daten: Was soll sich ändern? Und was soll angezeigt werden? Die meisten Systeme beantworten beide mit demselben Modell – denselben Entities, demselben Mapping, denselben Objekten. CQRS beantwortet sie mit zwei.\n\nDie häufigste Anschlussfrage an das Akronym – Command Query Responsibility Segregation – dreht sich trotzdem um Werkzeuge: Welche Library, welches Paket? Danach sucht man vergeblich. Die Grenze zwischen Schreib- und Lesemodell verläuft durch die Domäne, nicht durch den Dependency-Baum. Was CQRS ist, was es ausdrücklich nicht ist, wann sich die Trennung lohnt und wo die teuersten Fehler liegen – darum geht es hier. Das Ergebnis ist unspektakulärer, als das Akronym verspricht, und genau das ist die gute Nachricht.\n\n## Woher der Begriff kommt\n\nCQRS steht für Command Query Responsibility Segregation. Der Kern ist eine einzige Idee: Man verwendet ein anderes Modell zum Ändern von Informationen als das Modell zum Lesen. Was in klassischen Systemen ein einziges konzeptionelles Modell ist – dieselben Entities, mit denen man schreibt und liest –, wird bewusst in zwei getrennte Modelle gespalten. Eines für Commands, also für Absichten und Änderungen. Eines für Queries, also für Sichten und Queries.\n\nMartin Fowler bringt die Begründung auf den Punkt: Für viele Probleme, besonders in komplexeren Domänen, führt ein gemeinsames konzeptionelles Modell für Commands und Queries zu einem Modell, das beide Aufgaben schlechter erfüllt, als zwei spezialisierte Modelle es täten. Fowler selbst hörte den Begriff zuerst bei Greg Young, der CQRS um 2010 prägte und ausformulierte.\n\nWichtig ist die Abgrenzung zu einem älteren Prinzip, mit dem CQRS gern verwechselt wird: Command Query Separation, kurz CQS, von Bertrand Meyer. CQS trennt auf Methodenebene – eine Methode ist entweder ein Command, der Zustand verändert und nichts zurückgibt, oder eine Query, die einen Wert liefert, ohne Zustand zu ändern. CQRS hebt genau dieses Prinzip auf die Architekturebene: nicht mehr zwei Arten von Methoden, sondern zwei getrennte Objektmodelle. CQRS baut konzeptionell auf CQS auf, arbeitet aber viel gröber.\n\n## Die zwei Seiten haben eine unterschiedliche Form\n\nSchreib- und Leseseite haben nicht nur unterschiedliche Aufgaben, sie haben eine unterschiedliche Form. Das ist keine kosmetische Beobachtung, sondern der eigentliche Grund für die Trennung.\n\nDie Schreibseite arbeitet mit einem reichen Domänenmodell. Hier liegen die Invarianten, die fachlichen Regeln, die entscheiden, ob eine Änderung überhaupt erlaubt ist. Ein Command ist der Ausdruck einer fachlichen Absicht – imperativ formuliert, benennbar, ablehnbar. `DeactivateInventoryItem` ist kein Datensatz-Update, sondern eine Aussage: „Ich möchte diesen Artikel deaktivieren.“ Das passt hervorragend zu aufgabenorientierten Oberflächen, in denen der Nutzer Absichten äußert statt Formularfelder zu befüllen.\n\nDie Leseseite dagegen will nichts entscheiden. Sie will anzeigen. Ihre natürliche Form sind flache, auf die Darstellung zugeschnittene DTOs – oft eine direkte Projection dessen, was am Bildschirm erscheint. Regeln, Invarianten, Verhalten: All das braucht die Leseseite nicht. In ein reiches Domänenmodell zwingt man sie nur, weil es zufällig schon da ist.\n\nGenau hier setzt CQRS an. Statt beide Seiten in ein Modell zu pressen, das keine von beiden gut bedient, gibt man jeder Seite die Form, die sie verdient.\n\n```mermaid\nflowchart LR\n    Client -->|Command| CommandHandler\n    CommandHandler --> WriteModel\n    WriteModel --> Store[(Store)]\n    Client -->|Query| QueryService\n    QueryService --> ReadModel\n    ReadModel --> Store\n```\n\nMan beachte: Beide Pfade können denselben Store nutzen. Dazu gleich mehr – es ist wichtiger, als es aussieht.\n\n## Ein Blick auf die Schreibseite\n\nIllustrativ, in TypeScript. Die Schreibseite nimmt einen Command entgegen, lädt das reiche Write Model, lässt es die fachliche Regel durchsetzen und speichert.\n\n```ts\ninterface DeactivateInventoryItem {\n  itemId: string;\n  reason: string;\n}\n\nclass InventoryCommandHandler {\n  constructor(private readonly repo: InventoryItemRepository) {}\n\n  handle(cmd: DeactivateInventoryItem): void {\n    const item = this.repo.findById(cmd.itemId); // rich write model\n    item.deactivate(cmd.reason);                 // domain rule enforced here\n    this.repo.save(item);\n  }\n}\n```\n\nDas Interessante steht in der mittleren Zeile. `item.deactivate(cmd.reason)` ist der Ort, an dem die Fachlichkeit sitzt. Ob ein Artikel deaktiviert werden darf, ob ein Grund verpflichtend ist, ob ein bereits deaktivierter Artikel den Command ablehnt: Das entscheidet das Domänenobjekt, nicht der Handler. Der Command-Handler ist bewusst dünn. Er orchestriert, er entscheidet nicht.\n\n## Und ein Blick auf die Leseseite\n\nDie Leseseite ignoriert dieses reiche Modell vollständig. Sie fragt eine auf Anzeige optimierte Sicht ab und gibt ein flaches DTO zurück.\n\n```ts\ninterface InventoryListItemDto {\n  id: string;\n  name: string;\n  isActive: boolean;\n}\n\nclass InventoryQueryService {\n  constructor(private readonly readDb: ReadDatabase) {}\n\n  listActiveItems(): InventoryListItemDto[] {\n    return this.readDb.query(\n      \"SELECT id, name, is_active FROM inventory_view WHERE is_active = true\",\n    );\n  }\n}\n```\n\nKein Repository, kein Domänenobjekt, keine Invariante. Nur eine Query gegen eine Sicht, die genau das liefert, was die Liste braucht. Man könnte einwenden, dass hier rohes SQL direkt in einem Service steht – für die Leseseite ist das oft genau richtig. Es gibt nichts zu schützen, keine Regel zu wahren. Der Umweg über ein reiches Modell wäre reine Zeremonie.\n\nDer Punkt, auf den alles hinausläuft: Diese beiden Klassen kennen einander nicht. Sie teilen kein gemeinsames Modell. Sie sind zwei getrennte Antworten auf zwei getrennte Fragen. Das ist CQRS.\n\n## Klein anfangen – ein Store genügt\n\nUnd jetzt kommt der Teil, der die meisten überrascht. Nichts an den beiden Beispielen oben verlangt zwei Datenbanken. `InventoryItemRepository` auf der Schreibseite und `readDb` auf der Leseseite können auf dieselbe Datenbank zeigen. Fowler formuliert es unmissverständlich: Die Modelle können sich denselben Datenspeicher teilen – die Datenbank dient dann als Kommunikationskanal zwischen beiden Modellen.\n\nDas bedeutet: Man kann CQRS praktizieren, ohne einen einzigen zusätzlichen Store einzuführen. Ein reiches Schreibmodell, das gegen die Tabellen arbeitet. Eine Sicht oder ein View, den die Leseseite direkt abfragt. Beides in derselben Datenbank. Man hat die fachliche Trennung, ohne sich einen zweiten Datenspeicher und dessen Konsequenzen einzukaufen.\n\nIn einem Projekt hatten wir das Muster jahrelang aufgeschoben, weil es als unerschwinglich galt – zu viel Infrastruktur, zu viel Betrieb. Die Sorge beruhte auf einer Verwechslung: CQRS wurde mit einer bestimmten, aufwendigen Ausbaustufe von CQRS gleichgesetzt. Die Trennung der Modelle ist billig. Was Geld kostet, sind getrennte Stores, und die sind optional.\n\n## Was CQRS ist – und was nicht\n\nWeil sich rund um den Begriff so viele Halbwahrheiten sammeln, hier die klare Sortierung. CQRS ist:\n\n- die fachliche Trennung von Schreib- und Lesemodell,\n- ein Muster für ausgewählte Bounded Contexts,\n- kombinierbar mit Event Sourcing, wenn die Domäne es rechtfertigt,\n- von Anfang an mit einem einzigen Store praktizierbar.\n\nCQRS ist nicht:\n\n- ein Framework oder eine Library,\n- ein Synonym für Event Sourcing,\n- eine Pflicht zu zwei Datenbanken,\n- ein systemweiter Architekturstandard, den man überall ausrollt.\n\nAn dieser zweiten Liste hängt der meiste Ärger, den ich in Reviews sehe.\n\n## Die drei teuersten Verwechslungen\n\nDie erste ist der Versuch, CQRS überall einzusetzen. Es ist ein Minderheitsfall, kein Default. Fowler warnt ausdrücklich, dass CQRS für die meisten Systeme riskante Komplexität hinzufügt und man beim Einsatz sehr vorsichtig sein sollte. Die Trennung gehört in einen einzelnen Bounded Context, wo die Domäne sie rechtfertigt – nicht in jedes Modul, nicht in jede Entity. Wer CQRS systemweit ausrollt, zahlt überall die Kosten der Trennung und erntet den Nutzen nur an den wenigen Stellen, an denen die Modelle wirklich auseinanderdriften.\n\nDie zweite ist, CQRS mit Event Sourcing zu verwechseln. Das ist die häufigste Verwechslung überhaupt, und ich verstehe, woher sie kommt – die beiden treten in Vorträgen und Beispielen fast immer gemeinsam auf. Aber sie sind unabhängige Muster. Event Sourcing ist eine Entscheidung über Persistenz: Statt den aktuellen Zustand zu speichern, speichert man die Folge der Events, die zu ihm führten. CQRS ist eine Entscheidung über Modelle: Schreiben und Lesen bekommen getrennte Modelle. Man kann jedes ohne das andere haben. Vaughn Vernon zeigt in seinen IDDD-Beispielen zwar Kontexte, die Event Sourcing und CQRS kombinieren – aber auch dort bleibt es eine bewusste Kombination zweier Muster, keine Definition, in der eines das andere enthält. Wer CQRS sagt und Event Sourcing meint, verhandelt in Diskussionen ständig aneinander vorbei.\n\nDie dritte ist, zwei Datenbanken zu früh einzuführen. Getrennte Read- und Write-Stores sind eine optionale, spätere Optimierung – meist getrieben von asymmetrischer Last, wenn man Lese- und Schreibseite unabhängig skalieren will. Führt man sie zu früh ein, holt man sich zwei Kosten ins Haus, bevor irgendein Bedarf erwiesen ist: den Synchronisationsaufwand zwischen den Stores und, schwerwiegender, eventual consistency. Ab dem Moment, in dem der Read Store dem Write Store hinterherläuft, sieht der Nutzer möglicherweise Daten, die schon veraltet sind. Das ist ein fachliches Problem, kein technisches Detail – und man sollte es sich nur einhandeln, wenn man dafür einen konkreten Grund hat.\n\nSo sähe diese Ausbaustufe aus – die man bewusst erst dann geht, wenn die Last es verlangt:\n\n```mermaid\nflowchart LR\n    CommandHandler --> WriteModel\n    WriteModel --> WriteStore[(Write Store)]\n    WriteStore -.->|projection<br/>eventual consistency| ReadStore[(Read Store)]\n    QueryService --> ReadStore\n```\n\nDer gestrichelte Pfeil ist der Preis. Zwischen Write Store und Read Store liegt jetzt eine Projection, und mit ihr eine Verzögerung. Solange dieser Pfeil nicht nötig ist, sollte er nicht existieren.\n\n## Wann sich die Grenze wirklich lohnt\n\nNach all den Warnungen die konstruktive Seite: Es gibt Situationen, in denen CQRS die richtige Antwort ist. Ich sehe im Wesentlichen drei.\n\nDie erste sind komplexe Domänen, in denen ein gemeinsames Modell keine Seite gut bedient. Wenn das Schreibmodell vor lauter Invarianten und Verhalten kaum noch abfragbar ist und die Leseseite sich mühsam durch dieses Modell quält, um simple Listen zu erzeugen, dann kämpfen beide gegen dieselbe Struktur. Die Trennung befreit beide.\n\nDie zweite ist asymmetrische Last. Viele Systeme lesen um Größenordnungen häufiger, als sie schreiben. Getrennte Modelle – und, in der Ausbaustufe, getrennte Stores – erlauben es, die Leseseite unabhängig zu skalieren, ohne die Schreibseite anzufassen.\n\nDie dritte sind aufgabenorientierte Oberflächen. Wenn die UI ohnehin in Absichten denkt – „Artikel deaktivieren“, „Bestellung stornieren“ – statt in CRUD-Formularen, dann liegt die Command-Seite von CQRS ohnehin schon in der Luft. Man muss sie nur noch benennen.\n\nAlle drei Kriterien haben denselben Ursprung: Die Struktur folgt aus der Fachlichkeit, nicht aus dem Wunsch nach einem modernen Diagramm. CQRS ist kein Ziel. Es ist eine Antwort – und nur dort richtig, wo die Domäne die passende Frage stellt.\n\n## Fazit\n\nWer CQRS als Framework begreift, sucht an der falschen Stelle. Es gibt nichts zu installieren. Die einzige Entscheidung, die zählt, ist eine fachliche: Profitiert diese Domäne davon, dass Schreiben und Lesen unterschiedliche Modelle bekommen? Wenn ja, zieht man die Grenze – klein, mit einem einzigen Store, ohne Event Sourcing, in einem einzelnen Bounded Context. Wenn nein, lässt man es, und das ist der häufigere Fall.\n\nDie getrennten Datenbanken, die Projections, die eventual consistency – all das sind spätere, optionale Ausbaustufen, die man geht, wenn die Last es verlangt, und nicht früher. CQRS mit diesen Ausbaustufen gleichzusetzen ist der Fehler, der das Muster teuer und angsteinflößend macht. In seiner Essenz ist es das Gegenteil: eine unspektakuläre, billige, fachlich motivierte Trennung. Zwei Fragen, zwei Modelle. Mehr braucht es nicht, um anzufangen.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html\n- Martin Fowler, „CQRS“: [martinfowler.com/bliki/CQRS.html](https://martinfowler.com/bliki/CQRS.html)\n- Martin Fowler, „CommandQuerySeparation“: [martinfowler.com/bliki/CommandQuerySeparation.html](https://martinfowler.com/bliki/CommandQuerySeparation.html)\n- Greg Young, „CQRS Documents“ (PDF): [cqrs.wordpress.com](https://cqrs.wordpress.com/documents/)\n- Vaughn Vernon, „Implementing Domain-Driven Design“, Kapitel 4 (Architecture / CQRS), sowie die [IDDD_Samples](https://github.com/VaughnVernon/IDDD_Samples)\n- Mein eigenes Vortragsmaterial „CQRS + Event Sourcing“ (SlideShare), aus dem ein Teil der hier gezeigten Beispiele stammt"},{"locale":"de","translation_key":"nodejs-training-event-loop-architektur","slug":"nodejs-training-event-loop-architektur","title":"Node.js-Training: Vom Event Loop zur Architekturentscheidung","summary":"Node.js lässt sich nicht am Framework erklären, sondern am Event Loop, an Streams und an der Frage, welche Architekturentscheidung ein Team morgen noch versteht – genau das übe ich mit Teilnehmenden im Repo introduction-nodejs.","tags":["Software","Node.js","Backend"],"published_at":"2019-05-12T10:00:00+00:00","updated_at":"2026-07-13T08:37:03.3766+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/29735c31777bf26bfd87b2f5ba9736e54b77af7bb892d1e7d1ec8c4a818d2442/nodejs-training-event-loop-architektur-vorlesen.mp3","audio_duration_secs":1215,"text":"# Node.js-Training: Vom Event Loop zur Architekturentscheidung\n\nExpress beantwortet genau eine Frage: welche Funktion bei welcher URL läuft. Die Fragen, an denen ein Node-Backend im Betrieb tatsächlich scheitert, beantwortet es nicht – was passiert, wenn ein einzelner Aufruf den einzigen Thread blockiert, wenn eine Antwort größer wird als der freie Speicher, wenn eine Promise abgelehnt wird und niemand zuhört. Wer mit einem Framework anfängt, lernt eine API auswendig. Wer mit dem Event Loop anfängt, versteht, warum diese API so aussieht, wie sie aussieht, und was genau passiert, wenn man sie falsch benutzt.\n\nDie Frage \"Warum bauen wir das nicht einfach mit Express?\" kommt in Node-Trainings – ob direkt oder über Partner wie [Grossweber](https://grossweber.com/) – trotzdem sehr früh. Sie ist berechtigt und trotzdem verfrüht. Der Anfang liegt deshalb woanders: bei einer einzigen Zeile, die auf den ersten Blick nichts mit Architektur zu tun hat.\n\n## Der erste Codeschnipsel, der schon alles zeigt\n\n```js\nconst fs = require(\"fs\");\n\nconst data = fs.readFileSync(\"input.txt\");\nconsole.log(data.toString());\nconsole.log(\"Fertig\");\n```\n\nDas ist kein aufregender Code. Genau deshalb eignet er sich als Einstieg. `readFileSync` blockiert den Prozess, bis die Datei komplett gelesen ist. Erst dann läuft die nächste Zeile. Ich lasse Teilnehmer diesen Code laufen, dann verändere ich eine Zeile:\n\n```js\nconst fs = require(\"fs\");\n\nfs.readFile(\"input.txt\", (err, data) => {\n  if (err) return console.error(err);\n  console.log(data.toString());\n});\nconsole.log(\"Fertig\");\n```\n\nJetzt steht \"Fertig\" zuerst in der Konsole, obwohl die Zeile im Quelltext danach kommt. Für Einsteiger ist das oft der erste kleine Schreckmoment: Der Code läuft nicht von oben nach unten ab, jedenfalls nicht so, wie man es aus anderen Sprachen gewohnt ist. Genau an diesem winzigen Unterschied lässt sich der ganze Rest des Trainings aufhängen. Node.js ist im Kern kein Framework und keine Sammlung von Modulen, sondern eine Entscheidung: Auf einen langsamen Ein-/Ausgabevorgang reagiert ein Programm mit Weitermachen statt mit Warten.\n\n## Der Event Loop ist Architektur, keine Randnotiz\n\nNode läuft auf der V8-Engine aus Chrome und in einem einzigen JavaScript-Thread. Das überrascht Teilnehmer regelmäßig, weil der Server trotzdem Tausende gleichzeitiger Verbindungen bedienen kann. Der Widerspruch löst sich auf, sobald man zwischen nebenläufig und parallel unterscheidet. Node arbeitet zu einem Zeitpunkt immer nur ein Stück JavaScript ab, aber während dieses Stück auf eine Antwort von der Festplatte, dem Netzwerk oder einer Datenbank wartet, gibt es die Arbeit nach unten weiter, an libuv, den Kernel oder einen internen Thread-Pool. Der Event Loop ist die Instanz, die zurückgemeldete Ergebnisse wieder abholt und die passenden Callbacks aufruft, sobald der Hauptthread frei ist.\n\nDas ist der Punkt, an dem ich in der Schulung bewusst langsamer werde, weil hier die eigentliche Architekturaussage steckt: Concurrency in Node ist kein Implementierungsdetail, das man ignorieren kann, solange der Code funktioniert. Sie bestimmt, welche Arbeit sofort passieren darf und welche warten muss, und sie bestimmt, was ein einzelner blockierender Aufruf für alle anderen gleichzeitig laufenden Anfragen bedeutet. Eine CPU-lastige Schleife, ein synchrones JSON.parse über mehrere Megabyte, eine verschachtelte Regex mit katastrophalem Backtracking – all das legt nicht nur die eine Anfrage lahm, die es ausgelöst hat, sondern den kompletten Prozess, weil es keinen zweiten Thread gibt, der in der Zwischenzeit übernehmen könnte.\n\n```mermaid\nflowchart LR\n  subgraph Call[\"Call Stack (ein Thread)\"]\n    direction TB\n    JS[\"dein JavaScript\"]\n  end\n  JS -->|\"gibt I/O ab\"| LibUV[\"libuv / Kernel / Thread-Pool\"]\n  LibUV -->|\"Ergebnis liegt vor\"| Queue[\"Callback-Queue\"]\n  Queue -->|\"Call Stack ist leer\"| JS\n```\n\nFür Teilnehmer, die aus Java- oder .NET-Umgebungen kommen, ist das oft die größte Umstellung. Der Satz, der hängenbleiben soll, lautet nicht \"Node ist schnell\". Er lautet: Node ist fair, solange man ihm keine blockierende Arbeit unterschiebt. Das ist ein Betriebsversprechen und kein Marketingsatz, und es hat direkte Konsequenzen für das, was in einem Node-Service überhaupt landen darf.\n\n## Warum Callbacks, EventEmitter, Streams und Promises in genau dieser Reihenfolge drankommen\n\nIm Repo `introduction-nodejs`, das ich mit den Teilnehmern gemeinsam durcharbeite, folgen die Kapitel bewusst dieser Reihenfolge: erst Callbacks, dann EventEmitter, dann Streams, danach Promises und ganz am Ende RxJS. Das sieht aus wie eine willkürliche Liste von Async-Werkzeugen, ist aber tatsächlich eine Lernkurve mit einer klaren Logik dahinter, und die lohnt es sich einmal auszubuchstabieren.\n\nEin Callback liefert genau ein Ergebnis, genau einmal, und die Error Handling ist reine Konvention: Das erste Argument ist im Fehlerfall gesetzt, sonst nicht. Diese Konvention nennt sich error-first, und sie funktioniert nur, wenn jede Funktion sie diszipliniert einhält. Ein EventEmitter geht einen Schritt weiter und liefert beliebig viele Events über die Zeit, aber er bringt keinen eingebauten Fehlerkanal mit. Ein `error`-Event ist reine Verabredung, und wenn niemand darauf hört, wirft Node die Ausnahme ungefangen weiter nach oben. Ein Stream ist im Kern ein spezialisierter EventEmitter, der zusätzlich zwei Dinge mitbringt, die für den Alltag entscheidend sind: eine feste Rolle (Readable, Writable, Duplex oder Transform) und Backpressure, also eine eingebaute Bremse, wenn das Ziel langsamer ist als die Quelle. Eine Promise schließlich kehrt zurück zu genau einem Ergebnis, genau einmal, gewinnt dabei aber einen echten, komponierbaren Fehlerkanal über `.catch`, den weder der Callback noch der EventEmitter besitzen. RxJS setzt am Ende beide Eigenschaften zusammen: viele Werte über die Zeit, wie beim EventEmitter, aber mit demselben verlässlichen Fehler- und Abschlussvertrag, den Promises eingeführt haben.\n\nWenn Teilnehmer diesen Bogen einmal gesehen haben, hören sie auf, nach dem \"besten\" Async-Pattern zu fragen. Die Frage verschiebt sich zu etwas Brauchbarerem: Wie viele Werte erwarte ich, wie viele Male darf ein Fehler passieren, und wer trägt die Verantwortung dafür, ihn zu behandeln?\n\n## Streams und Backpressure am konkreten Beispiel\n\nKein Kapitel im Training bringt so viele Aha-Momente wie Streams, weil sie das erste Mal zeigen, dass Node-Architektur auch eine Frage von Speicher und Durchsatz ist, nicht nur von Syntax. Ein kleines, oft gezeigtes Beispiel reicht dafür völlig aus:\n\n```js\nconst fs = require(\"fs\");\nconst zlib = require(\"zlib\");\n\nfs.createReadStream(\"input.txt\")\n  .pipe(zlib.createGzip())\n  .pipe(fs.createWriteStream(\"input.txt.gz\"));\n```\n\nAuf den ersten Blick ist das nur eine bequeme Art, eine Datei zu komprimieren. Interessant wird die Zeile erst, wenn man sich fragt, was passiert, wenn `input.txt` zehn Gigabyte groß ist. Ohne Streams müsste man die komplette Datei in den Speicher laden, bevor überhaupt komprimiert werden kann. Mit `pipe` liest Node einen Chunk, komprimiert ihn, schreibt ihn, und erst dann kommt der nächste Chunk an die Reihe – und zwar automatisch nur so schnell, wie das Schreibziel mithalten kann. Das ist Backpressure: eine eingebaute Queue, die verhindert, dass eine schnelle Quelle ein langsames Ziel mit Daten überschwemmt, bis der Prozess an seiner Speichergrenze erstickt.\n\n```mermaid\nflowchart LR\n  Source[\"Readable<br/>(z. B. Datei)\"] --> Transform[\"Transform<br/>(z. B. Gzip)\"]\n  Transform --> Sink[\"Writable<br/>(z. B. Zieldatei)\"]\n  Sink -. \"Backpressure\" .-> Transform\n  Transform -. \"pause / resume\" .-> Source\n```\n\nFür die Architektur eines Backends ist das kein Nischenwissen für Dateikonvertierung. Jeder Datei-Upload, jeder CSV-Export, jeder Log-Tail und jede Weiterleitung eines HTTP-Response-Bodys profitiert von genau demselben Prinzip. Wer stattdessen den kompletten Request-Body erst in einen Buffer sammelt, bevor irgendetwas mit ihm passiert, hat eine Speichergrenze eingebaut, die im Test mit einer kleinen Testdatei nie auffällt und im Betrieb mit echten Nutzerdateien plötzlich sehr wohl.\n\n## Express ist kein Architekturmuster\n\nDamit sind wir endlich bei der Frage angekommen, mit der die Teilnehmer eigentlich starten wollten. Express ist ein hervorragendes, schlankes Routing-Werkzeug, aber es trifft keine einzige der Entscheidungen, die eine Web-Architektur eigentlich ausmachen. Diese Entscheidungen liegen woanders: Antwortet der Server mit vollständig gerendertem HTML, wie beim klassischen Server-Side-Rendering? Antwortet er mit strukturierten Daten auf einen RPC-artigen Aufruf, bei dem eine Funktion und ihre Parameter im Body stecken? Oder folgt er dem RESTful-Gedanken, bei dem Ressourcen über URIs adressiert werden und HTTP-Methoden ihre jeweilige Bedeutung tragen?\n\nFür Letzteres nutze ich im Training gern das Richardson Maturity Model als kleine Orientierungshilfe, weil es die Abstufungen greifbar macht. Auf Stufe 0 gibt es nur eine einzige URI, meist mit POST, und die eigentliche Aktion steckt im Body – im Grunde RPC über HTTP. Auf Stufe 1 kommen mehrere URIs für unterschiedliche Ressourcen dazu, aber noch ohne saubere Nutzung der HTTP-Methoden. Stufe 2 nutzt GET, POST, PUT, DELETE und Statuscodes so, wie sie gemeint sind: 200 für Erfolg, 201 für angelegt, 204 ohne Inhalt, 404 wenn die Ressource fehlt. Stufe 3 fügt Hypermedia hinzu, also Links in der Antwort, die dem Client sagen, welche nächsten Schritte möglich sind, statt dass der Client das vorher wissen muss. Die meisten Systeme, die ich in Projekten sehe, bleiben bei Stufe 2 stehen, und das ist meistens auch völlig in Ordnung. Wichtig ist nur, dass die Entscheidung bewusst getroffen wird und nicht einfach das Ergebnis davon ist, welche Express-Beispiele man zuerst kopiert hat.\n\nWas Express tatsächlich beisteuert, ist etwas anderes, und es hat einen erstaunlichen Bezug zu Streams: eine Middleware-Pipeline.\n\n```js\nconst express = require(\"express\");\nconst app = express();\n\napp.use(express.json());\napp.use((req, res, next) => {\n  console.log(`${req.method} ${req.url}`);\n  next();\n});\n\napp.get(\"/invoices/:id\", async (req, res, next) => {\n  try {\n    const invoice = await loadInvoice(req.params.id);\n    if (!invoice) return res.status(404).json({ error: \"not_found\" });\n    res.status(200).json(invoice);\n  } catch (err) {\n    next(err);\n  }\n});\n\napp.use((err, req, res, next) => {\n  console.error(err);\n  res.status(500).json({ error: \"internal\" });\n});\n\napp.listen(3000);\n```\n\nJede Middleware bekommt Request und Response, tut etwas und reicht mit `next()` weiter, oder sie bricht mit einem Fehler ab, der beim vier-Parameter-Error-Handler landet. Das ist strukturell dasselbe Prinzip wie bei den Streams weiter oben: eine Quelle, eine Kette von Transformationen, ein Ziel, und ein eigener Kanal für den Fehlerfall. Sobald Teilnehmer diese Verwandtschaft sehen, hört Express auf, eine Liste auswendig zu lernender Aufrufe zu sein. Es wird zu einer von mehreren Ausprägungen desselben Pipeline-Gedankens, der sich durch das ganze Training zieht.\n\n## Skalierung ohne Illusionen\n\nEin einzelner Node-Prozess nutzt genau einen Kern der CPU. Das überrascht Teilnehmer mit Servern, die acht oder sechzehn Kerne haben, regelmäßig, weil unter Last nur einer davon etwas zu tun bekommt, solange man nichts weiter unternimmt. Node bietet dafür `child_process` an, mit drei Werkzeugen, die unterschiedlich grobkörnig sind: `spawn` startet einen beliebigen Systembefehl und liefert seine Ausgabe als Stream, `exec` tut ähnliches, sammelt die Ausgabe aber komplett im Speicher, bevor sie zurückkommt, und `fork` startet gezielt ein weiteres Node-Skript als eigenen Prozess mit einem eingebauten Nachrichtenkanal. Für rechenintensive Arbeit, die den Event Loop sonst blockieren würde, ist das der saubere Weg: Arbeit auslagern, statt den einzigen Thread zu opfern.\n\nEin `fork` sieht im Repo zum Beispiel so aus:\n\n```js\nconst { fork } = require(\"child_process\");\n\nconst worker = fork(\"./heavy-computation.js\");\nworker.send({ numbers: [1, 2, 3, 4, 5] });\nworker.on(\"message\", (result) => {\n  console.log(\"Result from worker process:\", result);\n});\n```\n\nDer Hauptprozess bleibt frei, während `heavy-computation.js` in einem eigenen Prozess rechnet und das Ergebnis über den eingebauten Nachrichtenkanal zurückschickt. Das ist grobkörniger als ein Thread, weil jeder `child_process` seinen eigenen V8-Kontext und seinen eigenen Speicher mitbringt, aber genau diese Isolation ist in vielen Fällen ein Vorteil: Ein abgestürzter Worker reißt den Hauptprozess nicht mit.\n\nGerade jetzt, im Frühjahr 2019, wird dieses Bild interessanter. Node 10 ist die Long-Term-Support-Version, die aktuell in den meisten Projekten produktiv läuft, solide und ausgereift. Node 12 ist vor wenigen Wochen erschienen und bringt zwei Dinge mit, über die ich in der Schulung schon spreche, ohne sie im Produktivbetrieb zu empfehlen: Worker Threads, die jetzt ohne Kommandozeilen-Flag laufen, aber von den Node-Maintainern selbst noch nicht als vollständig ausgereift bezeichnet werden, und experimentelle Unterstützung für ECMAScript-Module hinter dem Flag `--experimental-modules`. Beides zeigt, wohin sich Node entwickelt, aber wer heute etwas ausliefert, bleibt bei `require`, bei CommonJS und bei der 10er-Linie, bis die 12er zur LTS-Version wird. Ich finde diese Unterscheidung wichtig genug, um sie explizit zu machen: Neugier auf das Neue und Verantwortung für das Laufende sind zweierlei, und ein gutes Training zeigt beides.\n\n## Fehler sind auch Architektur, nicht nur ein try/catch\n\nIm Express-Beispiel weiter oben landet ein Fehler beim vier-Parameter-Handler, weil ich ihn mit `next(err)` explizit dorthin weitergereicht habe. Das ist der saubere Fall. Interessant wird es bei den Fehlern, die niemand explizit weitergereicht hat. Dafür bietet Node zwei globale Netze, und ich zeige Teilnehmern bewusst, dass es Netze und keine Reparaturwerkzeuge sind.\n\n```js\nprocess.on(\"uncaughtException\", (err) => {\n  console.error(\"Unexpected error, process is in an undefined state:\", err);\n  // only synchronous cleanup, then exit\n  process.exit(1);\n});\n\nprocess.on(\"unhandledRejection\", (reason) => {\n  console.error(\"Promise rejected without .catch:\", reason);\n});\n```\n\nDie Node-Dokumentation ist an dieser Stelle ungewöhnlich deutlich: Nach einer `uncaughtException` befindet sich der Prozess in einem undefinierten Zustand. Der Satz ist wörtlich gemeint. Irgendein Modul kann mitten in einer Operation stehengeblieben sein, eine Datei halb geschrieben, eine Verbindung halb aufgebaut. Im Handler macht man deshalb nicht weiter. Man räumt so schnell und so synchron wie möglich auf und beendet den Prozess, damit ein Supervisor – `pm2`, systemd, Kubernetes, was auch immer im jeweiligen Projekt läuft – ihn frisch neu startet. `unhandledRejection` ist die Promise-Variante desselben Problems: eine Promise, die abgelehnt wurde, ohne dass irgendwo ein `.catch` darauf gewartet hat.\n\nFür Teilnehmer, die aus einer Welt mit zentralem Exception Handling kommen, ist das gewöhnungsbedürftig. Die eigentliche Lektion lautet: Ein globaler Handler ersetzt niemals das `try/catch` oder das `.catch` an der Stelle, an der der Fehler fachlich etwas bedeutet – dass eine Rechnung nicht gefunden wurde, dass eine Zahlung fehlgeschlagen ist, dass eine Datei nicht existiert. Er ist das letzte Sicherheitsnetz für das, was durch alle bewusst gesetzten Netze hindurchgefallen ist. Dazu passt auch, dass Node über `process.on(\"SIGINT\", ...)` und verwandte Signale einen kontrollierten Shutdown erlaubt: laufende Verbindungen zu Ende bedienen, Datenbankverbindungen sauber schließen, dann erst beenden. Dahinter steckt derselbe Gedanke wie bei Backpressure: Ein System sagt ehrlich, wann es fertig ist, statt einfach abgewürgt zu werden.\n\n## Testen, bevor es wehtut\n\nDer letzte Baustein, den ich im Training bewusst nicht auslasse, ist Testing, und zwar aus einem einfachen Grund: Alles, was bisher gezeigt wurde – Backpressure, Fehlerpfade, die Reihenfolge von Middleware – lässt sich im Handumdrehen unsichtbar kaputtmachen, wenn niemand eine Erwartung daran festgehalten hat. Ich arbeite mit Mocha, weil es 2019 ein bewährter, unaufgeregter Standard ist, und mit dem eingebauten `assert`-Modul, weil man dafür keine zusätzliche Bibliothek braucht, um die Idee zu verstehen.\n\n```js\nconst assert = require(\"assert\");\nconst { describe, it } = require(\"mocha\");\n\ndescribe(\"Array.reverse\", () => {\n  it(\"reverses the order of elements\", () => {\n    const sut = \"ABC\".split(\"\");\n    const actual = sut.reverse();\n    assert.deepEqual(actual, [\"C\", \"B\", \"A\"]);\n  });\n});\n```\n\nArrange, Act, Assert: Testdaten aufbauen, die Funktion ausführen, das Ergebnis prüfen. Diese drei Schritte klingen banal, aber die meisten schwer lesbaren Tests verletzen genau diese Trennung, indem Aufbau und Prüfung munter durcheinandergemischt werden. Bei asynchronem Code zahlt sich Mocha zusätzlich aus, weil ein Test entweder einen `done`-Callback entgegennimmt oder schlicht eine Promise zurückgibt:\n\n```js\nit(\"resolves with the expected value after the async call\", () => {\n  return computeAsync().then((actual) => {\n    assert.equal(actual, 2);\n  });\n});\n```\n\nGibt die Testfunktion eine Promise zurück, wartet Mocha automatisch darauf, bevor es das Ergebnis bewertet. Vergisst man das `return`, meldet der Test unter Umständen Erfolg, bevor die eigentliche Assertion überhaupt gelaufen ist – ein Fehler, der in Code-Reviews leicht übersehen wird, weil der Test ja grün ist. Für Integrationstests kommen `before`, `after`, `beforeEach` und `afterEach` dazu, um zum Beispiel eine Testdatenbank einmal aufzusetzen und nach jedem Test wieder in einen bekannten Zustand zu bringen. Die Testpyramide bleibt dabei die Leitplanke: viele schnelle Unit-Tests an der Basis, weniger, aber aussagekräftige Integrationstests in der Mitte, eine Handvoll Ende-zu-Ende-Tests an der Spitze. Wer diese Verteilung umdreht, merkt es meistens erst an der Laufzeit der Build-Pipeline, wenn es zu spät ist, um sie günstig zu ändern.\n\n## Das Repository ist selbst schon Architektur\n\nEin Punkt, den ich Teilnehmern gerne erst am Ende erkläre, weil er vorher zu abstrakt wäre: `introduction-nodejs` ist selbst als Yarn-Workspaces-Monorepo aufgebaut und eben nicht bloß ein Ordner voller Markdown-Dateien. Im Wurzelverzeichnis steht eine `package.json` mit `\"private\": true` und einem `workspaces`-Feld, das auf einen `packages`-Ordner zeigt, und jedes Beispiel liegt als eigenständiges Paket darunter: `ARCHITECTURE`, `BASICS`, `ECMA`, `EVENTEMITTER`, `EXPRESSJS`, `FUNCTIONALJS`, `HTTP2`, `RXJS`, `STREAMS`, `TESTING`, `TYPESCRIPT`. Jedes dieser Pakete hat seine eigenen Abhängigkeiten und lässt sich einzeln installieren und ausführen, ohne dass die Beispiele sich gegenseitig verunreinigen.\n\nDas ist kein Zufall und auch kein reines Ordnungsprinzip. Es ist dieselbe Lektion, die vorher schon bei Streams und bei Express auftauchte, nur eine Ebene höher: klare Grenzen zwischen Bausteinen, jeder mit seiner eigenen Verantwortung, verbunden über einen expliziten, sichtbaren Mechanismus statt über stille Abhängigkeiten. Ich zeige Teilnehmern bewusst diese Struktur des Repos selbst, weil ein Monorepo mit sauberen Workspace-Grenzen ziemlich genau dasselbe Architekturproblem löst wie ein Backend, das aus mehreren Services besteht: Wo darf etwas geteilt werden, und wo muss es getrennt bleiben, damit eine Änderung an einer Stelle nicht überraschend woanders etwas kaputt macht?\n\n## Wie ich die Schulung tatsächlich gebe\n\nIch zeige selten eine Folie, ohne direkt danach den Code aufzumachen. Die Folienübersicht zum Training gibt es zum Nachschlagen und für alle, die zwischen den Terminen noch einmal die Übersicht sehen wollen, hier: [Introduction to Node.js – Folien](https://slides.mikebild.dev/introduction-nodejs.html). Aber die Folie ist der Wegweiser, nicht der Weg selbst. Das eigentliche Lernen passiert im Repository, gemeinsam: Ich tippe, ein Teilnehmer tippt, wir bauen einen Fehler absichtlich ein und schauen uns gemeinsam an, wie die Fehlermeldung aussieht, dann reparieren wir ihn zusammen. Wer nur zuschaut, merkt sich die Syntax für den Moment. Wer selbst tippt und selbst den Callback vergisst zurückzugeben oder das `await` an der falschen Stelle setzt, merkt sich die Grenze – und Grenzen sind es, die ein Jahr später noch abrufbar sind, nicht Syntax.\n\nGetragen wird die Schulung deshalb vom Repo [introduction-nodejs](https://github.com/mikebild/introduction-nodejs) und nicht vom Foliensatz. Die 23 Kapitel sind als eigenständige Markdown-Dateien angelegt, die man in beliebiger Reihenfolge nachschlagen kann und die als Ganzes eine Lernkurve vom ersten Skript zur Betriebsreife ergeben – von der Einführung über Event Loop, Streams und Error Handling bis zu Express, Testing, Promises, RxJS und TypeScript. Die dazugehörigen `EXAMPLES` sind lauffähiger Code, kein Pseudocode – genau der Code, den wir im Raum gemeinsam verändern.\n\n## Was am Ende bleiben soll\n\nAm letzten Schulungstag frage ich Teilnehmer manchmal, was sie mitnehmen. Die Antwort, die mich am meisten freut, ist selten \"ich kenne jetzt Express\". Sie lautet eher so etwas wie: \"Ich weiß jetzt, wann ich zu einem Callback greife und wann zu einem Stream, und ich weiß, warum ein `await` trotzdem noch etwas ist, worüber ich nachdenken muss.\" Genau das ist der Unterschied zwischen einer Werkzeugliste und einem Architekturverständnis. Ein Framework kann man in einem Wochenende nachlernen. Ein Gefühl dafür, welche Entscheidung sich später rächt, braucht die Übung an echtem, manchmal absichtlich kaputtem Code.\n\nNode.js taugt als Trainingsobjekt aus einem Grund, der mit Aktualität oder Beliebtheit nichts zu tun hat: Seine zentrale Designentscheidung – nicht-blockierendes I/O in einem einzigen Thread – ist so kompromisslos, dass sie ihre eigenen Konsequenzen erzwingt. Man kann sie nicht ignorieren, ohne dass der Server sich irgendwann merkwürdig verhält. Und genau an diesen merkwürdigen Momenten lernt man am meisten.\n\nSelbst Ryan Dahl, der Node vor zehn Jahren erfunden hat, hat vor einiger Zeit in einem vielbeachteten Vortrag öffentlich einige seiner eigenen Designentscheidungen infrage gestellt und experimentiert seitdem an einem möglichen Nachfolger. Das finde ich, ganz unabhängig davon, wohin dieses Experiment führt, bemerkenswert gesund für ein Ökosystem: dass der Erfinder selbst bereit ist zu sagen, was er heute anders machen würde. Genau diese Haltung versuche ich auch in der Schulung zu vermitteln. Node.js ist kein fertiges, geschlossenes Weltbild, das man auswendig lernt. Es ist eine Reihe von Entscheidungen, jede mit ihrem Preis, jede diskutierbar. Wer das einmal verinnerlicht hat, liest auch die nächste Technologie, die in fünf Jahren angesagt sein wird, als eine weitere Menge von Entscheidungen, die man verstehen und gegebenenfalls widerlegen kann – und nicht als Wahrheit.\n\n## Weiterführende Quellen\n\n- Repository introduction-nodejs (Basis für die gemeinsamen Übungen): https://github.com/mikebild/introduction-nodejs\n- Folienübersicht zum Training: https://slides.mikebild.dev/introduction-nodejs.html\n- Node.js, Event Loop und Timers (offizielle Dokumentation): https://nodejs.org/learn/asynchronous-work/event-loop-timers-and-nexttick\n- Node.js Streams API: https://nodejs.org/api/stream.html\n- Node.js 12 Release-Ankündigung: https://nodejs.org/en/blog/release/v12.0.0/\n- Richardson Maturity Model, Übersicht: https://martinfowler.com/articles/richardsonMaturityModel.html"},{"locale":"de","translation_key":"cdk-infrastruktur-als-programmiersprache","slug":"cdk-infrastruktur-als-programmiersprache","title":"CDK-Anfänge: Infrastruktur mit einer Programmiersprache","summary":"Mit dem CDK rückt Infrastruktur in dieselbe Werkzeugkette wie Anwendungscode, wodurch Tests, Reviews und logische Identitäten plötzlich über den Bestand von Produktionsdaten entscheiden.","tags":["Software","AWS","Cloud"],"published_at":"2019-03-12T10:00:00+00:00","updated_at":"2026-07-13T13:43:01.671293+00:00","url":"https://www.mikebild.dev/de/blog/cdk-infrastruktur-als-programmiersprache/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/7c0b251ee92a5e66b14124aab19ab8ce9971d17c7a5a9edd548b2fe0e21108e6/cdk-infrastruktur-als-programmiersprache-vorlesen.mp3","audio_duration_secs":787,"text":"# CDK-Anfänge: Infrastruktur mit einer Programmiersprache\n\nSeit ein paar Wochen liegt das AWS Cloud Development Kit als Developer Preview vor, und es verändert spürbar, wie ich über Infrastruktur nachdenke. Statt YAML zu schreiben und zu hoffen, dass die Einrückung stimmt, schreibe ich TypeScript. Ich bekomme Typen, Autovervollständigung, Schleifen, Funktionen und Klassen. Das klingt nach einer reinen Komfortverbesserung, ist aber eine Verschiebung der Verantwortung. Wer Infrastruktur in einer echten Programmiersprache beschreibt, erbt alle Werkzeuge dieser Sprache. Er erbt aber auch ihre Fehlerklassen.\n\n**Redaktionelle Einordnung (Juli 2026):** Das CDK ist keine eigene Programmiersprache, sondern ein Framework, mit dem Infrastruktur in vorhandenen Sprachen definiert und über CloudFormation bereitgestellt wird. Der Code zeigt die Developer Preview und später CDK v1: getrennte `@aws-cdk/*`-Pakete und damalige Lambda-Runtimes. CDK v2 bündelt die stabile Construct Library in `aws-cdk-lib`; neue Projekte sollten die Beispiele deshalb nicht wörtlich übernehmen. Das gilt auch für die Deployment-Action weiter unten: Aktuelle GitHub-Actions-Workflows sollten AWS über OIDC und kurzlebige Rollen-Credentials anbinden, nicht über langlebige Access Keys in Repository-Secrets.\n\nIch nehme im Folgenden einen kleinen, plausiblen Stack als roten Faden: einen S3-Bucket, in den Nutzer Dateien laden, und eine Lambda-Function, die diese Dateien verarbeitet. An diesem Beispiel lässt sich die interessante Architekturfrage besser zeigen als an einer Aufzählung von Merkmalen.\n\n## Vom Template zum Programm\n\nCloudFormation kennt jeder, der länger mit AWS arbeitet. Man beschreibt den Zielzustand deklarativ, und der Dienst gleicht ab. Das Modell ist robust, aber das Format ist mühsam. Wiederholung lässt sich nur über Parameter und Mappings ausdrücken, und sobald eine Vorlage über tausend Zeilen wächst, verliert man den Überblick darüber, welche Ressource eigentlich von welcher abhängt.\n\nDas CDK dreht die Richtung um. Ich schreibe Code, und dieser Code erzeugt am Ende wieder eine CloudFormation-Vorlage. Dieser Schritt heißt Synthese. Wichtig ist, dass darunter weiterhin CloudFormation arbeitet. Das CDK ersetzt den Provisionierungsmechanismus nicht, es setzt eine Programmierschicht darüber. Der Vorteil ist offensichtlich: Abstraktion, Wiederverwendung, Typprüfung. Der Preis ist, dass zwischen meinem Quelltext und den realen Ressourcen jetzt ein Übersetzungsschritt liegt, dessen Ergebnis ich kennen sollte.\n\nIn der aktuellen Vorabversion ist die Bibliothek nach Diensten aufgeteilt. Es gibt ein Kernpaket und je ein Paket pro AWS-Dienst. Wer S3 und Lambda nutzt, installiert genau diese Pakete. Das ist ungewohnt granular, hat aber den Effekt, dass man die eigenen Abhängigkeiten klein hält.\n\n## Die drei Ebenen: App, Stack, Construct\n\nDas Modell hat drei Schichten, und es lohnt sich, sie sauber auseinanderzuhalten, weil jede eine andere Aufgabe hat.\n\nGanz unten stehen die Constructs. Ein Construct ist ein Baustein. Es kapselt eine oder mehrere CloudFormation-Ressourcen samt sinnvoller Voreinstellungen. Ein S3-Bucket ist ein Construct, eine Lambda-Function ist ein Construct, und ein selbst geschriebenes Modul, das beide zu einem Upload-Verarbeiter verbindet, ist ebenfalls eines. Constructs lassen sich verschachteln, und genau daraus entsteht die Wiederverwendbarkeit.\n\nEine Ebene darüber liegt der Stack. Er ist die Einheit, die deployt wird, und entspricht eins zu eins einem CloudFormation-Stack. Was in einem Stack liegt, wird gemeinsam ausgerollt und im Fehlerfall gemeinsam zurückgenommen.\n\nGanz oben sitzt die App. Sie ist der Entry Point und bündelt einen oder mehrere Stacks. Wenn die App durchläuft, wird für jeden Stack eine Vorlage erzeugt.\n\n```mermaid\nflowchart TD\n  App[\"App (Einstiegspunkt)\"] --> Stack[\"Stack (Deployment-Einheit)\"]\n  Stack --> C1[\"Construct: S3-Bucket\"]\n  Stack --> C2[\"Construct: Lambda-Funktion\"]\n  C1 --> Synth[\"Synthese\"]\n  C2 --> Synth\n  Synth --> CFN[\"CloudFormation-Vorlage\"]\n  CFN --> AWS[\"Ressourcen in der Cloud\"]\n```\n\nDiese Hierarchie ist kein Selbstzweck. Sie bestimmt, was unabhängig geändert werden kann und was nicht. Zwei Dinge im selben Stack teilen ihr Schicksal beim Rollback. Zwei Dinge in getrennten Stacks lassen sich getrennt aktualisieren, müssen dann aber ihre Verbindung explizit über Referenzen ausdrücken.\n\n## Der Stack als Code\n\nSo sieht der erwähnte Upload-Verarbeiter in der aktuellen Bibliothek aus. Bewusst klein gehalten, damit die Entscheidung sichtbar bleibt und nicht im Beiwerk verschwindet.\n\n```ts\nimport cdk = require(\"@aws-cdk/core\");\nimport s3 = require(\"@aws-cdk/aws-s3\");\nimport lambda = require(\"@aws-cdk/aws-lambda\");\n\nclass UploadStack extends cdk.Stack {\n  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {\n    super(scope, id, props);\n\n    // Storage for incoming files.\n    // RETAIN keeps the bucket even when the stack is deleted.\n    const uploads = new s3.Bucket(this, \"Uploads\", {\n      removalPolicy: cdk.RemovalPolicy.RETAIN\n    });\n\n    const handler = new lambda.Function(this, \"ProcessUpload\", {\n      runtime: lambda.Runtime.NODEJS_10_X,\n      handler: \"index.handler\",\n      code: lambda.Code.fromAsset(\"dist/handler\"),\n      environment: {\n        // The bucket name is resolved at runtime, not hard-coded.\n        BUCKET_NAME: uploads.bucketName\n      }\n    });\n\n    // Instead of writing an IAM policy by hand:\n    // the construct grants the necessary permissions and nothing more.\n    uploads.grantReadWrite(handler);\n  }\n}\n\nconst app = new cdk.App();\nnew UploadStack(app, \"UploadStack\");\napp.synth();\n```\n\nDrei Stellen verdienen einen zweiten Blick. Der Aufruf `uploads.grantReadWrite(handler)` schreibt keine Policy von Hand, sondern leitet aus der Beziehung der beiden Constructs ab, welche Aktionen die Funktion auf dem Bucket braucht. Das ist mehr als Bequemlichkeit, denn es macht das Prinzip der minimalen Rechte zum Standardweg statt zur Ausnahme. Die Zeile `BUCKET_NAME: uploads.bucketName` zeigt, dass `bucketName` zur Synthesezeit kein fertiger String ist, sondern ein Verweis, den CloudFormation später auflöst. Und `removalPolicy: RETAIN` ist die kleine, unscheinbare Zeile, von der gleich noch die Rede sein wird, weil ihr Fehlen teuer wird.\n\nWas hier auffällt: Es ist normaler Code. Ich kann ihn refaktorieren, in eine Funktion auslagern, über eine Liste von Umgebungen iterieren. Genau das ist der Reiz. Und genau hier beginnt die Verantwortung.\n\n## Was man sich mit der Programmiersprache einhandelt\n\nSolange Infrastruktur in YAML steht, ist sie statisch und langweilig, aber gut überschaubar. Sobald sie Code ist, gelten die Gesetze des Codes. Ein Tippfehler in einer Schleife erzeugt nicht eine falsche Ressource, sondern fünfzig. Eine geänderte Konstante wirkt überall dort, wo sie gelesen wird. Eine Abstraktion, die zu viel versteckt, verbirgt auch Kosten und Rechte vor demjenigen, der den Stack reviewt.\n\nDamit verschiebt sich, was Sorgfalt hier heißt: Wenn Infrastruktur programmierbar wird, muss sie so behandelt werden wie Anwendungscode. Sie braucht Tests, sie braucht Reviews, und sie braucht ein Verständnis dafür, was beim Ändern passiert. Das ist keine Bürde, die das CDK uns aufdrückt, sondern die ehrliche Konsequenz daraus, eine echte Sprache zu benutzen.\n\nTests sind dabei kein Beiwerk. Die Bibliothek bringt bereits ein Assertion-Modul mit, mit dem sich das synthetisierte Ergebnis prüfen lässt, ohne überhaupt zu deployen:\n\n```ts\nimport { expect, haveResource } from \"@aws-cdk/assert\";\n\ntest(\"Bucket survives deletion of the stack\", () => {\n  const app = new cdk.App();\n  const stack = new UploadStack(app, \"TestStack\");\n\n  expect(stack).to(haveResource(\"AWS::S3::Bucket\", {\n    DeletionPolicy: \"Retain\"\n  }, undefined, true));\n});\n```\n\nDieser Test deployt nichts. Er prüft die erzeugte Vorlage. Damit lässt sich eine Regel festschreiben, die sonst nur im Kopf eines erfahrenen Kollegen existiert: dieser Bucket darf nicht versehentlich verschwinden. Genau solche Prüfungen unterscheiden einen Stack, der eine Demo überlebt, von einem, der einen Personalwechsel überlebt.\n\n## Der Fehler, der wirklich passiert\n\nDer gefährlichste Fehler im CDK ist kein Syntaxfehler, denn den fängt der Compiler ab. Er hat mit der logischen Identität von Ressourcen zu tun, und er ist deshalb so tückisch, weil der Code danach völlig in Ordnung aussieht.\n\nCloudFormation identifiziert jede Ressource über eine logische ID. Das CDK erzeugt diese ID aus dem Pfad des Constructs im Baum, also im Wesentlichen aus dem zweiten Argument des Konstruktors, dem Namen. In meinem Beispiel heißt der Bucket `\"Uploads\"`. Angenommen, jemand findet diesen Namen unschön und benennt ihn aus reiner Kosmetik um:\n\n```ts\nconst uploads = new s3.Bucket(this, \"UploadBucket\", {\n  removalPolicy: cdk.RemovalPolicy.RETAIN\n});\n```\n\nFunktional ändert sich nichts. Der Code kompiliert, die Tests zum Verhalten der Funktion laufen weiter. Aber die logische ID hat sich geändert. Für CloudFormation bedeutet das nicht: dieselbe Ressource mit neuem Namen. Es bedeutet: die alte Ressource ist verschwunden, eine neue ist hinzugekommen. Beim nächsten Deployment wird also ein neuer, leerer Bucket angelegt, und die Anwendung zeigt anschließend auf diesen leeren Speicher. Für die alte Ressource greift die Lösch- oder Austausch-Policy.\n\nAn dieser Stelle rettet die unscheinbare Zeile von vorhin. Steht `removalPolicy: RETAIN` im Code, wird der alte Bucket nicht gelöscht, sondern aus dem Stack entlassen und bleibt als verwaiste Ressource bestehen. Die Daten überleben, auch wenn die Anwendung sie nicht mehr findet, bis jemand manuell aufräumt. Fehlt diese Policy, versucht CloudFormation die alte Ressource zu entfernen. Einen nicht leeren S3-Bucket leert CloudFormation dabei nicht stillschweigend; die Löschung scheitert, solange Objekte enthalten sind, sofern nicht zusätzlich ein Mechanismus wie `autoDeleteObjects` eingerichtet wurde. Das macht die Umbenennung nicht harmlos: Die Anwendung zeigt bereits auf einen neuen, leeren Bucket, und bei anderen löschbaren Ressourcen oder expliziter automatischer Leerung kann der Austausch tatsächlich Daten vernichten.\n\nDer entscheidende Punkt ist nicht die einzelne Policy. Der Punkt ist, dass eine harmlose Umbenennung im Code eine zerstörerische Operation in der Infrastruktur auslöst, und dass diese Folge im Quelltext nicht sichtbar ist. Sie wird erst im `cdk diff` sichtbar, das eine Ersetzung als solche markiert. Wer den Diff vor dem Deployment liest, sieht den Schaden kommen. Wer ihn überspringt, weil das letzte Deployment ja auch durchlief, sieht ihn danach.\n\n```text\n$ cdk diff\nResources\n[-] AWS::S3::Bucket Uploads      destroy\n[+] AWS::S3::Bucket UploadBucket  create\n```\n\nDaraus folgt eine konkrete Betriebsregel: Bei Stacks mit Zustand ist der Diff kein optionaler Zwischenschritt, sondern Teil des Reviews. Und zustandsbehaftete Ressourcen, also Buckets, Datenbanken, Tabellen, bekommen eine explizite Removal-Policy, damit eine Stack-Löschung oder eine Ersetzung niemals stillschweigend Daten mitnimmt.\n\n## Abstraktion ist eine Entscheidung, keine kostenlose Annehmlichkeit\n\nDer Aufruf `grantReadWrite` ist ein gutes Beispiel für eine gelungene Abstraktion, weil er Wiederholung entfernt und einen sicheren Default erzwingt. Es gibt aber die andere Sorte. Ein selbst geschriebenes Construct, das einen ganzen Microservice mit Datenbank, Queue, Funktion und Alarm kapselt, ist verlockend. Es macht den aufrufenden Code kurz. Es macht aber auch unsichtbar, welche zwölf Ressourcen und welche Rechte dabei entstehen.\n\nEine gute Abstraktion im CDK reduziert Wiederholung und kapselt vernünftige Voreinstellungen, ohne zu verschleiern, was sie kostet und welche Berechtigungen sie verteilt. Der Prüfstein für ein eigenes Construct ist deshalb nicht seine Eleganz. Er ist die Frage, ob jemand im Review noch versteht, was er sich damit einkauft. Wenn die Antwort nur lautet, dass es funktioniert, ist die Abstraktion noch nicht reif.\n\nHier hilft, das Ergebnis der Synthese gelegentlich anzusehen. Ein `cdk synth` schreibt die fertige Vorlage auf die Konsole. Bei einem unscheinbaren Stack sind das schnell ein paar Hundert Zeilen, und es lohnt sich, dieses Verhältnis zwischen kurzem Code und umfangreicher Vorlage einmal bewusst wahrzunehmen. Es ist der ehrlichste Indikator dafür, wie viel die Abstraktion gerade für einen tut.\n\n## Wie sich das in eine Pipeline einfügt\n\nInfrastruktur als Code entfaltet ihren Wert erst, wenn niemand mehr von Hand deployt. Ich hatte dafür 2019 eine kleine GitHub Action gebaut, die in einem Container das CDK installiert und `deploy` mit AWS-Zugangsdaten aus Repository-Secrets ausführt. Dieses Credential-Pattern ist historisch; für neue Workflows nehme ich OIDC und eine zeitlich begrenzte AWS-Rolle. Geblieben ist der Reiz, dass derselbe Mechanismus Anwendungscode und Infrastruktur ausliefert. Ein Pull Request ändert dann nicht nur den Dienst, sondern auch seinen Unterbau, und beides durchläuft denselben Review.\n\nGenau an dieser Stelle schließt sich der Kreis zur Verantwortung. Wenn ein Merge ausreicht, um Produktionsinfrastruktur zu verändern, dann ist der Review der letzte Ort, an dem ein Mensch eingreifen kann. Der Diff gehört in diesen Review. Die Tests laufen vor dem Deployment. Und für Regeln, die nicht verhandelbar sind, etwa dass kein Bucket öffentlich lesbar sein darf, lohnt sich eine maschinelle Prüfung der synthetisierten Vorlage, eine Art Policy as Code für den eigenen CDK-Output. So wandert Wissen, das sonst von der Tagesform des Reviewers abhängt, in eine Prüfung, die immer gleich streng ist.\n\n## Was ich nach den ersten Wochen mitnehme\n\nDas CDK ist noch jung, die API bewegt sich, und manches wird sich bis zur stabilen Version ändern. Trotzdem ist die Richtung klar und sie überzeugt mich. Infrastruktur wird testbar, wiederverwendbar und refaktorierbar. Das ist ein echter Gewinn gegenüber handgeschriebenem YAML.\n\nDer Gewinn ist aber an eine Haltung gebunden. Wer Infrastruktur programmiert, muss sie wie Software behandeln, mit allem, was dazugehört: kleine, prüfbare Bausteine, ein Test für jede Annahme, die teuer wäre, wenn sie bricht, ein gelesener Diff vor jedem Deployment und eine bewusste Entscheidung darüber, was eine Abstraktion verbergen darf und was nicht. Die logische ID und die Removal-Policy sind dabei keine Randnotizen, sondern die Stellen, an denen sich entscheidet, ob ein Refactoring harmlos bleibt oder Daten kostet.\n\nDer Werkzeugwechsel von YAML zu TypeScript ist also der kleinere Teil der Geschichte. Der größere Teil ist, dass Betrieb und Codequalität jetzt dasselbe Thema sind. Wer das annimmt, bekommt eine Infrastruktur, die man lesen, prüfen und mit Vertrauen ändern kann. Wer es ignoriert, hat am Ende nur die alten Fehler in einer neuen Sprache.\n\n## Weiterführende Quellen\n\n- [AWS CDK v2, Einführung](https://docs.aws.amazon.com/cdk/v2/guide/home.html)\n- [Constructs als Bausteine](https://docs.aws.amazon.com/cdk/v2/guide/constructs.html)\n- [CloudFormation `DeletionPolicy`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html) und [`UpdateReplacePolicy`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-updatereplacepolicy.html)\n- [GitHub OIDC mit AWS](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws)\n- GitHub Action fürs CDK-Deployment: https://github.com/MikeBild/aws-cdk-js-github-action\n- Policy as Code fürs CDK (cloudpatrol): https://github.com/MikeBild/cloudpatrol"},{"locale":"de","translation_key":"aws-parameter-store-im-build","slug":"aws-parameter-store-im-build","title":"AWS Parameter Store im Build","summary":"Parameter Store im Build macht Konfiguration explizit, wirft aber harte Fragen zu Secrets und Reproduzierbarkeit auf.","tags":["Software","Frontend","AWS"],"published_at":"2019-02-12T10:00:00+00:00","updated_at":"2026-07-13T08:36:48.631838+00:00","url":"https://www.mikebild.dev/de/blog/aws-parameter-store-im-build/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/082e5960c2292c7cfb00b9db69345c79198109fdee470a3573bc7518f22f1c55/aws-parameter-store-im-build-vorlesen.mp3","audio_duration_secs":732,"text":"# AWS Parameter Store im Build\n\n```bash\n$ gatsby build\nsuccess Building production JavaScript and CSS bundles - 42.108s\nDone in 71.4s\n\n$ grep -o \"undefined/graphql\" public/app-8f2c1a.js\nundefined/graphql\n```\n\n`GATSBY_API_URL` stand beim Build nicht in `process.env`. Der Build ist trotzdem grün durchgelaufen, das Artefakt ist deploybar, und der leere Wert ist in das ausgelieferte JavaScript eingebacken – auffallen wird er zuerst im Browser eines Nutzers. Kein Absturz, keine Fehlermeldung in der Pipeline, nur ein statisches Bundle, das gegen nichts spricht.\n\nDer konkrete Anlass, das aufzuschreiben, ist ein kleines Gatsby-Plugin, das ich gebaut habe: [gatsby-plugin-aws-parameter-store-environment](https://github.com/MikeBild/gatsby-plugin-aws-parameter-store-environment). Es zieht beim Build Konfigurationswerte aus dem AWS Systems Manager Parameter Store und stellt sie als Environment-Variablen bereit. Fünfzig Zeilen Code, ein sehr überschaubares Problem – und trotzdem eine gute Gelegenheit, eine Architekturfrage sichtbar zu machen, die deutlich größer ist als das Plugin selbst.\n\nDie Frage lautet nicht „Wie hole ich einen Wert aus einem AWS-Service?“, sondern: „Wo gehört die Konfiguration eines statischen Frontends hin, wer besitzt sie, und was kostet mich die Antwort im Betrieb?“ Genau an dieser Grenze entscheidet sich, ob ein Deployment reibungslos läuft oder ob jedes Release ein kleiner manueller Kraftakt bleibt. Ein winziges Plugin ist oft der ehrlichste Ort, um so eine Entscheidung durchzudenken, weil nichts von der eigentlichen Frage ablenkt.\n\n## Das Problem: Konfiguration in einem statischen Build\n\nGatsby erzeugt zur Build-Zeit statisches HTML, CSS und JavaScript. Das ist der Kern des JAMstack-Versprechens: schnelle, cache-freundliche Auslieferung ohne Server im Anfragepfad. Der Preis dafür ist eine Verschiebung, die viele unterschätzen – Konfiguration wird nicht zur Laufzeit gelesen, sondern zur Build-Zeit eingebacken. Was während `gatsby build` in `process.env` steht, landet im Ergebnis. Was fehlt, fehlt für immer, bis der nächste Build läuft.\n\nIn der Praxis wächst daraus schnell ein bekanntes Muster. Jede Umgebung – lokal, Staging, Produktion – bekommt ihre eigene `.env`-Datei. Manche Werte liegen im CI-System als Secret, andere im Git-Repository, ein paar nur im Kopf desjenigen, der zuletzt deployt hat. Es gibt keine einzelne Quelle, sondern eine Streuung. Und Streuung erzeugt Drift: Staging läuft gegen einen anderen API-Endpoint als gedacht, ein Feature-Flag ist in Produktion anders gesetzt als dokumentiert, ein rotierter Zugangsschlüssel wurde an drei von vier Stellen aktualisiert.\n\nDas ist kein exotisches Randproblem. Es ist die häufigste Reibungsquelle zwischen „Code ist fertig“ und „Änderung ist live“. Und es ist teuer, weil es nicht als Ausfall auftritt, sondern als schleichende Unsicherheit: Niemand weiß mehr mit Bestimmtheit, welche Konfiguration ein bestimmter Build wirklich gesehen hat.\n\n## Die Idee: eine einzige Quelle für Build-Konfiguration\n\nDer Parameter Store dreht diese Streuung um. Statt viele `.env`-Dateien zu pflegen, definiere ich die Konfiguration hierarchisch an einer Stelle in AWS, geordnet nach Anwendung und Umgebung:\n\n```bash\n# One source of truth, organized by app and environment\naws ssm put-parameter \\\n  --name \"/mikebild-dev/production/GATSBY_API_URL\" \\\n  --value \"https://api.mikebild.com/graphql\" \\\n  --type \"String\"\n\naws ssm put-parameter \\\n  --name \"/mikebild-dev/production/CONTENTFUL_DELIVERY_TOKEN\" \\\n  --value \"cda-xxxxxxxx\" \\\n  --type \"SecureString\" \\\n  --key-id \"alias/build-config\"\n```\n\nDer Build zieht dann den ganzen Teilbaum einer Umgebung und exportiert ihn als Environment-Variablen. Im `gatsby-config.js` sieht das bewusst unspektakulär aus:\n\n```js\nmodule.exports = {\n  plugins: [\n    {\n      resolve: \"gatsby-plugin-aws-parameter-store-environment\",\n      options: {\n        // Pull the whole subtree for this environment\n        path: `/mikebild-dev/${process.env.DEPLOY_ENV}/`,\n        withDecryption: true,\n      },\n    },\n  ],\n};\n```\n\nDie Hierarchie ist der eigentliche Gewinn, nicht der API-Aufruf. Ein Pfad wie `/app/environment/KEY` gibt der Konfiguration eine Struktur, die man per IAM-Policy schneiden kann: Der Produktions-Build darf `/mikebild-dev/production/*` lesen, sonst nichts. Werte vom Typ `SecureString` liegen mit KMS verschlüsselt, und jeder Zugriff hinterlässt in CloudTrail eine Spur. Aus „irgendwo liegt eine Datei“ wird „ein benannter, versionierter, zugriffskontrollierter Wert mit Audit-Trail“.\n\n## Architektur: Build-Zeit gegen Laufzeit\n\nBevor ich das Plugin einsetze, ziehe ich eine Linie. Sie ist die wichtigste Entscheidung des ganzen Themas, und das Plugin trifft sie nicht für mich.\n\n```mermaid\nflowchart LR\n  PS[\"Parameter Store<br/>/app/env/*\"] -->|build time| B[\"gatsby build\"]\n  B --> OUT[\"Static bundle<br/>HTML / JS / CSS\"]\n  OUT --> CDN[\"CDN / Browser\"]\n  RT[\"Runtime secrets<br/>never here\"] -.->|not in bundle| OUT\n```\n\nAlles, was zur Build-Zeit in das statische Bundle wandert, ist öffentlich. Punkt. Ein API-Endpoint, ein öffentlicher Content-Delivery-Key, ein Feature-Flag, eine Analytics-ID – das darf im ausgelieferten JavaScript stehen, weil es ohnehin für jeden Browser sichtbar ist. Gatsby macht das durch die `GATSBY_`-Präfixkonvention sogar explizit: Diese Variablen werden bewusst in das Client-Bundle eingebettet.\n\nAlles, was ein echtes Geheimnis ist – ein schreibender Datenbank-Zugang, ein privater API-Key, ein Signaturschlüssel – gehört niemals in einen Build-Time-Wert für ein Frontend. Nicht, weil der Parameter Store es nicht schützen könnte, sondern weil das Ziel ein statisches, öffentlich ausgeliefertes Artefakt ist. Der sicherste Speicher der Welt hilft nichts, wenn ich den entschlüsselten Wert danach in eine Datei schreibe, die auf einem CDN landet.\n\nDer Parameter Store verführt hier ein wenig, und das ist die harte Frage zu Secrets: Weil er `SecureString` und KMS anbietet, fühlt sich jeder Wert „sicher“ an. Aber die Sicherheit endet an der Grenze des Builds. Ich sortiere deshalb jeden Parameter vorab in genau eine von zwei Schubladen: „darf öffentlich sein“ oder „ist ein Laufzeit-Geheimnis“. Nur die erste Schublade darf das Plugin überhaupt anfassen. Echte Laufzeit-Secrets gehören in eine Serverless-Function oder ein Backend, das sie zur Laufzeit selbst aus dem Parameter Store liest und nie an den Client gibt.\n\n## Der zweite Trade-off: Reproduzierbarkeit\n\nDie zweite harte Frage ist subtiler und wird gern übersehen. In dem Moment, in dem der Build externe Konfiguration liest, ist er keine Pure Function des Repositories mehr. Derselbe Git-Commit erzeugt nicht mehr zwangsläufig dasselbe Ergebnis – er erzeugt das Ergebnis, das zum externen Zustand des Parameter Store zum Build-Zeitpunkt passt.\n\nDas ist ein realer Verlust. Ändert jemand einen Wert im Parameter Store und stößt kein Rebuild an, driften Deployment und deklarierte Konfiguration auseinander, ohne dass ein Commit das anzeigt. Ein Rollback auf einen alten Commit stellt womöglich nicht die alte Konfiguration wieder her, weil die Parameterwerte sich inzwischen verändert haben. „Funktioniert bei mir“ bekommt eine neue, unangenehme Dimension: bei mir mit dem Parameter-Stand von gestern.\n\nDer Parameter Store hat für dieses Problem ein Werkzeug, und ich halte es für den entscheidenden methodischen Hebel: Jeder Parameter ist versioniert. Ich kann eine konkrete Version referenzieren – `/app/prod/KEY:4` – statt „den jeweils aktuellen Wert“. Damit wird der Build wieder deterministischer: Ein Commit plus ein gepinnter Parameter-Stand ergibt ein reproduzierbares Artefakt. Der Preis ist eine bewusste Disziplin, denn jemand muss die Version anheben und damit die Konfigurationsänderung genauso behandeln wie eine Code-Änderung: sichtbar, nachvollziehbar, rollback-fähig. Genau das ist der Punkt, an dem Konfiguration aufhört, ein Nebenschauplatz zu sein, und Teil der Architektur wird.\n\n## Was das messbar besser macht\n\nDer Aufwand lohnt sich, weil er an drei Stellen konkrete Wirkung zeigt, nicht nur Eleganz.\n\nKürzere Zyklen: Eine neue Umgebung ist ein neuer Pfad im Parameter Store, kein neues Ritual aus `.env`-Dateien, Copy-Paste und Nachfragen im Chat. Ein Deploy braucht keine manuelle Vorbereitung mehr, weil die Konfiguration dort liegt, wo der Build sie ohnehin abholt. Der Weg von „Wert ändern“ zu „Wert ist live“ verkürzt sich auf ein Parameter-Update plus einen Build.\n\nWeniger Reibung: Der Zugriff ist über IAM an Umgebungen gebunden, nicht an Personen mit Dateizugriff. Ein Entwickler kann eine Staging-Konfiguration selbst setzen, ohne an ein produktives Geheimnis zu kommen. Self-Service innerhalb sauberer Grenzen ersetzt das Nadelöhr, an dem sonst eine einzelne Person sitzt, die „die `.env` kennt“.\n\nHöhere Qualität: Config-Drift wird strukturell unwahrscheinlicher, weil es nur noch eine Quelle gibt. Und wenn doch etwas schiefgeht, gibt es einen Audit-Trail. CloudTrail beantwortet die Frage „Wer hat wann welchen Wert geändert?“ – die Frage, die bei einer Streuung aus Dateien und CI-Secrets prinzipiell unbeantwortbar bleibt.\n\nEs gibt noch einen vierten Effekt, der leicht übersehen wird, aber im Alltag viel Reibung spart: Dieselbe Mechanik funktioniert lokal. Ein Entwickler, der die Staging-Werte lesen darf, startet seinen lokalen Build gegen exakt denselben Pfad im Parameter Store wie die Pipeline – kein manuelles Kopieren einer `.env`, kein veralteter lokaler Stand, keine Diskussion darüber, warum etwas lokal anders läuft als in Staging. Das schließt eine der ärgerlichsten Lücken im Entwicklungszyklus, nämlich die zwischen der Konfiguration auf dem Laptop und der Konfiguration im CI. Damit verliert das „Funktioniert bei mir“ von weiter oben einen seiner häufigsten Gründe, weil Laptop und Pipeline aus derselben Quelle lesen. Wichtig bleibt auch hier die Grenze: lokal darf nur der öffentliche, build-taugliche Teilbaum sichtbar sein, niemals ein produktives Laufzeit-Geheimnis.\n\n## Worauf ich vor dem Einsatz prüfe\n\nEine Idee ist erst belastbar, wenn ihr Fehlerpfad beschrieben ist. Bevor ich das Plugin in eine Pipeline hänge, gehe ich ein paar Fragen durch, die im Demo-Modus alle unsichtbar bleiben und im Betrieb entscheiden.\n\nWas passiert, wenn der Parameter Store beim Build nicht erreichbar ist oder ein erwarteter Wert fehlt? Ein Build, der stillschweigend mit einem leeren `process.env.GATSBY_API_URL` durchläuft, ist gefährlicher als einer, der laut abbricht – denn er produziert ein defektes, aber deploybares Artefakt. Ich will hier ein hartes Fail-Fast, kein `undefined`, das erst im Browser des Nutzers auffällt.\n\nIst der Zugriff eng genug geschnitten? Der Build-Runner sollte über eine IAM-Rolle genau den einen Umgebungspfad lesen dürfen und `withDecryption` nur für die Werte, die er wirklich braucht. Ein weit gefasster `ssm:GetParametersByPath`-Zugriff über die gesamte Hierarchie ist bequem und genau die Art von Bequemlichkeit, die ein Sicherheits-Review später teuer macht.\n\nUnd die entscheidende Frage: Liegt in dem Pfad, den der Build liest, versehentlich ein echtes Geheimnis? Das ist kein technischer, sondern ein disziplinärer Fehler – und der häufigste. Deshalb trenne ich die Hierarchie schon in der Benennung, sodass build-öffentliche Werte und Laufzeit-Secrets gar nicht erst im selben Teilbaum landen und ein zu weiter Zugriff nicht sofort ein Leak bedeutet.\n\n## Der typische Fehler\n\nDer verführerischste Fehler bei diesem Thema ist, das Werkzeug mit der Lösung zu verwechseln. Der Parameter Store ist keine Konfigurationsarchitektur, so wenig wie ein verschlüsselter Speicher automatisch eine Secrets-Strategie ist. Er ist ein sehr guter Ort, um eine Grenze auszudrücken – die Grenze zwischen build-öffentlicher Konfiguration und Laufzeit-Geheimnis, zwischen Umgebungen, zwischen dem, was ein Build lesen darf, und dem, was er nie sehen sollte. Aber diese Grenze erzeuge ich, nicht der Service.\n\nGenau darin liegt der eigentliche Wert dieses kleinen Plugins. Es zwingt mich, die Frage zu beantworten, die die `.env`-Streuung erfolgreich verdeckt hat: Was von der Konfiguration meines Frontends ist öffentlich, was ist geheim, und wer besitzt jeden dieser Werte über seinen Lifecycle hinweg? Sobald diese Antwort steht, ist der technische Rest – ein Pfad, ein Plugin, ein `GetParametersByPath` – fast trivial.\n\n## Schluss\n\nParameter Store im Build ist ein gutes Beispiel dafür, dass die interessante Entscheidung selten im Toolnamen steckt. Das Plugin holt Werte aus AWS – das ist die einfache Hälfte. Die tragende Hälfte ist die Methodik dahinter: Konfiguration explizit machen, sie an genau einer Stelle mit klaren Zugriffsgrenzen führen, die Trennung von öffentlich und geheim erzwingen und die Reproduzierbarkeit über gepinnte Versionen zurückholen.\n\nWer diese Linien zieht, gewinnt kürzere Deploy-Zyklen, weniger Reibung bei jeder Umgebung und weniger stille Fehler im Betrieb. Wer sie nicht zieht, hat am Ende einen sehr sicheren Speicher, aus dem trotzdem Geheimnisse in ein öffentliches Bundle sickern. Der Unterschied liegt nicht im Service, sondern in der Entscheidung, die er sichtbar macht."},{"locale":"de","translation_key":"docker-eigene-registry","slug":"docker-eigene-registry","title":"Eine eigene Docker Registry betreiben","summary":"Wie ich in Projekten eine private Docker Registry mit registry:2 aufsetze: Images taggen, pushen und pullen, und danach mit htpasswd und TLS absichern.","tags":["Software","Platform"],"published_at":"2018-11-27T10:00:00+00:00","updated_at":"2026-07-13T07:28:25.481931+00:00","url":"https://www.mikebild.dev/de/blog/docker-eigene-registry/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/65a01a1ed070b002a16c1404c84d171de988269e4c5f4fdfba82533fbd6f1315/docker-eigene-registry-vorlesen.mp3","audio_duration_secs":957,"text":"Eine Docker Registry ist kein Dateiserver, auf dem man Images ablegt. Sie ist der Namensraum, über den Docker Images überhaupt adressiert: Ein voll qualifizierter Image-Name hat die Form `host:port/name:tag`, und der Host-Teil darin entscheidet, wohin ein `push` geht und woher ein `pull` kommt. Fehlt er, ist Docker Hub gemeint – auch dann, wenn im Image der eigene Anwendungscode steckt.\n\n**Redaktionelle Einordnung (Juli 2026):** Das Tutorial beschreibt den Stand von 2018. Docker Content Trust basiert auf Notary v1 und wird von Docker abgekündigt; für neue Signatur- und Verifikationsabläufe nennt Docker Sigstore oder Notation. Auch Portus ist keine heutige Produktempfehlung mehr: Das Projekt wurde 2023 archiviert. Der grundlegende Registry-Betrieb mit `registry:2`, TLS, Authentifizierung und immutable Digests bleibt davon unberührt.\n\nWer diesen Host-Teil selbst setzt, entscheidet damit auch, wo die eigenen Images liegen, woher sie stammen und wer dafür geradesteht, dass in Produktion genau das läuft, was gebaut und geprüft wurde. Der Weg dahin ist kurz. Zuerst klären wir, warum eine private Registry überhaupt sinnvoll ist. Dann starten wir `registry:2` mit einem einzigen Kommando, taggen ein Image, pushen es und ziehen es auf einem anderen Host wieder herunter. Weil eine offene Registry ein echtes Problem ist, sichern wir sie mit Basic-Auth und TLS ab. Zum Schluss geht es über das Werkzeug hinaus: um Herkunft, Signatur und Betriebsverantwortung der eigenen Images. Wer Docker Compose schon kennt – etwa aus meinem Artikel zu [Node.js und Redis mit Docker Compose](https://www.mikebild.dev/de/blog/docker-compose-nodejs-redis/) – wird sich hier schnell zurechtfinden.\n\n## Warum überhaupt eine eigene Registry?\n\nDocker Hub ist bequem. Man pusht ein Image, es liegt in der Cloud, jeder kann es ziehen. Genau das ist aber in vielen Firmenkontexten das Problem: Der eigene Anwendungscode steckt im Image, und der soll nicht öffentlich einsehbar sein. Klar, es gibt private Repositories bei Docker Hub, aber dann hängt die gesamte Deployment-Kette an einem externen Dienst und an einer Internetverbindung, die durchaus mal langsam oder gestört sein kann.\n\nEine private Registry im eigenen Netz löst diese Punkte auf einen Schlag. Die Images bleiben intern, das Ziehen läuft über das lokale Netzwerk und ist damit spürbar schneller, und man behält die volle Kontrolle darüber, wo die Daten liegen und wie lange sie aufbewahrt werden. Gerade in einer CI/CD-Pipeline, die viele Builds am Tag durch die Gegend schiebt, macht sich das schnell bemerkbar.\n\nDamit die Unterschiede greifbar werden, stelle ich beides gern direkt gegenüber:\n\n- Die private Registry hoste ich selbst, im eigenen Netz, mit voller Kontrolle über Speicherort und Lifecycle – dafür betreibe und sichere ich sie auch selbst.\n- Docker Hub ist ein gehosteter Dienst mit Accounts, Organisationen, Web-Oberfläche und offiziellen Images – dafür internetabhängig und außerhalb der eigenen Infrastruktur.\n\nBeides hat seine Berechtigung. Offizielle Basis-Images wie `node`, `redis` oder eben `registry` selbst ziehe ich weiterhin von Docker Hub. Die eigenen Anwendungs-Images landen dagegen in der privaten Registry. Das eine schließt das andere nicht aus.\n\n## Die Registry ist selbst nur ein Container\n\nKommen wir zum eigentlichen Werkzeug. Die Open-Source-Registry, die hinter Docker Hub dieselbe Technik verwendet, heißt „Docker Distribution“ und wird als fertiges Image `registry:2` bereitgestellt. Kein separater Server, keine aufwendige Installation – ein `docker run`, und die Registry läuft. Standardmäßig hört sie auf Port 5000.\n\n```bash\ndocker run -d \\\n  -p 5000:5000 \\\n  --restart=always \\\n  --name registry \\\n  -v /mnt/registry:/var/lib/registry \\\n  registry:2\n```\n\nEin paar Dinge sind hier bewusst gesetzt. Das `-d` startet den Container im Hintergrund. `--restart=always` sorgt dafür, dass die Registry nach einem Neustart des Docker-Daemons oder des Hosts von allein wieder hochkommt – für einen Dienst, an dem die ganze Pipeline hängt, will man das. Und ganz wichtig: das Volume mit `-v`. Die Registry legt ihre Images per Default über den Filesystem-Storagetreiber unter `/var/lib/registry` ab. Ohne Volume liegen diese Daten nur im Container. Löscht man den Container, sind die Images weg. Mit dem gemounteten Verzeichnis `/mnt/registry` bleiben sie erhalten.\n\nDamit läuft die Registry. Sie tut jetzt aber noch nichts Sichtbares – sie wartet auf ihr erstes Image.\n\n## Taggen, pushen, pullen\n\nDer entscheidende Punkt beim Umgang mit einer eigenen Registry ist der Image-Name. Docker steuert nämlich nicht über einen separaten Konfigurationsschalter, in welche Registry ein Image wandert, sondern über den Namen selbst. Ein voll qualifizierter Image-Name hat die Form `host:port/name:tag`. Fehlt der Host-Teil, geht Docker automatisch von Docker Hub (`docker.io`) aus. Setze ich dagegen meinen eigenen Registry-Host vor den Namen, weiß Docker beim `push` und `pull` genau, wohin.\n\nNehmen wir an, ich habe lokal ein Image `app:1.0` gebaut. Dann tagge ich es für meine Registry um:\n\n```bash\ndocker tag app:1.0 registry.local:5000/app:1.0\n```\n\n`docker tag` kopiert dabei nichts und baut nichts neu – es hängt lediglich einen zweiten Namen an dasselbe Image. Anschließend schiebe ich es in die Registry:\n\n```bash\ndocker push registry.local:5000/app:1.0\n```\n\nDocker liest den Host-Teil `registry.local:5000` aus dem Namen und lädt die einzelnen Layer dorthin hoch. Auf einem anderen Rechner im selben Netz – oder auf dem CI-Runner, der später das Deployment übernimmt – hole ich das Image genauso wieder herunter:\n\n```bash\ndocker pull registry.local:5000/app:1.0\n```\n\nDas ist der komplette Kreislauf. Bauen, taggen, pushen, an anderer Stelle pullen. Genau diesen Bogen halte ich gern als Diagramm fest, weil er das Zusammenspiel auf einen Blick zeigt:\n\n```mermaid\nflowchart LR\n    A[docker build<br/>app:1.0] --> B[docker tag<br/>registry.local:5000/app:1.0]\n    B --> C[docker push]\n    C --> D[(Private Registry<br/>:5000)]\n    D --> E[docker pull<br/>anderer Host / CI]\n```\n\nAm Registry-Host hängt damit die ganze Mechanik. Das erklärt auch, warum das Umtaggen vor dem Push nötig ist: Ein Image, das nur `app:1.0` heißt, würde Docker in Richtung Docker Hub schicken.\n\n## Der wunde Punkt: Ab Werk steht alles offen\n\nDie Registry, die wir gerade gestartet haben, läuft ohne jede Absicherung. Kein Passwort, keine Verschlüsselung. Jeder, der `registry.local:5000` im Netz erreicht, kann pushen und pullen. Für einen kurzen lokalen Test auf dem eigenen Rechner ist das in Ordnung. Sobald die Registry aber für mehr als einen Rechner erreichbar ist, darf sie so nicht bleiben.\n\nAbsicherung besteht dabei aus zwei voneinander unabhängigen Bausteinen, die man nicht verwechseln sollte:\n\n- TLS verschlüsselt den Transport, damit niemand mitlesen kann, was über die Leitung geht.\n- Basic-Auth per htpasswd schützt den Zugriff, damit nur berechtigte Nutzer pushen und pullen.\n\nDas eine ersetzt das andere nicht. TLS ohne Auth verschlüsselt zwar, lässt aber jeden herein. Auth ohne TLS wiederum wird von der Registry gar nicht akzeptiert – die Passwörter dürften ja im Klartext übers Netz gehen, und das lässt `registry:2` bewusst nicht zu. Beides gehört also zusammen.\n\nSchauen wir uns zuerst die Auth an. Für Basic-Auth braucht die Registry eine `htpasswd`-Datei, und zwar zwingend mit bcrypt-Hashes. Die erzeuge ich mir am einfachsten mit dem `httpd`-Image, das das Werkzeug `htpasswd` mitbringt:\n\n```bash\ndocker run --rm --entrypoint htpasswd httpd:2 \\\n  -Bbn deploy s3cret > auth/htpasswd\n```\n\nDie Flags sind schnell erklärt: `-B` erzwingt bcrypt (das ist Pflicht für die Registry), `-b` übergibt das Passwort direkt in der Kommandozeile, und `-n` gibt das Ergebnis auf stdout aus, statt es in eine Datei zu schreiben – deshalb leite ich die Ausgabe selbst nach `auth/htpasswd` um. Herausgekommen ist ein Nutzer `deploy` mit dem Passwort `s3cret`.\n\nFür TLS brauche ich ein Zertifikat und den passenden Schlüssel. In einer echten Umgebung kommen die von einer internen CA oder von Let's Encrypt; im Testnetz tut es ein selbstsigniertes Paar. Die beiden Dateien lege ich als `domain.crt` und `domain.key` in ein Verzeichnis `certs`.\n\nJetzt starte ich die Registry neu – diesmal mit beiden Schutzschichten. Die Konfiguration übergebe ich über Umgebungsvariablen, die die Registry beim Start ausliest:\n\n```bash\ndocker run -d \\\n  -p 5000:5000 \\\n  --restart=always \\\n  --name registry \\\n  -v \"$(pwd)\"/auth:/auth \\\n  -v \"$(pwd)\"/certs:/certs \\\n  -v /mnt/registry:/var/lib/registry \\\n  -e REGISTRY_AUTH=htpasswd \\\n  -e \"REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm\" \\\n  -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd \\\n  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \\\n  -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \\\n  registry:2\n```\n\nDie `REGISTRY_AUTH_*`-Variablen schalten die htpasswd-Authentifizierung ein und zeigen auf die eben erzeugte Datei im gemounteten `/auth`-Verzeichnis. Die beiden `REGISTRY_HTTP_TLS_*`-Variablen aktivieren TLS mit Zertifikat und Schlüssel aus `/certs`. Von jetzt an muss man sich anmelden, bevor man etwas pushen darf:\n\n```bash\ndocker login registry.local:5000\n```\n\nNach der Anmeldung mit Nutzername und Passwort funktionieren `push` und `pull` wieder wie gewohnt – nur eben abgesichert. Docker merkt sich das Login lokal, sodass die Pipeline nach einmaligem `docker login` durchläuft.\n\nDer Vollständigkeit halber: Statt alles über Umgebungsvariablen zu setzen, kann man der Registry auch eine eigene `config.yml` mitgeben. Dort stehen dieselben Angaben strukturiert unter `auth.htpasswd`, `http.tls` und `storage.filesystem`. Man baut sich dann ein kleines Image `FROM registry:2`, kopiert die Konfiguration hinein und startet sie über den passenden Entrypoint. Beide Wege sind gängig; für den Einstieg finde ich die Variante mit Umgebungsvariablen übersichtlicher, weil man alles in einem Kommando sieht.\n\nWie die beiden Schutzschichten zusammenspielen und wo der unsichere Notausgang liegt, zeigt dieses Bild:\n\n```mermaid\nflowchart LR\n    C[Client] -->|TLS| R[Registry-Container :5000]\n    R -->|htpasswd-Auth| S[(Storage-Volume<br/>/var/lib/registry)]\n    C2[Client ohne TLS] -.HTTP.-> I[insecure-registries<br/>nur Testnetz]\n    I -.-> R\n```\n\n## Wenn kein TLS zur Hand ist\n\nBeim schnellen Ausprobieren kommt es vor, dass gerade kein Zertifikat greifbar ist, man aber trotzdem einen Push testen will. Dann läuft man in eine typische Fehlermeldung: `http: server gave HTTP response to HTTPS client`. Der Docker-Client erwartet nämlich standardmäßig HTTPS und verweigert die Kommunikation mit einer reinen HTTP-Registry.\n\nFür genau diesen Fall gibt es eine Ausnahme – die man aber wirklich nur im abgeschotteten Testnetz einsetzen sollte. Man trägt die Registry auf jedem Client als „insecure“ in die Datei `/etc/docker/daemon.json` ein:\n\n```json\n{\n  \"insecure-registries\": [\"registry.local:5000\"]\n}\n```\n\nDanach muss der Docker-Daemon neu gestartet werden, damit die Änderung greift. Wichtig ist das „auf jedem Client“: Der Eintrag gilt lokal pro Rechner, nicht zentral in der Registry. Wer die Registry auf fünf Hosts nutzt, pflegt den Eintrag fünfmal. Für eine dauerhaft betriebene Registry ist das kein Zustand – da führt an TLS kein Weg vorbei. Kommt ein selbstsigniertes Zertifikat zum Einsatz, muss man es übrigens als CA auf den Clients hinterlegen, sonst misstraut ihm der Docker-Client genauso.\n\n## Die Registry als Kontrollpunkt in der Lieferkette\n\nBis hierhin war die Registry vor allem ein Transportmittel: bauen, taggen, pushen, pullen. Der eigentliche Hebel liegt aber eine Ebene höher. Sobald alle eigenen Images durch eine Registry laufen, die ich selbst kontrolliere, wird sie zum zentralen Punkt, an dem sich die Herkunft dessen entscheidet, was in Produktion läuft. In vielen Firmenkontexten zählt genau das mehr als die paar Sekunden, die ein Pull im lokalen Netz spart.\n\nDer erste Punkt ist die Herkunft. Ein Tag wie `registry.local:5000/app:1.0` ist bequem, aber veränderlich. Nichts hindert jemanden daran, denselben Tag später mit einem anderen Inhalt zu überschreiben – der Name bleibt gleich, das Image dahinter ist ein anderes. Wer verbindlich wissen will, welches Image läuft, referenziert es über seinen Digest statt über den Tag:\n\n```bash\ndocker pull registry.local:5000/app@sha256:9b2a4c...\n```\n\nDer Digest ist der Hash über den Image-Inhalt und damit immutable. Zieht ein CI-Runner oder ein Produktionshost ein Image per Digest, bekommt er garantiert genau die Bits, die einmal gebaut und geprüft wurden – nicht das, was zufällig gerade unter dem Tag liegt. In der Pipeline heißt das: Der Build gibt den Digest aus, das Deployment pinnt genau diesen Digest, und der Tag bleibt nur ein lesbarer Name für Menschen, kein Vertrauensanker.\n\nDer zweite Punkt ist die Signatur. Die Herkunft über den Digest sagt „es ist dasselbe Image“, aber noch nicht „es kommt von dem, von dem es kommen soll“. Dafür gibt es Docker Content Trust. Setze ich `DOCKER_CONTENT_TRUST=1`, signiert Docker die Images beim Push und verlangt beim Pull eine gültige Signatur:\n\n```bash\nexport DOCKER_CONTENT_TRUST=1\ndocker push registry.local:5000/app:1.0\n```\n\nIm Hintergrund verwaltet ein Notary-Dienst die Signaturen und die zugehörigen Schlüssel. Der Gewinn ist, dass ein Client ein untergeschobenes oder manipuliertes Image erkennt und den Pull verweigert, statt es blind auszuführen. Das kostet Aufwand – Schlüssel wollen erzeugt, sicher verwahrt und rotiert werden – und ist für einen reinen Testaufbau überzogen. Sobald Images aber bis in die Produktion laufen, ist die Frage „wurde das von uns gebaut und seitdem nicht angefasst?“ keine akademische mehr.\n\nDer dritte Punkt ist die Betriebsverantwortung, die Kehrseite der ganzen Kontrolle. Wer die Registry selbst betreibt, entscheidet nicht nur, wer pushen und pullen darf. Er ist auch dafür verantwortlich, dass der Dienst läuft, gepatcht ist, seine Daten behält und im Zweifel wiederherstellbar bleibt. Diese Verantwortung verschwindet nicht, sie wechselt nur den Besitzer. Bei Docker Hub trägt sie der Anbieter, bei der eigenen Registry trage ich sie.\n\nDaraus ergab sich 2018 das eigentliche Entscheidungskriterium. `registry:2` reichte, solange Herkunft und Zugriff mit Digests, einer Handvoll htpasswd-Nutzern und Content Trust abgedeckt waren. Sobald aber viele Teams, feingranulare Rechte, nachvollziehbare Audit-Logs und eine belastbare Trennung zwischen „gebaut“ und „produktionsfreigegeben“ gefordert waren, kamen Produkte wie Portus, Sonatype Nexus oder JFrog Artifactory ins Spiel. Portus ist inzwischen archiviert; für eine heutige Auswahl muss der Wartungs- und Supportstatus neu geprüft werden.\n\n## Was man beim Betrieb im Blick behalten sollte\n\nZwei Dinge gehen im ersten Enthusiasmus gern unter. Das erste ist die schon erwähnte Persistenz: Ohne gemountetes Volume verliert man beim nächsten Container-Neustart alle Images. Das Volume ist also nicht optional, sondern Grundausstattung.\n\nDas zweite ist der Speicherplatz. Das Filesystem-Backend wächst mit jedem Push, und alte, längst nicht mehr benötigte Layer verschwinden nicht von allein. Mit der Zeit läuft die Platte voll. Die Registry bringt dafür eine Garbage Collection mit, die man regelmäßig laufen lassen sollte, um nicht mehr referenzierte Blobs aufzuräumen. Das ist im Betrieb schnell vergessen und rächt sich dann Monate später mit einer vollen Festplatte. Ein Backup des Storage-Verzeichnisses gehört ebenfalls dazu – bei einer selbst betriebenen Registry kümmert sich niemand sonst darum. Das sind die konkreten Handgriffe hinter dem Wort Betriebsverantwortung. Dass `registry:2` mit einem Kommando startet, nimmt sie einem nicht ab – sie liegen von da an bei mir.\n\n## Fazit\n\nEine eigene Docker Registry klingt nach Infrastrukturprojekt, ist technisch aber eine Sache von wenigen Minuten – solange man die entscheidenden Punkte verinnerlicht. Die Registry ist selbst nur ein Container, `registry:2`, und der Registry-Host wird über den Image-Namen `host:port/name:tag` angesteuert. Ab Werk steht alles offen, und Absicherung braucht immer beide Bausteine – TLS für den verschlüsselten Transport und htpasswd für den Zugriffsschutz. Der `insecure-registries`-Eintrag ist eine Testnetz-Krücke, kein Betriebszustand.\n\nDer eigentliche Gewinn zeigt sich erst im Betrieb. Die eigenen Images liegen im eigenen Netz, sind schneller verfügbar und verkürzen die Wege in der Pipeline. Über Digests und den damals üblichen Docker Content Trust wurde aus schnellem Ausliefern ein nachvollziehbares Ausliefern – man wusste, was lief und woher es kam. Genauso klar sind die Grenzen: Wo Governance über viele Teams, feingranulare Rechte und lückenlose Audits verlangt ist, endet `registry:2` und ein spezialisiertes Produkt beginnt. Für alles davor reichen ein Container, ein sauber gesetzter Host-Teil im Image-Namen und zwei Schutzschichten.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-docker-kubernetes.html\n- [Deploy a registry server – docs.docker.com](https://docs.docker.com/registry/deploying/)\n- [Run an externally-accessible registry (Basic-Auth + TLS)](https://docs.docker.com/registry/deploying/#run-an-externally-accessible-registry)\n- [Registry configuration reference (config.yml)](https://docs.docker.com/registry/configuration/)\n- [Test an insecure registry (daemon.json)](https://docs.docker.com/registry/insecure/)\n- [docker tag / docker push / docker pull / docker login – CLI-Referenz](https://docs.docker.com/engine/reference/commandline/tag/)\n- [Docker Content Trust und Notary v1](https://docs.docker.com/engine/security/trust/)\n- [Docker: abgekündigte Produkte und empfohlene Alternativen](https://docs.docker.com/retired/)\n- [Portus – archiviertes Repository](https://github.com/SUSE/Portus)\n- [Node.js und Redis mit Docker Compose](https://www.mikebild.dev/de/blog/docker-compose-nodejs-redis/)"},{"locale":"de","translation_key":"kubernetes-grundlagen-deployment-druck","slug":"kubernetes-grundlagen-deployment-druck","title":"Kubernetes-Grundlagen durch Deployment-Druck","summary":"Unter dem Druck eines echten Deployments sortieren sich die Kubernetes-Konzepte von selbst nach Wichtigkeit – vom Pod über Deployment und Service bis zum Ingress.","tags":["Software","Platform"],"published_at":"2018-10-24T10:00:00+00:00","updated_at":"2026-07-14T17:06:45.428736+00:00","url":"https://www.mikebild.dev/de/blog/kubernetes-grundlagen-deployment-druck/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/54d0903061f2b963b97aaac292874baf616bf19efcf221a311c4e2ab9efe5bee/kubernetes-grundlagen-deployment-druck-vorlesen.mp3","audio_duration_secs":691,"text":"# Kubernetes-Grundlagen durch Deployment-Druck\n\nUm zwei Uhr nachts stirbt ein Container. Kein Angriff, kein Hardware-Defekt – der Node.js-Prozess darin ist über ein Speicherleck gestolpert, das Betriebssystem hat ihn beendet, und mit dem Prozess ist auch der Container weg. Ab diesem Moment entscheidet eine einzige Frage über den Rest der Nacht: Wer startet ihn neu, wenn niemand hinschaut? Auf einem klassisch betriebenen Server ist die Antwort immer eine Kette aus Menschen und Halbautomatik – ein Monitoring, das jemanden anruft, eine systemd-Unit mit Restart-Regel, ein Admin mit SSH-Zugang und wenig Schlaf. Die Konsequenz aus solchen Nächten ist der eigentliche Grund, warum es Kubernetes gibt: ein System, in dem der Neustart keine menschliche Reaktion ist, sondern der Normalbetrieb einer Maschine, die ununterbrochen Soll und Ist vergleicht.\n\n## Die Doku erklärt alles, nur nicht die Reihenfolge\n\nWer Kubernetes über die Konzept-Dokumentation lernen will, bekommt ein Vokabelheft: Pods, ReplicaSets, Deployments, Services, Endpoints, Ingress, ConfigMaps, Secrets, Volumes, Namespaces, DaemonSets, StatefulSets, Jobs, CronJobs. Alles korrekt beschrieben, alles gleichberechtigt nebeneinander. Genau das ist das Problem. Die Doku ist ein Nachschlagewerk, keine Lernreihenfolge – und ohne Reihenfolge fühlt sich Kubernetes an wie eine Fremdsprache, bei der man erst sprechen darf, wenn man das komplette Wörterbuch auswendig kann.\n\nMir ist das dieses Jahr in einem Projekt aufgefallen, in dem eine bestehende Node.js-Anwendung samt Datenbank in ein Cluster umziehen sollte – mit Termin, nicht irgendwann. Unter diesem Deployment-Druck passierte etwas Interessantes: Die Konzepte sortierten sich von selbst. Nicht nach der Gliederung der Dokumentation, sondern nach der Frage, ohne welches Objekt die Anwendung jetzt nicht läuft. Übrig blieb eine erstaunlich kurze Liste:\n\n- Pod – das, was wirklich läuft\n- Deployment – das, was Pods am Leben hält\n- Service – eine stabile Adresse vor unstabilen Pods\n- Ingress – die Tür nach draußen\n- ConfigMap und Secret – Konfiguration raus aus dem Image\n\nAlles andere – StatefulSets, DaemonSets, NetworkPolicies, die Feinheiten von RBAC – kam erst später dran, als die Anwendung schon lief und der Druck nachgelassen hatte. Die Beispiele, an denen ich diese Reihenfolge durchgespielt habe, liegen öffentlich im Repository [introduction-kubernetes](https://github.com/MikeBild/introduction-kubernetes): eine Materialsammlung rund um eine kleine Todo-Anwendung aus Frontend, Backend und Datenbank, lokal mit Minikube nachvollziehbar.\n\n## Zielzustand statt Kommando-Choreografie\n\nDie wichtigste Grundeinsicht steht in keinem YAML-Beispiel, sondern dahinter: Kubernetes ist deklarativ. Man sagt dem Cluster nicht, was er tun soll, sondern beschreibt, wie die Welt aussehen soll, wenn alles gut ist. Drei Kopien dieses Containers, erreichbar unter diesem Namen, mit dieser Konfiguration. Ein Controller-Loop vergleicht diesen Zielzustand pausenlos mit der Wirklichkeit und korrigiert die Differenz. Stirbt ein Pod, fehlt einer – also wird einer gestartet. Nicht weil jemand einen Befehl gibt, sondern weil Soll und Ist nicht mehr übereinstimmen.\n\n```mermaid\nflowchart LR\n  M[Manifest<br/>todo-api.yaml] -->|kubectl apply| A[API-Server]\n  A --> E[(etcd<br/>Zielzustand)]\n  C[Controller-Loop] -->|liest Soll| E\n  C -->|misst Ist| P[Pods im Cluster]\n  C -->|korrigiert Differenz| P\n```\n\nDas erklärt auch, warum `kubectl apply -f` das zentrale Kommando ist – und nicht eine Choreografie aus „starte dies, dann jenes, dann verdrahte beides\". Auf dem alten Server war ein Deployment ein Drehbuch: Shell-Skripte in der richtigen Reihenfolge, und wehe, Schritt vier schlägt fehl, während Schritt drei schon durch ist. In Kubernetes gibt es dieses Drehbuch nicht mehr. Es gibt nur eine Beschreibung des Zielzustands, und `apply` übergibt sie. Was danach passiert, ist Sache der Controller – auch nachts um zwei.\n\n## Der Pod: das, was wirklich läuft\n\nEin Pod ist die kleinste Einheit, die Kubernetes startet: ein oder mehrere Container, die sich Netzwerk und Lifecycle teilen. In der Praxis fast immer ein Container pro Pod. Die zweite Einsicht unter Druck: Pods sind Wegwerfware. Man legt sie selten direkt an, man pflegt sie nicht, man repariert sie nicht. Ein Pod, der stirbt, wird nicht geheilt, sondern ersetzt – mit neuem Namen und neuer IP-Adresse. Wer das akzeptiert, versteht den Rest des Systems fast von allein. Wer dagegen versucht, an einzelnen Pods zu hängen, per `kubectl exec` hineinzuklettern und Zustand zu retten, kämpft gegen die Plattform statt mit ihr.\n\n## Das Deployment: Selbstheilung als Kern-Idee\n\nWeil Pods sterblich sind, braucht es etwas, das sie am Leben hält. Das ist das Deployment – für mich das eigentliche Herzstück:\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: todo-api\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: todo-api\n  template:\n    metadata:\n      labels:\n        app: todo-api\n    spec:\n      containers:\n        - name: todo-api\n          image: mikebild/todo-api:1.4.2\n          ports:\n            - containerPort: 3000\n          readinessProbe:\n            httpGet:\n              path: /health\n              port: 3000\n            initialDelaySeconds: 5\n          livenessProbe:\n            httpGet:\n              path: /health\n              port: 3000\n            initialDelaySeconds: 15\n```\n\nSeit Kubernetes 1.9 ist `apps/v1` die stabile API-Version dafür, das Rätselraten der frühen Beta-Versionen ist vorbei. Das Deployment beschreibt drei Dinge: wie viele Kopien laufen sollen, wie ein Pod auszusehen hat und woran der Cluster erkennt, ob ein Pod gesund ist. Die Readiness-Probe entscheidet, ob ein Pod Traffic bekommt; die Liveness-Probe entscheidet, ob er neu gestartet wird. Diese Unterscheidung habe ich anfangs unterschätzt – bis ein Backend beim Start zwanzig Sekunden für den Datenbank-Verbindungsaufbau brauchte und ohne Readiness-Probe munter Anfragen in ein noch nicht bereites System liefen.\n\nDer Moment, in dem Kubernetes bei mir „klick\" gemacht hat, war ein bewusst herbeigeführter Ausfall:\n\n```bash\nkubectl apply -f todo-api.yaml\nkubectl get pods --watch\nkubectl delete pod todo-api-7d9f6c8b45-x2x7k   # simulate a crash\n# a replacement pod appears within seconds\nkubectl rollout status deployment todo-api\nkubectl rollout undo deployment todo-api        # roll back a bad release\n```\n\nMan löscht einen Pod, und bevor man die Ausgabe gelesen hat, steht der Ersatz schon da. Das ist die Antwort auf die Zwei-Uhr-nachts-Frage – nicht als Feature-Versprechen, sondern beobachtbar im Terminal. Und `rollout undo` macht aus einem misslungenen Release keinen Notfall mehr, sondern einen Schritt zurück zum letzten funktionierenden Zielzustand.\n\n## Der Service: eine stabile Adresse vor unstabilen Pods\n\nWenn Pods ständig kommen und gehen und dabei ihre IP-Adressen wechseln, kann sich niemand direkt mit ihnen verbinden. Der Service löst genau dieses Problem: eine stabile virtuelle Adresse und ein DNS-Name, dahinter eine wechselnde Menge von Pods, ausgewählt über Labels.\n\n```yaml\napiVersion: v1\nkind: Service\nmetadata:\n  name: todo-api\nspec:\n  selector:\n    app: todo-api\n  ports:\n    - port: 80\n      targetPort: 3000\n```\n\nAb jetzt erreicht jeder Pod im Cluster das Backend unter `http://todo-api` – egal, welche drei Pods gerade dahinterstehen, egal, wie oft sie ersetzt wurden. Das Frontend der Todo-Anwendung kennt keine IP-Adressen mehr, nur noch diesen Namen. Für mich war das der Punkt, an dem sich die Umzugsarbeit zum ersten Mal gelohnt hat: Service-Discovery, die vorher aus gepflegten Konfigurationsdateien und Hoffnung bestand, ist im Cluster schlicht DNS.\n\n## Der Ingress: die Tür nach draußen\n\nServices sind zunächst nur innerhalb des Clusters erreichbar. Für den Weg nach draußen gibt es den Ingress – eine Regel, die Hostnamen und Pfade auf Services abbildet, ausgeführt von einem Ingress-Controller wie ingress-nginx:\n\n```yaml\napiVersion: extensions/v1beta1\nkind: Ingress\nmetadata:\n  name: todo-api\nspec:\n  rules:\n    - host: todo.example.com\n      http:\n        paths:\n          - path: /\n            backend:\n              serviceName: todo-api\n              servicePort: 80\n```\n\n```mermaid\nflowchart LR\n  B[Browser] --> I[Ingress<br/>todo.example.com]\n  I --> S[Service<br/>todo-api]\n  S --> P1[Pod]\n  S --> P2[Pod]\n  S --> P3[Pod]\n```\n\nEhrlicherweise ist der Ingress die unfertigste Ecke dieser Liste: Die Ressource steckt seit Jahren im Beta-Status (`extensions/v1beta1`), der Controller ist nicht Teil des Clusters, sondern muss separat installiert werden, und je nach Umgebung – Minikube, eigenes Cluster, GKE – verhält sich die Sache leicht unterschiedlich. Trotzdem gehört er in die Grundausstattung, denn ohne Tür nach draußen bleibt die schönste Anwendung ein Selbstgespräch.\n\n## ConfigMap und Secret: Konfiguration raus aus dem Image\n\nDer letzte Baustein der Druck-Liste klingt unspektakulär, hat aber die größte Wirkung auf den Alltag: Konfiguration gehört nicht in das Container-Image. Ein Image, das für Staging neu gebaut werden muss, weil eine Datenbank-Adresse anders lautet, ist kein Artefakt, sondern eine Bastelei. ConfigMaps und Secrets ziehen diese Werte aus dem Image heraus in den Cluster:\n\n```yaml\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: todo-api-config\ndata:\n  DATABASE_HOST: \"postgres\"\n  LOG_LEVEL: \"info\"\n```\n\nIm Deployment wird daraus per `envFrom` ein Satz Umgebungsvariablen, und dasselbe Image läuft unverändert lokal in Minikube und im Cluster beim Cloud-Anbieter. Bei Secrets lohnt ein nüchterner Blick: Die Werte sind Base64-kodiert, nicht verschlüsselt. Das trennt sie sauber von der übrigen Konfiguration und hält sie aus Git heraus, ein Tresor ist es nicht.\n\n## Fehlersuche ohne SSH\n\nWas unter Druck ebenfalls sofort gelernt wird: Fehlersuche funktioniert anders als auf einem Server. Es gibt kein SSH auf „die Maschine\", weil unklar ist, welche Maschine überhaupt gemeint wäre. Stattdessen fragt man den Cluster, was er über den Zustand weiß:\n\n```bash\nkubectl describe pod todo-api-7d9f6c8b45-x2x7k\nkubectl logs todo-api-7d9f6c8b45-x2x7k\nkubectl logs todo-api-7d9f6c8b45-x2x7k --previous   # logs of the crashed container\nkubectl get events --sort-by=.metadata.creationTimestamp\n```\n\n`describe` zeigt die Events – dort stehen die Klassiker im Klartext: `ImagePullBackOff`, wenn das Image nicht gefunden wird, `CrashLoopBackOff`, wenn der Container beim Start stirbt. Und `logs --previous` zeigt die Ausgabe des Containers, der gerade abgestürzt ist – genau das, was man um zwei Uhr nachts wissen will. Einfacher als vorher ist das nicht unbedingt, aber es ist systematischer: Der Cluster protokolliert, was er entschieden hat, und man muss es nicht aus vier verschiedenen Logdateien zusammenraten.\n\n## Was der Druck nicht wegdiskutiert\n\nZur Ehrlichkeit gehört auch die andere Seite. Für eine einzige kleine Anwendung stehen jetzt fünf YAML-Dateien im Repository, zusammen deutlich über hundert Zeilen – für etwas, das mit Docker Compose in zwanzig Zeilen beschrieben wäre. Helm verspricht hier Linderung durch Paketierung, bringt aber in Version 2 mit Tiller eine eigene Server-Komponente mit weitreichenden Rechten ins Cluster – ein Tausch von YAML-Menge gegen Betriebs- und Sicherheitsfragen, den ich noch nicht in jedem Projekt eingehen würde. Und auch wenn Amazon seit Juni mit EKS als letzter der großen Anbieter ein verwaltetes Kubernetes anbietet und GKE wie AKS den Cluster-Aufbau abnehmen: Die Konzepte nehmen sie einem nicht ab, und ein selbst per kubeadm aufgesetztes Cluster ist noch einmal eine ganz eigene Betriebsaufgabe.\n\nDeshalb die nüchterne Gegenprobe, bevor der Umzug beginnt. Ein einzelner Host mit Docker Compose reicht schlicht aus, wenn ein paar Dinge zusammenkommen:\n\n- die Anwendung läuft auf einer Maschine, und kurze Ausfälle sind verkraftbar\n- eine Restart-Policy im Compose-File deckt den nächtlichen Prozess-Tod ausreichend ab\n- es gibt kein Team, das parallel deployt, und keine Last, die Skalierung erfordert\n\nDann kauft Kubernetes vor allem Komplexität ein und liefert wenig zurück. Der Punkt, an dem die Rechnung kippt, ist erstaunlich präzise benennbar: sobald die Frage „wer startet das neu, wenn niemand hinschaut?\" nicht mehr mit „die eine Maschine, hoffentlich\" beantwortet werden darf.\n\n## Was ich daraus mitnehme\n\nDeployment-Druck ist ein unangenehmer, aber ehrlicher Lehrer. Er hat mir die Konzept-Doku nicht ersetzt, aber er hat sie sortiert: erst der Pod als das, was wirklich läuft, dann das Deployment als Wächter darüber, dann der Service als stabile Adresse, der Ingress als Tür nach draußen, ConfigMap und Secret als ausgelagerte Konfiguration. Fünf Objekte, mit denen eine echte Anwendung produktiv läuft – der Rest des Wörterbuchs kann warten, bis er gebraucht wird.\n\nDie tiefere Einsicht ist die deklarative Denkweise. Der Wechsel vom Drehbuch („führe diese Schritte aus\") zum Zielzustand („so soll es aussehen\") verändert, wie man über Betrieb nachdenkt – Ausfälle sind keine Zwischenfälle mehr, sondern Differenzen, die ein Controller ausgleicht. Und die Zwei-Uhr-nachts-Frage vom Anfang bekommt damit ihre beste Antwort: Es startet ihn niemand neu. Als der Erste morgens auf das Dashboard schaut, ist der Neustart eine Zeile in den Events – passiert, protokolliert, erledigt.\n\n## Weiterführende Quellen\n\n- Repository mit den Beispielen: https://github.com/MikeBild/introduction-kubernetes\n- Kubernetes-Dokumentation zu Deployments: https://kubernetes.io/docs/concepts/workloads/controllers/deployment/\n- Kubernetes-Dokumentation zu Services: https://kubernetes.io/docs/concepts/services-networking/service/\n- Kubernetes-Dokumentation zu Ingress: https://kubernetes.io/docs/concepts/services-networking/ingress/\n- ConfigMaps in Pods verwenden: https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/"},{"locale":"de","translation_key":"docker-logging-mit-elk","slug":"docker-logging-mit-elk","title":"Zentrales Logging mit dem ELK-Stack in Docker","summary":"Container-Logs verstreuen sich über viele Container und sind flüchtig. Dieser Artikel zeigt, wie ein ELK-Stack aus Elasticsearch, Logstash und Kibana im Compose-Setup Logs zentralisiert, indiziert und durchsuchbar macht.","tags":["Software","Platform"],"published_at":"2018-09-18T10:00:00+00:00","updated_at":"2026-07-13T10:00:10.602524+00:00","url":"https://www.mikebild.dev/de/blog/docker-logging-mit-elk/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/f3f09b2e69b9edea710a7faf454d612e680162ce453f44a9a603890cab7ca70f/docker-logging-mit-elk-vorlesen.mp3","audio_duration_secs":1010,"text":"`docker logs <container>` skaliert bis genau eins. Bei einem Frontend, einer API, einer Datenbank und einem Cache sind es vier Aufrufe in vier Terminals, bei drei Hosts und ein paar Replikaten schnell fünfzehn – und jeder einzelne zeigt nur seinen Ausschnitt, und das nur so lange, wie der Container lebt.\n\n**Redaktionelle Einordnung (Juli 2026):** Das Beispiel verwendet bewusst Docker Compose und ELK 6.4 aus dem Jahr 2018. Es ist kein aktuelles Produktions-Template. Unabhängig von der Version unterstützt der Docker-GELF-Treiber sowohl UDP als auch TCP; die frühere Aussage, er könne ausschließlich UDP, war bereits 2018 falsch.\n\nDie Entscheidung dahinter ist weniger eine technische als eine strategische. Sie lautet nicht „welchen Logging-Driver konfiguriere ich?“, sondern „wie viel Sichtbarkeit in mein System will ich haben, und was zahle ich dafür an Speicher, Rechenzeit und Betriebsaufwand?“ Zentrales Logging ist kein Feature, das man anschaltet, sondern eine Investition mit laufenden Kosten. Wer das ELK-Setup als reine API-Übung angeht, baut sich zuverlässig ein System, das entweder zu wenig zeigt oder die Platte volllaufen lässt. Deshalb steht die Einordnung der Logs hier vor dem ersten umkonfigurierten Container.\n\nGenau da setzt der ELK-Stack an. In diesem Artikel gehe ich den Weg durch, den ich auch in Projekten gehe: erst Logs in die Observability-Strategie einordnen, dann verstehen, wo Docker die Logs eigentlich hinschreibt und welche Logging-Driver es gibt, danach einen kompletten ELK-Stack per Docker Compose aufsetzen, die Logs eines App-Containers dorthin schicken und am Ende in Kibana durchsuchbar machen. Dazwischen sammle ich die Fallstricke ein, die mir in der Praxis am häufigsten begegnet sind.\n\n## Logs als eine von drei Säulen\n\nBevor ein einziger Driver umgestellt wird, gehört die Einordnung geklärt: Logs sind nur eine von drei Säulen, auf denen Sichtbarkeit in ein verteiltes System steht, und keine der drei ersetzt die andere. Metrics sind aggregierte Zahlen über die Zeit – Requests pro Sekunde, Fehlerrate, Speicherauslastung – und beantworten „ist gerade etwas kaputt, und seit wann?“. Logs sind einzelne Events mit Kontext und beantworten „was genau ist in diesem einen Fall passiert?“. Traces verfolgen einen Request quer über mehrere Services und beantworten „an welcher Stelle im Pfad hängt es?“. Der ELK-Stack deckt die mittlere Säule ab, und es hilft ungemein, das bewusst zu wissen: Wer mit Logs allein eine Fehlerrate über die Zeit beobachten will, zahlt dafür viel mehr, als eine simple Metric gekostet hätte.\n\nUnd damit sind wir beim Kern der Sache, den Kosten. Logs sind die verführerischste und zugleich teuerste der drei Säulen, weil jede einzelne Zeile gespeichert und in Elasticsearch standardmäßig indiziert wird. Der Preistreiber heißt Kardinalität. Ein Feld mit wenigen möglichen Werten – etwa ein `log_level` mit `info`, `warn`, `error` – ist billig zu indizieren. Ein Feld mit fast unbegrenzt vielen unterschiedlichen Werten – eine `request_id`, eine `user_id`, ein voller Query-String – treibt die Größe des Index und damit den Speicher- und RAM-Bedarf nach oben. Bei Metrics wird eine solche hohe Kardinalität schnell existenzbedrohend, bei Logs ist sie teuer, aber beherrschbar, solange man sie bewusst steuert.\n\nDiese Steuerung ist die eigentliche Entwurfsarbeit, und sie besteht aus wenigen Hebeln. Erstens: Was landet überhaupt im Log, und auf welchem Level? Ein `DEBUG`, das in Produktion mitläuft, ist reiner Kostentreiber ohne Gegenwert. Zweitens: Wie lange bewahre ich Logs auf? Der tagesbasierte Index, den ich weiter unten baue, ist genau dafür der Hebel – ganze Tage lassen sich in einem Rutsch löschen. Drittens: Muss wirklich jedes Event vollständig indiziert werden, oder reicht bei hohem Volumen eine Stichprobe? Die Regel dahinter ist schlicht und in der Umsetzung trotzdem lästig: Geloggt wird nicht alles, was möglich ist, sondern das, was man im Fehlerfall wirklich lesen will – für den Rest zahlt man nicht. Der Rest dieses Artikels zeigt die Mechanik; dass sie mit einem Kostenbewusstsein aufgesetzt wird, entscheidet darüber, ob das Setup nach drei Wochen noch trägt.\n\n## Wo Docker-Logs standardmäßig landen\n\nDocker hat ein Konzept, das viele im ersten Moment überrascht: Es kümmert sich nicht darum, was in eurer Anwendung passiert, sondern nur darum, was auf STDOUT und STDERR geschrieben wird. Alles, was der Prozess mit PID 1 im Container auf diese beiden Streams ausgibt, fängt Docker ab und reicht es an einen sogenannten Logging-Driver weiter.\n\nDer Default-Driver heißt `json-file`. Er schreibt jede Logzeile als JSON-Objekt in eine Datei auf dem Host, typischerweise unter `/var/lib/docker/containers/<id>/<id>-json.log`. Genau aus dieser Datei liest `docker logs`. Das ist auch der Grund für eine Eigenheit, die in der Praxis für Verwirrung sorgt: `docker logs` funktioniert nur mit `json-file` (und `journald`). Stellt man den Driver auf `gelf` oder `syslog` um, weil man die Logs woanders hinschicken will, dann ist der lokale `docker logs`-Befehl für diesen Container leer. Die Logs sind nicht verschwunden, sie werden nur nicht mehr lokal vorgehalten.\n\nDie verfügbaren Driver, Stand 2018, sind eine ganze Reihe:\n\n- `json-file` und `journald` – lokal, mit `docker logs` lesbar.\n- `syslog`, `gelf`, `fluentd`, `splunk` – Weiterleitung an einen zentralen Empfänger.\n- `awslogs`, `gcplogs`, `etwlogs` – plattformspezifische Ziele.\n- `none` – Logging komplett aus.\n\nFür die Zentralisierung sind vor allem `gelf` und `syslog` interessant. Sie schicken die Logzeilen über das Netzwerk an einen Endpoint weiter – und dieser Endpoint kann Logstash sein.\n\nEin Logging-Driver lässt sich pro Container beim `docker run` setzen:\n\n```bash\ndocker run \\\n  --log-driver=gelf \\\n  --log-opt gelf-address=udp://logstash:12201 \\\n  --log-opt tag=\"myapp\" \\\n  myorg/myapp:latest\n```\n\nIn Compose sieht das gleiche pro Service so aus:\n\n```yaml\nversion: \"3\"\nservices:\n  app:\n    image: myorg/myapp:latest\n    logging:\n      driver: \"gelf\"\n      options:\n        gelf-address: \"udp://logstash:12201\"\n        tag: \"myapp\"\n```\n\nEin Detail, das man kennen sollte: Der `gelf`-Driver unterstützt UDP und TCP. In diesem Beispiel ist UDP gewählt. Das ist schnell und schlank, bestätigt den Empfang aber nicht – geht eine Nachricht unter Last verloren, ist sie weg. TCP arbeitet verbindungsorientiert, macht aus einem Log-Transport jedoch noch keinen revisionssicheren Audit-Trail.\n\n## Die drei Rollen im ELK-Stack\n\nBevor wir Compose schreiben, lohnt sich der Blick auf die drei Buchstaben. ELK steht für Elasticsearch, Logstash und Kibana, und jede Komponente hat genau eine klar umrissene Aufgabe. Elasticsearch speichert und indiziert: Es ist die Suchmaschine im Zentrum, die jede Logzeile durchsuchbar macht und die Daten vorhält. Logstash nimmt an, parst und transformiert – es ist die Eingangstür, die Logs aus verschiedenen Quellen entgegennimmt, sie in Struktur bringt und an Elasticsearch weiterreicht; seine Pipeline besteht aus `input`, `filter` und `output`. Und Kibana visualisiert und durchsucht: die Weboberfläche, in der man Logs filtert, Dashboards baut und Muster sichtbar macht.\n\nDer Datenfluss ist eine kurze Kette:\n\n```mermaid\nflowchart LR\n    A[App Container] -->|stdout / gelf| B[Logstash]\n    B -->|index| C[Elasticsearch]\n    C -->|query| D[Kibana]\n    E[Browser] -->|http :5601| D\n```\n\nDie App schreibt nach STDOUT, der Docker-Driver leitet an Logstash weiter, Logstash indiziert in Elasticsearch, und Kibana macht das Ganze im Browser sichtbar. Wichtig ist: Die Anwendung selbst weiß von alldem nichts. Sie loggt nach STDOUT und STDERR – so, wie es das Twelve-Factor-Prinzip vorsieht – und der Transport ist Sache der Infrastruktur. Kein eigenes Logfile-Handling im Container, keine Rotationslogik in der App. Das hält die Anwendung sauber und macht den Log-Pfad austauschbar.\n\n## Der Compose-Stack\n\nJetzt bauen wir den Stack. Ich pinne die Images bewusst auf eine feste Version – in diesem Fall die 6.4er-Reihe – weil ein ungetaggtes `elasticsearch:latest` die zuverlässigste Quelle für „bei mir sieht es aber anders aus“ ist. Hier die `elk-compose.yml`:\n\n```yaml\nversion: \"3\"\nservices:\n  elasticsearch:\n    image: docker.elastic.co/elasticsearch/elasticsearch:6.4.0\n    environment:\n      - discovery.type=single-node\n      - \"ES_JAVA_OPTS=-Xms512m -Xmx512m\"\n    volumes:\n      - es-data:/usr/share/elasticsearch/data\n    ports:\n      - \"9200:9200\"\n      - \"9300:9300\"\n\n  logstash:\n    image: docker.elastic.co/logstash/logstash:6.4.0\n    volumes:\n      - ./pipeline:/usr/share/logstash/pipeline\n    ports:\n      - \"12201:12201/udp\"\n    depends_on:\n      - elasticsearch\n\n  kibana:\n    image: docker.elastic.co/kibana/kibana:6.4.0\n    environment:\n      - ELASTICSEARCH_URL=http://elasticsearch:9200\n    ports:\n      - \"5601:5601\"\n    depends_on:\n      - elasticsearch\n\nvolumes:\n  es-data:\n```\n\nEin paar Punkte, die in der Konfiguration nicht zufällig so stehen. Elasticsearch bekommt `discovery.type=single-node`, damit es sich nicht vergeblich nach Cluster-Kollegen umschaut. Der Heap wird mit `ES_JAVA_OPTS` fix auf 512 Megabyte gesetzt – zum Ausprobieren reicht das, in Produktion würde man großzügiger dimensionieren, aber immer mit gleichem `Xms` und `Xmx`. Und die Daten liegen auf einem Named Volume `es-data`, damit sie einen Neustart des Containers überleben. Das ist kein Detail: Vergisst man das Volume, sind bei jedem `docker-compose down` alle indizierten Logs verloren – ausgerechnet beim Log-System besonders ärgerlich.\n\nKibana bekommt mit `ELASTICSEARCH_URL` die Adresse von Elasticsearch. Der Servicename `elasticsearch` funktioniert als Hostname, weil Compose alle Services in dasselbe Netzwerk hängt und Namensauflösung mitbringt.\n\nJetzt fehlt noch die Logstash-Pipeline. Die liegt als `pipeline/logstash.conf` neben der Compose-Datei und definiert, wie Logstash Nachrichten annimmt und wohin es sie schreibt:\n\n```ruby\ninput {\n  gelf {\n    port => 12201\n  }\n}\n\nfilter {\n  # room for grok, mutate, date & co.\n}\n\noutput {\n  elasticsearch {\n    hosts => [\"elasticsearch:9200\"]\n    index => \"docker-logs-%{+YYYY.MM.dd}\"\n  }\n}\n```\n\nDer `gelf`-Input lauscht auf Port 12201 – genau der Port, an den unser App-Service seine Logs schickt. Der `filter`-Block ist hier leer, aber genau dort passiert in echten Setups die eigentliche Arbeit: Zeilen mit `grok` in Felder zerlegen, Zeitstempel mit `date` normalisieren, Felder mit `mutate` umbenennen. Der `output`-Block schreibt nach Elasticsearch, und zwar in einen tagesbasierten Index `docker-logs-2018.09.18`. Dieses Muster ist bewusst gewählt: Ein Index pro Tag macht das spätere Aufräumen alter Logs einfach, weil man ganze Indizes löschen kann, statt einzelne Dokumente zu suchen.\n\n## Die App anschließen\n\nFehlt noch die Anwendung, deren Logs wir sehen wollen. Ich hänge einen App-Service an denselben Stack und gebe ihm den `gelf`-Logging-Driver mit:\n\n```yaml\n  app:\n    image: myorg/myapp:latest\n    logging:\n      driver: \"gelf\"\n      options:\n        gelf-address: \"udp://localhost:12201\"\n        tag: \"myapp\"\n    depends_on:\n      - logstash\n```\n\nBeim `gelf`-Driver gibt es eine Stolperstelle, die beim ersten Aufsetzen fast garantiert auftaucht: Die `gelf-address` wird vom Docker-Daemon auf dem Host aufgelöst, nicht aus dem Container-Netzwerk heraus. Deshalb steht dort `udp://localhost:12201` und der gemappte Host-Port, nicht der Servicename `logstash`. Der Daemon kennt das Compose-interne DNS nicht – er sieht nur den Port, den Logstash auf den Host veröffentlicht.\n\nStartet man den Stack mit `docker-compose -f elk-compose.yml up`, fährt zuerst Elasticsearch hoch, dann Logstash und Kibana, dann die App. Ab jetzt fließt jede Logzeile der App als GELF-Nachricht an Logstash, wird indiziert und ist in Kibana sichtbar.\n\nEin Wort zur Reihenfolge: `depends_on` steuert nur, in welcher Reihenfolge Docker die Container startet – nicht, ob der jeweilige Dienst schon einsatzbereit ist. Elasticsearch braucht nach dem Start einige Sekunden, bis der Index grün ist, und in dieser Zeit meldet Kibana im Browser gerne „Kibana server is not ready yet“. Das ist kein Fehler, das ist die Realität asynchroner Startvorgänge. Einmal durchatmen, Seite neu laden.\n\n## In Kibana durchsuchen\n\nKibana läuft auf Port 5601. Beim ersten Aufruf will es einen Index Pattern wissen – man gibt `docker-logs-*` ein, wählt das Zeitfeld aus, und schon zeigt der Discover-Tab die eintrudelnden Logzeilen. Von hier aus filtert man nach dem `tag`-Feld (`myapp`), sucht nach Volltext in den Nachrichten, grenzt auf Zeiträume ein und baut bei Bedarf Visualisierungen. Der Aha-Moment kommt zuverlässig genau hier: Aus verstreuten `docker logs`-Aufrufen über mehrere Terminals wird eine einzige durchsuchbare Oberfläche.\n\n## Fallstricke aus der Praxis\n\nDrei Dinge gehen bei diesem Setup am häufigsten schief, und alle drei habe ich mehr als einmal live erlebt.\n\nDer Klassiker ist, dass Elasticsearch gar nicht erst startet und im Log `max virtual memory areas vm.max_map_count [65530] is too low` steht. Elasticsearch 6.x verlangt auf dem Host `vm.max_map_count=262144`. Das ist eine Kernel-Einstellung, kein Container-Parameter, und muss auf dem Docker-Host gesetzt werden:\n\n```bash\nsudo sysctl -w vm.max_map_count=262144\n```\n\nAuf einer Docker-Machine mit VirtualBox setzt man das entsprechend in der VM. Vergisst man es, hilft kein Neustart des Containers – Elasticsearch stirbt reproduzierbar beim Hochfahren.\n\nDer zweite Fallstrick ist das Log-Volumen. Der Default-Driver `json-file` schreibt unbegrenzt auf die Platte. Ein gesprächiger Container kann so eine Entwicklungsmaschine über Nacht volllaufen lassen. Deshalb gehört bei `json-file` immer eine Begrenzung dazu:\n\n```yaml\n    logging:\n      driver: \"json-file\"\n      options:\n        max-size: \"10m\"\n        max-file: \"3\"\n```\n\nUnd beim hier gewählten UDP-Transport von `gelf` gilt, was ich oben schon angerissen habe: Unter Last können Nachrichten verloren gehen, ohne dass es irgendwo knallt. Für kritische Logs kommen GELF über TCP oder ein gepufferter Collector infrage. Ob ein Log vollständig, unveränderbar und nachweisbar sein muss, bleibt darüber hinaus eine eigene fachliche Anforderung.\n\nDer dritte Punkt ist die schon erwähnte Startkopplung. Logstash und Kibana brauchen ein erreichbares Elasticsearch. `depends_on` garantiert nur den Start, nicht die Readiness. In Produktion löst man das mit Health-Checks und Retry-Logik; beim lokalen Ausprobieren reicht meist das Wissen, dass „not ready“ in den ersten Sekunden normal ist und kein Grund zur Panik.\n\n## Zwei Wege der Weiterleitung\n\nZum Abschluss noch eine Einordnung, die zeigt, dass der Logging-Driver nicht der einzige Weg ist. Grundsätzlich gibt es zwei Ansätze, Logs aus Containern zu Logstash zu bekommen. Der erste ist der, den wir hier gegangen sind: Der Docker-Logging-Driver am App-Service schickt direkt weiter. Der zweite ist ein Log-Collector als Sidecar – ein zusätzlicher Container wie logspout, der den Docker-Socket liest und die gesammelten Logs aller Container per syslog weiterleitet. Der Vorteil des Collector-Ansatzes ist, dass man an den App-Services nichts ändern muss und `docker logs` weiterhin funktioniert, weil die Container beim Default-Driver bleiben. Der Nachteil ist eine weitere bewegliche Komponente im Stack. Welcher Weg besser passt, hängt davon ab, wie viel Kontrolle man über die einzelnen Services hat – bei fremden Images ist der Collector oft die pragmatischere Wahl.\n\nWer den ELK-Stack in ein größeres Compose-Setup einbetten will, findet in [Node.js und Redis mit Docker Compose](https://www.mikebild.dev/de/blog/docker-compose-nodejs-redis/) die Grundlagen für mehrteilige Stacks. Mehrere parallele Projekte trennt Compose über eigene Projektnamen und die daraus abgeleiteten Netzwerke.\n\n## Fazit\n\nContainer-Logs sind per Default lokal und flüchtig – das ist bei einem Container kein Problem und bei zwanzig ein großes. Der ELK-Stack löst das mit einer klaren Arbeitsteilung: Logstash nimmt an und transformiert, Elasticsearch speichert und indiziert, Kibana macht durchsuchbar. Docker liefert mit seinen Logging-Drivern die Brücke, um die Logs eines Containers überhaupt erst dorthin zu bekommen, ohne die Anwendung anfassen zu müssen.\n\nDie Wirkung, auf die es mir dabei ankommt, ist eine Verschiebung im Arbeitsalltag. Der Weg von der Störung zur Ursache wird kürzer, weil man nicht mehr über mehrere Terminals hinweg `docker logs` zusammensucht, sondern in einer Oberfläche filtert. Die Reibung sinkt, weil die App sauber bleibt – sie loggt nach STDOUT und STDERR, der Transport bleibt Sache der Infrastruktur und damit austauschbar. Und die Qualität der Diagnosen steigt, weil ein durchsuchbarer Verlauf Muster sichtbar macht, die im flüchtigen Einzel-Log untergehen. Wer die drei großen Fallstricke kennt – `vm.max_map_count`, unbegrenztes Log-Volumen und die Readiness beim Start – hat diesen Weg in einem Nachmittag hinter sich.\n\nEbenso wichtig ist die Kenntnis der Grenzen. Logs sind eines von mehreren Telemetriesignalen, nicht die ganze Observability: Für Trends über die Zeit sind Metrics billiger, für den Weg eines Requests durch mehrere Services sind Traces das richtige Werkzeug. Die Kosten wachsen mit Volumen und Kardinalität, weshalb Aufbewahrung, Log-Level und die Frage, welche Felder indiziert werden, bewusste Entscheidungen bleiben müssen. Und das hier verwendete `gelf` über UDP eignet sich für unkritische Anwendungslogs, aber nicht für Audit-Trails oder Abrechnungsdaten, bei denen keine Nachricht verloren gehen darf. Innerhalb dieser Grenzen bleibt der Kern einfach: Die App loggt nach STDOUT und STDERR, alles andere ist Infrastruktur – und was diese Infrastruktur kostet, entscheidet man selbst.\n\n## Weiterführende Quellen\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-docker-kubernetes.html\n- [Docker GELF logging driver – TCP- und UDP-Konfiguration](https://docs.docker.com/engine/logging/drivers/gelf/)\n- [Docker 17.11 Release Notes – Einführung der GELF-TCP-Unterstützung](https://docs.docker.com/engine/release-notes/17.11/)\n- [Docker: Configure logging drivers](https://docs.docker.com/config/containers/logging/configure/)\n- [Docker: json-file logging driver](https://docs.docker.com/config/containers/logging/json-file/)\n- [Docker: gelf logging driver](https://docs.docker.com/config/containers/logging/gelf/)\n- [Docker: syslog logging driver](https://docs.docker.com/config/containers/logging/syslog/)\n- [Elastic: Getting started with the Elastic Stack and Docker Compose](https://www.elastic.co/blog/getting-started-with-the-elastic-stack-and-docker-compose)\n- [Elasticsearch 6.4: Install with Docker](https://www.elastic.co/guide/en/elasticsearch/reference/6.4/docker.html)\n- [Kibana 6.4: Running Kibana on Docker](https://www.elastic.co/guide/en/kibana/6.4/docker.html)\n- [Logstash 6.4: Running Logstash on Docker](https://www.elastic.co/guide/en/logstash/6.4/docker.html)\n- [Referenz-Stack: deviantony/docker-elk](https://github.com/deviantony/docker-elk)"},{"locale":"de","translation_key":"micro-frontends-teamschnitt-browser","slug":"micro-frontends-teamschnitt-browser","title":"Micro-Frontends: Teamschnitt im Browser","summary":"Warum die eigentliche Arbeit bei Micro-Frontends nicht in der Integrationstechnik steckt, sondern im Teamschnitt – gezeigt an einer lauffähigen Beispiel-Landschaft aus Gateway, vier Anwendungen und einer Komponenten-Bibliothek.","tags":["Software","Frontend"],"published_at":"2018-08-21T10:00:00+00:00","updated_at":"2026-07-14T17:04:47.915864+00:00","url":"https://www.mikebild.dev/de/blog/micro-frontends-teamschnitt-browser/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/9b987ac70a9ef15b671bb56cc12c66a81cca417481151665466b9f6411d86871/micro-frontends-teamschnitt-browser-vorlesen.mp3","audio_duration_secs":729,"text":"# Micro-Frontends: Teamschnitt im Browser\n\nVier Teams, ein `index.html`, ein gemeinsames Deployment pro Woche. Die Rechnung dahinter sieht harmlos aus und ist es nicht: Jedes Release verlangt zwei Tage Code-Freeze, eine Regressionsrunde über die komplette Oberfläche und vier Freigaben. Ist ein Team nicht fertig, warten drei andere. Bei fünfzig Arbeitswochen im Jahr sind das im besten Fall fünfzig Gelegenheiten, etwas auszuliefern – und in der Praxis deutlich weniger, weil ein einziger fehlgeschlagener Smoke-Test das gesamte Release zurückhält. Dabei sind die Backends dieser Teams längst getrennte Services mit eigenen Pipelines. Im Browser aber laufen alle vier in einem einzigen JavaScript-Bundle wieder zusammen, und mit dem Bundle kehrt genau der Engpass zurück, den die Aufteilung in Services eigentlich beseitigen sollte.\n\n## Ein Organisationsproblem mit technischem Symptom\n\nMicro-Frontends werden gern als Frontend-Thema verhandelt: welches Framework, welche Integrationstechnik, wie klein ein Fragment sein darf. Mir ist in den letzten Monaten aufgefallen, dass diese Diskussion regelmäßig am Kern vorbeiläuft. Die eigentliche Frage lautet: Bildet die Struktur im Browser die Struktur der Organisation ab – oder arbeitet sie dagegen? Conways Beobachtung von 1968 gilt auch hier: Systeme spiegeln die Kommunikationswege der Organisation, die sie baut. Wenn vier Teams fachlich getrennt arbeiten, aber eine gemeinsame Single-Page-Anwendung pflegen, entsteht die Reibung genau an dieser Naht – als Merge-Konflikte in der Router-Konfiguration, als Abstimmungsrunden über CSS-Klassen, als Release-Kalender, der zum Dauerthema wird.\n\nNeu ist das Muster nicht. Der ThoughtWorks Technology Radar führt „Micro Frontends\" seit November 2016, seit Mai dieses Jahres im Ring „Trial\". Zalando betreibt mit dem Mosaic-Projekt und dem Layout-Service Tailor seit gut zwei Jahren eine solche Architektur in Produktion. Neu ist höchstens die Einsicht, die sich beim Nachbauen einstellt: Der technische Teil ist der einfache.\n\n## Eine lauffähige Beispiel-Landschaft\n\nUm das nicht nur zu behaupten, habe ich im Juli das Repository `introduction-micro-frontends` zusammengestellt – eine lauffähige Beispiel-Landschaft mit einem Gateway auf Port 7000, dahinter vier eigenständige Anwendungen: Home (7010), Docs (7020), Products (7030) und Contact (7040), dazu eine Catalog-API, eine GraphQL-API auf Port 9000 und eine gemeinsame Komponenten-Bibliothek auf Port 5000. Jede Anwendung startet für sich, hat ihr eigenes Build und könnte von einem eigenen Team betrieben werden. Das Gateway kennt die Anwendungen über eine schlichte Service-Discovery – wahlweise aus Dateien, aus Docker/Kubernetes oder aus der Google Cloud – und routet nach Pfad.\n\n```mermaid\nflowchart LR\n  B[Browser] --> G[Gateway<br/>:7000]\n  G -->|/| H[home-app<br/>:7010<br/>Team A]\n  G -->|/docs| D[docs-app<br/>:7020<br/>Team B]\n  G -->|/products| P[products-app<br/>:7030<br/>Team C]\n  G -->|/contact| C[contact-app<br/>:7040<br/>Team D]\n  P --> Q[graphql-api<br/>:9000]\n  H -. shared UI .-> L[components-library<br/>:5000]\n  P -. shared UI .-> L\n```\n\nDas Diagramm zeigt bereits die zentrale Entwurfsentscheidung: Die Schnittlinien verlaufen vertikal. Jedes Team besitzt einen fachlichen Ausschnitt von der Route bis zur API – nicht eine horizontale Schicht wie „alle Buttons\" oder „das gesamte CSS\". Genau dieser Schnitt macht unabhängige Deployments erst möglich; alles andere ist Handwerk.\n\n## Der einfache Teil: Integration\n\nDie Integrationstechniken sind schnell aufgezählt, und keine davon ist spektakulär.\n\nDie älteste ist der Hyperlink. Wenn `/products` und `/contact` getrennte Anwendungen sind, reicht ein `<a href=\"/contact\">` – der Browser lädt die nächste Seite, das nächste Team übernimmt. Kein geteilter Code, keine geteilte Runtime, dafür ein sichtbarer Seitenwechsel. Für viele Übergänge ist das völlig ausreichend, und es ist die einzige Integration, die garantiert nie bricht.\n\nSollen Fragmente verschiedener Teams auf einer Seite erscheinen, komponiert man serverseitig. Server-Side-Includes beherrscht jeder nginx von Haus aus:\n\n```nginx\n# gateway: compose one page from team fragments\nlocation / {\n  ssi on;\n  proxy_pass http://home-app:7010;\n}\n\nlocation /fragment/header {\n  proxy_pass http://components-library:5000/header;\n}\n```\n\n```html\n<!-- home-app: index.html -->\n<!--#include virtual=\"/fragment/header\" -->\n<main>\n  <!--#include virtual=\"/fragment/product-teaser\" -->\n</main>\n```\n\nZalandos Tailor treibt dasselbe Prinzip weiter und streamt Fragmente parallel, mit Timeout und Fallback pro Fragment. Edge-Side-Includes verlagern die Komposition in den Varnish- oder CDN-Layer. Allen Varianten gemeinsam: Die Seite entsteht aus unabhängig deploybaren Teilen, und ein langsames Fragment blockiert nicht das ganze Release, sondern höchstens seinen eigenen Platzhalter.\n\nClientseitig sind Custom Elements die sauberste Klammer – seit v1 in Chrome und Safari nativ, in Firefox und Edge im Moment noch per Polyfill:\n\n```js\n// products-app: expose a fragment as a custom element\nclass ProductTeaser extends HTMLElement {\n  connectedCallback() {\n    const sku = this.getAttribute('sku');\n    fetch(`/products/api/teaser/${sku}`)\n      .then((res) => res.text())\n      .then((html) => { this.innerHTML = html; });\n  }\n\n  disconnectedCallback() {\n    // team C cleans up its own listeners here\n  }\n}\n\ncustomElements.define('product-teaser', ProductTeaser);\n```\n\nDas aufnehmende Team schreibt `<product-teaser sku=\"42\"></product-teaser>` und muss nicht wissen, mit welchem Framework das Fragment intern gebaut ist. Die DOM-Schnittstelle – Attribute rein, Events raus – ist der Vertrag zwischen den Teams. Daneben gibt es iframes: verrufen, aber die einzige Technik mit vollständiger Isolation von CSS, JavaScript und globalem State. Für das Zahlungsformular eines Drittanbieters oder ein Altmodul, das niemand mehr anfassen will, nach wie vor eine legitime Wahl. Und schließlich orchestriert single-spa mehrere Framework-Anwendungen innerhalb einer Single-Page-Anwendung – das löst das Routing-Problem elegant, holt aber alle Teams zurück in eine gemeinsame Runtime mit gemeinsamem Fehlerraum.\n\nWelche Technik trägt, entscheidet sich an wenigen Fragen:\n\n- Wie viel Seitenwechsel verträgt der Nutzerfluss – reicht ein Link?\n- Muss die Seite ohne JavaScript ein brauchbares Erstbild liefern (SSI, Tailor), oder ist die Zielgruppe ohnehin angemeldet (Client-Komposition)?\n- Wie hart müssen Fragmente isoliert sein – genügt Namensdisziplin, oder braucht es die iframe-Grenze?\n- Wer betreibt den Kompositionspunkt: ein Plattform-Team das Gateway, oder jedes Team seinen eigenen Einstieg?\n\n## Sorgfaltspflichten: Routing, Abhängigkeiten, CSS\n\nDrei Dinge muss man trotzdem sauber regeln, sonst holt einen der Monolith durch die Hintertür wieder ein.\n\nErstens die Routing-Hoheit. Die URL ist die öffentliche Schnittstelle der gesamten Anwendung, also braucht sie einen Eigentümer. Im Beispiel-Repository besitzt das Gateway die oberste Ebene – `/products` gehört Team C, und zwar vollständig, inklusive aller Unterpfade. Sobald zwei Teams über einen Pfad verhandeln müssen, ist der Schnitt falsch gezogen. Deep-Links müssen dabei funktionieren wie auf jeder anständigen Website: Ein Reload auf `/products/42` landet beim richtigen Team, ohne dass ein zentraler Client-Router davon wissen muss. Das Gateway selbst bleibt bewusst dumm – es kennt Pfade und Ziele, aber keine Fachlichkeit. Jede Regel mehr an dieser Stelle macht es zum nächsten gemeinsamen Deployment, über das wieder alle abstimmen müssen.\n\nZweitens die geteilten Abhängigkeiten. Vier Anwendungen, die je ihr eigenes React bündeln, schicken das Framework viermal über die Leitung – bei einer Bibliothek von gut 100 KB ist das messbar, aber selten der Untergang. Die Alternative, eine zentral vorgegebene Framework-Version für alle, klingt sparsamer und kostet mehr: Jedes Framework-Update wird wieder ein Vier-Team-Projekt, und der gemeinsame Release-Takt ist zurück. Im Repository bündelt deshalb jede Anwendung selbst. Diesen Preis zahle ich bewusst, weil er in Kilobyte anfällt statt in Meetings.\n\nDrittens die CSS-Isolation. CSS hat einen globalen Namensraum, und der ist in einer komponierten Seite das Einfallstor für Fernwirkung: Team B ändert eine Klasse `.card`, und bei Team C verrutscht das Layout. Präfix-Konventionen pro Team helfen sofort und kosten nichts. Shadow DOM kapselt Styles vollständig, hängt aber am selben Browser-Support wie Custom Elements. Der zuverlässigste Schutz bleibt Disziplin: keine globalen Selektoren, keine Element-Selektoren, kein `!important` über Team-Grenzen hinweg.\n\n## Der schwere Teil: Wem gehört der Header?\n\nBis hierher war alles Technik, und Technik lässt sich ausprobieren. Die Fragen, an denen solche Vorhaben tatsächlich hängen bleiben, stehen in keiner nginx-Konfiguration.\n\nDer Header ist das beste Beispiel. Er erscheint auf jeder Seite, gehört fachlich niemandem und technisch allen. In einem Projekt haben wir drei Antworten durchgespielt. Ein eigenes „Header-Team\" schafft eine neue horizontale Schicht und damit einen neuen Engpass – jede fachliche Änderung wird zum Ticket bei einem anderen Team. Die zweite Antwort: Ein fachliches Team besitzt den Header, alle anderen binden ihn als Fragment ein. Das funktioniert, solange dieses Team die Wünsche der anderen ernst nimmt – der Header wird zum internen Produkt mit internen Kunden. Die dritte Antwort steht im Beispiel-Repository: Der Header liegt in der Komponenten-Bibliothek, versioniert, und jedes Team aktualisiert in seinem eigenen Takt. Der Preis ist Ehrlichkeit gegenüber der Realität – für ein paar Tage sind zwei Header-Versionen gleichzeitig live. Wer das nicht aushält, hat sich gegen unabhängige Deployments entschieden und sollte es dann auch so nennen.\n\nDieselbe Struktur hat die Design-Frage. Ein gemeinsames Erscheinungsbild entsteht nicht durch ein zentrales CSS, sondern durch einen Styleguide, der wie ein Produkt gepflegt wird: mit Versionen, Changelog und Ansprechpartnern. Atomic Design liefert dafür ein brauchbares Vokabular – kleine, dumme Bausteine werden geteilt, zusammengesetzte Views gehören den Teams. Je höher eine Komponente in dieser Hierarchie steht, desto teurer ist ihr Teilen.\n\n## Was geteilter State kostet\n\nDie härteste Währung ist geteilter State. Das Standardbeispiel: Team C legt auf der Produktseite einen Artikel in den Warenkorb, und der Mini-Warenkorb im Header – Besitz eines anderen Teams – soll die neue Anzahl anzeigen. Der naheliegende Reflex ist ein globaler Store, den alle Fragmente lesen und schreiben. Damit handelt man sich exakt die Kopplung wieder ein, die man gerade losgeworden ist: ein gemeinsames Zustandsschema, dessen Änderung alle Teams gleichzeitig betrifft, plus die Frage, wessen Version des Stores geladen wird.\n\nDie günstigere Antwort: Fragmente teilen keinen Speicher, sie teilen Events. Das DOM bringt den Mechanismus mit, ganz ohne zusätzliche Bibliothek:\n\n```js\n// products-app: announce the change, share no memory\nwindow.dispatchEvent(new CustomEvent('cart:item-added', {\n  detail: { sku: '42', quantity: 1 }\n}));\n\n// header fragment: react and re-fetch its own truth\nwindow.addEventListener('cart:item-added', () => {\n  fetch('/cart/api/summary')\n    .then((res) => res.json())\n    .then((summary) => updateBadge(summary.count));\n});\n```\n\nDer Header hält seinen eigenen State und holt sich die Wahrheit aus der Warenkorb-API; das Event ist nur der Anstoß. Der Vertrag zwischen den Teams schrumpft auf einen Event-Namen und ein kleines `detail`-Objekt – beides lässt sich dokumentieren und abwärtskompatibel erweitern.\n\nÄhnlich liegt der Fall beim Anmeldestatus, dem zweiten Dauerkandidaten für geteilten State. Kein Fragment braucht das Session-Objekt eines anderen Teams: Ein Cookie auf der gemeinsamen Domain, vom Gateway geprüft, genügt als geteilte Tatsache – jedes Fragment entscheidet selbst, was es einem abgemeldeten Besucher zeigt. Wo das nicht reicht, etwa für den Anzeigenamen im Header, liefert wieder eine kleine API die Antwort, statt dass ein globales Objekt durch alle Fragmente gereicht wird. Trotzdem gilt: Jedes solche Event ist eine Schnittstelle, und Schnittstellen brauchen Pflege. Wenn die Liste der teamübergreifenden Events zweistellig wird, ist das kein Tooling-Problem, sondern ein Hinweis, dass der fachliche Schnitt nicht stimmt – die Teams arbeiten dann längst am selben Gegenstand, nur eben gegeneinander.\n\n## Unterm Strich\n\nDer Merksatz, den ich aus dem Bau der Beispiel-Landschaft mitnehme: Micro-Frontends kauft man nicht als Technik, man kauft sie als Organisationsform – die Technik ist in zwei Wochen gelernt, der Teamschnitt nicht. Wer nur ein Frontend-Team hat, braucht das alles nicht; ein gut strukturierter Monolith mit sauberen Modulgrenzen ist dann die ehrlichere Architektur. Interessant wird der Umbau, wenn Freigaberunden, Code-Freeze und Release-Queues messbar Zeit kosten und mehrere Teams tatsächlich unabhängig liefern könnten, wenn man sie ließe. Dann lohnt es sich, zuerst die unbequemen Fragen zu klären – wem gehört der Header, wer pflegt den Styleguide, welche Events bilden den Vertrag – und erst danach zwischen SSI, Custom Elements und iframe zu wählen. Die Integrationstechnik ist am Ende austauschbar. Der Teamschnitt, den sie in den Browser verlängert, ist es nicht.\n\n## Weiterführende Quellen\n\n- Repository mit den lauffähigen Beispielen: https://github.com/MikeBild/introduction-micro-frontends\n- ThoughtWorks Technology Radar zu Micro Frontends: https://www.thoughtworks.com/radar/techniques/micro-frontends\n- Zalando Tailor, Layout-Service aus Project Mosaic: https://github.com/zalando/tailor\n- single-spa, Router für mehrere Framework-Anwendungen: https://github.com/single-spa/single-spa\n- MDN zu Custom Elements: https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements"},{"locale":"de","translation_key":"frontend-schnittstellen-sind-apis","slug":"frontend-schnittstellen-sind-apis","title":"Frontend-Schnittstellen sind APIs","summary":"Warum Props, URLs, Events, CSS-Klassen und localStorage dieselbe Versionierungs-Disziplin verdienen wie ein REST-Endpoint – spätestens, wenn mehrere Teams im selben Browser arbeiten.","tags":["Software","Frontend"],"published_at":"2018-08-12T10:00:00+00:00","updated_at":"2026-07-14T20:57:53.475496+00:00","url":"https://www.mikebild.dev/de/blog/frontend-schnittstellen-sind-apis/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ea2c67d34b5781137f583e2546b713433ab870ddb57c44b513595c1b9a18596e/frontend-schnittstellen-sind-apis-vorlesen.mp3","audio_duration_secs":692,"text":"# Frontend-Schnittstellen sind APIs\n\n```diff\n UserCard.propTypes = {\n-  name: PropTypes.string.isRequired,\n+  fullName: PropTypes.string.isRequired,\n   avatarUrl: PropTypes.string,\n   onSelect: PropTypes.func\n };\n```\n\nEin Diff wie dieser geht im Review anstandslos durch. Eine Umbenennung, der neue Name ist sprechender, die eigene Anwendung läuft, die Tests sind grün, gemergt. Drei Wochen später zieht ein anderes Team die neue Version der gemeinsamen Komponenten-Bibliothek, und in deren Browser-Konsole steht:\n\n```\nWarning: Failed prop type: The prop `fullName` is marked as required\n  in `UserCard`, but its value is `undefined`.\n```\n\nDas ist noch der gute Fall, weil `propTypes` wenigstens laut wird. Der schlechtere Fall: Die Karte rendert einfach ohne Namen, niemand schaut in die Konsole, und der Fehler fällt erst auf, wenn ein Anwender ihn meldet – zwei Releases später, mit einem Diff, in dem nichts Verdächtiges mehr steht.\n\nHätte jemand dasselbe mit einem Feld in einer REST-Antwort gemacht, also `name` kommentarlos in `fullName` umbenannt, ohne Ankündigung und ohne Versionssprung, wäre der Ärger groß und berechtigt. Bei einer Komponenten-Prop passiert genau das ständig, und kaum jemand nennt es beim Namen. Dabei ist die Lage identisch: Es gibt einen Vertrag zwischen zwei Codebasen, die von unterschiedlichen Teams zu unterschiedlichen Zeitpunkten geändert und ausgeliefert werden. Das ist die Definition einer API. Dass der Vertrag aus JSX besteht statt aus HTTP, ändert daran nichts.\n\n## Mehr Oberflächen, als im Architekturdiagramm stehen\n\nIn einem Portal-Projekt, an dem ich länger mitgearbeitet habe, liefen Anwendungsteile von vier Teams im selben Browser-Tab: eine Shell, zwei Fachanwendungen, ein eingebettetes Widget. Als wir nach einem besonders zähen Integrationsfehler einmal aufgeschrieben haben, worüber diese Teile tatsächlich miteinander reden, kam eine Liste heraus, die deutlich länger war als alles, was je in einem Architekturdiagramm stand:\n\n- Props und Callbacks der geteilten Komponenten-Bibliothek\n- URLs mit Pfaden und Query-Parametern, auf die verlinkt wird\n- CustomEvents und `postMessage`-Nachrichten zwischen Seitenteilen\n- CSS-Klassen und CSS Custom Properties, die andere Teile gezielt verwenden\n- localStorage-Schlüssel, die mehr als ein Modul liest\n\nJede dieser Oberflächen hatte Konsumenten außerhalb des Teams, das sie pflegte. Keine davon war versioniert. Nur die erste war überhaupt dokumentiert. Die REST-APIs desselben Projekts hatten dagegen Versionspräfixe, Changelogs und eine Deprecation-Richtlinie – weil dort allen klar war, dass fremder Code von ihnen abhängt. Im Frontend war dieselbe Abhängigkeit da, nur unsichtbar.\n\n```mermaid\nflowchart LR\n  subgraph FE[Frontend eines Teams]\n    P[Props & Callbacks]\n    U[URLs & Parameter]\n    E[CustomEvents /<br/>postMessage]\n    C[CSS-Klassen &<br/>Custom Properties]\n    S[localStorage-<br/>Schlüssel]\n  end\n  A[Team B:<br/>Fachanwendung] --> P\n  B[Nutzer: Bookmarks,<br/>geteilte Links] --> U\n  M[Mails, Kampagnen,<br/>Monitoring-Checks] --> U\n  W[Widget im iframe] --> E\n  T[Team C:<br/>Theming] --> C\n  X[Altes Portal-Skript] --> S\n```\n\nDas Diagramm ist keine Übertreibung, sondern die aufgeräumte Version unserer damaligen Liste. Und es erklärt, warum „wir refactoren nur intern\" im Frontend so oft schiefgeht: Was intern aussieht, hat längst Konsumenten.\n\n## Props: der Vertrag zwischen Teams\n\nFür die Komponenten-Bibliothek haben wir daraus die naheliegende Konsequenz gezogen: Sie wird wie eine API behandelt. Konkret heißt das dreierlei. Erstens ist die Prop-Signatur der Vertrag, und `propTypes` machen ihn maschinenlesbar. Zweitens gilt Semantic Versioning ernsthaft – eine entfernte oder umbenannte Prop ist ein Breaking Change und damit eine Major-Version, egal wie klein der Diff aussieht. Drittens bekommt jede Änderung ein Deprecation-Fenster: Die alte Form funktioniert weiter, warnt aber im Entwicklungsmodus.\n\nFür das `UserCard`-Beispiel von oben sieht das so aus:\n\n```jsx\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\n// v2.3.0: `name` is deprecated in favor of `fullName`.\n// Both work until v3.0.0, where `name` will be removed.\nexport function UserCard({ fullName, name, avatarUrl, onSelect }) {\n  const displayName = fullName || name;\n\n  if (name && process.env.NODE_ENV !== 'production') {\n    console.warn(\n      'UserCard: prop `name` is deprecated, use `fullName` instead. ' +\n      'Support for `name` will be removed in v3.0.0.'\n    );\n  }\n\n  return (\n    <div className=\"user-card\" onClick={onSelect}>\n      {avatarUrl && <img className=\"user-card__avatar\" src={avatarUrl} alt=\"\" />}\n      <span className=\"user-card__name\">{displayName}</span>\n    </div>\n  );\n}\n\nUserCard.propTypes = {\n  fullName: PropTypes.string,\n  name: PropTypes.string, // deprecated, see above\n  avatarUrl: PropTypes.string,\n  onSelect: PropTypes.func\n};\n```\n\nDas ist mehr Code als die reine Umbenennung, und genau dieser Mehraufwand ist der Punkt. Er zwingt zu der Frage, ob die Umbenennung den Preis wert ist. Bei einer internen Hilfsfunktion ist die Antwort fast immer ja, weil der Compiler oder die Suche alle Aufrufer findet. Bei einer veröffentlichten Prop findet man die Aufrufer nicht – sie sitzen in Repositories, auf die man keinen Zugriff hat.\n\nAls Dokumentation hat sich bei uns Storybook bewährt – als lebende Vertragsbeschreibung, nicht bloß als hübscher Komponenten-Katalog: Für jede Komponente gibt es Stories, die die unterstützten Prop-Kombinationen zeigen, inklusive einer Story für die deprecatete Form, solange sie existiert. Wer wissen will, was `UserCard` kann, schaut nicht in den Quellcode des Komponenten-Teams, sondern in die gebaute Storybook-Instanz der Version, die er einsetzt. Das Team, das die Bibliothek pflegt, merkt dadurch außerdem selbst früher, wenn eine Änderung den Vertrag berührt – eine kaputte Story ist ein deutliches Signal.\n\n## URLs: der Vertrag mit allen anderen\n\nDie zweite Oberfläche wird noch häufiger unterschätzt: die URL. Routen fühlen sich wie ein internes Implementierungsdetail des Routers an, sind aber das genaue Gegenteil – die öffentlichste Schnittstelle, die ein Frontend hat. Auf eine Route zeigen Bookmarks, per Mail geteilte Links, Kampagnen, Monitoring-Checks, die Dokumentation des Nachbarteams und gelegentlich ein PDF, das vor zwei Jahren gedruckt wurde. Keiner dieser Konsumenten bekommt ein Update, wenn jemand im Code `/clients` in `/customers` umbenennt.\n\nEine Route umzubenennen ist deshalb ein Breaking Change mit besonders langlebigen Konsumenten, und die Deprecation-Phase heißt hier Redirect. Mit React Router v4 ist das eine Zeile plus Disziplin:\n\n```jsx\nimport { Switch, Route, Redirect } from 'react-router-dom';\n\n<Switch>\n  <Route path=\"/customers/:customerId\" component={CustomerPage} />\n  {/* Deprecated 2018-08: keep this redirect for at least 12 months. */}\n  <Redirect from=\"/clients/:customerId\" to=\"/customers/:customerId\" />\n</Switch>\n```\n\nDie Disziplin steckt im Kommentar: Der Redirect bleibt, bis die alten Links realistisch aus der Welt sind, nicht bis zum nächsten Aufräum-Commit. In dem Portal-Projekt haben wir irgendwann Zugriffe auf alte Routen mitgezählt, bevor ein Redirect entfernt wurde – dieselbe Praxis, mit der man auch einen alten REST-Endpoint abschaltet. Die Zahlen waren regelmäßig ernüchternd: Links, die wir für tot hielten, wurden noch Monate später aufgerufen.\n\nDasselbe gilt für Query-Parameter. Wer `?tab=invoices` unterstützt, hat einen Vertrag geschlossen, sobald der erste Nutzer den Link teilt. Und die URL ist gleichzeitig persistierter State: Was in ihr steht, übersteht Reloads und wandert zwischen Browsern – ein Grund mehr, sie bewusst zu entwerfen statt sie dem Router-Zufall zu überlassen. Bewusst entwerfen heißt vor allem: fachliche Bezeichner statt interner IDs, keine Implementierungsdetails im Pfad, und ein Schema, das ein Kollege ohne Blick in den Code erraten kann. Eine URL, die man am Telefon vorlesen kann, überlebt erfahrungsgemäß auch das nächste Redesign.\n\n## Events und Messages: Verträge zur Laufzeit\n\nSobald mehrere Anwendungsteile im selben Browser laufen, reden sie irgendwann direkt miteinander – bei uns über CustomEvents auf `window` und über `postMessage` zum eingebetteten Widget. Diese Nachrichten sind die flüchtigste Schnittstellenform: kein Typ-Check, kein gemeinsames Repository, oft nicht einmal ein gemeinsames Deployment. Genau deshalb brauchen sie den explizitesten Vertrag.\n\nWir haben dafür jede Nachricht wie ein kleines Wire-Format behandelt – benannter Typ, dokumentiertes Payload-Schema, Versionsfeld:\n\n```js\n// Contract: 'cart:item-added' (version 1)\n// detail: { version: number, sku: string, quantity: number, source: string }\nwindow.dispatchEvent(new CustomEvent('cart:item-added', {\n  detail: { version: 1, sku: 'A-4711', quantity: 1, source: 'product-page' }\n}));\n\n// Consumer side: tolerate unknown versions instead of guessing.\nwindow.addEventListener('cart:item-added', (event) => {\n  if (event.detail.version !== 1) return;\n  updateCartBadge(event.detail.quantity);\n});\n```\n\nDas Versionsfeld wirkt übervorsichtig, bis zum ersten Mal zwei Seitenteile mit unterschiedlichem Release-Stand im selben Tab laufen. Dann ist es der Unterschied zwischen einem ignorierten Event und einem `undefined`, das drei Funktionen weiter explodiert. Bei `postMessage` kommt die Origin-Prüfung dazu, aber das Prinzip bleibt: Der Empfänger validiert, der Sender verspricht Abwärtskompatibilität innerhalb einer Version. Custom Elements v1 macht diese Denkweise übrigens offiziell – ein Element mit Attributen und Events ist nichts anderes als eine im Browser registrierte API.\n\n## CSS und localStorage: die Verträge, die niemand schließen wollte\n\nDie letzten beiden Oberflächen sind die unangenehmsten, weil sie Verträge sind, die nie jemand bewusst geschlossen hat. Wer BEM-Klassen wie `user-card__avatar` ins DOM schreibt, publiziert sie. Irgendwo stylt ein anderes Team gegen diese Klasse, ein Test selektiert sie, ein Analytics-Snippet hängt daran. Nach derselben Logik sind CSS Custom Properties, die ein Theme nach außen anbietet – `--brand-primary`, `--spacing-unit` –, eine echte, gewollte API und sollten auch so gepflegt werden: benannt, dokumentiert, stabil. Die ungewollte Variante lässt sich eindämmen, indem man klar trennt, welche Klassen Vertragsbestandteil sind und welche generiert oder als privat markiert sind. Aber die Grundregel bleibt: Was beobachtbar ist und lange genug stabil bleibt, wird benutzt werden – unabhängig davon, was die Dokumentation dazu sagt.\n\nlocalStorage ist derselbe Fall in schlimmer: global pro Origin, ohne Namensräume, ohne Schema. Ein Schlüssel wie `user-settings`, den zwei Module lesen, ist eine ungewollte Datenbank-API inklusive Migrationsproblem – ändert ein Modul das Format, parst das andere Müll. Dazu kommt eine Eigenschaft, die Storage von allen anderen Oberflächen unterscheidet: Die alten Werte sind schon draußen. Ein Deployment tauscht den Code aus, aber nicht die Daten in tausenden Browsern – jede Formatänderung trifft dort auf Werte, die eine ältere Version geschrieben hat. Seit dem Portal-Projekt bekommen solche Schlüssel bei mir deshalb ein Präfix mit Modulname und eine Versionsnummer im Wert, und der lesende Code behandelt ein unbekanntes Format wie einen fehlenden Wert. Nicht weil das elegant wäre, sondern weil die Alternative ein Produktionsfehler ist, den man nur mit „Storage im DevTools-Panel leeren\" diagnostizieren kann.\n\n## Versionierung ist Kommunikation, nicht Bürokratie\n\nDer Einwand liegt nahe: Das ist viel Prozess für ein Frontend. Aber der Aufwand ist gestaffelt, und der größte Teil ist schlicht Kommunikation. Für die Komponenten-Bibliothek in unserem Lerna-Monorepo sah das Fenster für einen Breaking Change so aus:\n\n- Änderung im Changelog ankündigen, mit altem und neuem Vertrag\n- eine Minor-Version, in der beides funktioniert und die alte Form im Entwicklungsmodus warnt\n- Storybook-Story für die alte Form als deprecated markieren\n- Entfernung erst in der nächsten Major-Version, mit Migrationshinweis\n\nDas kostet pro Änderung vielleicht eine Stunde. Der Prop-Rename ohne dieses Fenster hat uns damals, alle Beteiligten zusammengerechnet, mehrere Tage gekostet – Fehlersuche in einer fremden Codebasis, Hotfix, Sonderrelease, und das Vertrauen zwischen zwei Teams gleich mit. Über die schludrige Behandlung von Code, der zwischen den Zuständigkeiten liegt, habe ich unter anderem in [Build-Skripte als Produktcode](https://www.mikebild.dev/de/blog/build-skripte-als-produktcode/) schon einmal geschrieben; Frontend-Schnittstellen werden auf dieselbe Weise übersehen, nur hängen hier mehr Teams daran.\n\nMir ist dabei aufgefallen, dass die Teams gar nicht an der Disziplin scheitern, sondern an der Wahrnehmung. Niemand weigert sich, eine API sauber zu versionieren – man sieht nur nicht, dass man gerade eine hat. Der wirksamste Schritt war deshalb nicht das Tooling, sondern die Liste vom Anfang: einmal aufschreiben, welche Oberflächen das eigene Frontend tatsächlich anbietet und wer daran hängt. Alles, was auf dieser Liste steht und einen Konsumenten außerhalb des eigenen Teams hat, verdient die drei bekannten Zutaten – expliziter Vertrag, semantische Version, Deprecation-Fenster.\n\n## Unterm Strich\n\nEin Frontend ist kein Blatt am Ende des Abhängigkeitsbaums, sondern selbst ein Anbieter von Schnittstellen: Props, URLs, Events, CSS-Oberflächen, gespeicherte Schlüssel. Solange ein einziges Team alles davon besitzt und in einem Schritt ausliefert, darf man das ignorieren. Spätestens wenn mehrere Teams im selben Browser arbeiten – und die Design-System- und Micro-Frontend-Bewegung sorgt gerade dafür, dass das der Normalfall wird –, gelten die Regeln, die im Backend seit Jahren selbstverständlich sind. Breaking Change heißt Major-Version. Umbenennen heißt deprecaten. Und ein harmlos aussehender Diff ist genau so harmlos wie die Zahl der Konsumenten, die niemand gefragt hat.\n\n## Weiterführende Quellen\n\n- Semantic Versioning 2.0.0 (deutsche Fassung): https://semver.org/lang/de/\n- React-Dokumentation: Typechecking mit PropTypes: https://legacy.reactjs.org/docs/typechecking-with-proptypes.html\n- MDN: CustomEvent: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n- MDN: Window.postMessage: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage\n- Storybook: https://storybook.js.org/"},{"locale":"de","translation_key":"docker-compose-nodejs-redis","slug":"docker-compose-nodejs-redis","title":"Node.js und Redis mit Docker Compose","summary":"Wie ich in Projekten eine Zwei-Container-App aus Node.js und Redis mit Docker Compose beschreibe: eine YAML für den ganzen Stack, Service Discovery über den Servicenamen, Persistenz per Volume – und warum depends_on nicht auf Betriebsbereitschaft wartet.","tags":["Software","Platform"],"published_at":"2018-07-24T10:00:00+00:00","updated_at":"2026-07-13T09:59:53.348841+00:00","url":"https://www.mikebild.dev/de/blog/docker-compose-nodejs-redis/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/4b528de46688ed9b7f59bc3945d12106845d620a1869c914765add8b50eecee4/docker-compose-nodejs-redis-vorlesen.mp3","audio_duration_secs":934,"text":"Ein zweiter Container verdoppelt die Arbeit nicht, er verändert sie. Bei einem einzelnen `docker run` geht es um ein Image, einen Port, vielleicht zwei Umgebungsvariablen. Sobald ein Node-Prozess auf Redis angewiesen ist, kommen Fragen dazu, die sich mit Kommandozeilen-Akrobatik nur noch mühsam beantworten lassen: In welchem Netz liegen beide Container? Unter welcher Adresse findet der eine den anderen? Wer startet zuerst – und wo bleiben die Daten, wenn ein Container ersetzt wird?\n\nDocker Compose beantwortet diese Fragen an einer einzigen Stelle. Das Wissen, wie der Stack hochfährt, steht danach in einer versionierten Datei statt in Köpfen und einer Setup-Doku: `git clone`, `docker-compose up`, läuft. Ein Neuzugang im Team verliert damit keinen halben Tag an Node-Versionen, lokaler Redis-Installation und belegten Ports. Bezahlt wird das mit einer Datei, die gepflegt werden will – ein Handel, der sich schnell rechnet.\n\nDen technischen Weg gehe ich vollständig: von der `docker-compose.yml` über Service Discovery und Persistenz bis zu dem Fallstrick, der beim ersten Mal leicht eine halbe Stunde kostet. Stand ist Sommer 2018, also Compose file v3 und die Bindestrich-CLI `docker-compose`.\n\n**Redaktionelle Einordnung (Juli 2026):** Aktuelles Docker Compose kann bei der Langform von `depends_on` mit `condition: service_healthy` auf einen erfolgreichen Healthcheck warten. Die Anwendung sollte Verbindungsabbrüche und Neustarts trotzdem selbst verkraften; ein Healthcheck ersetzt keine Retry-Strategie. Der Haupttext belässt die Einschränkung des damaligen Compose-v3-Formats.\n\n## Warum überhaupt Compose\n\nEin einzelner Container ist schnell erklärt. Sobald aber zwei Container zusammenspielen sollen, wird die imperative Variante mühsam: Netzwerk anlegen, beide Container darin starten, Ports publizieren, Umgebungsvariablen setzen, Startreihenfolge beachten. Das sind viele Kommandos, die niemand fehlerfrei aus dem Kopf reproduziert – schon gar nicht der Kollege, der das Projekt morgen zum ersten Mal klont.\n\nCompose dreht das um. Statt einer Kommandofolge schreibe ich eine deklarative Beschreibung des Zielzustands. Die Datei sagt, welche Services es gibt, welche Images sie nutzen, welche Ports offen sind und wie sie zusammenhängen. Der Startbefehl ist danach immer derselbe. Wer schon einmal mit Docker gearbeitet hat, kennt das Prinzip aus dem Dockerfile – Compose hebt es nur eine Ebene höher, von einem Image auf eine ganze Anwendung.\n\nDas Ganze folgt einer einfachen Idee: reproduzierbare, gekapselte Umgebungen, die auf jedem Rechner gleich hochfahren.\n\n## Die docker-compose.yml\n\nHier ist die Datei, mit der ich starte. Zwei Services, minimal gehalten, damit jede Zeile eine erkennbare Aufgabe hat.\n\n```yaml\nversion: '3'\nservices:\n  web:\n    build: .\n    environment:\n      NODE_ENV: production\n      REDIS_HOST: 'redis'\n      REDIS_PORT: '6379'\n    ports:\n      - '8080:8080'\n    depends_on:\n      - 'redis'\n  redis:\n    image: redis:4.0.11\n```\n\nDie erste Zeile ist 2018 Pflicht: `version: '3'`. Ohne diesen Key weigert sich Compose, die Datei zu lesen. Darunter kommen die Top-Level-Keys, die uns hier interessieren – `services:` auf jeden Fall, `volumes:` und `networks:` gleich noch.\n\nZwei Zeilen lohnt es, gezielt anzuschauen. Beim `web`-Service steht `build: .` – Compose baut das Image lokal aus dem Dockerfile im aktuellen Verzeichnis. Beim `redis`-Service steht `image: redis:4.0.11` – hier wird ein fertiges Image aus der Registry gezogen. Das ist der zentrale Gegensatz:\n\n- `build:` nutze ich für meinen eigenen Code, den es als fertiges Image noch nicht gibt. Compose ruft im Hintergrund einen `docker build` auf.\n- `image:` nutze ich für alles, was ich unverändert übernehme – Datenbanken, Caches, Message-Broker. Redis pinne ich dabei auf eine konkrete Version (`4.0.11`) statt auf `latest`, damit die Umgebung reproduzierbar bleibt.\n\nFür den Fall, dass mein Webservice bereits gebaut und in eine Registry geschoben wurde, tausche ich `build: .` einfach gegen `image: mikebild/compose-nodejs-redis:1.0.0`. Dieselbe Datei, ein anderer Bezugsweg – im Deploy-Kontext genau das, was man will.\n\nAuffällig ist auch, was beim `redis`-Service fehlt: kein `ports`. Das ist Absicht. Nur `web` publiziert mit `'8080:8080'` einen Port auf den Host, weil nur der Webservice von außen erreichbar sein soll. Redis bleibt containerintern und braucht deshalb keine Host-Veröffentlichung. Auf diesen Isolationspunkt komme ich weiter unten zurück, er hat nämlich eine handfeste Sicherheitsseite.\n\n## Service Discovery: Redis heißt einfach \"redis\"\n\nBleibt die Frage, woher der Node-Prozess weiß, unter welcher Adresse er Redis findet. Es steht ja nirgends eine IP.\n\nCompose legt beim Start automatisch ein Default-Netzwerk an, benannt nach dem Projekt, etwa `<projekt>_default`. Jeder Service hängt in diesem Netz und ist darin unter seinem Servicenamen per eingebautem DNS erreichbar. Anders gesagt: Jeder Service erreicht jeden anderen Service unter dessen Servicenamen. Der Name `redis` aus der YAML wird zum Hostnamen im Netzwerk.\n\nDeshalb setze ich in der Datei `REDIS_HOST: 'redis'`. Der Node-Client verbindet sich zu `redis:6379` – keine hartkodierte IP, keine `--link`-Akrobatik. Wenn Compose morgen dem Container eine andere interne Adresse gibt, ist das egal, weil über den Namen aufgelöst wird.\n\n```mermaid\ngraph LR\n  Client[\"Client / Browser\"] -->|\"Host-Port 8080\"| Web\n  subgraph net[\"Compose default network\"]\n    Web[\"web-Container\"] -->|\"DNS: redis:6379\"| Redis[\"redis-Container\"]\n  end\n  Redis --> Vol[(\"volume<br/>redis-data (/data)\")]\n```\n\nVon außen führt genau ein Weg herein, über den publizierten Host-Port 8080 auf `web`. Intern spricht `web` mit `redis` über den Servicenamen. Und die Redis-Daten liegen in einem Volume, um das es gleich geht.\n\nWer das Default-Netz sichtbar machen will, kann es auch explizit hinschreiben. Ich mache das in einem neuen Projekt gern einmal, damit klar wird, dass hier kein Zauber im Spiel ist:\n\n```yaml\nversion: '3'\nservices:\n  web:\n    build: .\n    environment:\n      REDIS_HOST: 'redis'\n      REDIS_PORT: '6379'\n    ports:\n      - '8080:8080'\n    networks:\n      - app-net\n    depends_on:\n      - 'redis'\n  redis:\n    image: redis:4.0.11\n    networks:\n      - app-net\nnetworks:\n  app-net:\n```\n\nFunktional ändert das gegenüber der ersten Datei nichts – Compose hätte ohnehin ein Netz gebaut. Aber der Mechanismus steht damit sichtbar in der Datei, und das Netz ist kein impliziter Side Effect mehr.\n\n## Der Node-Client\n\nDamit die Verbindung nicht abstrakt bleibt, hier der relevante Ausschnitt des Servers. Es ist ein schlanker Express-Server, der `node_redis` in der 2018 gängigen Version `^2.8` nutzt – also die Callback-API, noch nicht die späteren Promises.\n\n```js\nconst SERVICE_PORT = process.env.SERVICE_PORT || 8080;\nconst REDIS_HOST = process.env.REDIS_HOST || 'localhost';\nconst REDIS_PORT = process.env.REDIS_PORT || '6379';\n\nconst express = require('express');\nconst redis = require('redis');\nconst app = express();\nconst client = redis.createClient(REDIS_PORT, REDIS_HOST);\n\nclient.on('error', err => {\n  console.error(`Redis connection error.\\n${err.message}`);\n  process.exit(1);\n});\n\napp.get('/redis', (req, res, next) => {\n  client.get('foo', (error, result) => {\n    if (error) return next(error);\n    res.send(result);\n  });\n});\n\napp.post('/redis', (req, res, next) => {\n  client.set('foo', 'bar', (error, result) => {\n    if (error) return next(error);\n    res.status(201).send('done');\n  });\n});\n\napp.listen(SERVICE_PORT, () => console.log(`Listen on ${SERVICE_PORT}`));\n```\n\nDie entscheidende Zeile ist `redis.createClient(REDIS_PORT, REDIS_HOST)`. Host und Port kommen aus der Umgebung, und die Umgebung füllt Compose über den `environment`-Block. So bleibt der Code frei von Adressen. Auf meinem Laptop läuft er gegen `localhost`, im Compose-Netz gegen `redis` – ohne dass eine Zeile Anwendungscode sich ändert.\n\nEin Detail behalte ich im Hinterkopf: Der `client.on('error', …)`-Handler beendet den Prozess mit `process.exit(1)`, sobald die Redis-Verbindung scheitert. Das ist bewusst hart und führt direkt zum wichtigsten Fallstrick.\n\n## Der Fallstrick: depends_on wartet nicht auf \"ready\"\n\n`depends_on: ['redis']` liest sich, als würde Compose warten, bis Redis einsatzbereit ist, bevor es `web` startet. Das tut es nicht. `depends_on` steuert ausschließlich die Start-Reihenfolge: Compose startet den Redis-Container vor dem Web-Container. Es wartet aber nicht, bis Redis Verbindungen annimmt – nur, bis der Container gestartet wurde.\n\nDer Unterschied klingt akademisch, bis der harte Error-Handler oben zuschlägt. Redis braucht einen Moment, bis der Server im Container tatsächlich lauscht. Startet `web` in diesem Fenster und versucht sofort zu verbinden, feuert `client.on('error')`, der Prozess beendet sich mit Exit-Code 1 – und der frisch gestartete Stack ist schon wieder halb tot. Auf langsameren Rechnern passiert das reproduzierbar.\n\nDie saubere Lösung liegt nicht in der YAML, sondern in der Anwendung. Sie muss Verbindungsabbrüche vertragen und einen Reconnect mit Retry versuchen, statt beim ersten Fehler auszusteigen. Wo ich den Anwendungscode nicht anfassen will, schiebe ich in 2018 ein kleines Wartescript vor den Start – `wait-for-it.sh`, `dockerize` oder `wait-for` prüft, ob `redis:6379` erreichbar ist, bevor der Node-Prozess startet.\n\nEine Sache gehört hier ausdrücklich verneint: Die Langform `depends_on: {redis: {condition: service_healthy}}`, die auf einen Healthcheck wartet, gibt es in Compose v3 im Jahr 2018 nicht. Wer sie in ein v3-File schreibt, bekommt sie schlicht nicht anerkannt. Die Wartelogik gehört also in Anwendung oder Wartescript, Punkt.\n\n## Persistenz: Redis braucht ein Volume\n\nDer zweite Fallstrick ist stiller, dafür ärgerlicher. In der Startdatei hat Redis kein Volume. Solange der Container läuft, ist alles gut – die Daten liegen im Container-Dateisystem unter `/data`. Doch sobald der Container ersetzt wird, etwa nach `docker-compose down` und einem erneuten `up`, ist der Cache leer. Der Container ist eben flüchtig, und mit ihm sein Dateisystem.\n\nWer Redis nicht nur als Wegwerf-Cache nutzt, mountet ein benanntes Volume auf `/data`. Das redis-Image legt seine RDB-Snapshots genau dort ab.\n\n```yaml\nversion: '3'\nservices:\n  web:\n    build: .\n    environment:\n      REDIS_HOST: 'redis'\n      REDIS_PORT: '6379'\n    ports:\n      - '8080:8080'\n    depends_on:\n      - 'redis'\n  redis:\n    image: redis:4.0.11\n    volumes:\n      - 'redis-data:/data'\nvolumes:\n  redis-data:\n```\n\nDas benannte Volume `redis-data` überlebt den Lifecycle des Containers. Ich kann `web` neu bauen, den Stack herunterfahren und wieder hochziehen – die Redis-Daten sind noch da. Nur ein explizites `docker-compose down -v` räumt auch die Volumes ab.\n\nDamit habe ich die vier Bausteine beisammen, die eine Compose-Datei ausmachen:\n\n- `services` sind die Container der Anwendung, hier `web` und `redis`.\n- `ports` legt fest, welche Container-Ports auf den Host veröffentlicht werden; nur `web` bekommt einen.\n- `volumes` hält Daten in benannten Volumes, die den Container überleben sollen, hier `redis-data`.\n- `networks` beschreibt das meist automatische Netz, das Service Discovery per Servicename ermöglicht.\n\n## Der Zyklus: up, logs, down\n\nIm Betrieb sind es nur eine Handvoll Kommandos, und die bleiben über Projekte hinweg gleich. Ich starte den Stack im Hintergrund, schaue in die Logs und fahre am Ende alles wieder herunter.\n\n```bash\ndocker-compose up -d\ndocker-compose logs web\n\ncurl -X POST http://localhost:8080/redis\ncurl http://localhost:8080/redis\n\ndocker-compose down\n```\n\nDas `up -d` startet beide Container detached. `logs web` zeigt gezielt die Ausgabe des Webservice, was beim Debuggen des Startfensters oben hilft. Die beiden `curl`-Aufrufe schreiben zuerst den Wert nach Redis und lesen ihn dann zurück – der Beweis, dass `web` seinen Nachbarn unter dem Namen `redis` tatsächlich erreicht. `down` stoppt und entfernt Container und das Default-Netz; die benannten Volumes bleiben, sofern ich nicht `-v` ergänze.\n\nWer Docker Toolbox nutzt statt Docker for Mac oder Windows, erreicht den Stack übrigens nicht unter `localhost`, sondern unter der IP der docker-machine, in der Standardkonfiguration `192.168.99.100`. Das ist 2018 auf vielen Rechnern noch die Realität und kostet beim ersten Mal ein paar ratlose Minuten.\n\n## Der eigentliche Gewinn: Zeit bis zum ersten Commit\n\nDie YAML ist dabei nur das Mittel. Das Ergebnis ist eine Umgebung, die jeder im Team mit denselben zwei Befehlen bekommt. Wer heute ins Projekt kommt, klont das Repository, tippt `docker-compose up` und hat wenig später einen laufenden Stack aus Node und Redis vor sich – ohne die richtige Node-Version manuell zu suchen, ohne Redis lokal zu installieren, ohne die stille Annahme, dass Port 6379 frei ist. Die Umgebung steht in der Datei, nicht in einer Wiki-Seite, die niemand pflegt.\n\nDas ist der Punkt, an dem sich Compose betriebswirtschaftlich rechnet. Onboarding ist teuer, und der teuerste Teil ist selten das Verstehen des Codes – es ist das Herstellen einer Umgebung, in der der Code überhaupt läuft. Genau diesen Teil verschiebt Compose von jedem einzelnen Entwickler in eine versionierte Datei. Die Zeit bis zum ersten Commit, die sonst zwischen einem halben und einem ganzen Tag liegen kann, schrumpft auf die Dauer eines Image-Pulls.\n\nKostenlos ist das nicht. Ich handele mir eine zusätzliche Abstraktion ein, die das Team verstehen muss, und eine Datei, die gepflegt werden will. Versions-Pinning ist Disziplin: Ein `redis:latest` untergräbt genau die Reproduzierbarkeit, für die ich Compose überhaupt einsetze. Und Compose deckt Entwicklung und lokale Integration ab, nicht den Produktionsbetrieb mit seinen Fragen nach Ausfallsicherheit, Skalierung und Secrets.\n\nDie Entscheidung fällt deshalb an einer klaren Grenze. Sobald mehr als ein Prozess zusammenspielt und mehr als eine Person das Projekt anfasst, trägt Compose seinen Aufwand schnell wieder herein – jede vermiedene Setup-Stunde pro Neuzugang ist die Datei bereits wert. Bei einem einzelnen Tool ohne Nachbarn bleibt `docker run` die ehrlichere Antwort. Ausschlaggebend ist dabei weniger die Technik als die Reibung, die sie erspart.\n\n## Ein Wort zur Sicherheit\n\nDer fehlende `ports`-Eintrag bei Redis ist Absicht und der eigentliche Kern der Isolation. `ports` publiziert auf allen Host-Interfaces. Würde ich Redis mit `'6379:6379'` nach außen legen, stünde eine offene, standardmäßig ungesicherte Redis-Instanz im Netz – und Redis ist genau dafür immer wieder negativ aufgefallen. Innerhalb des Compose-Netzes erreicht `web` seinen Cache ohnehin über den Servicenamen. Von außen soll ihn niemand erreichen. Also lasse ich Redis unpubliziert. Das Prinzip bleibt schlicht: Nur Dienste, die vom Host erreichbar sein müssen, bekommen einen veröffentlichten Port.\n\nAm Rande: Der `links`-Eintrag, der einem in älteren Beispielen begegnet, ist Legacy. In v3 macht ihn das Default-Netz mit seinem DNS überflüssig. Wer ihn noch stehen hat, kann ihn streichen.\n\n## Fazit\n\nCompose macht aus einer Handvoll `docker run`-Kommandos eine einzige, lesbare Datei, die den ganzen Stack beschreibt. `image` gegen `build` trennt übernommene von selbstgebauten Diensten. Service Discovery über den Servicenamen räumt hartkodierte IPs komplett aus dem Weg – `REDIS_HOST: 'redis'` genügt, und der Node-Client verbindet sich zu `redis:6379`. Ein benanntes Volume auf `/data` rettet die Redis-Daten über den Container-Lifecycle hinweg. Und `ports` publiziert nur, was wirklich nach außen soll.\n\nDer eine Punkt, der mir am wichtigsten ist: `depends_on` ordnet den Start, garantiert aber keine Betriebsbereitschaft. Wer das nicht weiß, jagt einem Race-Condition-Fehler hinterher, den keine YAML-Zeile behebt – die Wartelogik gehört in die Anwendung oder in ein kleines Wartescript. Wer es weiß, baut den Stack von Anfang an widerstandsfähig.\n\nWichtiger als die einzelne YAML-Zeile ist aber, was sie dem Team spart. Eine reproduzierbare Umgebung verkürzt die Schleife vom Klonen zum ersten Commit, nimmt die Reibung aus dem Onboarding und macht \"läuft bei mir\" zu einer überprüfbaren Aussage statt einer Hoffnung. Das hebt nebenbei die Qualität, weil alle gegen denselben Zustand entwickeln und testen. Die Grenze bleibt klar: Compose ist ein Werkzeug für Entwicklung und lokale Integration, kein Produktions-Orchestrator. Innerhalb dieser Grenze fühlt sich `docker-compose up` jedes Mal wie ein einziger, verlässlicher Handgriff an – und genau das ist der Gewinn.\n\n## Weiterführende Quellen\n\n- [Docker Compose: Startreihenfolge und `service_healthy`](https://docs.docker.com/compose/how-tos/startup-order/)\n\n- Foliensatz zu diesem Thema: https://slides.mikebild.dev/introduction-docker-kubernetes.html\n- [Compose file v3 reference](https://docs.docker.com/compose/compose-file/)\n- [Networking in Compose (DNS, Default-Netz)](https://docs.docker.com/compose/networking/)\n- [Control startup order in Compose](https://docs.docker.com/compose/startup-order/)\n- [Compose CLI overview](https://docs.docker.com/compose/reference/overview/)\n- [redis Official Image, Tag 4.0.11](https://hub.docker.com/_/redis)"},{"locale":"de","translation_key":"containerisierung-falsche-sicherheit","slug":"containerisierung-falsche-sicherheit","title":"Containerisierung und die falsche Sicherheit","summary":"Warum „läuft im Container“ weder Isolation noch Reproduzierbarkeit noch geregelten Betrieb bedeutet – und welche Handgriffe die drei Lücken tatsächlich schließen.","tags":["Software","Platform"],"published_at":"2018-07-12T10:00:00+00:00","updated_at":"2026-07-14T17:00:42.669323+00:00","url":"https://www.mikebild.dev/de/blog/containerisierung-falsche-sicherheit/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/8228e884878f6d7aeb6791673dd0c57cd1a3a8316a88de0b902a19d677159559/containerisierung-falsche-sicherheit-vorlesen.mp3","audio_duration_secs":677,"text":"# Containerisierung und die falsche Sicherheit\n\n„Es läuft im Container“ hat sich in Projektgesprächen zu einer Art Gütesiegel entwickelt. Der Satz soll gleich drei Dinge auf einmal belegen: Die Anwendung sei isoliert, der Build sei reproduzierbar, und der Betrieb sei geregelt. Keine dieser drei Aussagen folgt aus der Verpackung. Ein Container ist zunächst nur ein gewöhnlicher Prozess mit eingeschränkter Sicht auf das System – ob er Sicherheit und Wiederholbarkeit mitbringt, entscheidet sich im Dockerfile und in der Startkonfiguration, nicht im Wort „Container“.\n\nMir fällt diese Verwechslung seit einigen Monaten in Reviews auf. Ein Team zeigt ein sauberes Deployment auf Kubernetes 1.10, alles grün, und auf die Frage nach dem Patch-Stand des Basis-Images kommt ein Achselzucken. Ein anderes Team baut seit einem Jahr auf `node:latest` und wundert sich, dass der CI-Build sich anders verhält als der lokale. Die drei falschen Sicherheiten lohnen einen genaueren Blick, weil sie drei verschiedene Gegenmittel brauchen.\n\n## Erste falsche Sicherheit: Isolation\n\nEin Container ist keine kleine virtuelle Maschine. Eine VM bringt einen eigenen Kernel mit und spricht mit dem Host über einen Hypervisor. Ein Container teilt sich den Kernel mit dem Host und mit allen anderen Containern auf derselben Maschine. Was ihn abgrenzt, sind Kernel-Namespaces für Prozesse, Netzwerk und Dateisystem sowie cgroups für Ressourcen – nützliche Mechanismen, aber eine deutlich dünnere Wand als ein Hypervisor.\n\n```mermaid\nflowchart TB\n  subgraph VM[\"Virtuelle Maschine\"]\n    A1[App] --> K1[Gast-Kernel]\n    K1 --> H1[Hypervisor]\n    H1 --> HW1[Host-Kernel<br/>+ Hardware]\n  end\n  subgraph CT[\"Container\"]\n    A2[App als Prozess] --> NS[Namespaces<br/>+ cgroups]\n    NS --> HW2[gemeinsamer<br/>Host-Kernel]\n  end\n```\n\nDie praktische Konsequenz: Wer im Container als root läuft, läuft auf dem Host als root. UID 0 ist UID 0. User Namespaces, die Container-root auf einen unprivilegierten Host-Benutzer abbilden, gibt es in Docker seit einer Weile – aber sie sind opt-in über `--userns-remap`, und in den Umgebungen, die ich dieses Jahr gesehen habe, war das Feature genau null Mal eingeschaltet. Solange das so ist, trennt einen root-Prozess im Container vom Host nur noch die Frage, ob er einen Weg nach draußen findet.\n\nEin `--privileged`-Container findet diesen Weg garantiert. Das Flag schaltet sämtliche Capabilities frei und gibt Gerätezugriff – damit lässt sich vom Container aus das Host-Dateisystem einhängen. Ich habe das Flag schon in Produktions-Setups gefunden, gesetzt vor Monaten, „weil es sonst nicht lief“, und nie wieder hinterfragt. Ein privilegierter Container ist keine Isolationsschicht mit einer Schwäche, er ist eine offene Tür mit einem Vorhang davor.\n\nDocker bringt seit Längerem ein seccomp-Standardprofil mit, das riskante Syscalls filtert, dazu AppArmor-Profile auf Ubuntu-Hosts. Das hilft, ändert aber nichts am Grundsatz: Die Grenze ist der Kernel, und der Kernel ist gemeinsam. Meltdown und Spectre haben im Januar zusätzlich gezeigt, dass selbst Prozessgrenzen auf CPU-Ebene wackeln können. Wer echte Mandantentrennung braucht, also fremden oder nicht vertrauenswürdigen Code fährt, nimmt weiterhin VMs – oder schaut sich gVisor an, das Google im Mai vorgestellt hat: ein Userspace-Kernel zwischen Container und Host. Spannender Ansatz, aber im Juli 2018 zu frisch, um eine Produktionsentscheidung darauf zu bauen.\n\nWas heute schon geht, ist die Angriffsfläche beim Start zu verkleinern:\n\n```bash\ndocker run -d \\\n  --read-only \\\n  --cap-drop ALL \\\n  --cap-add NET_BIND_SERVICE \\\n  --security-opt no-new-privileges \\\n  --memory 256m \\\n  order-service:1.4.2\n```\n\nAlles daran ist seit Jahren verfügbar, nichts davon ist Standard. Genau das ist der Punkt: Isolation ist beim Container kein Zustand, sondern eine Konfiguration, die jemand aktiv vornehmen muss.\n\n## Zweite falsche Sicherheit: Reproduzierbarkeit\n\nDie zweite Annahme lautet: Weil die Anwendung als Image ausgeliefert wird, ist der Build reproduzierbar. Das stimmt nur für das fertige Image – dieselbe Image-ID startet überall denselben Stand. Für den Weg dorthin stimmt es nicht. Ein Dockerfile wie dieses ist keine Beschreibung, sondern eine Momentaufnahme:\n\n```dockerfile\nFROM node:latest\nWORKDIR /app\nCOPY . .\nRUN apt-get update && apt-get install -y imagemagick\nRUN npm install\nENV API_SECRET=changeme-in-prod\nEXPOSE 3000\nCMD [\"node\", \"server.js\"]\n```\n\nHier ist fast jede Zeile ein Zeitzünder. `node:latest` ist keine Version, sondern eine Wette darauf, wann gebaut wird – letztes Jahr bekam man Node 8, seit ein paar Wochen Node 10, und niemand hat eine Entscheidung getroffen. `apt-get install` ohne Versionsangabe zieht, was der Spiegelserver heute hergibt. `npm install` ohne Lockfile würfelt die Abhängigkeitsversionen zum Build-Zeitpunkt aus; mit `package-lock.json` ist das seit npm 5 lösbar, aber nur, wenn die Datei auch eingecheckt und respektiert wird. Und das Secret in der `ENV`-Zeile liegt jetzt für immer in der Image-History – `docker history` zeigt es jedem, der das Image ziehen darf.\n\nDazu kommen Build-Args als stille Variable: Ein `ARG`, das auf dem CI-Server anders gesetzt ist als auf dem Entwicklerrechner, erzeugt zwei verschiedene Images aus identischem Quellstand – und weil das Argument nirgends im Repository steht, sieht man den Unterschied erst, wenn man beide Images nebeneinanderlegt. Zwei Builds desselben Dockerfiles im Abstand von sechs Wochen können sich also in Kernelnähe, Systempaketen und npm-Abhängigkeiten unterscheiden, ohne dass eine einzige Zeile im Repository geändert wurde. In einem Projekt im Frühjahr haben wir genau daran einen Nachmittag verloren: Der Hotfix-Build für einen sechs Wochen alten Stand verhielt sich anders als das laufende System, weil das Basis-Image unter demselben Tag inzwischen ein anderes war. Die ehrliche Formel ist: Ein Image ist ein Ergebnis. Reproduzierbar wird es erst, wenn alle Eingaben festgenagelt sind – Basis-Image per Tag oder besser per Digest (`node:8.11-alpine@sha256:...`), Systempakete mit Version, Anwendungsabhängigkeiten über das Lockfile.\n\n## Dritte falsche Sicherheit: Betrieb\n\nDie dritte Annahme ist die leiseste: Der Container läuft, also ist der Betrieb erledigt. Dabei friert ein Image nicht nur die Anwendung ein, sondern auch jede Bibliothek darunter – inklusive ihrer Lücken. Auf einem klassisch administrierten Server spielt `unattended-upgrades` nachts Sicherheitsupdates ein. Im Container gibt es diesen Weg nicht. Die einzige Patch-Route ist: neues Basis-Image, neuer Build, neues Deployment. Wer diese Kette nicht als Routine eingerichtet hat, betreibt eine Flotte, die mit jedem Tag stiller veraltet, während das Dashboard grün bleibt.\n\nVorgelagert kommt noch eine Frage, die überraschend oft unbeantwortet bleibt: Welche Images laufen überhaupt, und aus welchem Stand wurden sie gebaut? Auf einem Cluster mit ein paar Dutzend Deployments ist das ohne Inventar reine Archäologie. Als im Januar die ersten Meltdown-Patches kamen, habe ich in einem Projekt erlebt, wie lange allein die Bestandsaufnahme dauert, wenn Tags wie `latest` und `stable` im Umlauf sind – man weiß dann buchstäblich nicht, was man betreibt, nur dass es läuft.\n\n```mermaid\nflowchart LR\n  CVE[CVE im Basis-Image<br/>veröffentlicht] --> BASE[Basis-Image<br/>aktualisiert]\n  BASE --> BUILD[Rebuild<br/>aller Services]\n  BUILD --> SCAN[Image-Scan<br/>z. B. Clair]\n  SCAN --> DEPLOY[Rollout]\n  DEPLOY -. ohne Routine reißt<br/>die Kette hier ab .- BUILD\n```\n\nDass Betrieb die eigentliche Flanke ist, hat dieses Jahr ein prominenter Fall gezeigt: Im Februar wurde bekannt, dass die Kubernetes-Verwaltungskonsole von Tesla ohne Passwortschutz aus dem Internet erreichbar war. Die Angreifer haben keine Kernel-Lücke gebraucht und keinen Container ausgebrochen – sie haben sich über die offene Konsole eingerichtet, Krypto-Mining-Pods deployt, die CPU-Last gedrosselt und den Mining-Pool hinter Cloudflare versteckt, um nicht aufzufallen. Dieselbe Kategorie: Docker-Daemons, deren Remote-API unauthentifiziert auf Port 2375 lauscht und die reihenweise von Mining-Skripten abgegrast werden. In beiden Fällen war die Container-Technik völlig unschuldig. Verwundbar war das Betriebsmodell drumherum – exponierte Verwaltungsschnittstellen, fehlende Zugangskontrolle, niemand, der hinschaut.\n\nFür mich ist das die wichtigste Lektion aus dem Fall: Die Plattform verschiebt die Betriebsfragen, sie beantwortet sie nicht. Wer vorher wissen musste, welche Pakete auf dem Server liegen, muss jetzt wissen, welche Layer in den Images liegen. Wer vorher SSH abgesichert hat, muss jetzt Kubelet, API-Server und Dashboard absichern. Der Aufwand ist nicht verschwunden, er hat die Adresse gewechselt.\n\n## Was konkret hilft\n\nNichts davon ist ein Argument gegen Container – es ist ein Argument gegen das Gütesiegel. Die Gegenmittel sind unspektakulär und seit geraumer Zeit verfügbar. Am Dockerfile selbst sieht das so aus:\n\n```dockerfile\n# build stage\nFROM node:8.11-alpine AS build\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm install\nCOPY . .\nRUN npm run build && npm prune --production\n\n# runtime stage\nFROM node:8.11-alpine\nWORKDIR /app\nRUN addgroup -S app && adduser -S app -G app\nCOPY --from=build /app/dist ./dist\nCOPY --from=build /app/node_modules ./node_modules\nUSER app\nEXPOSE 3000\nCMD [\"node\", \"dist/server.js\"]\n```\n\nMulti-Stage-Builds gibt es seit Docker 17.05, sie sind also seit über einem Jahr etabliert und kein Experiment mehr. Der Effekt: Compiler, Dev-Abhängigkeiten und Build-Werkzeuge bleiben in der ersten Stufe zurück, ausgeliefert wird nur, was zur Laufzeit gebraucht wird. Die `USER`-Direktive sorgt dafür, dass der Prozess gar nicht erst als root startet – eine Zeile, die einen Großteil des Isolationsproblems aus dem ersten Abschnitt entschärft, weil ein Ausbruch dann bei einem unprivilegierten Benutzer landet. Das gepinnte Basis-Image nimmt der Reproduzierbarkeitsfrage die Würfel aus der Hand. Ein angenehmer Side Effect der kleinen Laufzeitstufe: Der Image-Scanner hat weniger zu melden, weil schlicht weniger Pakete an Bord sind – ein Alpine-Image mit einer Handvoll Bibliotheken erzeugt Befunde, die man tatsächlich liest, statt einer Liste mit dreihundert Einträgen, die nach der zweiten Woche niemand mehr öffnet.\n\nDarüber hinaus haben sich bei mir ein paar Punkte als Checkliste für Reviews eingespielt:\n\n- Basis-Images klein wählen – `alpine` für den Alltag, für kompilierte Sprachen die distroless-Images, die Google letztes Jahr veröffentlicht hat und die außer der Anwendung und ihren Laufzeitabhängigkeiten nichts enthalten, nicht einmal eine Shell.\n- Tags pinnen, für Produktions-Deployments zusätzlich den Digest festhalten – `latest` hat in einem Deployment-Manifest nichts verloren.\n- Image-Scanning in die CI-Kette hängen: Clair oder Anchore gleichen die Layer gegen bekannte CVEs ab und machen aus „wir müssten mal patchen“ einen roten Build.\n- Secrets niemals ins Image – nicht als `ENV`, nicht als `ARG`, nicht als kopierte Datei. Beides landet in der History beziehungsweise im Build-Kontext. Secrets kommen zur Laufzeit von außen, etwa als Kubernetes Secret oder über den Orchestrator.\n- Capabilities beim Start beschneiden und `--privileged` wie einen offenen root-Zugang behandeln: Wer es setzen will, muss begründen, warum.\n\nKeiner dieser Punkte ist schwer. Das eigentliche Hindernis ist, dass sie unsichtbar sind, solange alles läuft – und genau deshalb gehören sie ins Review und nicht in die Rubrik „machen wir, wenn Zeit ist“.\n\n## Unterm Strich\n\nContainer haben unsere Auslieferung spürbar besser gemacht: gleiche Artefakte in allen Umgebungen, schnelle Starts, saubere Schnittstelle zwischen Build und Betrieb. Was sie nicht liefern, ist das, was der Satz „läuft im Container“ so gern behauptet. Isolation ist eine Konfiguration, keine Eigenschaft – ohne `USER`, ohne beschnittene Capabilities und mit gemeinsamem Kernel ist die Wand dünner, als das Wort klingt. Reproduzierbarkeit ist eine Disziplin, keine Eigenschaft – ungepinnte Tags und Pakete machen aus dem Dockerfile ein Foto statt einer Bauanleitung. Und Betrieb ist eine Routine, keine Eigenschaft – ein Image, das niemand neu baut, ist ein Server, den niemand patcht, nur ohne die nächtlichen Updates.\n\nWenn mir heute jemand sagt, eine Anwendung sei sicher, weil sie containerisiert ist, frage ich drei Dinge: Als welcher Benutzer läuft der Prozess? Woher weiß der nächste Build, dass er dasselbe baut wie der letzte? Und wer baut neu, wenn morgen eine Lücke in der Basis veröffentlicht wird? An den Antworten erkennt man ziemlich zuverlässig, ob das Team ein Betriebsmodell hat – oder nur ein Gütesiegel.\n\n## Weiterführende Quellen\n\n- Repository introduction-docker: https://github.com/MikeBild/introduction-docker\n- Docker-Dokumentation zu Multi-Stage-Builds: https://docs.docker.com/build/building/multi-stage/\n- Docker Engine Security Overview: https://docs.docker.com/engine/security/\n- Clair, statische Analyse von Container-Images: https://github.com/quay/clair\n- Distroless-Images von Google: https://github.com/GoogleContainerTools/distroless\n- Bericht zum Tesla-Vorfall (CNBC, Februar 2018): https://www.cnbc.com/2018/02/21/hackers-hijack-teslas-cloud-system-to-mine-cryptocurrency-redlock.html"},{"locale":"de","translation_key":"mvp-kleinstes-lernendes-produkt","slug":"mvp-kleinstes-lernendes-produkt","title":"Meine Arbeitsdefinition für ein MVP: lernen statt halb fertig liefern","summary":"Ich benutze MVP für ein Experiment, das eine riskante Annahme ehrlich testet. Diese Arbeitsdefinition verhindert, dass ein bloß reduziertes Feature-Set schon als Lernen gilt.","tags":["Software","Produkt"],"published_at":"2018-05-24T10:00:00+00:00","updated_at":"2026-07-13T13:21:51.091079+00:00","url":"https://www.mikebild.dev/de/blog/mvp-kleinstes-lernendes-produkt/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/39aeb3ad58840a27f853bd7ef1fe2303174efd4f87a5d63f11ec907581b287ec/mvp-kleinstes-lernendes-produkt-vorlesen.mp3","audio_duration_secs":643,"text":"Wer die Hälfte weglässt und das Ergebnis MVP nennt, hat kein Risiko gesenkt, sondern nur den Tag verschoben, an dem der Irrtum auffällt. Bauzeit ist verbraucht, ausgeliefert wurde etwas Halbes, und die teuerste Frage steht unverändert im Raum: Woher wissen wir, dass wir überhaupt das Richtige bauen?\n\nTrotzdem hängt das Wort genau in dieser Bedeutung an Roadmaps, Ticket-Titeln und Budgetzeilen. Weniger Buttons, weniger Screens, weniger Backend – MVP ist zum höflichen Ausdruck für „das Produkt, aber schlechter“ geworden. Das reduzierte Feature-Set beantwortet keine einzige offene Frage. Es verwechselt Geschwindigkeit beim Bauen mit Geschwindigkeit beim Lernen.\n\nFür meine Arbeit halte ich mich an die Lesart aus Lean Startup: Ein MVP ist ein Experiment, die kleinste Version eines Produkts, mit der sich eine konkrete, riskante Annahme ehrlich testen lässt. Der Begriff wird in der Praxis auch anders verwendet; diese Arbeitsdefinition ist meine bewusste Entscheidung. Aus ihr folgt, was hineingehört, was nicht, und warum der scheinbare Umweg über das Lernen der schnellste Weg zum tragfähigen Produkt sein kann.\n\n## Die Definition, die alles trägt\n\nEric Ries hat den Begriff 2011 in „The Lean Startup“ so gefasst: ein MVP ist „that version of a new product which allows a team to collect the maximum amount of validated learning about customers with the least effort.“ Der Kern steckt in zwei Wörtern: *validated learning*. Der Zweck ist Lernen, das durch echte Daten bestätigt wird, und zwar über die *leap-of-faith assumptions* – jene Annahmen, auf denen die ganze Idee ruht und die bisher niemand belegt hat.\n\nDamit ist das MVP kein Auslieferungsschritt, sondern der Bau-Teil eines Experiments. Ries stellt es in den *Build-Measure-Learn*-Loop: Wir bauen etwas, messen die Reaktion, lernen daraus und entscheiden. Der Ausgang eines MVP ist immer eine Entscheidung, die Ries *pivot or persevere* nennt – Kurs halten oder Annahme verwerfen und drehen.\n\n```mermaid\nflowchart LR\n  A[Riskante Annahme] --> B[Build:<br/>MVP als Experiment]\n  B --> C[Measure:<br/>echte Nutzer, echte Metrik]\n  C --> D[Learn:<br/>validated learning]\n  D --> E{pivot or<br/>persevere?}\n  E -->|persevere| A\n  E -->|pivot| A\n```\n\nDaraus ergibt sich für diese Arbeitsdefinition ein hartes Kriterium, das im Alltag fehlt: Ein MVP ohne definierte Lernfrage und ohne Metric ist dann kein Experiment, sondern nur ein kleines Produkt. Der Unterschied ist nicht akademisch. Wenn niemand vorher aufgeschrieben hat, welche Annahme geprüft wird und woran man den Ausgang erkennt, kann das Ergebnis auch nichts widerlegen. Man baut, launcht, findet es „ganz okay“ und macht weiter – gelernt hat man nichts.\n\nSteve Blank formuliert die Gegenseite des Missverständnisses direkt. „A minimum viable product is not always a smaller/cheaper version of your final product.“ Sein Customer-Development-Ansatz kreist um einen einzigen Imperativ: *get out of the building*. Die Wahrheit über das Produkt steht nicht im Meetingraum, sie steht bei den Nutzern. Das MVP ist das Werkzeug, mit dem man rausgeht.\n\n## Vertikaler Schnitt statt horizontaler Amputation\n\nDer Unterschied lässt sich an zwei Schnitten durch denselben geplanten Funktionsumfang zeigen.\n\nDer falsche MVP ist ein horizontaler Schnitt. Man nimmt alle geplanten Features und baut jedes zu vierzig Prozent. Das Registrierungsformular steht halb, die Suche liefert Ergebnisse ohne Filter, der Checkout endet in einer Sackgasse. Nichts funktioniert end-to-end. Der Nutzer kommt an keiner Stelle vom Anfang bis zum Wert. Es gibt nichts zu messen, weil es keinen vollständigen Pfad gibt, den jemand durchlaufen könnte.\n\nDer MVP ist häufig ein vertikaler Schnitt: ein dünner, aber durchgehender Pfad vom Nutzer bis zum Wert, an dessen Ende eine Messung hängt. Bei Concierge-, Wizard-of-Oz- oder Landingpage-Experimenten kann die kleinste belastbare Prüfung jedoch anders aussehen. Entscheidend ist nicht die Form des Schnitts, sondern ob sie die riskante Annahme ehrlich prüft.\n\n```mermaid\nflowchart TB\n  subgraph L[Horizontal: halbfertig]\n    L1[Feature A – 40%]\n    L2[Feature B – 40%]\n    L3[Feature C – 40%]\n  end\n  subgraph R[Vertikal: kleinstes lernendes Produkt]\n    R1[Einstieg] --> R2[ein durchgehender Pfad] --> R3[Wert] --> R4[Metrik]\n  end\n```\n\nGenau hier liegt die Bedeutung von „viable“. Das Wort meint nicht die Qualität, es meint den Scope. Minimal ist der Umfang, nicht die Sorgfalt. Ein buggy zusammengeschusterter MVP verfälscht das Lernsignal, denn dann weiß man am Ende nicht, ob die Nutzer die Idee ablehnen oder nur die kaputte Umsetzung. „Viable“ heißt: gut genug, um ein ehrliches Signal zu erzeugen. Der schmale Pfad muss sauber sein, sonst misst man Rauschen.\n\n## Das MVP muss kein Code sein\n\nDer stärkste Beleg dafür, dass „viable“ nicht „fertig gebaut“ bedeutet, sind zwei MVP-Typen, die es lange vor 2018 gibt und die ganz ohne fertiges Produkt auskommen.\n\nBeim *Concierge-MVP* erbringt zunächst ein Mensch die Leistung von Hand, die später Software erbringen soll. Man tut nicht so, als gäbe es ein Produkt – man liefert den Wert direkt und persönlich an eine Handvoll echter Nutzer und beobachtet, ob sie ihn überhaupt wollen. Beim *Wizard-of-Oz-MVP* sieht der Nutzer eine echte Oberfläche, aber dahinter arbeitet kein System, sondern ein Mensch, der die Antworten von Hand einträgt. Der Nutzer glaubt an Software, gelernt wird über echtes Verhalten, gebaut wurde fast nichts.\n\nBeide testen eine Hypothese, bevor eine Zeile Produktionscode existiert. Sie beweisen die These auf die klarste Art: „viable“ heißt genug, um ehrlich zu lernen, nicht genug, um zu verkaufen.\n\nWichtig ist dabei die Trennung zum Prototyp, ohne daraus eine künstliche Mauer zu bauen. Ein Prototyp untersucht meist Machbarkeit oder Bedienbarkeit und kann dafür selbstverständlich mit echten Nutzern getestet werden. Ein MVP in meiner Arbeitsdefinition prüft dagegen eine Markt- oder Wert-Hypothese. Entscheidend sind Frage und Evidenz, nicht ob das Artefakt intern oder extern gezeigt wird.\n\n## Die Hypothese als Code\n\nWenn ein MVP ein Experiment ist, dann sollte das Experiment so präzise deklariert sein, dass man es widerlegen kann. In den Projekten, in denen das getragen hat, stand die Hypothese vor der ersten Zeile Code – strukturiert, versioniert, neben dem Code im Repository statt in einem vergessenen Slide.\n\n```yaml\n# experiment.yaml – declares the MVP before any code is written\nexperiment:\n  name: \"concierge-checkout\"\n  riskiest_assumption: \"users will connect a payment method to finish an order\"\n  hypothesis: \"at least 30% of activated users will add a payment method\"\n  target_metric: activation_rate      # added payment / reached checkout\n  success_threshold: 0.30\n  kill_criteria: \"activation_rate < 0.10 after 200 sessions\"\n  sample_size: 200\n  cohort: \"new signups, region DE\"\n```\n\nDer entscheidende Punkt sind die letzten Felder. Ohne `success_threshold` und `kill_criteria` ist es kein Experiment. Ein Experiment, das man nicht scheitern lassen kann, misst nichts. Am `kill_criteria` scheitert die Einigung am häufigsten, und genau darin liegt sein Wert: Es zwingt das Team, vorher zu vereinbaren, wann die Idee widerlegt ist – bevor die emotionale Bindung an die eigene Lösung das Urteil trübt. Ries nennt die Gegenspieler dieser ehrlichen Zahlen *vanity metrics*: Kennzahlen wie Gesamtregistrierungen, die immer nach oben zeigen und nie eine Entscheidung erzwingen. Der `target_metric` muss eine *actionable metric* sein, an der man eine Annahme kippen kann.\n\n## Den schmalen Pfad technisch sauber schneiden\n\nDer vertikale Schnitt hat auch eine technische Seite, und hier verbinden sich zwei Welten, die oft getrennt diskutiert werden: Produktdenken und Delivery.\n\nDer falsche MVP wächst wochenlang in einem langen Feature-Branch neben dem Hauptstrang und landet irgendwann in einem großen, riskanten Merge. Der bessere Weg ist, das Experiment auf dem Trunk zu bauen und über ein Feature-Flag nur für die Experiment-Kohorte einzuschalten. Alle anderen sehen den Status quo, der schmale neue Pfad ist für eine kleine Gruppe vollständig live.\n\n```javascript\n// the MVP path ships on trunk, gated by a flag – not hidden in a long branch\nfunction renderCheckout(user, cart) {\n  if (featureFlags.isEnabled(\"concierge_checkout\", user)) {\n    trackExperiment(\"concierge-checkout\", user);\n    return conciergeCheckout(cart); // narrow but complete path to value\n  }\n  return standardCheckout(cart);     // everyone else: unchanged status quo\n}\n```\n\nDas ist mehr als ein technischer Trick. Es macht sichtbar, was ein MVP ist: ein schmales, aber vollständig funktionierendes Segment – nicht ein überall halb sichtbares, nirgends fertiges Feature. Trunk-Based Development und kurzlebige Branches sorgen dafür, dass das Experiment jederzeit ausgeliefert und ebenso schnell wieder abgeschaltet werden kann. Techniken wie *Canary Release* und *Blue-Green Deployment* geben demselben Prinzip die Betriebsseite: eine kleine Kohorte bekommt das Neue, der Rest bleibt sicher.\n\nWenn das Experiment über einen Service hinausgeht, hilft ein weiterer Winkel beim ehrlichen Testen. Statt eine Vollintegration vorzutäuschen, erfüllt der MVP-Service einen minimalen, aber echten *Consumer-Driven Contract*. Der Konsument schreibt auf, was er wirklich braucht, und der MVP erfüllt genau das – nicht mehr.\n\n```groovy\n// consumer-driven contract: the MVP fulfils a real, minimal contract\n// instead of faking a full integration\nPact.provider(\"payment-service\").upon(\"checkout\")\n  .given(\"an activated user\")\n  .uponReceiving(\"a request to attach a payment method\")\n    .withRequest(method: \"POST\", path: \"/methods\")\n  .willRespondWith(status: 201, body: [status: \"attached\"])\n```\n\nDer Sinn dahinter: Der schmale Pfad ist echt, nicht Fassade. Er integriert wirklich gegen das, was er braucht, aber eben nur gegen das. So bleibt das Lernsignal sauber, ohne dass man das ganze System fertig bauen muss.\n\n## Warum das schneller ist, obwohl es aufwendiger klingt\n\nDer häufigste Einwand: Experimente, Metrics, Flags und Contracts aufzusetzen klingt nach mehr Arbeit, nicht nach weniger. Der Einwand verwechselt zwei Größen – Aufwand pro Auslieferung und Aufwand pro gelernter Erkenntnis.\n\n„Accelerate“ von Forsgren, Humble und Kim liefert dafür einen Teil des technischen Fundaments. Die vier damaligen DORA-Metrics – Deployment Frequency, Lead Time for Changes, Change Fail Rate und Time to Restore – stehen für Lieferfähigkeit, nicht für den Marktwert eines Experiments. Ein Team, das kleine Änderungen häufig und stabil ausliefern kann, senkt jedoch die technische Hürde für kurze Versuche und schnelle Rücknahmen.\n\nEin MVP, das nur ein reduziertes Feature-Set ist, spart einmalig Bauzeit und verschiebt das Risiko nach hinten. Ein MVP als Experiment kostet vorne etwas Disziplin und macht das Risiko früher sichtbar. Das ist keine Garantie für weniger Reibung oder höhere Qualität. Es trennt aber die Frage „Können wir es liefern?“ von der wichtigeren Frage „Welche Annahme prüfen wir damit?“.\n\nWer das MVP als Experiment ernst nimmt, denkt übrigens von Anfang an in Richtung tragfähiger Architektur. Ein Ansatz wie die *evolutionary architecture* mit *fitness functions* passt genau, weil er akzeptiert, dass sich das Produkt entlang dessen entwickelt, was man lernt – nicht entlang eines Plans, den niemand geprüft hat.\n\n## Fazit\n\nEin MVP ist kein amputiertes Produkt. In meiner Arbeitsdefinition ist es ein Experiment, das eine riskante Annahme ehrlich testet – die kleinste Version, mit der man eine Hypothese wirklich prüfen kann. Ein bestätigender Test braucht eine Lernfrage und ein vorab festgelegtes Entscheidungskriterium; explorative Discovery darf offener beginnen. Häufig ist das ein vertikaler Schnitt bis zum Wert, manchmal ein Concierge-Test oder eine Landingpage. „Minimal“ meint den nötigen Umfang, nicht Nachlässigkeit. Und es muss nicht einmal Code sein.\n\nWenn ein Team von „das Produkt, aber weniger“ auf „die kleinste Version, die eine Annahme ehrlich testet“ umschwenkt, ändert sich nicht der Werkzeugkasten, sondern die Leitfrage. Nicht mehr „Was können wir noch weglassen?“, sondern „Was müssen wir als Nächstes lernen, und wie sieht der kleinste ehrliche Test dafür aus?“. Diese Frage verhindert keine Fehlentscheidung, macht aber sichtbar, welches Lernen die nächste Investition rechtfertigen soll.\n\n## Weiterführende Quellen\n\n- Eric Ries, *The Lean Startup* (2011) – Definition des MVP, Build-Measure-Learn, validated learning, vanity vs. actionable metrics\n- Steve Blank, „A minimum viable product is not always…“ (Blog, 2013) und *The Four Steps to the Epiphany* (2005) – Customer Development\n- Melissa Perri, „Finding the Truth Behind MVPs“ (2016) – Concierge- und Wizard-of-Oz-MVP\n- Nicole Forsgren, Jez Humble, Gene Kim, *Accelerate* (2018) – die vier DORA-Metrics\n- Neal Ford, Rebecca Parsons, Patrick Kua, *Building Evolutionary Architectures* (O'Reilly, 2017) – fitness functions\n- Martin Fowler, „FeatureToggle“ (2017) und trunkbaseddevelopment.com – Feature-Flags und Trunk-Based Development\n- Consumer-Driven Contracts (Fowler/Robinson, 2006) sowie das Contract-Testing-Werkzeug Pact"},{"locale":"de","translation_key":"graphql-schema-in-der-fachsprache","slug":"graphql-schema-in-der-fachsprache","title":"GraphQL-Schema in der Fachsprache","summary":"Ein GraphQL-Schema ist der beste Ort, den es je für die ubiquitäre Fachsprache gab – und wenn die Domäne deutsch ist, darf sie dort auch deutsch bleiben.","tags":["Software","GraphQL","API"],"published_at":"2018-04-24T10:00:00+00:00","updated_at":"2026-07-14T16:58:22.628285+00:00","url":"https://www.mikebild.dev/de/blog/graphql-schema-in-der-fachsprache/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ae6c5e61c5ada1dd13a5ff8684e3ba3f096bbd99d0e5836f0c094a50ce9c890e/graphql-schema-in-der-fachsprache-vorlesen.mp3","audio_duration_secs":745,"text":"# GraphQL-Schema in der Fachsprache\n\n„Fachsprache\" hat zwei Lesarten, und die geläufigere ist hier ausdrücklich nicht gemeint. Es geht nicht um Jargon – nicht um das Vokabular, mit dem eine Branche Außenstehende auf Abstand hält. Gemeint ist das, was Eric Evans 2003 in „Domain-Driven Design\" als ubiquitous language beschrieben hat: die eine gemeinsame Sprache, die Fachseite und Entwicklung in einem Projekt tatsächlich sprechen. Dieselben Wörter im Meeting, im Ticket, im Modell, im Code. Ein Vokabular für alle – keine zwei Vokabulare mit einer Übersetzungstabelle dazwischen.\n\nDie Idee ist fünfzehn Jahre alt, und sie scheitert in der Praxis selten am Willen. Sie scheitert am Ort. Ein Glossar im Wiki veraltet ab dem Tag, an dem es angelegt wird, weil niemand es mitzieht, wenn ein Feld umbenannt wird. Der Code wäre der ehrlichere Ort, aber der Code gehört nur einer Seite: Die Fachabteilung liest keine Java-Klassen. Was all die Jahre fehlte, war ein Artefakt, das beide Seiten lesen können und das gleichzeitig maschinell geprüft wird.\n\nSeit ich mit GraphQL arbeite, bin ich überzeugt, dass es dieses Artefakt inzwischen gibt: das Schema. Und – das ist der unbequemere Teil der These – man darf die Fachsprache dort auch deutsch sprechen.\n\n## Zweimal übersetzen, zweimal verlieren\n\nIn Projekten mit deutscher Fachseite ist mir über die Jahre immer wieder dasselbe Muster begegnet. Die Fachabteilung sagt „Angebot\". In der Datenbank steht `OFFER`, im Service heißt die Klasse `Quote`, im Frontend taucht ein `Proposal` auf – drei Übersetzungen desselben Wortes, entstanden zu drei Zeitpunkten unter drei verschiedenen Zeitdrücken. Jedes Gespräch zwischen Fachseite und Entwicklung übersetzt seitdem zweimal: hin beim Zuhören, zurück beim Antworten.\n\nJede dieser Übersetzungen kostet nicht nur Zeit, sie verfälscht. Ob „Angebot\" nun offer, quote, bid oder proposal heißen soll, ist keine neutrale Wahl – jedes dieser Wörter trägt im Englischen eine eigene Bedeutung, und keine deckt sich genau mit dem, was die Fachseite meint. Die Entscheidung trifft am Ende ein Entwickler unter Termindruck, und sie steht dann für Jahre im System – unbeachtet, aber wirksam bei jedem einzelnen Gespräch über genau dieses Feld.\n\n```mermaid\nflowchart LR\n  F[\"Fachseite<br/>sagt „Angebot“\"] -->|übersetzen| E[\"Entwicklung<br/>Offer? Quote? Bid?\"]\n  E -->|übersetzen| S[\"System<br/>OFFER, Quote, Proposal\"]\n  S -->|rückübersetzen| E\n  E -->|rückübersetzen| F\n```\n\nDie teuersten Missverständnisse, die ich in Reviews erlebt habe, waren selten technischer Natur. Es waren Begriffe, die auf dem Weg durch diese Kette ihre Bedeutung gewechselt hatten – ein „storniertes Angebot\", das im System ein `cancelled quote` war, obwohl die Fachseite unter Stornierung etwas anderes verstand als die Entwicklung unter cancelled.\n\n## Das Experiment: uber-ng\n\nIm März habe ich dazu ein kleines Repository angelegt: [uber-ng](https://github.com/MikeBild/uber-ng), eine bewusst überschaubare Nachstellung einer Fahrtvermittlung, wie man sie von Uber kennt. Kein Produkt – ein Prototyp mit In-Memory-Daten, ein paar Mocha-Tests und einer einzigen Frage: Wie liest sich ein GraphQL-Schema, wenn die Fachbegriffe deutsch bleiben?\n\nDas Schema steht dort als eigene Datei in Schema-Notation – jener SDL, die gerade in die GraphQL-Spezifikation aufgenommen wird, nachdem sie jahrelang nur Konvention der Werkzeuge war. Der Kern sieht so aus:\n\n```graphql\nenum STATUS {\n  angefragt\n  warteAufBestaetigung\n  angenommen\n}\n\ntype Angebot implements Node {\n  id: ID!\n  fahrgast: Fahrgast\n  von: String!\n  nach: String!\n  fahrer: Fahrer\n  wartezeit: String\n  status: STATUS\n}\n\ntype Mutation {\n  fahrtAnfragen(input: AnfrageInput!): Angebot\n  angebotAnnehmen(input: AngebotAnnehmenInput!): Angebot\n  angebotAblehnen(input: AngebotAblehnenInput!): Angebot\n}\n\ntype Subscription {\n  onAngebotChanged: Angebot\n}\n```\n\nWer das liest, braucht kein Glossar daneben. Eine Fahrt wird angefragt; was dabei entsteht, ist ein Angebot; ein Angebot kann angenommen oder abgelehnt werden – und wer ablehnt, muss einen Grund nennen, denn `AngebotAblehnenInput` verlangt ein `grund: String!`. Die Mutationen sind Verben der Domäne, keine CRUD-Prosa. `fahrtAnfragen` erzwingt sogar eine fachliche Unterscheidung, die ein `createOffer` verschluckt hätte: Angefragt wird eine Fahrt – das Angebot ist die Antwort des Systems darauf, nicht das, was der Fahrgast selbst anlegt. Dieser Unterschied ist mir erst beim Formulieren des Schemas aufgefallen, nicht vorher.\n\nAuch die Anfragen der Clients sprechen anschließend diese Sprache:\n\n```graphql\nmutation {\n  fahrtAnfragen(input: {\n    fahrgastId: \"f1\"\n    von: \"Alexanderplatz\"\n    nach: \"Flughafen Tegel\"\n  }) {\n    id\n    status\n    wartezeit\n  }\n}\n```\n\nMan kann diese Mutation in einem Termin laut vorlesen, und die Fachseite versteht sie ohne Dolmetscher. Das ist keine Kleinigkeit. Es ist der Moment, in dem eine API aufhört, ein reines Entwickler-Artefakt zu sein.\n\nTechnisch ist der Aufbau bewusst gewöhnlich gehalten: Node, ein GraphQL-Server, Subscriptions über WebSockets, wie sie sich mit `subscriptions-transport-ws` inzwischen eingespielt haben. `onAngebotChanged` schiebt jede Zustandsänderung eines Angebots an die verbundenen Clients – der Fahrgast sieht, wenn aus `angefragt` ein `warteAufBestaetigung` wird, ohne nachfragen zu müssen. Für das Experiment ist das Beiwerk. Interessant ist nur, dass auch dieser Kanal die Fachsprache spricht: Was beim Client ankommt, heißt Angebot, nicht `OfferDTO`.\n\n## Was das Schema zum Glossar macht\n\nEin Glossar beschreibt eine Sprache. Das Schema erzwingt sie – und genau das hat es jedem Glossar voraus, das mir bisher untergekommen ist:\n\n- Jede Query wird gegen das Schema validiert. Wer einen Begriff erfindet oder falsch schreibt, bekommt einen Fehler statt eines stillen Missverständnisses.\n- Introspection macht das Vokabular abfragbar: GraphiQL zeigt Typen, Felder und Beschreibungen schon beim Tippen an – das Glossar liefert sich selbst aus.\n- `@deprecated` mustert Begriffe geordnet aus, mit Begründung und sichtbar für jeden Client. In uber-ng hängt genau so ein Vermerk an `fahrgastId`.\n- Das Schema steht in der Versionsverwaltung. Jede Begriffsänderung ist ein Diff, und ein Diff kann ein Review bekommen, an dem auch die Fachseite teilnimmt.\n\nDazu kommen die Beschreibungstexte: Die SDL erlaubt an jedem Typ, jedem Feld und jedem Enum-Wert eine Beschreibung, die Introspection mit ausliefert. Dort steht dann nicht nur, dass es ein `Angebot` gibt, sondern was die Fachseite darunter versteht – die Definition wandert mit dem Begriff mit, statt in einem anderen System zu altern.\n\nEin Wiki kann nichts davon. Ein UML-Modell auch nicht. Das GraphQL-Schema ist meines Wissens das erste Artefakt, das gleichzeitig für Menschen lesbar, für Maschinen prüfbar und für den Betrieb verbindlich ist. Das Schema ist das Glossar – nicht dessen Abschrift.\n\n## Zustände haben Namen\n\nDer unscheinbarste Teil des Schemas trägt dabei am meisten: das Enum. `STATUS` mit seinen drei Werten ist eine vollständige, prüfbare Beschreibung des Lebenszyklus eines Angebots – und die Werte heißen so, wie die Fachseite sie am Telefon nennen würde.\n\nDiesen Lifecycle habe ich in älteren Systemen selten irgendwo aufgeschrieben gefunden. Er verteilt sich dort auf Status-Strings in der Datenbank, if-Kaskaden im Service und das Gedächtnis der dienstältesten Kollegin. Hier ist er ein paar Zeilen lang, versioniert und für jeden Client sichtbar:\n\n```mermaid\nstateDiagram-v2\n  [*] --> angefragt: fahrtAnfragen\n  angefragt --> warteAufBestaetigung: Vermittlung läuft\n  warteAufBestaetigung --> angenommen: angebotAnnehmen\n  warteAufBestaetigung --> [*]: angebotAblehnen\n```\n\nHier zeigt sich allerdings auch die erste hässliche Stelle: `warteAufBestaetigung`. GraphQL-Namen erlauben nur ASCII – Buchstaben, Ziffern, Unterstrich. Das „ä\" muss draußen bleiben, die Fachsprache kommt nur gefiltert ins Schema. Ich schreibe das bewusst hin, statt es zu verstecken: Wer deutsche Bezeichner wählt, wählt auch `Bestaetigung`, `Strasse` und `ueberweisen`. Im Fließtext wäre das ein Rechtschreibfehler; im Schema ist es der Preis der Entscheidung, und man sollte ihn kennen, bevor man sie trifft.\n\n## Schema deutsch, Implementierung englisch\n\nDie zweite Frage, die das Experiment beantworten sollte: Wo verläuft die Grenze? Nach ein paar Wochen liegt sie für mich exakt an der Resolver-Map. Das Schema trägt die Fachsprache, alles dahinter bleibt englisch – Variablen, Hilfsfunktionen, Kommentare. Vereinfacht, hier mit `graphql-subscriptions` notiert, sieht das Muster so aus:\n\n```javascript\nconst uuid = require('uuid/v4');\nconst { PubSub } = require('graphql-subscriptions');\n\nconst pubsub = new PubSub();\nconst offers = {}; // in-memory store, resets on restart\n\nconst resolvers = {\n  Query: {\n    angebote: (root, { take = 10, skip = 0 }) =>\n      Object.values(offers).slice(skip, skip + take),\n  },\n  Mutation: {\n    fahrtAnfragen: (root, { input }) => {\n      // a ride request creates a new offer in its initial state\n      const offer = {\n        id: uuid(),\n        von: input.von,\n        nach: input.nach,\n        status: 'angefragt',\n      };\n      offers[offer.id] = offer;\n      pubsub.publish('offerChanged', { onAngebotChanged: offer });\n      return offer;\n    },\n    angebotAnnehmen: (root, { input }) => {\n      const offer = offers[input.angebotId];\n      // accepting is only valid while the offer awaits confirmation\n      if (offer.status !== 'warteAufBestaetigung') return offer;\n      offer.status = 'angenommen';\n      pubsub.publish('offerChanged', { onAngebotChanged: offer });\n      return offer;\n    },\n  },\n  Subscription: {\n    onAngebotChanged: {\n      subscribe: () => pubsub.asyncIterator('offerChanged'),\n    },\n  },\n};\n```\n\nDie deutschen Wörter tauchen genau dort auf, wo das Schema sie verlangt: als Schlüssel der Resolver-Map und als Enum-Werte. Der Rest ist gewöhnlicher englischer Code. Diese Trennung hat sich als erstaunlich stabil erwiesen, und sie entspricht der fachlichen Wahrheit: `offers` und `pubsub` sind Technik und dürfen englisch sein. `Angebot` ist ein Begriff mit fachlicher Bedeutung, und der gehört der Fachseite – nicht dem, der ihn gerade implementiert.\n\nEin Side Effect, mit dem ich nicht gerechnet hatte: Auch die Tests lesen sich plötzlich wie Fachtexte. Ein Mocha-Test, der `fahrtAnfragen` aufruft und danach prüft, ob der Status `angefragt` ist, beschreibt einen fachlichen Sachverhalt – man könnte ihn fast wörtlich als Abnahmekriterium ins Ticket kopieren. Aus Testabdeckung wird ein Stück dokumentierte Fachlichkeit, ohne dass dafür ein zusätzliches Werkzeug nötig wäre.\n\n## Was dagegen spricht\n\nEhrlich bleiben: Das Experiment hat auch die Widerstände sichtbar gemacht, und die sind nicht klein.\n\nDer Stilbruch zuerst. `type Angebot implements Node` mischt zwei Sprachen in einer Zeile. `onAngebotChanged` klebt ein englisches Präfix an ein deutsches Substantiv und hängt ein englisches Partizip dahinter – ein Bezeichner aus drei Sprachschichten. camelCase ist für englische Wortgrenzen gebaut; mit deutschen Komposita wird es holprig, `warteAufBestaetigung` liest niemand flüssig. Das stört beim Lesen, jeden Tag ein bisschen, und es hört nicht auf zu stören.\n\nDazu kommt das Umfeld. Jedes Tutorial, jede Stack-Overflow-Antwort, jedes Beispiel in der Apollo-Dokumentation ist englisch – wer Schnipsel überträgt, übersetzt jetzt in die Gegenrichtung. Und die härteste Grenze ist das Team selbst: Sobald eine Kollegin dazukommt, die kein Deutsch spricht, kippt die Rechnung vollständig. Dann ist das deutsche Schema keine Brücke zur Fachseite mehr, sondern eine Mauer mitten durch die Entwicklung.\n\nUnd ein praktischer Punkt, der im Alltag zählt: Suchbarkeit. Wer zu `angebotAnnehmen` nach einer Fehlermeldung sucht, findet nichts – wer zu `acceptOffer` sucht, findet wenigstens fremde Diskussionen, die halb passen. Deutsche Bezeichner koppeln ein Projekt ein Stück weit von der kollektiven Fehlersuche des Netzes ab. Für einen Prototyp ist das egal, für ein Team unter Termindruck nicht.\n\n## Wann die Fachsprache gewinnt\n\nDie Abwägung ist deshalb keine Geschmacksfrage, sondern eine Frage an die Domäne: In welcher Sprache ist sie selbst verfasst?\n\nEine Fahrtvermittlung ist ein dankbares Spielfeld, aber der eigentliche Anwendungsfall sind Domänen, die deutsch sind – nicht aus Gewohnheit, sondern von Rechts wegen. Verträge nach deutschem Recht. Tarifwerke. Abrechnungsregeln, deren Begriffe eine deutsche Verordnung wörtlich vorgibt. In einem Abrechnungsprojekt vor einigen Jahren waren Wörter wie „Abschlag\" und „Gutschrift\" juristisch belegt; ihre englischen Übersetzungen im Code haben regelmäßig Diskussionen ausgelöst, die es fachlich gar nicht gab – war der `discount` nun ein Abschlag oder doch ein Rabatt? Wenn das Gesetz deutsch spricht und die Fachseite deutsch denkt, ist eine englische API-Schicht die einzige Stelle im System, die übersetzt. Und damit die einzige Stelle, die unbemerkt lügen kann.\n\nUmgekehrt gilt das genauso. Ein internationales Team, ein Produkt für mehrere Märkte, eine öffentliche API – dort ist Englisch die Fachsprache, und dann gehört sie auch konsequent ins Schema. Einen brauchbaren Mittelweg bietet die SDL übrigens gleich mit: englische Bezeichner, aber deutsche Beschreibungstexte an Typen und Feldern. Dann trägt das Schema wenigstens die Definitionen der Begriffe, wenn schon nicht ihre Namen – und die Übersetzungstabelle steht dort, wo sie geprüft und versioniert wird, statt in einem Wiki zu verstauben.\n\n## Unterm Strich\n\nuber-ng wird kein Produkt, und das musste es nie werden. Das Experiment hat mir zwei Dinge gezeigt. Erstens: Der Ort stimmt. Ein GraphQL-Schema kann leisten, was Glossare, Wikis und Modell-Dokumente fünfzehn Jahre lang versprochen und nicht gehalten haben – eine gemeinsame Sprache, die geprüft wird, statt nur beschrieben zu werden. Zweitens: Die Sprache im Schema ist eine Architekturentscheidung, keine Stilfrage. Deutsch im Schema kostet – Stilbrüche, ASCII-Krücken, Reibung mit dem Ökosystem. Es zahlt sich genau dann aus, wenn die Domäne deutsch ist und jede Übersetzung eine zweite, ungeprüfte Wahrheit erzeugen würde.\n\nFür die Projekte dazwischen bleibt die Frage offen, und das ist in Ordnung. Wichtig ist mir nur, dass sie überhaupt gestellt wird. Bisher wurde sie in jedem Schema, das ich gesehen habe, stillschweigend mit „englisch\" beantwortet – und stillschweigende Antworten sind selten die durchdachten.\n\n## Weiterführende Quellen\n\n- [uber-ng – GraphQL-Demo mit deutschem Schema (GitHub)](https://github.com/MikeBild/uber-ng)\n- [GraphQL-Dokumentation: Schemas and Types](https://graphql.org/learn/schema/)\n- [GraphQL Specification](https://spec.graphql.org/)\n- [Martin Fowler: Ubiquitous Language](https://martinfowler.com/bliki/UbiquitousLanguage.html)\n- [Eric Evans: Domain-Driven Design Reference](https://www.domainlanguage.com/ddd/reference/)"},{"locale":"de","translation_key":"angular-react-uebergaenge","slug":"angular-react-uebergaenge","title":"Angular, React und der Wert von Übergängen","summary":"Ob ein Framework-Wechsel zum Umzug oder zum Neubau wird, entscheidet sich daran, wie billig zwei Welten monatelang nebeneinander laufen können.","tags":["Software","Frontend"],"published_at":"2018-03-12T10:00:00+00:00","updated_at":"2026-07-14T16:56:24.827181+00:00","url":"https://www.mikebild.dev/de/blog/angular-react-uebergaenge/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/389e739fff39f1ec5b6604c2853f54f3f9d6bc195e0c3768f09e6a1a5ab26891/angular-react-uebergaenge-vorlesen.mp3","audio_duration_secs":632,"text":"# Angular, React und der Wert von Übergängen\n\nEin Beschluss wie „wir schreiben das Frontend komplett neu\" richtet seinen Schaden nicht sofort an, sondern mit etwa neun Monaten Verzögerung. Dann existieren zwei halbe Produkte: ein altes AngularJS-Frontend, offiziell eingefroren, das trotzdem laufend Hotfixes bekommt, weil zahlende Nutzer damit arbeiten – und ein neues, das bei gefühlten sechzig Prozent steht und keinen Release-Termin hat, weil „erst alles fertig sein muss\". Jede Fachanforderung wird ab da doppelt verhandelt: einmal für die alte Welt, einmal für die, die noch nicht ausgeliefert ist. Das Team teilt sich still in Bewahrer und Neubauer, und beide Gruppen werden langsamer.\n\nIch habe diesen Verlauf inzwischen mehr als einmal aus der Nähe gesehen, zuletzt in einem Produktteam mit einer über Jahre gewachsenen AngularJS-Anwendung. Der Fehler lag nie im Ziel-Framework. Er lag in einem Wort, das im Beschluss fehlte: Übergang. Ein Framework-Wechsel ist in der Praxis kein Umschreiben, sondern ein Zustand, in dem zwei Welten monatelang parallel laufen. Und ob dieser Zustand billig oder ruinös wird, hat mit Angular oder React erstaunlich wenig zu tun.\n\n## Der Treiber: AngularJS bekommt ein Ablaufdatum\n\nSeit Ende Januar ist offiziell, was sich lange abgezeichnet hat: AngularJS 1.x bekommt mit Version 1.7 einen letzten Entwicklungszyklus und wechselt danach in eine dreijährige Long-Term-Support-Phase. Ab dann gibt es nur noch Sicherheitskorrekturen und Anpassungen an neue Browser- und jQuery-Versionen, keine Features mehr. Für Teams mit großen 1.x-Anwendungen ist das der Moment, in dem aus „irgendwann müssen wir da raus\" ein Termin wird.\n\nEntsprechend viele Migrationsentscheidungen fallen gerade. Ob das Ziel Angular 5 heißt (Angular 6 steht für die kommenden Monate an) oder React 16 – die Richtung finde ich zweitrangig. Interessant ist, wie die Entscheidung formuliert wird. „Wir schreiben neu\" ist ein Projekt mit Enddatum, und dieses Enddatum reißt fast immer. „Wir betreiben beide Welten parallel und verschieben Stück für Stück\" ist dagegen ein Zustand, den man steuern, messen und notfalls anhalten kann.\n\n## Umschreiben oder umziehen\n\nDamit bin ich bei der eigentlichen These: Die Qualität einer Frontend-Architektur zeigt sich nicht daran, wie modern ihr Framework ist, sondern daran, wie billig der Parallelbetrieb zweier Frameworks wäre. Wer Fachlogik framework-frei gehalten hat – reine Module, Services ohne DI-Magie, State außerhalb der Komponenten – zieht um. Wer Berechnungen, Validierungen und API-Aufrufe in Controller, Direktiven und Komponenten gegossen hat, schreibt neu, ob er will oder nicht. Das Framework war dann nie ein Rahmen, sondern der Träger des gesamten Gebäudes, und Träger tauscht man nicht im laufenden Betrieb.\n\nIn dem erwähnten Produktteam haben wir vor dem ersten Migrationsschritt zwei Wochen lang gar nicht migriert. Wir haben Fachlogik aus Direktiven herausgezogen und in schlichte ES-Module verschoben, mit den bestehenden AngularJS-Services als dünner Hülle darüber. Erst danach war überhaupt entscheidbar, welcher Teil ein Umzug wird und welcher ein Neubau bleiben muss. Die Unterscheidung war ernüchternd konkret: Was ohne `angular.module`-Import auskam, ließ sich verschieben wie ein Möbelstück. Alles andere musste einzeln bewertet werden.\n\n## Hybridbetrieb mit ngUpgrade\n\nFür die Richtung AngularJS nach Angular ist Parallelbetrieb kein Trick, sondern ein dokumentierter, offiziell unterstützter Modus. Das `UpgradeModule` startet die alte Anwendung innerhalb der neuen:\n\n```typescript\n// app/app.module.ts — Angular 5 hosting AngularJS 1.6\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { UpgradeModule } from '@angular/upgrade/static';\n\n@NgModule({\n  imports: [BrowserModule, UpgradeModule],\n})\nexport class AppModule {\n  constructor(private upgrade: UpgradeModule) {}\n\n  ngDoBootstrap() {\n    // AngularJS boots inside Angular, not the other way around\n    this.upgrade.bootstrap(document.documentElement, ['orderApp'], { strictDi: true });\n  }\n}\n```\n\nAb diesem Punkt laufen beide Frameworks im selben DOM-Baum. Neue Angular-Komponenten lassen sich in alte Templates hineinreichen:\n\n```typescript\n// expose a new Angular component to old AngularJS templates\nimport { downgradeComponent } from '@angular/upgrade/static';\nimport { InvoiceFooterComponent } from './invoice-footer.component';\n\nangular\n  .module('orderApp')\n  .directive('invoiceFooter', downgradeComponent({ component: InvoiceFooterComponent }));\n```\n\nUmgekehrt lassen sich alte Services in die neue Dependency Injection hochreichen. Das klingt bequem, und genau darin liegt die Gefahr: Wer die Brücke zu oft benutzt, verflechtet beide Welten enger, als sie es vor der Migration waren. Zwei Change-Detection-Mechanismen laufen gleichzeitig: der Digest-Zyklus von AngularJS und die Zone-basierte Erkennung von Angular. Jedes Event, das die Grenze quert, wird in beide Welten übersetzt, und Fehler an dieser Naht sind unangenehm zu suchen. Der Hybridbetrieb ist ein Werkzeug, um eine Übergangszeit zu überstehen – nicht, um sie zu verlängern. Er braucht ein Ende, das jemand ausspricht.\n\n## Route für Route: der Strangler-Ansatz\n\nDie Idee dahinter ist deutlich älter als jedes der beteiligten Frameworks. Martin Fowler hat schon 2004 beschrieben, wie neue Systeme alte umwachsen wie eine Würgefeige ihren Wirtsbaum – die Strangler Application. Auf ein Frontend übersetzt heißt das: Eine schmale Shell besitzt den Router und entscheidet pro Route, welche Welt rendert. Für genau dieses Muster gibt es mit single-spa inzwischen sogar ein eigenes kleines Framework, aber im Kern reicht Routing-Disziplin.\n\n```mermaid\nflowchart LR\n  B[Browser] --> S[Router-Shell]\n  S --> O[\"/orders<br/>AngularJS 1.6\"]\n  S --> I[\"/invoices<br/>Angular 5\"]\n  S --> R[\"/reports<br/>Angular 5\"]\n  O -. \"Route für Route<br/>wandert um\" .-> I\n```\n\nDer Schnitt entlang von Routen hat drei Eigenschaften, die ich an keinem anderen Migrationsschnitt in dieser Kombination gefunden habe:\n\n- Jeder Schritt ist einzeln zurücknehmbar – eine Route zurückzuschalten ist ein Router-Eintrag, kein Rollback-Drama.\n- Der Fortschritt ist messbar und für alle sichtbar: so viele Routen alt, so viele neu.\n- Die Grenze ist fachlich, nicht technisch. „Rechnungen sind umgezogen\" versteht auch der Produktverantwortliche; „der Direktiven-Layer ist portiert\" versteht niemand außerhalb des Teams.\n\nDie Big-Bang-Alternative hat keine dieser Eigenschaften. Sie hat nur einen Stichtag, und Stichtage verteidigen sich nicht selbst.\n\nNebenbei ändert der Routen-Schnitt auch die Teamdynamik. Statt einer Bewahrer- und einer Neubauer-Gruppe gibt es ein Team, das dieselbe Anwendung betreibt und dabei Route für Route umbaut. Jeder abgeschlossene Schritt landet in Produktion und wird von echten Nutzern getreten – die Rückmeldung kommt nach Wochen, nicht nach anderthalb Jahren. Das ist unspektakulär, aber genau darin liegt der Wert.\n\n## Fachlogik, die den Umzug überlebt\n\nDas billigste Umzugsgut ist Code, der von keinem Framework weiß. In der erwähnten Anwendung war die Rechnungssummen-Logik so ein Kandidat – vorher verteilt über eine Direktive und zwei Controller, nachher ein einziges Modul:\n\n```javascript\n// billing/invoice-totals.js — plain ES module, no framework imports\nexport function calculateInvoiceTotal(items, taxRate) {\n  const net = items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n  const tax = net * taxRate;\n  return { net, tax, gross: net + tax };\n}\n```\n\nDie alte Welt nutzt das Modul über eine AngularJS-Komponente:\n\n```javascript\n// old world: AngularJS 1.6 component wrapping the plain module\nimport { calculateInvoiceTotal } from '../billing/invoice-totals';\n\nangular.module('orderApp').component('invoiceFooter', {\n  bindings: { items: '<', taxRate: '<' },\n  controller: function InvoiceFooterController() {\n    this.$onChanges = () => {\n      this.totals = calculateInvoiceTotal(this.items, this.taxRate);\n    };\n  },\n  template: '<strong>{{ $ctrl.totals.gross | currency }}</strong>',\n});\n```\n\nDie neue Welt – hier bewusst React 16, um zu zeigen, dass die Richtung egal ist – nutzt dasselbe Modul unverändert:\n\n```jsx\n// new world: React 16 component, same module untouched\nimport { calculateInvoiceTotal } from '../billing/invoice-totals';\n\nexport function InvoiceFooter({ items, taxRate }) {\n  const totals = calculateInvoiceTotal(items, taxRate);\n  return <strong>{totals.gross.toFixed(2)} €</strong>;\n}\n```\n\nDie Abhängigkeitsrichtung ist dabei die eigentliche Regel, nicht das Modulformat:\n\n```mermaid\nflowchart TD\n  OLD[\"AngularJS-Komponenten<br/>alte Welt\"] --> CORE[\"Fachlogik-Module<br/>ohne Framework-Import\"]\n  NEW[\"React- oder Angular-Komponenten<br/>neue Welt\"] --> CORE\n  CORE -. \"verboten:<br/>Kern kennt kein UI\" .-> OLD\n```\n\nFramework-frei halten lässt sich mehr, als der erste Blick vermuten lässt: Berechnungen und Validierungen als Pure Functions, der API-Zugriff hinter einem eigenen Modul statt `$http` oder `HttpClient` direkt in Komponenten, der Anwendungszustand in einem eigenen Store. Redux ist hier ein gutes Beispiel, weil es absichtlich framework-neutral gebaut ist – `react-redux` und `ng-redux` sind nur dünne Bindings. Ein Redux-Store samt Reducern zieht ohne eine geänderte Zeile von AngularJS nach React um. Was übrig bleibt, sind dünne Komponenten, die Daten annehmen und Events abgeben. Genau die sind es dann auch, die neu geschrieben werden – und das ist der Teil der Arbeit, der schnell geht und wenig Risiko trägt.\n\n## Custom Elements als neutrale Brücke\n\nWer nicht AngularJS nach Angular migriert, sondern etwa Angular und React im selben Produkt versöhnen muss, hat kein `UpgradeModule`. Die neutralste Brücke, die sich hier abzeichnet, ist die Web-Plattform selbst: Custom Elements. Eine Komponente, die als `<invoice-footer>` im DOM registriert ist, kann von jeder Welt gerendert werden – React schreibt das Tag einfach ins JSX, AngularJS in ein Template, ein serverseitig gerendertes CMS in seinen HTML-Strom.\n\nMit Angular Elements ist genau dafür ein offizielles Labs-Projekt angekündigt, das mit Angular 6 greifbar werden soll: Angular-Komponenten als Custom Elements verpacken, ohne Adapter je Ziel-Framework. Ich finde die Richtung bemerkenswert, weil sie die Brücke aus dem Framework-Streit herauszieht und auf einen Browser-Standard stellt. Ehrlich bleiben muss man bei der Browser-Lage: Custom Elements v1 laufen in Chrome und Safari nativ, anderswo braucht es aktuell noch Polyfills. Für interne Anwendungen ist das meist tragbar, für öffentliche Seiten will es abgewogen sein.\n\n## Der ehrliche Preis: zwei Bundles\n\nParallelbetrieb ist nicht gratis, und ich halte nichts davon, das kleinzureden. Wer AngularJS und Angular – oder Angular und React – gleichzeitig ausliefert, schickt zwei Framework-Laufzeiten über die Leitung. Je nach Kombination sind das schnell 150 Kilobyte zusätzliches komprimiertes JavaScript, bevor die erste eigene Zeile geladen ist. Dazu kommen zwei Rendering-Modelle im selben Browser-Tab, doppelte Datums- und Zahlformatierung, im schlechten Fall doppelte HTTP-Schichten mit getrennten Caches.\n\nDas frisch erschienene webpack 4 macht wenigstens die Bundle-Seite besser handhabbar: `splitChunks` ersetzt das alte CommonsChunkPlugin und zieht gemeinsam genutzte Module – etwa die framework-freien Fachlogik-Pakete – automatisch in geteilte Chunks. Aber Werkzeuge lindern den Preis nur, sie heben ihn nicht auf. Deshalb gehört zu einem ehrlichen Übergang ein Budget: eine gemessene Obergrenze für das Gesamtgewicht, ein Datum, ab dem das alte Bundle nicht mehr wachsen darf, und ein Zielquartal, in dem es verschwindet. Der Parallelbetrieb ist ein Kredit. Man darf ihn aufnehmen – man sollte nur den Zins kennen und den Tilgungsplan aufschreiben.\n\n## Was ich daraus mitnehme\n\nDie LTS-Ankündigung für AngularJS hat vielen Teams gerade eine Deadline verpasst, und Deadlines verleiten zu Heldenbeschlüssen. Der Big-Bang-Rewrite ist so ein Heldenbeschluss: Er fühlt sich am Tag der Entscheidung gut an und neun Monate später nach zwei halben Produkten. Der Übergang ist die unspektakuläre Alternative – Hybridbetrieb wo es ihn gibt, Strangler-Schnitt entlang der Routen, Custom Elements als Brücke, ein ehrlich beziffertes Ladegewicht.\n\nWas mich an dem Thema aber eigentlich beschäftigt, ist der Blick zurück auf die eigene Architektur. Der Parallelbetrieb ist ein Prüfstand: Er macht sichtbar, wie viel der Anwendung wirklich uns gehört und wie viel dem Framework. Fachlogik in reinen Modulen, State außerhalb der Komponenten, API-Zugriff hinter eigenen Grenzen – das zahlt sich nicht erst bei der Migration aus, aber bei der Migration wird es unbarmherzig abgerechnet. Und da nach diesem Wechsel irgendwann der nächste kommt, schreibe ich die neue Welt gleich so, dass sie den übernächsten Übergang billig macht. Das ist vielleicht die nützlichste Frage an jeden Frontend-Entwurf, ganz ohne Migrationsdruck: Wie teuer wäre es, neben dieser Anwendung eine zweite Welt zu starten?\n\n## Weiterführende Quellen\n\n- Angular-Dokumentation: Upgrading from AngularJS: https://angular.io/guide/upgrade\n- Martin Fowler: StranglerApplication (2004): https://martinfowler.com/bliki/StranglerApplication.html\n- Angular-Blog: Stable AngularJS and Long Term Support: https://blog.angular.io/stable-angularjs-and-long-term-support-7e077635ee9c\n- single-spa: https://single-spa.js.org/"},{"locale":"de","translation_key":"javascript-prototypen-modell-hinter-class","slug":"javascript-prototypen-modell-hinter-class","title":"Prototypen: das Objektmodell hinter JavaScript-Klassen","summary":"class in ES2015 ist im Kern Syntax-Zucker über Prototypen: Wer die [[Prototype]]-Kette, Object.create und den new-Ablauf versteht, debuggt this-Fehler und geteilte Methoden souveräner.","tags":["Software","Frontend"],"published_at":"2017-11-21T10:00:00+00:00","updated_at":"2026-07-13T13:21:34.260955+00:00","url":"https://www.mikebild.dev/de/blog/javascript-prototypen-modell-hinter-class/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ad42ae2f0d282cfcfcad12b717b4a46d024f422bcfdb2b4cf715cb565fab7d51/javascript-prototypen-modell-hinter-class-vorlesen.mp3","audio_duration_secs":686,"text":"```js\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n  speak() {\n    return this.name + ' makes a sound';\n  }\n}\n\nconst minka = new Animal('Minka');\nconst rex = new Animal('Rex');\n\nminka.speak === rex.speak;                         // true\nminka.hasOwnProperty('speak');                     // false\nObject.getPrototypeOf(minka) === Animal.prototype; // true\n```\n\nDrei Zeilen Ausgabe, und in ihnen steckt der ganze Artikel. Die Methode `speak` existiert genau einmal, obwohl zwei Instanzen sie aufrufen. Keiner der beiden Instanzen gehört sie – `hasOwnProperty` sagt nein. Gefunden wird sie an einem dritten Objekt, `Animal.prototype`, auf das beide Instanzen mit einem internen Verweis zeigen.\n\nDieses dritte Objekt hat `class` nicht erfunden, es hat es nur aus dem Blickfeld geräumt. Der Verweis darauf trägt in JavaScript jede Methodensuche, jede Vererbung und jeden verlorenen `this`-Bezug. Deshalb baue ich das Modell hier von unten auf: erst reine Prototypen mit `Object.create`, dann Constructor-Functions und der `new`-Ablauf, dann `class` als die Fassade, die beides zusammenfasst.\n\n## Jedes Objekt hat einen Link nach oben\n\nDas Fundament ist erstaunlich schlicht. Jedes Objekt in JavaScript trägt einen internen Verweis, in der Spezifikation `[[Prototype]]` genannt. Dieser Verweis zeigt entweder auf ein anderes Objekt – den Prototyp – oder auf `null`. Wenn du auf eine Property zugreifst, die das Objekt selbst nicht besitzt, schaut die Sprache nicht auf und gibt `undefined` zurück. Sie folgt zunächst dem `[[Prototype]]`-Link und sucht dort weiter. Und findet sie dort nichts, geht sie einen Link höher. So entsteht die Prototyp-Kette, und sie endet bei `null`.\n\nAm klarsten sieht man das ohne jede `class` und ohne `new`, nur mit `Object.create`:\n\n```js\nconst animal = {\n  describe() {\n    return this.name + ' makes ' + this.sound;\n  }\n};\n\nconst dog = Object.create(animal);\ndog.name = 'Rex';\ndog.sound = 'woof';\n\ndog.describe(); // 'Rex makes woof'\n\nObject.getPrototypeOf(dog) === animal; // true\ndog.hasOwnProperty('describe');        // false\ndog.hasOwnProperty('name');            // true\n```\n\nSchau dir an, was hier geschieht. Das Objekt `dog` besitzt selbst nur `name` und `sound` – das bestätigt `hasOwnProperty`. Die Methode `describe` findet es nicht bei sich, sondern erst einen Schritt höher, bei `animal`. Beim Aufruf zählt aber, wer der Empfänger war: `this` ist `dog`, deshalb liest `describe` `Rex` und `woof`. Die Methode liegt am Prototyp, die Daten liegen an der Instanz, und der Lookup verbindet beides. Das ist der ganze Mechanismus – keine Klassen, keine Konstruktoren, nur ein Objekt, das auf ein anderes zeigt.\n\n`Object.create` macht diesen Link explizit sichtbar: Der erste Parameter wird direkt zum `[[Prototype]]` des neuen Objekts. Du kannst sogar `Object.create(null)` schreiben und bekommst ein Objekt ganz ohne Prototyp – ohne `toString`, ohne `hasOwnProperty`, ein blankes Wörterbuch. Nützlich, wenn man ein Objekt als reine Key-Value-Ablage will und keine geerbten Eigenschaften im Weg haben möchte.\n\n## Die Kette, visualisiert\n\nWenn `dog.describe()` aufgerufen wird, läuft der Lookup die Kette hoch. Das folgende Diagramm zeigt die Stationen bis zum Ende bei `null`:\n\n```mermaid\ngraph TD\n  A[\"dog<br/>own: name, sound\"] -->|\"[[Prototype]]\"| B[\"animal<br/>own: describe\"]\n  B -->|\"[[Prototype]]\"| C[\"Object.prototype<br/>own: hasOwnProperty, toString\"]\n  C -->|\"[[Prototype]]\"| D[\"null\"]\n```\n\nJeder Pfeil ist ein `[[Prototype]]`-Verweis, und der Lookup steigt an ihnen entlang auf. Sucht die Sprache `describe`, wird sie bei `animal` fündig. Suchte sie `toString`, ginge es eine Station weiter bis `Object.prototype`. Und suchte sie etwas, das es nirgends gibt, käme sie bei `null` an und lieferte `undefined`. Diese Kette ist kein Sonderfall für selbstgebaute Objekte – jedes Objekt, jedes Array, jede Funktion hängt an so einer Kette, deren Wurzel `Object.prototype` ist.\n\n## Constructor-Functions: der Weg vor `class`\n\nVor ES2015 baute man wiederverwendbare „Typen“ mit Constructor-Functions. Der Trick sitzt in zwei Teilen, die man auseinanderhalten muss. Erstens: Jede Funktion besitzt eine Property namens `prototype` – ein gewöhnliches Objekt, das als Vorlage dient. Zweitens: Der `new`-Operator verbindet ein frisches Objekt mit genau dieser Vorlage.\n\n```js\nfunction Animal(name) {\n  this.name = name;\n}\n\nAnimal.prototype.speak = function () {\n  return this.name + ' makes a sound';\n};\n\nconst cat = new Animal('Minka');\ncat.speak(); // 'Minka makes a sound'\n\nObject.getPrototypeOf(cat) === Animal.prototype; // true\ncat.hasOwnProperty('speak');                     // false\n```\n\nWas tut `new Animal('Minka')` konkret? Der Ablauf ist – vereinfacht – dreistufig. Zuerst wird ein neues, leeres Objekt erzeugt, dessen `[[Prototype]]` auf `Animal.prototype` gesetzt wird. Dann wird `Animal` aufgerufen, wobei `this` auf dieses neue Objekt zeigt – so landet `this.name = name` als eigene Property an der Instanz. Und schließlich: Gibt die Funktion selbst kein Objekt zurück, wird das neue Objekt das Ergebnis. Deshalb steht `speak` nicht an der Instanz, sondern an `Animal.prototype`, und wird von allen Katzen geteilt.\n\nVererbung war vor `class` Handarbeit – und genau diese Handarbeit zeigt, was `extends` später automatisiert:\n\n```js\nfunction Dog(name) {\n  Animal.call(this, name);       // Parent-Konstruktor auf eigenem this\n}\n\nDog.prototype = Object.create(Animal.prototype); // Kette einhängen\nDog.prototype.constructor = Dog;                 // constructor wieder setzen\n\nDog.prototype.speak = function () {\n  return this.name + ' makes woof';\n};\n\nconst rex = new Dog('Rex');\nrex.speak();                 // 'Rex makes woof'\nrex instanceof Dog;          // true\nrex instanceof Animal;       // true\n```\n\nDrei Zeilen tragen hier die Last. `Animal.call(this, name)` ruft den Eltern-Konstruktor auf dem eigenen `this` auf, damit `name` gesetzt wird. `Dog.prototype = Object.create(Animal.prototype)` hängt die Prototyp-Kette ein, sodass eine Dog-Instanz erst bei `Dog.prototype`, dann bei `Animal.prototype`, dann bei `Object.prototype` sucht. Und die dritte Zeile repariert etwas, das die zweite kaputtgemacht hat: Beim Überschreiben von `Dog.prototype` ging die `constructor`-Rückverweisung verloren, die wir manuell wiederherstellen. Genau solche Details sind es, die man in der Praxis vergisst – und die `class` einem abnimmt.\n\n## Dieselbe Sache als `class`\n\nJetzt derselbe Code in ES2015-Syntax, Seite an Seite gedacht. Das Ergebnis ist identisch im Objektmodell – dieselben Prototyp-Objekte, dieselbe Kette, dieselben geteilten Methoden:\n\n```js\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n  speak() {\n    return this.name + ' makes a sound';\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name) {\n    super(name);\n  }\n  speak() {\n    return this.name + ' makes woof';\n  }\n}\n\nconst rex = new Dog('Rex');\nObject.getPrototypeOf(rex) === Dog.prototype;              // true\nObject.getPrototypeOf(Dog.prototype) === Animal.prototype; // true\n```\n\nVergleiche das mit der ES5-Fassung, und die Übersetzung wird direkt sichtbar. Die Methoden `speak` im Class-Body landen auf `Animal.prototype` bzw. `Dog.prototype` – nicht an der Instanz. `extends Animal` erledigt das Einhängen der Kette, für das wir eben `Object.create(Animal.prototype)` von Hand geschrieben haben. Und `super(name)` ersetzt das manuelle `Animal.call(this, name)`. Die letzte Zeile beweist es: `rex` zeigt auf `Dog.prototype`, und dieses zeigt auf `Animal.prototype`. Dieselbe Kette wie vorher, nur ohne den Boilerplate und ohne die vergessene `constructor`-Zeile.\n\nEhrlich bleiben muss man trotzdem: `class` ist Syntax-Zucker, aber nicht ausschließlich. Ein Class-Body läuft immer im Strict Mode. Eine Klasse lässt sich nicht ohne `new` aufrufen – der Versuch wirft einen Fehler, während eine Constructor-Function sich auch als normale Funktion missbrauchen ließe. Und `class`-Deklarationen werden nicht wie `function`-Deklarationen an den Anfang gezogen und initialisiert; sie liegen in einer temporalen toten Zone und sind vor ihrer Definitionszeile nicht benutzbar. Auch `super` in Methoden greift auf einen internen Mechanismus (`[[HomeObject]]`) zurück, den man mit reinem ES5 nicht 1:1 nachbaut. Die Fassade ist also bequem und an ein paar Kanten strenger als das Original – aber das Modell darunter bleibt Prototyp.\n\n## `prototype`, `__proto__` und `Object.create` sauber trennen\n\nDie häufigste Verwirrung, die mir in Code-Reviews begegnet, dreht sich um zwei ähnlich klingende Namen. `prototype` und `__proto__` sind nicht dasselbe, und die Verwechslung produziert Fehler, die man lange anstarrt. Diese Liste sortiert die drei Werkzeuge:\n\n- Eine konstruierbare Funktion besitzt üblicherweise eine eigene `prototype`-Property. `new` verwendet das dort referenzierte Objekt als Prototyp der Instanz. Gewöhnliche Instanzen haben keine eigene `prototype`-Property; Pfeilfunktionen und Methoden sind nicht konstruierbar und besitzen ebenfalls keine solche Vorlage.\n- `__proto__` (bzw. das interne `[[Prototype]]`) ist der tatsächliche Kettenlink, den jedes Objekt trägt. Der kanonische Zugriff läuft über `Object.getPrototypeOf(obj)`; `__proto__` selbst ist in ES2015 nur über Annex B standardisiert und gilt als Legacy.\n- `Object.create(proto)` erzeugt ein Objekt und setzt dessen `[[Prototype]]` direkt auf `proto` – ganz ohne Constructor-Function. Das ist der direkte Weg, einen Kettenlink zu legen.\n\nDer entscheidende Unterschied: `Fn.prototype` ist die Vorlage auf der Funktion, `instance.[[Prototype]]` ist der Link auf dem erzeugten Objekt. Beim Aufruf von `new Fn()` wird das eine zum anderen. Und um es endgültig zu entwirren – die Funktion selbst ist auch ein Objekt und hat ihren eigenen Link:\n\n```js\nfunction Fn() {}\nconst obj = new Fn();\n\nObject.getPrototypeOf(obj) === Fn.prototype; // true  (Instanz-Link)\nobj.prototype;                               // undefined (Instanz hat keine)\nObject.getPrototypeOf(Fn) === Function.prototype; // true (Fn ist selbst Objekt)\n```\n\nAchte auf die letzte Zeile. `Fn.__proto__` ist `Function.prototype`, nicht `Fn.prototype`. Wer diese beiden verwechselt, sucht Methoden an der falschen Stelle. Im Zweifel hilft immer `Object.getPrototypeOf`, um die Kette Schritt für Schritt abzugehen, statt zu raten.\n\n## Der teuerste Fallstrick: Methoden im Konstruktor\n\nJetzt zu dem Punkt, der in echten Codebasen Speicher kostet und in Reviews oft durchrutscht. Es ist ein handfester Unterschied, ob eine Methode am Prototyp liegt oder im Konstruktor erzeugt wird:\n\n```js\nfunction WidgetBad() {\n  this.render = function () { /* ... */ }; // pro Instanz eine neue Funktion\n}\n\nfunction WidgetGood() {}\nWidgetGood.prototype.render = function () { /* ... */ }; // geteilt\n\nconst a1 = new WidgetBad();\nconst a2 = new WidgetBad();\na1.render === a2.render; // false  -> zwei getrennte Funktionen\n\nconst b1 = new WidgetGood();\nconst b2 = new WidgetGood();\nb1.render === b2.render; // true   -> eine Funktion, geteilt\n```\n\nDer Beweis steht in den Vergleichen. Bei `WidgetBad` bekommt jede Instanz ihre eigene `render`-Funktion – bei tausend Widgets sind das tausend identische Funktionen im Speicher. Bei `WidgetGood` liegt `render` einmal an `WidgetGood.prototype`, und alle Instanzen teilen sie sich. Genau das tut `class` automatisch: Methoden im Class-Body landen am Prototyp, nicht an der Instanz. Man muss sich für den guten Fall in `class` also gar nicht anstrengen – man muss ihn nur nicht durch eine Zuweisung im `constructor` zerstören.\n\nDer zweite häufige Fallstrick ist der Verlust von `this`. Eine Prototyp-Methode kennt ihren Empfänger nur, wenn sie als `obj.method()` aufgerufen wird. Reißt man sie los, ist der Bezug weg:\n\n```js\nconst cat = new Animal('Minka');\n\nconst fn = cat.speak;\nfn(); // this ist nicht mehr cat -> Fehler oder falsches Ergebnis\n\nconst bound = cat.speak.bind(cat);\nbound(); // 'Minka makes a sound' -> this wieder gebunden\n```\n\nDas ist kein Bug, sondern eine direkte Folge des Modells: `this` wird beim Aufruf bestimmt, nicht bei der Definition. Löst man `cat.speak` in eine freie Variable, fehlt der Empfänger. Die Werkzeuge dagegen sind 2017 etabliert: `.bind(cat)` erzeugt eine fest gebundene Variante, oder man wickelt den Aufruf in eine Arrow-Function, die `this` aus dem umgebenden Bereich übernimmt. Ein Ausblick am Rande: An Klassen-Feldern mit Arrow-Functions wird gearbeitet, die genau dieses Binden eleganter machen sollen – das ist Ende 2017 aber noch ein TC39-Proposal und kein Standard. Wer es heute produktiv braucht, greift zu `bind` oder Arrow-Wrapper.\n\n## Warum sich das auszahlt\n\nMan kann JavaScript jahrelang mit `class` schreiben, ohne je „Prototyp“ zu sagen. Bis zu dem Tag, an dem `this` in einem Event-Handler `undefined` ist, an dem eine geerbte Methode nicht gefunden wird, oder an dem ein Profiler tausendfach dieselbe Funktion im Heap zeigt. Dann trennt sich, wer das Modell kennt, von dem, der rät. Die drei wiederkehrenden Symptome – verlorenes `this`, Methode an der falschen Stelle, Speicher pro Instanz – sind allesamt keine Marotten der Sprache, sondern logische Konsequenzen einer Kette aus Objekten, die aufeinander zeigen.\n\n`class` hat seine Berechtigung: lesbar, strikt, und es nimmt einem den fehleranfälligen Boilerplate der ES5-Vererbung ab. Aber es ist eine Fassade, und hinter der Fassade steht immer noch `Object.create`, `Fn.prototype` und ein `new`, das beides verbindet. Wenn du das nächste Mal `extends` schreibst, denk kurz an die drei Zeilen, die es ersetzt – die eingehängte Kette, den `super`-Aufruf, den `constructor`-Rückverweis. Dann ist `class` keine Magie mehr, sondern eine Abkürzung, deren Langform du jederzeit selbst hinschreiben könntest.\n\nDieses prototypische Denken ist derselbe rote Faden, der sich durch die [JavaScript-Patterns zieht, die geblieben sind](https://www.mikebild.dev/de/blog/javascript-patterns-module-hof-currying/) – Objekte, die auf Objekte zeigen, Funktionen als Bausteine. Wer dieses Fundament versteht, baut auf Frameworks ruhiger auf.\n\n## Weiterführende Quellen\n\n- MDN, Inheritance and the prototype chain: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain\n- MDN, Object.create: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create\n- MDN, Object.getPrototypeOf: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf\n- MDN, Object.setPrototypeOf: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf\n- MDN, Object.prototype.\\_\\_proto\\_\\_: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto\n- MDN, Classes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\n- MDN, new operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new\n- ECMAScript 2015 (ES6) Spec: https://www.ecma-international.org/ecma-262/6.0/\n- ECMAScript 2017 (ES8) Spec: https://www.ecma-international.org/ecma-262/8.0/"},{"locale":"de","translation_key":"redux-als-protokoll","slug":"redux-als-protokoll","title":"Redux als Protokoll für UI-Änderungen","summary":"Der Store ist der langweiligste Teil von Redux – wertvoll ist das Nachrichtenprotokoll aus benannten, serialisierbaren Actions, das UI-Änderungen nachvollziehbar, testbar und diskutierbar macht.","tags":["Software","Frontend"],"published_at":"2017-10-12T10:00:00+00:00","updated_at":"2026-07-14T17:09:15.018598+00:00","url":"https://www.mikebild.dev/de/blog/redux-als-protokoll/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ebfb39d33ce697f0dd04fea471b08b6b5b3d5def1bda1d23e09b16726d2d3d2a/redux-als-protokoll-vorlesen.mp3","audio_duration_secs":725,"text":"# Redux als Protokoll für UI-Änderungen\n\nIn der Netzwerktechnik ist ein Protokoll keine Software, sondern eine Vereinbarung: Es legt fest, welche Nachrichten zwischen Parteien fließen dürfen, wie jede Nachricht aufgebaut ist und was sie bedeutet. TCP schreibt niemandem vor, welches Programm an den Endpoints läuft – es bestimmt nur die Form der Pakete und die Regeln des Austauschs. Genau dieser Begriff, auf eine Benutzeroberfläche übertragen, beschreibt Redux treffender als die übliche Kurzformel.\n\nDie lautet nämlich: Redux sei ein globaler State-Container für React-Anwendungen. Das ist nicht falsch, aber es zeigt auf den langweiligsten Teil. Ein Objekt, das Anwendungszustand hält, hat jede Anwendung – notfalls als `window.appState`, und damit ist noch gar nichts gewonnen. Interessant an Redux ist die Vereinbarung darüber, wie sich dieses Objekt ändern darf: ausschließlich über benannte, serialisierbare Nachrichten. Redux ist weniger ein Behälter als ein Protokoll für Änderungen – zwischen den Teilen der Oberfläche und, was gern übersehen wird, über die Zeit hinweg. Wer heute eine Action dispatcht, redet auch mit dem Kollegen, der in drei Monaten das Action-Log eines Fehlerberichts liest.\n\n## Drei Bausteine, sehr ungleich verteilt\n\nRedux besteht aus drei Teilen: dem Store, der den State hält, den Actions, die Änderungen beschreiben, und den Reducern, die aus altem State und Action den neuen State berechnen. Der Store selbst ist erstaunlich unspektakulär – ein paar Dutzend Zeilen um ein Objekt, eine `dispatch`-Funktion und eine Subscriber-Liste. Wer den Quelltext von `createStore` liest, ist nach einer Tasse Kaffee durch.\n\nDer Wert steckt in dem, was die beiden anderen Bausteine erzwingen. Eine Action ist ein einfaches Objekt mit einem `type` und Nutzdaten:\n\n```js\n// actions.js\nexport const ORDER_SUBMITTED = 'ORDER_SUBMITTED';\nexport const ORDER_ACCEPTED = 'ORDER_ACCEPTED';\nexport const ORDER_REJECTED = 'ORDER_REJECTED';\n\nexport const submitOrder = order => ({\n  type: ORDER_SUBMITTED,\n  payload: { orderId: order.id, items: order.items }\n});\n```\n\nKein Funktionszeiger, keine Klasseninstanz, kein Verweis auf eine Komponente. Nur Daten, die sich als JSON aufschreiben lassen. Das wirkt wie eine Einschränkung – und ist genau als solche gemeint. Eine Nachricht, die sich serialisieren lässt, lässt sich auch aufzeichnen, versenden, vergleichen und Jahre später noch lesen. Ein Methodenaufruf kann das alles nicht.\n\nDer Reducer ist die zweite Hälfte der Vereinbarung: eine Pure Function, die niemals selbst etwas auslöst, sondern nur beantwortet, was eine Nachricht für den State bedeutet.\n\n```js\n// ordersReducer.js\nimport { ORDER_SUBMITTED, ORDER_ACCEPTED } from './actions';\n\nconst initialState = { pending: [], accepted: [] };\n\nexport default function ordersReducer(state = initialState, action) {\n  switch (action.type) {\n    case ORDER_SUBMITTED:\n      return { ...state, pending: [...state.pending, action.payload.orderId] };\n    case ORDER_ACCEPTED:\n      return {\n        ...state,\n        pending: state.pending.filter(id => id !== action.payload.orderId),\n        accepted: [...state.accepted, action.payload.orderId]\n      };\n    default:\n      return state;\n  }\n}\n```\n\nAus dieser Trennung – Nachricht hier, Bedeutung dort – folgt fast alles, was Teams an Redux schätzen. Meist wird es unter „Vorhersagbarkeit\" verbucht. Mir hilft eine andere Sortierung:\n\n- Jede Änderung lässt sich aufzeichnen und wieder abspielen, weil sie als Datenobjekt vorliegt.\n- Jede Änderung lässt sich ohne Browser testen, weil der Reducer eine Pure Function ist.\n- Jede Änderung hat einen Namen, über den man im Code-Review und mit der Fachseite reden kann.\n- Jede Änderung lässt sich von außen beobachten, ohne die UI anzufassen.\n\nDas sind keine vier Features. Das ist viermal dieselbe Eigenschaft: Es gibt ein Protokoll.\n\n## Zeitreise ist keine Zauberei\n\nDie Redux DevTools führen das am eindrucksvollsten vor. Jede Action erscheint dort als Zeile in einem Log, und weil der State nur aus der Faltung aller bisherigen Actions über die Reducer entsteht, kann man im Log beliebig zurückspringen – die Oberfläche folgt. Beim ersten Vorführen wirkt das wie ein Trick. Tatsächlich ist es die banale Konsequenz aus dem Protokollgedanken: Wer alle Nachrichten kennt und eine deterministische Funktion darauf anwendet, kann jeden Zwischenstand rekonstruieren. Netzwerkleute kennen das seit Ewigkeiten – ein Paketmitschnitt plus State Machine ergibt die komplette Sitzung.\n\nIn einem Projekt in diesem Sommer hat uns genau das einen zähen Fehler erspart. Ein Anwender meldete einen State, den niemand nachstellen konnte: eine Bestellung, die gleichzeitig als offen und als bestätigt angezeigt wurde. Statt Vermutungen zu sammeln, haben wir uns den exportierten Action-Verlauf schicken lassen und ihn lokal wieder eingespielt. Die fehlerhafte Reihenfolge – `ORDER_ACCEPTED` traf vor `ORDER_SUBMITTED` ein, weil zwei Requests sich überholt hatten – stand nach fünf Minuten schwarz auf weiß im Log. Mit verteilten `setState`-Aufrufen wäre dieselbe Diagnose ein Nachmittag mit Debugger und Glück gewesen.\n\nAuch das Testen profitiert von der Nachrichtenform, und zwar ohne jede Test-Infrastruktur:\n\n```js\n// ordersReducer.test.js\nimport ordersReducer from './ordersReducer';\nimport { submitOrder } from './actions';\n\nit('moves a submitted order into pending', () => {\n  const state = ordersReducer(undefined, submitOrder({ id: '42', items: [] }));\n  expect(state.pending).toEqual(['42']);\n});\n```\n\nKein DOM, kein Mock eines Stores, kein Rendern. Eingabe, Ausgabe, fertig. Reducer-Tests gehören zu den wenigen Frontend-Tests, die ich noch nie flaky gesehen habe.\n\n## Events statt Befehle\n\nGenau an dieser Stelle geht der Wert allerdings auch am schnellsten verloren – nicht durch die Bibliothek, sondern durch den Zuschnitt der Nachrichten. In einem Code-Review im Frühjahr stand ein Reducer vor mir, dessen Action-Liste so aussah: `SET_LOADING_TRUE`, `SET_LOADING_FALSE`, `SET_ORDERS`, `SET_ERROR`, `RESET_ERROR`. Formal alles korrekt: benannte, serialisierbare Objekte, reine Reducer, DevTools funktionieren. Trotzdem war das Protokoll wertlos, denn die Nachrichten beschrieben nicht, was passiert ist, sondern welchen Feldwert der Absender gern hätte. Das ist kein Ereignisprotokoll, das sind entfernte Zuweisungen – `setState` mit Umweg und mehr Tipparbeit.\n\nDer Unterschied wird im direkten Vergleich deutlich:\n\n```js\n// commands: the sender prescribes how state must change\ndispatch({ type: 'SET_LOADING_TRUE' });\ndispatch({ type: 'SET_ORDERS', payload: orders });\ndispatch({ type: 'SET_LOADING_FALSE' });\n\n// events: the sender reports what happened in the domain\ndispatch({ type: 'ORDERS_REQUESTED' });\ndispatch({ type: 'ORDERS_LOADED', payload: { orders } });\ndispatch({ type: 'ORDERS_LOADING_FAILED', payload: { error } });\n```\n\nDie Ereignisvariante hat drei Eigenschaften, die der Befehlsvariante fehlen. Erstens trägt sie Fachsprache in den Code: `ORDER_SUBMITTED` ist ein Satz, den auch die Produktverantwortliche versteht, `SET_LOADING_TRUE` versteht nur der Autor der Komponente. Im Review reden wir dann über die Frage „Darf eine abgelehnte Bestellung erneut eingereicht werden?\" statt über Boolean-Choreografie. Zweitens ist ein Event vergangen und damit unstrittig – es wird berichtet, nicht angeordnet. Der Absender muss nicht wissen, wer zuhört. Drittens skaliert genau deshalb der Empfängerkreis: Wenn später ein zweiter Reducer die Zahl offener Bestellungen für einen Badge zählen soll, abonniert er `ORDER_SUBMITTED` einfach mit. Bei `SET_ORDERS` müsste der Absender umgebaut werden. Ein Befehl kennt seinen Empfänger, ein Event kennt nur seinen Anlass – im Protokollbild ist das der Unterschied zwischen einem RPC-Aufruf und einem Broadcast.\n\nSeitdem lese ich Action-Dateien wie ein Nachrichtenverzeichnis. Steht dort ein Vokabular der Fachdomäne in Vergangenheitsform, trägt das Protokoll. Steht dort eine Liste von Settern, hat das Team einen zweiten `setState`-Mechanismus gebaut, nur umständlicher.\n\n```mermaid\nsequenceDiagram\n  participant V as View\n  participant M as Middleware\n  participant R as Reducer\n  participant S as Store\n  V->>M: dispatch(ORDER_SUBMITTED)\n  Note over M: Abhörpunkt:<br/>Logging, Analytics, DevTools\n  M->>R: action (unverändert)\n  R->>S: neuer Zustand\n  S-->>V: notify + render\n```\n\n## Middleware: das Protokoll abhören\n\nWer Actions als Nachrichten ernst nimmt, bekommt eine zweite Fähigkeit geschenkt, die bei der Behälter-Sichtweise unsichtbar bleibt: Man kann den Nachrichtenstrom anzapfen. Genau das ist Middleware – eine Funktion, die zwischen `dispatch` und Reducer sitzt und jede Nachricht sieht, bevor sie Bedeutung bekommt.\n\n```js\n// analyticsMiddleware.js\nconst analyticsMiddleware = store => next => action => {\n  if (action.type.startsWith('ORDER_')) {\n    trackEvent(action.type, action.payload);\n  }\n  return next(action);\n};\n```\n\nDie dreifach gestaffelte Signatur ist gewöhnungsbedürftig, aber schlicht angewandtes Currying – wie solche Funktionsketten entstehen, habe ich vor ein paar Wochen in [JavaScript-Patterns: Module, Higher-Order-Functions, Currying](https://www.mikebild.dev/de/blog/javascript-patterns-module-hof-currying/) auseinandergenommen. Wichtiger als die Form ist die Konsequenz: Analytics braucht keinen einzigen Aufruf in einer Komponente. In dem Bestell-Projekt hängt die Produktauswertung komplett an dieser einen Datei. Als eine neue Kennzahl gewünscht wurde – wie oft eine Ablehnung auf eine Einreichung folgt – war das eine Änderung in der Middleware, nicht in dreißig Komponenten. Dasselbe gilt für Logging im Fehlerfall: Die letzten fünfzig Actions in einen Ringpuffer zu schreiben und an den Error-Report zu hängen, kostet zwanzig Zeilen.\n\nAuch die Async-Frage ist am Ende eine Protokollfrage. Ob `redux-thunk` für die einfachen Fälle oder `redux-saga` und `redux-observable`, wenn Abläufe orchestriert werden müssen – alle drei sind Middleware, und alle drei münden am Ende wieder in gewöhnliche Actions. Der asynchrone Teil ändert die Sprache nicht, er spricht sie nur zeitversetzt. Wie sich Push- und Pull-Datenflüsse dabei grundsätzlich unterscheiden, steht in [RxJS: Push und Pull](https://www.mikebild.dev/de/blog/rxjs-push-und-pull/) – Redux ist konsequent auf der Push-Seite unterwegs.\n\n## Die Grenze: Nicht jede Änderung verdient eine Nachricht\n\nSo nützlich das Protokoll ist – es hat einen Preis pro Nachricht: eine Konstante, ein Action-Creator, ein Reducer-Zweig, im Zweifel ein Test. Diesen Preis sollte nur zahlen, was ihn wert ist. Ob ein Dropdown gerade offen ist, welcher Tab aktiv ist, was in einem Eingabefeld steht, bevor es abgeschickt wird – das ist lokaler UI State, und der gehört in die Komponente, in ein schlichtes `setState`. Niemand will im Action-Log dreißig `INPUT_CHANGED` zwischen zwei fachlichen Events lesen; das Protokoll verrauscht, und die Zeitreise wird zur Diashow.\n\nDan Abramov selbst hat das im vergangenen Jahr in „You Might Not Need Redux\" deutlich aufgeschrieben, und der Text ist keine Distanzierung, sondern eine Preisliste: Die Vorteile von Redux entstehen genau aus seinen Einschränkungen, also lohnt es sich nur dort, wo man die Vorteile auch einlöst. Meine Prüffragen, bevor State in den Store wandert:\n\n- Lesen mehrere, im Baum weit voneinander entfernte Komponenten diesen State?\n- Hat die Änderung einen fachlichen Namen, der in einem Fehlerbericht etwas erklären würde?\n- Interessiert die Historie dieser Änderungen irgendwen – Support, Analyse, Debugging?\n\nDreimal Nein heißt: Komponente. React kann lokalen State seit jeher selbst, und daran hat auch das gerade erschienene React 16 nichts geändert – der neue Fiber-Kern rendert anders, aber `setState` bleibt `setState`. Die beiden Mechanismen konkurrieren nicht, sie bedienen verschiedene Fragen.\n\n```mermaid\nflowchart TD\n  A[Zustand entsteht] --> B{Lesen entfernte<br/>Komponenten mit?}\n  B -- nein --> L[Lokal:<br/>setState in der Komponente]\n  B -- ja --> C{Fachlicher Name?<br/>Historie relevant?}\n  C -- nein --> L\n  C -- ja --> S[Store:<br/>Action + Reducer]\n```\n\nIm Repository [introduction-react](https://github.com/MikeBild/introduction-react), in dem ich seit dem Frühjahr React-Themen für Vorträge und Beispiele sammle, ist der Redux-Teil aus genau diesem Grund bewusst klein: eine überschaubare Beispiel-App, in der das Nachrichtenvokabular auf eine Handvoll fachlicher Events begrenzt bleibt. Nicht, weil mehr nicht ginge – sondern weil der Unterschied zwischen Protokoll und Behälter an einem kleinen, sauberen Vokabular besser sichtbar wird als an einem großen, verrauschten.\n\n## Was ich daraus mitnehme\n\nMir ist mit der Zeit aufgefallen, dass die Teams, die mit Redux glücklich sind, und die, die darüber fluchen, gar nicht verschiedene Bibliotheken benutzen – sie benutzen verschiedene Protokolle. Die einen haben ein Vokabular fachlicher Events, das man laut vorlesen kann; ihr Action-Log liest sich wie ein Ablaufbericht der Anwendung. Die anderen haben Setter mit Großbuchstaben und wundern sich, dass der versprochene Nutzen ausbleibt: Die DevTools zeigen Rauschen, die Tests prüfen Zuweisungen, und im Review gibt es nichts zu diskutieren, weil `SET_VALUE` keine fachliche Aussage enthält, der man widersprechen könnte.\n\nDeshalb halte ich den Store inzwischen für ein Implementierungsdetail und das Protokoll für die eigentliche Architekturentscheidung. Die drei Fragen, die den Unterschied machen, haben mit der Bibliothek wenig zu tun: Welche Events gibt es in dieser Anwendung? Wie heißen sie in der Sprache der Fachdomäne? Und wer darf sie auslösen? Wer diese Fragen beantwortet hat, bekommt von Redux Nachvollziehbarkeit, Testbarkeit und eine gemeinsame Sprache fast geschenkt. Wer sie überspringt, bekommt einen globalen State-Container mit Zeremonie – und hätte dann tatsächlich kein Redux gebraucht.\n\nSollte Redux irgendwann von etwas anderem abgelöst werden, bleibt die Übung trotzdem wertvoll. Ein Protokoll benannter, serialisierbarer Änderungsnachrichten ist keine Erfindung dieser Bibliothek – die Netzwerktechnik lebt seit Jahrzehnten davon, und Event-getriebene Systeme auf dem Server ebenso. Redux hat diese Disziplin nur an eine Stelle getragen, an der sie vorher selten war: mitten in die UI.\n\n## Weiterführende Quellen\n\n- [MikeBild/introduction-react](https://github.com/MikeBild/introduction-react) – Repository mit React-Beispielen, inklusive Flux/Redux-Teil und Beispiel-App\n- [Redux-Dokumentation: Motivation](https://redux.js.org/understanding/thinking-in-redux/motivation) – warum Mutation plus Asynchronität das eigentliche Problem ist\n- [Dan Abramov: You Might Not Need Redux](https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367) – die Preisliste zu den Einschränkungen, vom Autor selbst\n- [React v16.0 Release-Ankündigung](https://legacy.reactjs.org/blog/2017/09/26/react-v16.0.html) – der frische Fiber-Kern, der am Datenflussmodell nichts ändert"},{"locale":"de","translation_key":"javascript-patterns-module-hof-currying","slug":"javascript-patterns-module-hof-currying","title":"JavaScript-Patterns, die geblieben sind: Module, Higher-Order Functions, Currying","summary":"Drei JavaScript-Pattern haben jeden Framework-Wechsel überlebt: das Module-Pattern für saubere Kapselung, Higher-Order Functions für Funktionen als Werte und Currying für spezialisierte Varianten. Warum sie das Fundament moderner Utility-Libraries bilden.","tags":["Software","Frontend"],"published_at":"2017-09-19T10:00:00+00:00","updated_at":"2026-07-13T13:21:18.680262+00:00","url":"https://www.mikebild.dev/de/blog/javascript-patterns-module-hof-currying/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0e4eb7d89382a1d51aea496c4b34ade00bd698529190020be01153604288b344/javascript-patterns-module-hof-currying-vorlesen.mp3","audio_duration_secs":625,"text":"Ein Pattern ist keine Bibliothek und kein Framework-Feature. Es ist die Form, in der Code angeordnet wird – und die liegt eine Ebene unter dem, was gerade als Framework darüberliegt. Zwischen jQuery, Backbone, Angular 1, Angular 2 und React lagen bei uns wenige Jahre. Ausgetauscht wurden die Werkzeuge; die Anordnung darunter blieb erstaunlich konstant.\n\nDrei dieser Anordnungen greife ich hier heraus: das Module-Pattern, Higher-Order Functions und Currying beziehungsweise Partial Application. Sie bauen aufeinander auf, und wer sie einmal auseinandergenommen hat, liest modernen JavaScript-Code mit anderen Augen. Ich setze dabei ES2015 als Baseline voraus.\n\nDie drei Muster in einem Satz:\n\n- Module-Pattern kapselt State und gibt nur eine bewusst gewählte öffentliche API frei.\n- Higher-Order Functions behandeln Funktionen als Werte – sie nehmen Funktionen entgegen oder geben welche zurück.\n- Currying und Partial Application erzeugen aus einer Generic Function spezialisierte, vorkonfigurierte Varianten.\n\n## Module-Pattern: zwei Wege, ein Ziel\n\nDas älteste Problem in Browser-JavaScript ist der globale Namespace. Früher landete jede Variable, die man nicht bewusst kapselte, am `window`-Objekt, und zwei Skripte konnten sich gegenseitig überschreiben, ohne es zu merken. Die Lösung vor ES6 war eine Konvention, kein Sprachmittel: die Immediately Invoked Function Expression, kurz IIFE. Man packt Code in eine Funktion, ruft sie sofort auf und nutzt den dabei entstehenden Scope als privaten Raum. Was drinnen deklariert wird, bleibt drinnen – außer man gibt es bewusst als Objekt zurück. Diese Rückgabe des öffentlichen APIs nennt man auch Revealing Module Pattern.\n\n```js\nconst counterModule = (function () {\n  let count = 0; // private, not accessible from outside\n\n  return {\n    increment() {\n      return ++count;\n    },\n    get() {\n      return count;\n    }\n  };\n})();\n\ncounterModule.increment(); // 1\ncounterModule.increment(); // 2\ncounterModule.get();       // 2\ncounterModule.count;       // undefined – deliberately not exposed\n```\n\nDer Trick liegt in der Closure: Die zurückgegebenen Methoden behalten Zugriff auf `count`, obwohl die äußere Funktion längst durchgelaufen ist. Von außen gibt es keinen Weg, `count` direkt zu setzen. Genau das wollten wir – Kapselung ohne Sprachunterstützung, allein durch Scope und Closure.\n\nSeit ES2015 gibt es echte Module in der Sprache. Jede Datei ist ihr eigener Modul-Scope, nichts leakt automatisch nach global, und was nach außen sichtbar sein soll, markiert man mit `export`. Der Import erfolgt statisch mit `import`. Dasselbe Beispiel als ES-Modul:\n\n```js\n// counter.js\nlet count = 0; // module-private, only visible in this file\n\nexport function increment() {\n  return ++count;\n}\n\nexport function get() {\n  return count;\n}\n```\n\n```js\n// app.js\nimport { increment, get } from './counter.js';\n\nincrement(); // 1\nincrement(); // 2\nget();       // 2\n```\n\nBeide verfolgen dasselbe Ziel: privater State und eine klar definierte öffentliche API. Der Unterschied ist die Semantik. Beim IIFE ist die Kapselung eine Laufzeit-Konstruktion, die auf Funktionen und Closures beruht. Beim ES-Modul ist sie Teil des Modulsystems – Werkzeuge können die Imports schon vor der Ausführung analysieren und ungenutzten Code entfernen. Importierte Bindings sind außerdem live und können vom Importeur nicht neu zugewiesen werden. Module laufen implizit im Strict Mode.\n\n```mermaid\ngraph LR\n  A[IIFE + Closure] --> C[Kapselung<br/>privater Zustand<br/>klare öffentliche API]\n  B[ES6 import/export] --> C\n```\n\nEin ehrliches Wort zum Stand 2017: Node.js kennt native ES-Module noch nicht stabil. Dort schreibt man weiterhin CommonJS mit `require` und `module.exports`; das experimentelle `--experimental-modules`-Flag ist gerade erst mit Node 8.5.0 erschienen. In den Browsern ist die Unterstützung frisch – Chrome 61 und Safari 10.1 können `type=\"module\"` bereits, Firefox und Edge noch hinter einem Flag. In der Praxis bündeln wir 2017 also mit webpack oder Rollup und lassen Babel die `import/export`-Syntax übersetzen. Das ändert am Muster nichts: Wir denken in Modulen, auch wenn das Deployment noch über einen Bundler läuft.\n\n## Higher-Order Functions: Funktionen sind Werte\n\nDer zweite Baustein ist die eigentliche Stärke von JavaScript, und die meisten von uns haben sie benutzt, lange bevor sie einen Namen dafür hatten. In JavaScript sind Funktionen First-Class Values: Man kann sie in Variablen speichern, als Argument übergeben und aus anderen Funktionen zurückgeben. Eine Funktion, die eine Funktion als Argument entgegennimmt oder eine Funktion zurückgibt, heißt Higher-Order Function.\n\nDie bekanntesten Beispiele sind die Array-Methoden `map`, `filter` und `reduce`. Sie sind seit ES5 (2009) überall verfügbar und ersetzen imperative Schleifen durch deklarative Transformationen. Statt zu beschreiben, wie iteriert wird, beschreibt man, was mit jedem Element geschieht:\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\n\nconst doubled = numbers.map(n => n * 2);        // [2, 4, 6, 8, 10]\nconst evens = numbers.filter(n => n % 2 === 0); // [2, 4]\nconst sum = numbers.reduce((acc, n) => acc + n, 0); // 15\n```\n\nJede dieser Methoden ist selbst eine Higher-Order Function, weil sie einen Callback entgegennimmt. `map` ruft den Callback für jedes Element auf und sammelt die Rückgaben in einem neuen Array. `filter` behält nur die Elemente, für die der Callback wahr liefert. `reduce` faltet das Array auf einen einzigen Wert zusammen, indem es einen Akkumulator durch alle Elemente trägt.\n\nDie andere Hälfte des Musters – Funktionen, die Funktionen zurückgeben – ist der Schlüssel zu allem, was danach kommt. Eine Funktion, die eine konfigurierte Funktion produziert, nennt man manchmal Funktionsfabrik:\n\n```js\nconst multiplyBy = factor => n => n * factor;\n\nconst double = multiplyBy(2);\nconst triple = multiplyBy(3);\n\ndouble(5); // 10\ntriple(5); // 15\n\n[1, 2, 3].map(double); // [2, 4, 6]\n```\n\n`multiplyBy(2)` gibt keine Zahl zurück, sondern eine neue Funktion, die sich `factor` per Closure gemerkt hat. `double` und `triple` sind spezialisierte Werkzeuge, gebaut aus einer einzigen Generic Function. Und weil sie ganz normale Funktionen sind, lassen sie sich direkt an `map` übergeben. Genau hier verzahnen sich Higher-Order Functions mit dem nächsten Muster.\n\n## Currying und Partial Application: aus generisch wird speziell\n\nCurrying bedeutet, eine Funktion mit mehreren Argumenten in eine Kette einstelliger Funktionen umzuwandeln. Aus `f(a, b, c)` wird `f(a)(b)(c)`. Jeder Aufruf nimmt genau ein Argument und gibt eine Funktion zurück, die auf das nächste wartet – bis alle Argumente da sind und das Ergebnis berechnet wird. Realisiert wird das wieder über Closures.\n\n```js\nconst add = (a, b) => a + b;          // ordinary, two arguments at once\nconst curriedAdd = a => b => a + b;   // curried, unary chain\n\ncurriedAdd(10)(5); // 15\n\nconst add10 = curriedAdd(10); // specialized function, waits for b\nadd10(5);  // 15\nadd10(90); // 100\n```\n\nEng verwandt, aber nicht dasselbe ist Partial Application. Dabei fixiert man einige Argumente einer Funktion und erhält eine neue Funktion mit weniger Parametern. Der Unterschied zum Currying: Partial Application zwingt nicht in einstellige Ketten, sondern legt einfach ein paar Argumente vorab fest. In JavaScript kann man das ganz ohne eigene Helfer mit `Function.prototype.bind` bekommen, das ebenfalls seit ES5 verfügbar ist:\n\n```js\nconst add = (a, b) => a + b;\n\n// bind fixes this (here null) and the leading arguments\nconst add10 = add.bind(null, 10);\n\nadd10(5);  // 15\nadd10(90); // 100\n```\n\nDer Nutzen zeigt sich, sobald man solche spezialisierten Funktionen komponiert. Aus einem kleinen Vorrat generischer Bausteine baut man passgenaue Varianten und steckt sie zusammen. Ein Beispiel, das zeigt, wie natürlich sich so ein Baustein in die Array-Methoden fügt – `add10` aus dem `bind`-Schritt wandert direkt in `map`:\n\n```js\nconst numbers = [1, 2, 3, 4];\n\nconst shifted = numbers.map(add10);                   // [11, 12, 13, 14]\nconst total = shifted.reduce((sum, n) => sum + n, 0); // 50\n```\n\nDer Bogen von der generischen zur spezialisierten Funktion lässt sich gut als Fluss lesen:\n\n```mermaid\ngraph LR\n  A[\"add(a, b)<br/>generisch, zwei Argumente\"] --> B[\"curriedAdd(10)<br/>bzw. add.bind(null, 10)\"]\n  B --> C[\"add10(n)<br/>spezialisiert, ein Argument\"]\n```\n\nUnd genau das ist der Grund, warum diese Muster über Jahre geblieben sind: Sie sind das Fundament moderner Utility-Libraries. Ramda (seit 2013) und `lodash/fp` liefern viele Funktionen curried und mit „data-last“-Signatur aus – die Daten kommen zuletzt, damit man die Konfiguration vorab fixieren und die entstehenden Bausteine bequem komponieren kann. Wer das Prinzip hinter `multiplyBy` und `curriedAdd` verstanden hat, versteht auch, warum diese Bibliotheken so aufgebaut sind.\n\n## Drei Fallstricke, die ich immer wieder sehe\n\nSo elegant die Muster sind, so zuverlässig stolpern Teams über dieselben Stellen. Drei davon will ich benennen, weil sie in echten Codebases teuer werden.\n\nDer erste betrifft die `this`-Bindung bei Higher-Order Functions. Übergibt man eine Objekt-Methode direkt als Callback, geht der Receiver verloren. Die Methode wird ohne ihr Objekt aufgerufen, und `this` ist dann undefined oder das globale Objekt:\n\n```js\nconst counter = {\n  count: 0,\n  increment() {\n    this.count += 1; // this depends on HOW it is called\n  }\n};\n\n[1, 2, 3].forEach(counter.increment);\n// TypeError, i.e. counter.count stays 0 – this is not counter\n```\n\nDie Lösung 2017 ist eindeutig. Man bindet `this` mit `bind` fest, umschließt den Aufruf mit einer Arrow Function, die ihr `this` lexikalisch aus der Umgebung bezieht, oder nutzt den `thisArg`-Parameter, den `map`, `filter` und `forEach` als zweites Argument anbieten:\n\n```js\n[1, 2, 3].forEach(counter.increment.bind(counter));\n[1, 2, 3].forEach(() => counter.increment());\n[1, 2, 3].forEach(counter.increment, counter); // thisArg\n```\n\nArrow Functions sind hier das schärfste Werkzeug, weil sie gar kein eigenes `this` mitbringen – sie erben es aus dem umgebenden Scope. Damit verschwindet die Fehlerklasse in vielen Fällen ganz.\n\nDer zweite Fallstrick ist die Überverwendung von Currying. Tief verschachtelte `f(a)(b)(c)(d)`-Ketten sehen im Blogpost schick aus, aber im Team-Code kosten sie Lesbarkeit. Sie sind schwerer zu debuggen, die Stacktraces werden unübersichtlich, und wer den Code sechs Monate später liest, muss die Kette gedanklich wieder auffalten. Currying zahlt sich dort aus, wo Spezialisierung oder Komposition einen konkreten Vorteil bringt. Wo es nur funktional aussieht, kostet es mehr, als es bringt.\n\nDer dritte betrifft `reduce` ohne Startwert. Lässt man das `initialValue`-Argument weg, nimmt `reduce` das erste Array-Element als Startwert – und wirft bei einem leeren Array einen TypeError. Außerdem ist die Semantik des Akkumulators dann an den Elementtyp gekoppelt, was schnell zu subtilen Fehlern führt:\n\n```js\n[].reduce((sum, n) => sum + n);    // TypeError: Reduce of empty array\n[].reduce((sum, n) => sum + n, 0); // 0 – correct, because initial value set\n```\n\nFür Summen, Listenaufbau und andere Faltungen mit einem neutralen Element setze ich den Startwert deshalb explizit. Wo es fachlich kein neutrales Element gibt, behandle ich den leeren Fall lieber bewusst, statt einen künstlichen Startwert zu erfinden.\n\n## Fazit\n\nWenn ich die drei Muster nebeneinanderlege, fällt eine gemeinsame Linie auf. Das Module-Pattern kapselt State, egal ob per IIFE und Closure oder per ES-Modul – das Ziel bleibt dasselbe, nur die Ebene wandert von der Konvention in die Sprache. Higher-Order Functions machen Funktionen zu Werten und ersetzen Schleifen durch Transformationen. Currying und Partial Application bauen aus Generic Functions spezialisierte Varianten, die sich komponieren lassen. Die Syntax hat sich zwischen ES5 und ES6 verschoben, das Prinzip dahinter nicht.\n\nGenau das ist es, was ich über die Jahre gelernt habe: Muster schlagen Syntax. Die Sprach-Features werden sich weiter ändern – zwischen der ersten IIFE und dem heutigen `import` liegen Jahre –, aber Kapselung, Funktionen als Werte und Spezialisierung durch Vorkonfiguration sind stabil geblieben. Wer diesen Kern beherrscht, muss beim nächsten Framework-Wechsel nicht von vorn anfangen. Er erkennt die alten Bekannten in neuem Gewand wieder, und das ist auf lange Sicht mehr wert als jede aktuelle Bibliotheksversion.\n\n## Weiterführende Quellen\n\n- [ES-Module Guide (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n- [export (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) und [import (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\n- [IIFE (MDN Glossary)](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) und [Closures (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n- [Array.prototype.map (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), [filter (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [reduce (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)\n- [Function.prototype.bind (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) und [Arrow functions (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n- [ECMAScript 2015 (ES6) Specification](https://www.ecma-international.org/ecma-262/6.0/)\n- [Eloquent JavaScript – Higher-Order Functions](https://eloquentjavascript.net/05_higher_order.html)"},{"locale":"de","translation_key":"websockets-nicht-immer-antwort","slug":"websockets-nicht-immer-antwort","title":"WebSockets sind nicht immer die Antwort","summary":"Warum Server-Sent Events für die meisten Echtzeit-Anforderungen die einfachere Wahl sind und wann sich der Preis einer echten WebSocket-Verbindung tatsächlich lohnt.","tags":["Software","Node.js","Backend"],"published_at":"2017-09-12T10:00:00+00:00","updated_at":"2026-07-14T17:07:20.712151+00:00","url":"https://www.mikebild.dev/de/blog/websockets-nicht-immer-antwort/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/4956c7709bd3815b187c28deb84429743f9e504e9346e6cfc0efae16ccaa9875/websockets-nicht-immer-antwort-vorlesen.mp3","audio_duration_secs":638,"text":"# WebSockets sind nicht immer die Antwort\n\nEin Dashboard, das neue Bestellungen anzeigt. Eine Benachrichtigung, wenn der Build durchgelaufen ist. Ein Fortschrittsbalken für einen Import, der zwanzig Minuten braucht. Drei typische „Echtzeit“-Anforderungen – und in allen drei Fällen fließen die Daten ausschließlich in eine Richtung: vom Server zum Client. Trotzdem lautet die erste technische Antwort darauf erstaunlich oft: WebSockets, socket.io, eine persistente bidirektionale Verbindung.\n\nDer Reflex „Echtzeit gleich WebSocket“ sitzt tief, und er ist verständlich. WebSockets sind das prominenteste Werkzeug im Regal, jede zweite Tutorial-Serie baut damit einen Chat. Nur: Ein Chat ist bidirektional. Ein Bestell-Dashboard ist es nicht. Wer für reines Server-zu-Client-Push die schwere Maschinerie anwirft, bezahlt für Fähigkeiten, die er nie abruft – und der Preis ist nicht null.\n\n## Was „Echtzeit“ im Anforderungstext wirklich bedeutet\n\nNimmt man die Anforderung ernsthaft auseinander, steht dort selten „Client und Server tauschen fortlaufend Messages in beide Richtungen aus“. Dort steht: Der Nutzer soll etwas sehen, sobald es passiert, ohne F5 zu drücken. Das ist Benachrichtigung, nicht Konversation. Der Client redet weiterhin über gewöhnliche Requests mit dem Server – er klickt, er speichert, er lädt nach. Neu ist nur, dass der Server von sich aus etwas sagen darf.\n\nGanz nebenbei: Für manche dieser Fälle reicht sogar simples Polling. Ein Fortschrittsbalken, der alle zwei Sekunden einen GET absetzt, ist keine elegante Lösung, aber eine, die jeder im Team versteht, die jeder Cache und jeder Proxy kennt und die sich in einer Minute wegwerfen und ersetzen lässt. Die Frage ist also nicht nur „WebSocket oder nicht“, sondern wie viel Maschinerie die Anforderung überhaupt rechtfertigt.\n\nMir ist das in einem Shop-Projekt in diesem Frühjahr deutlich geworden. Das Team hatte für ein Auftrags-Dashboard socket.io eingebaut, und die Verbindung selbst war nie das Problem. Das Problem war alles drumherum: Nach jedem Deployment hingen Clients an toten Verbindungen, bis der selbstgebaute Reconnect griff. Der Load-Balancer brauchte Sonderbehandlung für das Protokoll-Upgrade. Und wenn ein Browser dreißig Sekunden offline war, fehlten genau die Bestellungen aus diesen dreißig Sekunden – das Wiederaufsetzen beim letzten bekannten Stand hatte schlicht niemand gebaut, weil das Protokoll es nicht mitbringt.\n\n## Der Preis einer WebSocket-Verbindung\n\nEin WebSocket beginnt als HTTP-Request, verlässt HTTP aber nach dem Upgrade-Handshake und wird zu einem eigenen Protokoll (RFC 6455) auf einer rohen TCP-Verbindung. Ab diesem Moment gilt nichts mehr von dem, was die HTTP-Welt an Infrastruktur und Semantik mitbringt. Konkret kauft man sich ein:\n\n- Verbindungs-State-Management auf dem Server: Wer ist verbunden, seit wann, mit welcher Session?\n- Eigene Heartbeats, denn tote TCP-Verbindungen fallen nicht von allein auf – Ping/Pong ist Handarbeit oder Bibliotheks-Feature, aber immer Teil der eigenen Verantwortung.\n- Reconnect-Logik im Client, inklusive Backoff und der Frage, was während der Funkstille verpasst wurde.\n- Sonderfälle in der Infrastruktur: Proxies, Load-Balancer und Firmen-Firewalls, die das Upgrade nicht kennen oder lange stille Verbindungen kappen.\n\nNichts davon ist unlösbar. Bibliotheken wie socket.io nehmen einem vieles ab, genau deshalb existieren sie. Aber es bleibt Komplexität, die betrieben, überwacht und im Fehlerfall verstanden werden will. Für einen Kanal, der nur in eine Richtung sendet, ist das ein schlechter Tausch.\n\n```javascript\nconst WebSocket = require('ws')\nconst server = new WebSocket.Server({ port: 8080 })\n\nserver.on('connection', socket => {\n  socket.isAlive = true\n  socket.on('pong', () => { socket.isAlive = true })\n})\n\n// dead connections are not detected for free – ping/pong is on us\nsetInterval(() => {\n  server.clients.forEach(socket => {\n    if (!socket.isAlive) return socket.terminate()\n    socket.isAlive = false\n    socket.ping()\n  })\n}, 30000)\n```\n\nDas ist nur der Heartbeat. Reconnect, Nachrichtenpuffer und das Wiederaufsetzen nach einer Unterbrechung stehen auf einem anderen Blatt – und auf dem steht in den meisten Projekten, die ich gesehen habe, erstaunlich wenig.\n\n## Server-Sent Events: Push über gewöhnliches HTTP\n\nServer-Sent Events sind das unspektakuläre Gegenstück: ein ganz normaler HTTP-GET-Request, dessen Response nie endet. Der Server hält die Verbindung offen und schreibt Events als Text hinein, der Browser konsumiert sie über die `EventSource`-API. Kein Protokollwechsel, kein Upgrade, kein neues Vokabular für die Infrastruktur. Ein SSE-Endpoint in Express ist ein paar Zeilen:\n\n```javascript\nconst express = require('express')\nconst app = express()\n\nlet nextEventId = 0\nconst eventLog = []\nconst clients = []\n\napp.get('/events', (req, res) => {\n  res.set({\n    'Content-Type': 'text/event-stream',\n    'Cache-Control': 'no-cache',\n    Connection: 'keep-alive'\n  })\n  res.flushHeaders()\n\n  // replay everything the client missed while it was offline\n  const lastEventId = Number(req.get('Last-Event-ID') || 0)\n  eventLog\n    .filter(event => event.id > lastEventId)\n    .forEach(event => res.write(toMessage(event)))\n\n  clients.push(res)\n  req.on('close', () => clients.splice(clients.indexOf(res), 1))\n})\n\nfunction broadcast(data) {\n  const event = { id: ++nextEventId, data }\n  eventLog.push(event)\n  clients.forEach(res => res.write(toMessage(event)))\n}\n\nfunction toMessage({ id, data }) {\n  return `id: ${id}\\ndata: ${JSON.stringify(data)}\\n\\n`\n}\n\napp.listen(3000)\n```\n\nDer Client ist noch kürzer – und das ist der eigentliche Punkt:\n\n```javascript\nconst source = new EventSource('/events')\n\nsource.onmessage = event => {\n  const order = JSON.parse(event.data)\n  renderOrder(order)\n}\n\n// no reconnect code here: EventSource reconnects on its own\n// and sends the Last-Event-ID header with every new attempt\n```\n\nDer Kommentar im Client-Code ist keine Behauptung, sondern Spezifikation. Reißt die Verbindung ab, verbindet sich `EventSource` selbstständig neu – die Wartezeit kann der Server sogar per `retry:`-Feld im Stream vorgeben. Und beim Wiederverbinden schickt der Browser automatisch den Header `Last-Event-ID` mit der ID des letzten empfangenen Events mit. Der Server kann damit exakt dort weitermachen, wo der Client stehengeblieben ist. Genau das Feature, das im Shop-Projekt so schmerzhaft fehlte, ist hier Teil des Protokolls.\n\n```mermaid\nsequenceDiagram\n    participant B as Browser (EventSource)\n    participant S as Server (Express)\n    B->>S: GET /events\n    S-->>B: Event 41 (Bestellung A-1041)\n    S-->>B: Event 42 (Bestellung A-1042)\n    Note over B,S: Verbindung bricht ab<br/>(Deployment, Funkloch, Proxy-Timeout)\n    B->>S: GET /events mit Header Last-Event-ID 42\n    S-->>B: Event 43 (alles seit 42 wird nachgeliefert)\n```\n\nDazu kommt ein Vorteil, den man erst im Betrieb zu schätzen lernt: Der gesamte Kanal ist gewöhnliches HTTP. Load-Balancer routen ihn wie jeden anderen Request, Authentifizierung läuft über dieselben Header und Cookies wie der Rest der Anwendung, und Debugging braucht kein Spezialwerkzeug:\n\n```bash\n$ curl -N http://localhost:3000/events\nid: 1\ndata: {\"orderId\":\"A-1041\",\"total\":89.9}\n\nid: 2\ndata: {\"orderId\":\"A-1042\",\"total\":24.5}\n```\n\nWer schon einmal versucht hat, einen WebSocket-Frame-Mitschnitt gemeinsam mit einem Kollegen aus dem Betrieb durchzugehen, weiß, was dieser eine curl-Aufruf wert ist. Der Stream ist lesbarer Text, jedes Event trägt seine ID, und dieselbe Ausgabe sieht auch der Browser.\n\n## Wo SSE ehrlich an Grenzen stößt\n\nDamit das keine Werbeveranstaltung wird: Server-Sent Events haben Grenzen, und die gehören auf den Tisch, bevor die Entscheidung fällt.\n\nDer Kanal ist strikt unidirektional. Will der Client etwas sagen, macht er das über einen normalen POST – für Formulare, Klicks und Kommandos ist das völlig in Ordnung und ohnehin der natürliche Weg, für einen hochfrequenten Rückkanal ist es keiner. Zweitens: Internet Explorer und Edge kennen `EventSource` bis heute nicht, dort braucht es ein Polyfill. Die verfügbaren Polyfills funktionieren ordentlich, aber es ist ein Baustein mehr, den man einplanen muss. Drittens teilt sich SSE unter HTTP/1.1 das Browser-Limit von ungefähr sechs Verbindungen pro Host – wer pro Tab mehrere Streams öffnet, rennt dagegen. Unter HTTP/2 entspannt sich das deutlich, weil alle Streams über eine einzige multiplexte Verbindung laufen. Und schließlich: Puffernde Proxies muss man gelegentlich per Konfiguration davon überzeugen, den Stream sofort durchzureichen statt ihn zu sammeln – das ist aber eine Zeile nginx-Konfiguration, kein Architekturproblem.\n\n## GraphQL-Subscriptions: derselbe Reflex, ein Stockwerk höher\n\nInteressant wird es, wenn der Reflex in Frameworks einzieht. Im Apollo-Ökosystem laufen GraphQL-Subscriptions standardmäßig über `subscriptions-transport-ws`, also über WebSockets. Dabei sind Subscriptions das Lehrbuchbeispiel für unidirektionalen Datenfluss: Der Client meldet einmal an, was ihn interessiert, und ab dann redet nur noch der Server. Queries und Mutations gehen ohnehin über HTTP. Die bidirektionale Fähigkeit des Transports wird für einen einzigen Handshake benutzt – danach liegt sie brach, während ihre Betriebskosten bleiben.\n\nDas hat mich in diesem Frühjahr genug beschäftigt, um es auszuprobieren: `subscriptions-transport-sse` ist meine API-kompatible SSE-Variante dieses Transports, entstanden in meiner GitHub-Organisation CodeCommission. Server-seitig hängt sich der `SubscriptionServer` an eine Express-App und den `SubscriptionManager` aus `graphql-subscriptions`, client-seitig wird der `SubscriptionClient` wie gewohnt an das Network-Interface von Apollo gehängt:\n\n```javascript\nimport { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-sse'\n\nconst httpClient = createNetworkInterface({ uri: 'https://example.com/graphql' })\nconst sseClient = new SubscriptionClient('https://example.com/subscriptions')\nconst apolloClient = new ApolloClient({\n  networkInterface: addGraphQLSubscriptions(httpClient, sseClient)\n})\n\napolloClient.subscribeToMore({\n  document: gql`\n    subscription onOrderCreated {\n      orderCreated {\n        id\n        total\n      }\n    }`,\n  updateQuery: (prev, { subscriptionData }) => {\n    // merge the new order into the store and return the new state\n  }\n})\n```\n\nAus Sicht der Anwendung ändert sich nichts – dieselbe Subscription, dasselbe `subscribeToMore`. Nur der Transport darunter ist jetzt gewöhnliches HTTP mit allem, was oben beschrieben ist: automatischer Reconnect, `Last-Event-ID`, curl-Debugging. Als Praxistest habe ich im April eine kleine Presence-List damit gebaut – wer ist gerade online, React und Apollo im Frontend, Node im Backend, Events über SSE. Beides sind bewusst schlanke Projekte, eher Beleg als Produkt. Es ging mir darum zu zeigen, dass „GraphQL-Subscriptions brauchen WebSockets“ eine Konvention ist, keine Notwendigkeit.\n\n## Wann WebSockets die richtige Antwort sind\n\nNach so viel Gegenrede die andere Seite, denn es gibt sie. WebSockets sind die richtige Wahl, wenn tatsächlich beide Seiten fortlaufend und mit niedriger Latenz senden:\n\n- Kollaboratives Editieren, bei dem Tastenanschläge und Operationen beider Seiten zusammenlaufen\n- Cursor-Positionen und Präsenz-Signale, die viele Male pro Sekunde in beide Richtungen fließen\n- Spiele und Simulationen, in denen jede Runde Client-Eingaben gegen Server-Zustand abgeglichen wird\n- Frontends, bei denen der Overhead eines eigenen POST pro Client-Message wirklich ins Gewicht fällt\n\nDer gemeinsame Nenner: Der Rückkanal ist kein gelegentliches Kommando, sondern ein Strom. Dann lohnt sich das Protokoll, und dann ist auch die Betriebskomplexität gerechtfertigt – man nutzt ja, was man bezahlt. Die Entscheidungsfrage ist deshalb nicht „Brauchen wir Echtzeit?“, sondern „Wohin fließen die Daten, und wie oft?“.\n\n```mermaid\nflowchart TD\n    A[Anforderung: Echtzeit] --> B{Fließen Daten fortlaufend<br/>in beide Richtungen?}\n    B -- nein --> C[Server-Sent Events<br/>plus normale HTTP-Requests]\n    B -- ja --> D{Ist der Rückkanal ein Strom<br/>mit Latenzanforderung?}\n    D -- nein --> C\n    D -- ja --> E[WebSockets –<br/>Betriebskosten einplanen]\n```\n\nWer diese zwei Fragen ehrlich beantwortet, landet nach meiner Erfahrung in der großen Mehrheit der Fälle links im Diagramm. Das Auftrags-Dashboard, der Build-Monitor, der Import-Fortschritt, die Benachrichtigungsglocke oben rechts in der Anwendung – alles Fälle für SSE. Der Editor mit den Live-Cursorn der Kollegen ist der seltene, echte Fall für die rechte Seite.\n\n## Unterm Strich\n\nAus dem Shop-Projekt und den beiden SSE-Experimenten nehme ich vor allem eine Beobachtung mit: Die Kosten einer Technologie stecken selten dort, wo ihre Stärken beworben werden – sie stecken im Betrieb, im Debugging und in den Fehlerfällen, die das Protokoll nicht von sich aus abdeckt. WebSockets können etwas, das SSE nicht kann, und wenn man dieses Etwas braucht, sind sie konkurrenzlos. Aber „Echtzeit“ im Anforderungstext ist noch kein Beleg dafür, dass man es braucht. Meistens will da nur ein Server etwas mitteilen, und dafür reicht ein HTTP-Request, der nie endet – mit eingebautem Reconnect, eingebautem Wiederaufsetzen und einem Debugging-Erlebnis, das aus einem einzigen curl-Aufruf besteht.\n\nDie langweiligere Technik gewinnt hier nicht trotz, sondern wegen ihrer Langeweile. Sie hat weniger bewegliche Teile – und jedes bewegliche Teil, das man gar nicht erst einbaut, kann nachts um drei nicht kaputtgehen.\n\n## Weiterführende Quellen\n\n- [subscriptions-transport-sse auf GitHub](https://github.com/CodeCommission/subscriptions-transport-sse) – GraphQL-Subscriptions über Server-Sent Events, API-kompatibel zu subscriptions-transport-ws\n- [graphql-subscriptions-sse-presence-list auf GitHub](https://github.com/MikeBild/graphql-subscriptions-sse-presence-list) – Presence-List-Beispiel mit React, Apollo und SSE\n- [Server-Sent Events in der HTML-Spezifikation (WHATWG)](https://html.spec.whatwg.org/multipage/server-sent-events.html)\n- [EventSource-API auf MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)\n- [RFC 6455 – The WebSocket Protocol](https://tools.ietf.org/html/rfc6455)"},{"locale":"de","translation_key":"knockoutjs-observables-computed-vor-signals","slug":"knockoutjs-observables-computed-vor-signals","title":"KnockoutJS: fein-granulare Reaktivität mit Observables und Computed","summary":"Wie KnockoutJS Reaktivität löst: Observables als get/set-Funktionen, Computed mit automatischem Dependency-Tracking und gezielte DOM-Updates statt globalem Baum-Vergleich.","tags":["Software","Frontend"],"published_at":"2017-08-22T10:00:00+00:00","updated_at":"2026-07-13T09:59:11.759377+00:00","url":"https://www.mikebild.dev/de/blog/knockoutjs-observables-computed-vor-signals/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/96fac8afe29d45c9c7651ba5fd19f30f1dd3ca2ff441e0b0301ab501196a3559/knockoutjs-observables-computed-vor-signals-vorlesen.mp3","audio_duration_secs":712,"text":"Drei Funktionen genügen, um in KnockoutJS eine ganze Oberfläche reaktiv zu halten: `ko.observable`, `ko.observableArray` und `ko.computed`. Keine davon nimmt eine Abhängigkeitsliste entgegen. Trotzdem weiß Knockout nach dem ersten Durchlauf, welcher Wert an welcher Stelle im DOM hängt. Es liest die Abhängigkeiten aus dem tatsächlichen Programmablauf ab.\n\n**Redaktionelle Einordnung (Juli 2026):** Dieser Beitrag erklärt KnockoutJS als historischen Vorläufer heutiger fein-granularer Reaktivität. Ich empfehle damit nicht, 2026 ein neues Frontend auf Knockout aufzubauen. Interessant geblieben ist die Mechanik: Abhängigkeiten beim Lesen erfassen und nur die betroffenen Stellen aktualisieren.\n\nKnockout koppelt das DOM über Bindings wie `text`, `value`, `foreach` und `click` deklarativ an ein ViewModel. Hier schaue ich eine Ebene tiefer: Wie merkt Knockout, dass sich etwas geändert hat, und wie findet es heraus, welche Stellen der Oberfläche davon betroffen sind? Der Kern dieser Mechanik heißt Observables und Computed.\n\n## Ein Observable ist eine Funktion – keine Eigenschaft\n\nDer erste gedankliche Sprung, den man bei Knockout machen muss, ist dieser: Ein Observable ist in KnockoutJS keine Eigenschaft, sondern eine Funktion. Genauer gesagt eine Funktion, die gleichzeitig Getter und Setter ist. Rufe ich sie ohne Argument auf, lese ich den Wert. Rufe ich sie mit einem Argument auf, schreibe ich den Wert – und Knockout benachrichtigt alle, die an diesem Wert interessiert sind.\n\n```js\nvar name = ko.observable('Bob');\n\nname();          // read  -> 'Bob'\nname('Mary');    // write -> sets the value and notifies subscribers\nname();          // read  -> 'Mary'\n```\n\nDas ist der ganze Trick. Kein `Object.defineProperty`, kein Proxy, keine Compiler-Magie. Nur eine Funktion, die sich merkt, wer sie gelesen hat und wer benachrichtigt werden will. Das Schreiben ist übrigens chainbar, weil der Setter das ViewModel zurückgibt:\n\n```js\nviewModel.name('Mary').age(50);\n```\n\nFür Listen gibt es die passende Variante. Ein `ko.observableArray` verhält sich beim Lesen wie ein Observable – `arr()` liefert das dahinterliegende Array – bringt aber zusätzlich Mutations-Methoden mit, die das Tracking auslösen:\n\n```js\nvar todos = ko.observableArray([]);\n\ntodos();                 // read -> the current array\ntodos.push({ title: 'Buy milk' });\ntodos.remove(someItem);\ntodos.removeAll();\n```\n\nHier lauert schon der erste Fallstrick, auf den ich später zurückkomme: Diese `push`-, `remove`- und `splice`-Methoden sind Knockout-eigene Wrapper. Sie sind es, die eine Benachrichtigung auslösen. Wer stattdessen `todos().push(x)` schreibt, greift am rohen Array vorbei und Knockout bekommt von der Änderung nichts mit.\n\n## Computed leitet ab – und verfolgt automatisch, was es liest\n\nJetzt kommt der eigentlich interessante Teil. Selten will man einen Wert nur speichern und wieder ausgeben. Meistens braucht man abgeleitete Werte: die Summe eines Warenkorbs, den vollständigen Namen aus Vor- und Nachname, die Anzahl offener Aufgaben. Dafür gibt es `ko.computed`.\n\n```js\nvar firstName = ko.observable('Mike');\nvar lastName  = ko.observable('Bild');\n\nvar fullName = ko.computed(function () {\n  return firstName() + ' ' + lastName();\n});\n\nfullName();            // 'Mike Bild'\nfirstName('Michael');\nfullName();            // 'Michael Bild'\n```\n\nUnd hier passiert etwas, das ich mir beim ersten Kontakt mit Knockout selbst zweimal angeschaut habe, weil es der Dreh- und Angelpunkt des ganzen Modells ist. Ich habe Knockout nirgends gesagt, dass `fullName` von `firstName` und `lastName` abhängt. Ich habe keine Abhängigkeitsliste deklariert. Knockout hat das selbst herausgefunden.\n\nWie? Beim ersten Ausführen der Evaluator-Funktion beobachtet Knockout, welche Observables tatsächlich gelesen werden. `firstName()` und `lastName()` melden sich in diesem Moment gewissermaßen an: „Dieses Computed liest gerade mich.“ Knockout registriert daraufhin eine Subscription. Der Dependency-Graph entsteht damit zur Laufzeit, allein durchs Ausführen – deklariert wird nichts. Das ist das fein-granulare, automatische Dependency-Tracking, das Knockout ausmacht.\n\nDer Evaluator läuft dabei nicht nur einmal. Er wird sofort bei der Erstellung einmal ausgeführt, und danach jedes Mal neu, wenn sich eine seiner gelesenen Abhängigkeiten ändert. Wichtig ist der zweite Teil: Bei jeder Neuauswertung ermittelt Knockout die Abhängigkeiten frisch. Das erlaubt dynamische Abhängigkeiten hinter Bedingungen:\n\n```js\nvar showFullName = ko.observable(true);\n\nvar displayName = ko.computed(function () {\n  if (showFullName()) {\n    return firstName() + ' ' + lastName();\n  }\n  return firstName();\n});\n```\n\nSolange `showFullName` auf `true` steht, hängt `displayName` von drei Observables ab. Steht es auf `false`, wird `lastName()` gar nicht mehr gelesen – und Knockout entfernt diese Abhängigkeit beim nächsten Lauf automatisch wieder. Eine Änderung an `lastName` löst dann keine Neuauswertung mehr aus. Genau das meint „dynamisch“: Der Graph passt sich dem tatsächlichen Kontrollfluss an.\n\nAls Graph gezeichnet sieht dieser Zusammenhang so aus:\n\n```mermaid\ngraph LR\n  A[firstName<br/>observable] --> C[fullName<br/>computed]\n  B[lastName<br/>observable] --> C\n  C --> D[text-binding<br/>DOM]\n```\n\nDie Pfeile bedeuten „wird gelesen von und benachrichtigt“. Ändert sich `firstName`, wandert die Benachrichtigung entlang der Kante zu `fullName`, das sich neu berechnet, und von dort weiter zum Text-Binding im DOM. Nur dieser eine Pfad wird aktiv. Nichts anderes im Baum wird angefasst.\n\nFür den Werkzeugkasten reicht fürs Erste dieses kleine Trio:\n\n- `ko.observable(value)` – ein einzelner reaktiver Wert, gelesen mit `obs()`, geschrieben mit `obs(newValue)`.\n- `ko.observableArray([...])` – eine reaktive Liste mit Mutations-Methoden wie `push`, `remove` und `splice`, die Bindings benachrichtigen.\n- `ko.computed(fn)` – ein abgeleiteter Wert, der automatisch verfolgt, welche Observables er liest, und sich bei deren Änderung neu berechnet.\n\n## Vom ViewModel ins DOM: die Todos-App\n\nDamit das nicht abstrakt bleibt, hier eine kleine Todos-Anwendung. Sie zeigt alle drei Bausteine im Zusammenspiel.\n\n```js\nfunction TodoViewModel() {\n  var self = this;\n\n  self.todos = ko.observableArray([]);\n  self.newTodo = ko.observable('');\n\n  self.remaining = ko.computed(function () {\n    return self.todos().filter(function (t) {\n      return !t.done();\n    }).length;\n  });\n\n  self.addTodo = function () {\n    self.todos.push({\n      title: self.newTodo(),\n      done: ko.observable(false)\n    });\n    self.newTodo('');\n  };\n}\n\nko.applyBindings(new TodoViewModel());\n```\n\nEin paar Dinge sind hier bewusst so gebaut. `self.todos` ist ein `observableArray`, `self.newTodo` ein einfaches Observable für das Eingabefeld. `self.remaining` ist ein Computed, das die noch offenen Aufgaben zählt. Es liest `self.todos()` und pro Eintrag `t.done()` – und damit hängt es sowohl an der Liste als auch an jedem einzelnen `done`-Observable. Fügt man ein Todo hinzu oder hakt eines ab, rechnet `remaining` von selbst neu.\n\nBeachtenswert ist, dass jedes einzelne Todo ein eigenes `done: ko.observable(false)` bekommt. Nur so ist der Erledigt-Status pro Eintrag reaktiv. Ein reines `done: false` wäre ein toter Wert, an dem sich nichts beobachten ließe.\n\nDie View koppelt das ViewModel deklarativ ans DOM. Hier der relevante Ausschnitt:\n\n```html\n<input data-bind=\"value: newTodo\" />\n<button data-bind=\"click: addTodo\">Add</button>\n\n<ul data-bind=\"foreach: todos\">\n  <li data-bind=\"text: title\"></li>\n</ul>\n\n<span data-bind=\"text: remaining\"></span> remaining\n```\n\n`ko.applyBindings` aktiviert diese Verknüpfungen einmalig beim Start. Ab da läuft alles über das Tracking: Tippt der Nutzer ins Feld, aktualisiert das `value`-Binding `newTodo`. Ein Klick auf den Button ruft `addTodo` auf, das per `push` die Liste verändert. Diese Änderung benachrichtigt das `foreach`-Binding (neuer Listeneintrag) und das Computed `remaining` (Neuberechnung), das wiederum das `text`-Binding im `<span>` aktualisiert. Jede dieser Aktualisierungen trifft gezielt genau die Stelle, die betroffen ist.\n\n## Warum gezieltes Tracking ein anderes Modell ist\n\nAn diesem Punkt lohnt sich die Abgrenzung, die dem Ganzen erst Kontur gibt. Es gibt einen zweiten, sehr verbreiteten Ansatz für dasselbe Problem: das Virtual-DOM-Diffing, wie man es etwa von React kennt. Dort baut man bei jeder Änderung einen neuen virtuellen Baum, vergleicht ihn mit dem alten und wendet die Differenz aufs echte DOM an. Das Framework weiß nicht von vornherein, welche Datenänderung welche DOM-Stelle betrifft – es rechnet den Unterschied nachträglich aus.\n\nKnockout geht den umgekehrten Weg. Durch das fein-granulare Tracking weiß es pro Observable exakt, welche Computed und welche Bindings davon abhängen. Es muss nichts vergleichen. Ändert sich ein Wert, folgt Knockout einfach den registrierten Kanten des Dependency-Graphen und aktualisiert nur die dort hängenden DOM-Stellen. Kein Baum-Vergleich, kein Neu-Rendern von Teilbäumen, die sich gar nicht geändert haben.\n\nDie Sequenz einer einzelnen Änderung sieht so aus:\n\n```mermaid\nsequenceDiagram\n  participant U as User\n  participant O as observable\n  participant C as computed\n  participant D as DOM-Binding\n  U->>O: obs(newValue)\n  O->>C: notify subscriber\n  C->>C: re-evaluate\n  C->>D: gezieltes text-Update\n```\n\nBeide Modelle haben ihre Berechtigung, und ich möchte keines zum Sieger erklären. Aber wer den Unterschied einmal an dieser Stelle verstanden hat, versteht auch, warum die beiden Welten sich so unterschiedlich anfühlen. Knockouts Ansatz ist unmittelbar nachvollziehbar, weil man den Graphen im Code fast sehen kann. Der Preis dafür ist die Disziplin: Man muss konsequent mit Observables arbeiten, sonst reißt der Graph an einer Stelle ab.\n\n## Fallstricke aus der Praxis\n\nGenau an dieser Disziplin reißt der Graph gern, und zwar an drei wiederkehrenden Stellen. Alle drei haben mich in eigenen Projekten schon Stunden gekostet, weil sie stillschweigend danebengehen.\n\nDer Klassiker sind vergessene Klammern. Ein Observable ist eine Funktion. Wer sie ohne Klammern verwendet, arbeitet mit der Funktion selbst statt mit ihrem Wert:\n\n```js\n// wrong: todo.done is the function itself, so always truthy\nif (todo.done) {\n  // this branch ALWAYS runs\n}\n\n// correct: todo.done() reads the value\nif (todo.done()) {\n  // ...\n}\n```\n\nDer Fehler ist tückisch, weil er keinen Fehler wirft. Eine Funktion ist truthy, also läuft die Bedingung schlicht immer ins gleiche Ergebnis. Man sucht dann lange an der falschen Stelle. Zum Lesen gehören immer Klammern, ohne Ausnahme.\n\nDer zweite Fallstrick sind die nativen Array-Methoden. Ich hatte es oben angedeutet:\n\n```js\n// wrong: mutates the raw array without notification\ntodos().push(newItem);\n\n// correct: KO wrapper, notifies dependent bindings\ntodos.push(newItem);\n```\n\n`todos()` liefert das darunterliegende JavaScript-Array. Dessen natives `push` verändert zwar den Inhalt, aber Knockout erfährt nichts davon – das `foreach`-Binding bleibt stehen. Der KO-Wrapper `todos.push` hingegen löst das Tracking aus. Der Unterschied liegt einzig in den Klammern vor dem `.push`, was den Fehler wieder unangenehm subtil macht.\n\nDer dritte betrifft den `this`-Kontext in Computed. Wenn der Evaluator auf das ViewModel zugreifen will, muss `this` auch wirklich aufs ViewModel zeigen:\n\n```js\nfunction ViewModel() {\n  this.price = ko.observable(10);\n  this.count = ko.observable(3);\n\n  // wrong: this does not reliably point to the ViewModel here\n  this.total = ko.computed(function () {\n    return this.price() * this.count();   // this.price is undefined\n  });\n}\n```\n\nDer Evaluator wird von Knockout in einem anderen Kontext aufgerufen, sodass `this` nicht auf die Instanz zeigt. Es gibt zwei etablierte Auswege. Entweder man reicht den Kontext als zweites Argument nach:\n\n```js\nthis.total = ko.computed(function () {\n  return this.price() * this.count();\n}, this);   // second argument binds this\n```\n\nOder man verwendet das `self`-Muster, das ich im Todos-Beispiel schon genutzt habe:\n\n```js\nfunction ViewModel() {\n  var self = this;\n  self.price = ko.observable(10);\n  self.count = ko.observable(3);\n  self.total = ko.computed(function () {\n    return self.price() * self.count();\n  });\n}\n```\n\nIch bevorzuge in meinen Projekten das `self`-Muster, weil es durchgängig funktioniert – auch in Event-Handlern und Callbacks, nicht nur in Computed. Ein Muster für alles ist leichter zu merken als eine Sonderregel pro Fall.\n\nAm Rande sei noch `ko.pureComputed` erwähnt, das seit KO 3.2 zur Verfügung steht. Es verhält sich wie ein normales Computed, „schläft“ aber, solange niemand es abonniert, und spart so Neuberechnungen bei reinen Ableitungen ohne Side Effects. Für den Einstieg reicht `ko.computed`; sobald man merkt, dass ein rein ableitendes Computed unnötig oft rechnet, ist `pureComputed` die naheliegende Verbesserung.\n\n## Fazit\n\nWer den Kern von KnockoutJS verstanden hat, hält im Grunde nur drei Bausteine in der Hand: Observables als get/set-Funktionen, observableArrays für reaktive Listen und Computed für abgeleitete Werte. Das eigentlich Elegante liegt zwischen diesen Bausteinen: im automatischen Dependency-Tracking. Knockout beobachtet zur Laufzeit, welche Observables ein Computed liest, baut daraus einen Dependency-Graphen und aktualisiert bei jeder Änderung gezielt nur die betroffenen Stellen – neu ermittelt bei jedem Lauf, damit auch dynamische Abhängigkeiten hinter Bedingungen sauber abgebildet werden.\n\nDieses Modell steht bewusst quer zum Virtual-DOM-Diffing: Statt Bäume zu vergleichen, folgt Knockout den Kanten, die es beim Lesen selbst registriert hat. Das macht das Verhalten unmittelbar nachvollziehbar, verlangt aber Disziplin – Klammern zum Lesen, KO-Wrapper zum Mutieren von Listen, den richtigen `this`-Kontext im Computed. Sind diese drei Reflexe verinnerlicht, wird das Arbeiten mit Knockout überraschend ruhig. Man beschreibt, wovon ein Wert abhängt, und das Framework kümmert sich um den Rest. Genau diese Klarheit ist der Grund, warum ich Knockouts Reaktivitätsmodell nach wie vor für einen der besten Einstiege halte, um zu begreifen, was hinter reaktiven Oberflächen wirklich passiert.\n\n## Weiterführende Quellen\n\n- [Observables – KnockoutJS Documentation](https://knockoutjs.com/documentation/observables.html)\n- [Computed Observables – KnockoutJS Documentation](https://knockoutjs.com/documentation/computedObservables.html)\n- [How Dependency Tracking Works – KnockoutJS Documentation](https://knockoutjs.com/documentation/computed-dependency-tracking.html)\n- [Observable Arrays – KnockoutJS Documentation](https://knockoutjs.com/documentation/observableArrays.html)\n- [Pure Computed Observables – KnockoutJS Documentation](https://knockoutjs.com/documentation/computed-pure.html)"},{"locale":"de","translation_key":"pwa-weather-offline-feature","slug":"pwa-weather-offline-feature","title":"PWA Weather: offline ist ein Feature","summary":"Eine kleine Wetter-App als Progressive Web App zeigt, warum Offline-Verhalten eine Produktentscheidung ist und wie ehrlich eine Oberfläche mit veralteten Daten umgehen sollte.","tags":["Software","Architektur"],"published_at":"2017-08-12T10:00:00+00:00","updated_at":"2026-07-14T17:05:39.041102+00:00","url":"https://www.mikebild.dev/de/blog/pwa-weather-offline-feature/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/ee6e481ffd6af2d91ea7fba8a0294b6513d3a5114c8b59dde6ee9f9cad99ff8d/pwa-weather-offline-feature-vorlesen.mp3","audio_duration_secs":677,"text":"# PWA Weather: offline ist ein Feature\n\nU-Bahn zwischen zwei Stationen, kein Empfang. Die Wetter-App öffnet sich, zeigt kurz einen Ladekreisel und dann: nichts. Ein weißer Bildschirm. Dabei hätte die Wetterlage von heute Morgen völlig gereicht – die Frage war, ob der Schirm mit muss, nicht ob es in dieser Minute 21,3 oder 21,4 Grad hat. Die App hatte diese Daten sogar schon einmal geladen. Sie hat sie nur weggeworfen, weil niemand entschieden hat, dass sie ohne Netz etwas wert sind.\n\nDieser weiße Bildschirm ist kein technischer Defekt. Er ist das Ergebnis einer Nicht-Entscheidung. Irgendwo im Backlog stand vermutlich „Offline-Support“ als technisches Nice-to-have, hinter dem nächsten Feature und dem übernächsten Redesign. Genau das halte ich für den Denkfehler: Offline ist kein Add-on, das man später an eine fertige App schraubt. Offline ist ein Feature mit Produktfragen – was soll ohne Netz funktionieren, was ausdrücklich nicht, und wie ehrlich zeigt die Oberfläche den Zustand der Daten an.\n\n## Ein kleines Demo als Prüfstand\n\nUm das für mich selbst durchzuspielen, habe ich im April dieses Jahres ein kleines Repository angelegt: [pwa-weather-demo](https://github.com/MikeBild/pwa-weather-demo). Es ist bewusst kein Produkt, sondern eine Nachbau-Übung entlang von Googles Tutorial „Your First Progressive Web App“ – eine Wetterkarte pro Stadt, eine öffentliche Wetter-API dahinter, ein Service Worker davor. Lokal startet das Ganze mit einem simplen `http-server`, mehr Infrastruktur braucht es nicht. Der Wert liegt nicht im Funktionsumfang, sondern darin, dass man an einem überschaubaren Beispiel jede Entscheidung einzeln anfassen kann.\n\nUnd Entscheidungen gibt es mehr, als der Begriff „Caching“ vermuten lässt. Beim Durcharbeiten ist mir aufgefallen, dass die eigentliche Arbeit nicht im Service-Worker-Code steckt. Der ist nach einem Nachmittag geschrieben. Die Arbeit steckt in der Frage, welche Antwort die App einem Menschen ohne Netzverbindung schuldet.\n\n## Offline ist eine Produktfrage, keine Cache-Option\n\nFür die Wetter-App sieht meine Antwort so aus:\n\n- Die zuletzt geladene Wetterlage der gemerkten Städte wird angezeigt – immer, sofort, auch ohne Netz.\n- Die Oberfläche selbst (Layout, Icons, Schrift, Logik) lädt vollständig aus dem lokalen Cache.\n- Die Suche nach neuen Orten funktioniert offline nicht – und sagt das auch, statt einen Spinner drehen zu lassen.\n- Jede angezeigte Wetterkarte trägt einen Zeitstempel: „Stand: vor 2 Stunden“ statt stillschweigend alter Daten.\n\nDer dritte Punkt ist mir wichtig. Es wäre technisch möglich, auch Suchergebnisse zu cachen und offline irgendetwas anzuzeigen. Aber eine Ortssuche gegen einen zwei Tage alten Cache liefert keine Suche, sondern eine Attrappe. Nicht alles, was cachebar ist, gehört gecacht. Die Grenze verläuft entlang der Frage, ob eine veraltete Antwort noch eine ehrliche Antwort ist: Die Wetterlage von heute Morgen ist eine ehrliche, klar datierte Information. Ein Suchergebnis von vorgestern ist es nicht.\n\nDer vierte Punkt ist die zweite Hälfte derselben Entscheidung. Wer alte Daten anzeigt, ohne sie als alt zu kennzeichnen, lügt per Interface. Ein kleiner Zeitstempel verwandelt denselben Datensatz von einer potenziellen Falschinformation in eine brauchbare Auskunft. Das kostet eine Zeile UI und ein Datum – und es ist der Unterschied zwischen „die App zeigt irgendwas“ und „die App sagt mir, was sie weiß und wie sicher sie sich ist“.\n\n## Der Service Worker: ein Proxy mit Lifecycle\n\nTechnisch hängt das alles am Service Worker – einem Skript, das der Browser getrennt von der Seite ausführt und das als programmierbarer Proxy zwischen App und Netzwerk sitzt. Jede Anfrage der Seite läuft durch seinen `fetch`-Handler, und dort entscheidet Code statt Zufall, ob eine Antwort aus dem Netz, aus dem Cache oder aus einer Kombination von beidem kommt.\n\nWer zum ersten Mal damit arbeitet, stolpert weniger über die API als über den Lifecycle. Ein Service Worker wird registriert, installiert, wartet gegebenenfalls auf das Ende der alten Version und übernimmt erst dann die Kontrolle über die Seite:\n\n```mermaid\nflowchart LR\n  A[register] --> B[install<br/>App-Shell precachen]\n  B --> C[waiting<br/>alte Version läuft noch]\n  C --> D[activate<br/>alte Caches aufräumen]\n  D --> E[fetch<br/>Requests kontrollieren]\n```\n\nDie Registrierung selbst ist unspektakulär und gehört ans Ende des App-Starts:\n\n```js\n// app.js\nif ('serviceWorker' in navigator) {\n  navigator.serviceWorker\n    .register('/service-worker.js')\n    .then(function (registration) {\n      console.log('service worker registered, scope:', registration.scope);\n    })\n    .catch(function (error) {\n      console.error('service worker registration failed', error);\n    });\n}\n```\n\nDas `if` ist keine Formsache, sondern Teil der Architektur: In Browsern ohne Service Worker läuft die App einfach als normale Website weiter. Dazu später mehr, denn dieser Fall ist 2017 alles andere als exotisch.\n\nZwei Eigenheiten des Lifecycle haben mich im Demo tatsächlich Zeit gekostet. Erstens: Ein aktualisierter Service Worker übernimmt standardmäßig erst, wenn alle Tabs der alten Version geschlossen sind – wer beim Entwickeln nur neu lädt und sich wundert, warum der neue Code nicht greift, kämpft gegen `waiting`, nicht gegen einen Bug. Zweitens: Der `activate`-Schritt ist der richtige Ort, um alte Cache-Versionen zu löschen. Wer das auslässt, sammelt bei jedem Deployment einen weiteren Cache an und wundert sich Monate später über den Speicherverbrauch.\n\n## App-Shell: das Gerüst kommt immer aus dem Cache\n\nDie erste Cache-Entscheidung betrifft die App-Shell – also alles, was die Anwendung zum Anzeigen braucht, bevor auch nur ein Byte Wetterdaten da ist: HTML, CSS, JavaScript, Icons. Diese Dateien ändern sich nur mit einem Deployment, deshalb werden sie beim `install` einmal komplett in den Cache gelegt (Precache) und danach immer von dort ausgeliefert:\n\n```js\n// service-worker.js\nvar SHELL_CACHE = 'weather-shell-v1';\nvar DATA_CACHE = 'weather-data-v1';\n\nvar SHELL_FILES = [\n  '/',\n  '/index.html',\n  '/styles/app.css',\n  '/scripts/app.js',\n  '/images/icons/icon-192.png'\n];\n\nself.addEventListener('install', function (event) {\n  event.waitUntil(\n    caches.open(SHELL_CACHE).then(function (cache) {\n      return cache.addAll(SHELL_FILES);\n    })\n  );\n});\n\nself.addEventListener('activate', function (event) {\n  event.waitUntil(\n    caches.keys().then(function (keys) {\n      return Promise.all(\n        keys\n          .filter(function (key) {\n            return key !== SHELL_CACHE && key !== DATA_CACHE;\n          })\n          .map(function (key) {\n            return caches.delete(key);\n          })\n      );\n    })\n  );\n});\n```\n\nDie Versionsnummer im Cache-Namen ist das Deployment-Konzept in seiner einfachsten Form: neue Shell, neuer Name, alte Caches fliegen beim `activate` raus. Werkzeuge wie `sw-precache` generieren diesen Teil aus dem Build heraus, und mit Workbox ist gerade ein frischer Nachfolger erschienen, der die gängigen Strategien als Bibliothek mitbringt. Für das Demo habe ich es bewusst von Hand geschrieben – nicht aus Prinzip, sondern weil man eine Strategie erst dann guten Gewissens einem Generator überlassen sollte, wenn man sie einmal selbst formuliert hat.\n\n## Zwei Datenarten, zwei Strategien\n\nDie interessantere Entscheidung fällt im `fetch`-Handler, denn App-Shell und Wetterdaten brauchen entgegengesetzte Strategien. Die Shell soll so schnell wie möglich kommen und darf ruhig einen Deployment-Zyklus alt sein: Cache zuerst. Die Wetterdaten sollen so frisch wie möglich sein, und der Cache ist nur das Sicherheitsnetz für den U-Bahn-Moment: Netzwerk zuerst, mit der letzten bekannten Antwort als Rückfallebene.\n\n```mermaid\nflowchart TD\n  R[fetch-Event] --> Q{Pfad beginnt mit<br/>/api/weather?}\n  Q -- ja --> N[Netzwerk zuerst]\n  N -- Antwort ok --> C1[Kopie in weather-data-v1<br/>Antwort an die App]\n  N -- kein Netz --> C2[letzte bekannte Antwort<br/>aus dem Cache]\n  Q -- nein --> S[Cache zuerst:<br/>App-Shell]\n  S -- Treffer --> C3[sofort ausliefern]\n  S -- kein Treffer --> C4[ans Netzwerk durchreichen]\n```\n\nIm Code sieht diese Weiche so aus:\n\n```js\nself.addEventListener('fetch', function (event) {\n  var url = new URL(event.request.url);\n\n  if (url.pathname.indexOf('/api/weather') === 0) {\n    // network first, cached data as offline fallback\n    event.respondWith(\n      fetch(event.request)\n        .then(function (response) {\n          var copy = response.clone();\n          caches.open(DATA_CACHE).then(function (cache) {\n            cache.put(event.request, copy);\n          });\n          return response;\n        })\n        .catch(function () {\n          return caches.match(event.request);\n        })\n    );\n    return;\n  }\n\n  // app shell: cache first, network as fallback\n  event.respondWith(\n    caches.match(event.request).then(function (cached) {\n      return cached || fetch(event.request);\n    })\n  );\n});\n```\n\nEine Alternative für die Datenroute wäre Stale-while-revalidate: sofort die gecachte Antwort ausliefern und parallel im Hintergrund die frische holen, die dann beim nächsten Rendern bereitsteht. Für eine Wetter-App ist das eine legitime Wahl – die Anzeige erscheint augenblicklich, und die Aktualisierung trudelt nach. Ich habe mich im Demo trotzdem für Network-first entschieden, weil bei Wetterdaten die frische Antwort den Vorrang verdient, solange das Netz da ist. Der Punkt ist nicht, welche der beiden Strategien „richtig“ ist. Der Punkt ist, dass es eine Wahl mit sichtbaren Konsequenzen ist – und dass sie pro Route getroffen wird, nicht pauschal für die ganze App. Jake Archibalds Offline Cookbook buchstabiert diese Muster einzeln durch und ist dafür seit Jahren meine Referenz.\n\n## Der Datenstand gehört in die Oberfläche\n\nDamit aus „alte Daten anzeigen“ kein stilles Unterschieben wird, muss die App wissen, wie alt eine Antwort ist. Praktischerweise steckt diese Information bereits in der gecachten Response – der `Date`-Header der ursprünglichen Server-Antwort wird mitgespeichert:\n\n```js\n// show data age when rendering a cached response\ncaches.match('/api/weather?city=berlin').then(function (cached) {\n  if (!cached) {\n    return;\n  }\n  var fetchedAt = new Date(cached.headers.get('date'));\n  var ageInMinutes = Math.round((Date.now() - fetchedAt.getTime()) / 60000);\n  showLastUpdated(ageInMinutes); // \"Stand: vor 120 Minuten\"\n});\n```\n\nDas sind zehn Zeilen, und sie verändern den Charakter der App. Aus „warum zeigt die mir Sonnenschein, draußen regnet es“ wird „ah, das ist der Stand von heute Morgen“. In einem Projekt-Review würde ich diese zehn Zeilen höher gewichten als die gesamte Cache-Logik darunter – die Cache-Logik entscheidet, ob etwas angezeigt wird; diese Zeilen entscheiden, ob man dem Angezeigten trauen kann.\n\n## Manifest, HTTPS und der Home-Bildschirm\n\nZur PWA gehören neben dem Service Worker noch zwei Bausteine. Das Web App Manifest beschreibt, wie sich die App verhält, wenn sie auf dem Home-Bildschirm landet:\n\n```json\n{\n  \"name\": \"PWA Weather\",\n  \"short_name\": \"Weather\",\n  \"start_url\": \"/index.html\",\n  \"display\": \"standalone\",\n  \"background_color\": \"#3f51b5\",\n  \"theme_color\": \"#3f51b5\",\n  \"icons\": [\n    {\n      \"src\": \"images/icons/icon-192.png\",\n      \"sizes\": \"192x192\",\n      \"type\": \"image/png\"\n    }\n  ]\n}\n```\n\nChrome auf Android bietet bei Manifest plus registriertem Service Worker plus wiederholter Nutzung von sich aus „Zum Startbildschirm hinzufügen“ an – die App startet dann ohne Browser-Chrome, mit eigenem Icon, und fühlt sich erstaunlich nach installierter Anwendung an. Ob eine Seite die Kriterien erfüllt, prüft Lighthouse; der PWA-Audit meckert zuverlässig über fehlende Icons, fehlendes Offline-Verhalten der Startroute oder fehlendes HTTPS.\n\nHTTPS ist dabei keine Empfehlung, sondern Bedingung: Service Worker registrieren Browser ausschließlich über sichere Verbindungen (mit `localhost` als Entwicklungs-Ausnahme). Das ist auch gut so – ein Skript, das sämtliche Requests einer Domain abfangen und beantworten darf, will man nicht über eine manipulierbare Verbindung ausliefern.\n\n## Die ehrliche Grenze: Safari\n\nJetzt der Teil, der in vielen PWA-Artikeln dieses Jahres auffällig leise vorkommt: Safari hat keinen Service Worker. Weder auf dem Mac noch – und das wiegt schwerer – auf iOS. Chrome, Firefox und Opera unterstützen die API, bei Microsoft Edge ist sie in Arbeit, und im WebKit-Statusboard ist der Eintrag kürzlich immerhin auf „In Development“ gewandert. Aber Stand heute, August 2017, ist eine PWA auf einem iPhone schlicht eine normale Website: kein Offline-Cache, kein Abfangen von Requests, kein Install-Banner.\n\nDas ist kein Grund, die Sache zu lassen – aber es gehört zwingend in die Produktentscheidung, nicht in die Fußnote. Für das Wetter-Demo heißt das konkret: Die App muss ohne Service Worker vollständig funktionieren, nur eben ohne Offline-Komfort. Der Service Worker ist eine Verbesserungsschicht (Progressive Enhancement im ursprünglichen Wortsinn), keine Voraussetzung. Wer seine App so baut, dass sie ohne Service Worker bricht, hat auf iOS gar nichts. Wer sie so baut, dass der Service Worker Verhalten hinzufügt statt trägt, hat auf iOS eine ordentliche Website und auf Android eine App, die den U-Bahn-Moment übersteht.\n\nJe nach Zielgruppe verschiebt das die Rechnung erheblich. Bei einem Publikum mit hohem iOS-Anteil kauft man sich mit dem PWA-Aufwand heute vor allem bessere Ladezeiten über den Shell-Cache in Chrome und Firefox – auch nicht nichts, aber ein anderes Versprechen als „funktioniert offline“. Diese Rechnung sollte im Team offen auf dem Tisch liegen, bevor jemand „offline-fähig“ auf eine Folie schreibt.\n\n## Unterm Strich\n\nDie Technik hinter dem Demo ist überschaubar: ein Lifecycle, zwei Cache-Strategien, ein Manifest, HTTPS. Was hängen bleibt, ist etwas anderes. Der weiße Bildschirm in der U-Bahn entsteht nicht, weil Caching schwer wäre – er entsteht, weil „offline“ nie als Feature behandelt wurde, mit denselben Fragen wie jedes andere Feature: Was genau soll es können? Was bewusst nicht? Woran erkennt der Mensch davor, was gerade passiert?\n\nMeine Antworten für die Wetter-App – letzte bekannte Lage ja, Ortssuche nein, Zeitstempel immer – sind nicht universell. Eine Banking-App zieht die Grenze anders, ein Nachrichtenangebot wieder anders. Universell ist nur, dass diese Grenze gezogen werden muss, bevor der erste `fetch`-Handler entsteht. Der Service Worker führt eine Produktentscheidung aus. Er ersetzt sie nicht.\n\n## Weiterführende Quellen\n\n- Repository: [MikeBild/pwa-weather-demo](https://github.com/MikeBild/pwa-weather-demo)\n- Jake Archibald: [The Offline Cookbook](https://jakearchibald.com/2014/offline-cookbook/)\n- MDN: [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)\n- MDN: [Web App Manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest)"},{"locale":"de","translation_key":"tic-tac-toe-minimax-react","slug":"tic-tac-toe-minimax-react","title":"Tic-Tac-Toe mit Minimax in React","summary":"Ein unschlagbarer Tic-Tac-Toe-Gegner in React zeigt, warum Spiellogik als Pure Function nichts vom Rendering wissen darf – und warum immutable Züge zu Reacts Modell passen.","tags":["Software","Frontend"],"published_at":"2017-06-12T10:00:00+00:00","updated_at":"2026-10-23T14:29:51.128339+00:00","url":"https://www.mikebild.dev/de/blog/tic-tac-toe-minimax-react/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/274503e068b76603c53b31c7a4e3a3e2f49348bc217ccfa45a6320b755bc70b6/tic-tac-toe-minimax-react-vorlesen.mp3","audio_duration_secs":618,"text":"# Tic-Tac-Toe mit Minimax in React\n\n```js\nfunction score(board, depth) {\n  if (winnerOf(board) === COMPUTER) return 10 - depth;\n  if (winnerOf(board) === HUMAN) return depth - 10;\n  return 0;\n}\n```\n\nMehr Bewertung braucht ein unschlagbarer Tic-Tac-Toe-Gegner nicht. Ein Brett ist `10 - depth` wert, wenn der Rechner gewonnen hat, `depth - 10`, wenn der Mensch gewonnen hat, und null bei Remis. Die Suchtiefe im Wert sorgt nebenbei für Spielstil: Ein Sieg in zwei Zügen zählt mehr als einer in vier, eine Niederlage in vier Zügen ist weniger schlimm als eine in zwei. Der Gegner gewinnt also so früh wie möglich und verliert so spät wie möglich – falls er überhaupt verlieren kann, was bei fehlerfreiem Spiel nie eintritt.\n\nAuffälliger als das, was in der Funktion steht, ist das, was fehlt: kein React, kein DOM, kein Event-Handler, kein `this`, kein `setState`. Ein Brett geht hinein, eine Zahl kommt heraus. Genau darum geht es in diesem Artikel. Das Spiel selbst ist trivial, jedes Kind lernt es in fünf Minuten. Interessant ist die Schnittlinie: Der komplette Gegner ist ein Satz Pure Functions über einem Array, und React rendert am Ende nur noch State. Wer diese Linie nicht zieht, hat später weder testbare Logik noch eine austauschbare Oberfläche.\n\nDas zugehörige Repository `react-tic-tac-toe` habe ich im Oktober 2016 gebaut, angestoßen durch Carsten Königs Othello in Elm – ein Projekt, das mich damals beeindruckt hat, weil dort dieselbe Trennung ganz selbstverständlich war. In Elm gibt es schlicht keine andere Möglichkeit: Spiellogik ist eine Funktion, die View eine andere. In JavaScript muss man sich dafür entscheiden.\n\n## Das Brett ist ein Array, ein Zug ist ein neues Brett\n\nDie Datenstruktur ist so klein, wie sie klingt: ein Array mit neun Feldern, jedes Feld `'X'`, `'O'` oder `null`. Die Indizes 0 bis 8 laufen zeilenweise von links oben nach rechts unten. Gewinnbedingungen sind acht Linien über diesen Indizes – drei Zeilen, drei Spalten, zwei Diagonalen.\n\n```js\nconst HUMAN = 'X';\nconst COMPUTER = 'O';\n\nconst LINES = [\n  [0, 1, 2], [3, 4, 5], [6, 7, 8],\n  [0, 3, 6], [1, 4, 7], [2, 5, 8],\n  [0, 4, 8], [2, 4, 6],\n];\n\nfunction winnerOf(board) {\n  const line = LINES.find(([a, b, c]) =>\n    board[a] && board[a] === board[b] && board[a] === board[c]);\n  return line ? board[line[0]] : null;\n}\n\nfunction movesFor(board) {\n  return board.reduce((moves, field, index) =>\n    field === null ? moves.concat(index) : moves, []);\n}\n\nfunction applyMove(board, index, player) {\n  const next = board.slice();\n  next[index] = player;\n  return next;\n}\n```\n\nDie wichtigste Entscheidung steckt in `applyMove`: Ein Zug verändert das Brett nicht, er erzeugt ein neues. `board.slice()` kopiert das Array, dann wird ein Feld gesetzt, das Original bleibt unangetastet. Für neun Elemente kostet das nichts, und es zahlt sich gleich doppelt aus.\n\nErstens für die Suche. Minimax probiert Züge hypothetisch aus: Was wäre, wenn der Rechner auf Feld 4 setzt und der Mensch dann auf Feld 0? Mit Mutation müsste jeder probierte Zug nach der Bewertung wieder zurückgenommen werden – klassisches Do/Undo mit allen Gelegenheiten, den Undo-Teil zu vergessen. Mit immutable Brettern gibt es nichts zurückzunehmen. Jeder Ast des Spielbaums hält sein eigenes Brett, und wenn die Rekursion zurückkehrt, ist das alte Brett noch exakt das alte Brett.\n\nZweitens für React. `setState` mit einem frischen Array bedeutet: Wer wissen will, ob sich etwas geändert hat, vergleicht Referenzen statt Inhalte. Dass das offizielle React-Tutorial – ausgerechnet ebenfalls ein Tic-Tac-Toe – an derselben Stelle `slice()` empfiehlt, ist kein Zufall. immutable Daten sind die Währung, in der React denkt. Dass dieselbe Entscheidung gleichzeitig den Suchalgorithmus vereinfacht und das UI-Modell bedient, war für mich der eigentliche Aha-Moment an diesem kleinen Projekt.\n\n## Minimax, rekursiv erzählt\n\nDer Algorithmus ist älter als jedes Web-Framework und lässt sich in einem Satz fassen: Ich wähle den Zug, der mein Ergebnis maximiert, unter der Annahme, dass der Gegner danach den Zug wählt, der mein Ergebnis minimiert – und so weiter, bis das Spiel entschieden ist. Zwei Spieler, abwechselnd Maximum und Minimum, daher der Name.\n\n```js\nfunction minimax(board, player, depth) {\n  if (winnerOf(board) || movesFor(board).length === 0) {\n    return score(board, depth);\n  }\n\n  const values = movesFor(board).map(index =>\n    minimax(\n      applyMove(board, index, player),\n      player === COMPUTER ? HUMAN : COMPUTER,\n      depth + 1\n    ));\n\n  return player === COMPUTER ? Math.max(...values) : Math.min(...values);\n}\n\nfunction bestMove(board) {\n  const moves = movesFor(board);\n  const values = moves.map(index =>\n    minimax(applyMove(board, index, COMPUTER), HUMAN, 1));\n  return moves[values.indexOf(Math.max(...values))];\n}\n```\n\nDie Rekursion hat drei Bausteine, und alle drei stehen sichtbar im Code:\n\n- Der Abbruch: Hat jemand gewonnen oder ist kein Feld mehr frei, liefert `score` den Wert des Endzustands.\n- Der Schritt: Für jedes freie Feld entsteht per `applyMove` ein Folge-Brett, das mit vertauschtem Spieler und um eins erhöhter Tiefe bewertet wird.\n- Die Auswahl: Ist der Rechner am Zug, gewinnt das Maximum der Kindwerte, sonst das Minimum.\n\n`bestMove` ist dann nur noch die oberste Ebene dieser Suche, ausgeschrieben: alle eigenen Züge bewerten, den Index des besten zurückgeben. Ein kleiner Spielbaum zeigt, warum die Tiefe in der Bewertung den Unterschied zwischen einem korrekten und einem klugen Gegner ausmacht:\n\n```mermaid\ngraph TD\n  R[\"Brett, O am Zug<br/>nimmt das Maximum\"] --> A[\"Zug auf Feld 2 blockt<br/>X am Zug, nimmt das Minimum\"]\n  R --> B[\"Zug auf Feld 5<br/>O gewinnt sofort: Wert +9\"]\n  A --> A1[\"X erzwingt später den Sieg<br/>Wert -6\"]\n  A --> A2[\"Remis<br/>Wert 0\"]\n  A -.-> AV[\"Minimum: -6\"]\n  B -.-> BV[\"Blatt: +9\"]\n```\n\nDer Rechner steht hier vor der Wahl, eine gegnerische Reihe zu blocken oder selbst zu gewinnen. Ohne Tiefenbonus wären beide Siege gleich viel wert und die Wahl hinge von der Reihenfolge der Auswertung ab. Mit `10 - depth` ist der sofortige Sieg strikt besser – der Gegner spielt nicht nur fehlerfrei, sondern zielstrebig.\n\nZur Größenordnung: Von einem leeren Brett aus gibt es rund 255.000 mögliche Spielverläufe, mit jedem gesetzten Stein schrumpft der Baum drastisch. Ein Laptop bewertet das in Millisekunden, Optimierung ist rechnerisch unnötig. Im Repository steckt trotzdem eine Variante mit Alpha-Beta-Pruning, nicht-rekursiv formuliert – das war Neugier entlang der Elm-Vorlage, denn für Othello mit seinem 8×8-Brett ist Pruning keine Spielerei mehr, sondern Voraussetzung. Für den Artikel hier bleibe ich bewusst bei der rekursiven Grundform: Sie ist die Version, die man am Whiteboard herleiten kann, und [einfach schlägt elegant](https://www.mikebild.dev/de/blog/einfach-schlagen-elegant-statt-prozess/), solange die einfache Form messbar reicht.\n\n## React rendert nur noch State\n\nErst jetzt kommt React ins Spiel, und zwar mit einer betont langweiligen Rolle. Der gesamte Spielzustand ist `state.board`, und die einzige Stelle, an der sich dieser State ändert, ist der Klick-Handler. Der Handler orchestriert zwei Züge – den des Menschen, dann den Antwortzug des Rechners – und delegiert alles Inhaltliche an die Pure Functions von oben.\n\n```jsx\nclass Game extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { board: Array(9).fill(null) };\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick(index) {\n    const afterHuman = applyMove(this.state.board, index, HUMAN);\n    const finished =\n      winnerOf(afterHuman) || movesFor(afterHuman).length === 0;\n    const nextBoard = finished\n      ? afterHuman\n      : applyMove(afterHuman, bestMove(afterHuman), COMPUTER);\n    this.setState({ board: nextBoard });\n  }\n\n  render() {\n    return <Board board={this.state.board} onSquareClick={this.handleClick} />;\n  }\n}\n\nconst Board = ({ board, onSquareClick }) => (\n  <div className=\"board\">\n    {board.map((field, index) => (\n      <button\n        key={index}\n        disabled={field !== null || winnerOf(board) !== null}\n        onClick={() => onSquareClick(index)}\n      >\n        {field}\n      </button>\n    ))}\n  </div>\n);\n```\n\n`Board` ist eine zustandslose Functional Component: Brett rein, neun Buttons raus. `Game` ist eine React-15-Klasse mit genau einem Zustandsfeld und genau einem Handler. Das Setup drumherum ist ein gewöhnliches create-react-app-Projekt – `npm install`, `npm start`, läuft auf Port 3000. Mehr Werkzeug braucht es 2017 für so etwas nicht mehr, und das ist eine angenehme Entwicklung.\n\nDer Kontrast zum offiziellen React-Tutorial ist lehrreich. Dort ist Tic-Tac-Toe das Vehikel, um React zu erklären: Komponenten zerlegen, State nach oben ziehen, Props nach unten reichen, am Ende eine Zeithistorie. Der Gegner ist ein zweiter Mensch, die Spiellogik beschränkt sich auf die Gewinnprüfung. Hier ist es genau andersherum: React ist das Vehikel, der Algorithmus das Zentrum. Beide Blickrichtungen sind berechtigt – aber nur die zweite zwingt einen, die Grenze zwischen Logik und Darstellung sauber zu ziehen, weil die Logik sonst sofort unhandlich wird.\n\n```mermaid\nflowchart LR\n  subgraph core[\"Reine Funktionen – kein React-Import\"]\n    score --> minimax\n    winnerOf --> minimax\n    movesFor --> minimax\n    applyMove --> minimax\n    minimax --> bestMove\n  end\n  subgraph ui[\"React 15\"]\n    state[\"state.board\"] --> render[\"render()\"]\n    render --> onclick[\"onClick(index)\"]\n  end\n  onclick -->|\"applyMove + bestMove\"| core\n  core -->|\"neues Brett\"| setState[\"setState\"]\n  setState --> state\n```\n\nDie Pfeile zwischen den beiden Kästen sind die ganze Kopplung: Der Handler ruft Funktionen auf und schreibt das Ergebnis zurück in den State. Kein Import läuft in die Gegenrichtung. Man könnte den rechten Kasten durch eine Konsolenanwendung ersetzen, durch jQuery oder eben durch Elm – der linke Kasten würde es nicht bemerken.\n\n## Tests ohne Browser\n\nDiese Trennung ist keine Geschmacksfrage, sie ist messbar – am direktesten in den Tests. Die Spiellogik läuft in Node, ohne DOM, ohne jsdom, ohne gemocktes Event-System. Jest, das bei create-react-app gleich dabei ist, führt so etwas in Millisekunden aus:\n\n```js\ntest('computer blocks an open line', () => {\n  const board = [\n    HUMAN,    HUMAN, null,\n    COMPUTER, null,  null,\n    null,     null,  null,\n  ];\n  expect(bestMove(board)).toBe(2);\n});\n\ntest('computer prefers the immediate win over the block', () => {\n  const board = [\n    HUMAN,    HUMAN,    null,\n    COMPUTER, COMPUTER, null,\n    null,     null,     null,\n  ];\n  expect(bestMove(board)).toBe(5);\n});\n```\n\nDas sind keine Unit-Tests im kleinteiligen Sinn, sondern Spielverstand als Spezifikation: Der Gegner muss eine offene Reihe blocken, und er muss den eigenen Sieg dem Block vorziehen. Solche Fälle lassen sich direkt aus Partien gewinnen – jedes Mal, wenn sich der Gegner beim Ausprobieren merkwürdig verhält, wird die Stellung zum Testfall. Bei mir war es anfangs genau so ein Fall: Ohne den Tiefenanteil in `score` schob die Suche einen sicheren Sieg vor sich her, weil ein Sieg in vier Zügen denselben Wert hatte wie einer in zwei. Die Stellung aus dem zweiten Test oben ist das Fossil dieses Fehlers.\n\nNun die Gegenprobe, und die habe ich in Reviews oft genug in freier Wildbahn gesehen: Die Zuglogik steckt im Klick-Handler, die Gewinnprüfung in `render`, der Rechnerzug in einem Lifecycle-Hook wie `componentDidUpdate`. Funktional identisch, aber jetzt gilt:\n\n- Jeder Logik-Test braucht eine gemountete Komponente und simulierte Klicks – aus einem Funktionsaufruf wird ein Browser-Ritual.\n- Die Stellung aus dem Fehlerfall lässt sich nicht direkt hinschreiben, sie muss durch eine Klickfolge erspielt werden.\n- Ein Wechsel der UI-Bibliothek oder auch nur ein größeres Umbauen des Komponentenbaums reißt die Spiellogik mit um.\n- Der Algorithmus ist nicht mehr am Stück lesbar, weil er über Handler, Render-Zweige und Lifecycle-Methoden verteilt ist.\n\nNichts davon ist bei drei mal drei Feldern dramatisch. Aber Tic-Tac-Toe ist hier ja nur das Versuchstier. Ersetzt man „Spiellogik\" durch „Preisberechnung\", „Validierung\" oder „Planungsregeln\", ist es dieselbe Entscheidung mit denselben Folgen – nur dass die verwobene Version dann nicht mehr an einem Nachmittag zu entflechten ist.\n\n## Was ich daraus mitnehme\n\nMinimax selbst wird kaum jemand im Projektalltag brauchen. Was bleibt, ist das Muster darunter. Der ganze Gegner ist eine Bewertungsfunktion plus eine Suche über immutable Werten – und weil das so ist, lässt er sich testen wie eine Preisformel und rendern mit was auch immer gerade da ist. React hat in diesem Projekt die Rolle, die ihm meiner View nach am besten steht: State entgegennehmen, Oberfläche daraus machen, Eingaben zurückmelden. Nicht mehr.\n\nBemerkenswert finde ich, wie sehr die Teile zusammenpassen, ohne füreinander gebaut zu sein. Minimax verlangt immutable Bretter, weil die Rekursion sonst Buchhaltung bräuchte. React belohnt immutable States, weil Vergleiche sonst teuer würden. Ein Algorithmus aus den Anfängen der Spieltheorie und eine UI-Bibliothek von 2013 treffen sich in derselben Disziplin: keine Mutation, Werte statt Änderungen. Das ist kein Zufall, sondern ein Hinweis darauf, dass diese Disziplin grundsätzlicher ist als jedes einzelne Werkzeug.\n\nWer das nachbauen will: ein Array mit neun Feldern, fünf Pure Functions, eine Klasse mit einem Handler. Ein Nachmittag – und danach ein präzises Gespür dafür, wo in den eigenen, deutlich größeren Anwendungen die Linie zwischen Logik und Darstellung verlaufen sollte. Und ein Spiel, gegen das man nie wieder gewinnt.\n\n## Weiterführende Quellen\n\n- Repository `react-tic-tac-toe` („Tic Tac Toe in React with Minimax-AI\"): https://github.com/MikeBild/react-tic-tac-toe\n- Carsten Königs Othello in Elm, die Inspirationsquelle: https://github.com/CarstenKoenig/ElmOthello\n- Das offizielle React-Tutorial (Tic-Tac-Toe, heutiger Stand): https://react.dev/learn/tutorial-tic-tac-toe\n- Minimax im Überblick: https://en.wikipedia.org/wiki/Minimax\n- Alpha-Beta-Pruning: https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning"},{"locale":"de","translation_key":"einfach-schlagen-elegant-statt-prozess","slug":"einfach-schlagen-elegant-statt-prozess","title":"Einfacher Entwurf kann Prozess sparen","summary":"In vielen Projekten kompensiert Prozess-Overhead einen zu großen oder spekulativen Entwurf. Kleiner zu schneiden kann Koordination sparen; externe Vorgaben und echte Abhängigkeiten bleiben.","tags":["Software","Produkt"],"published_at":"2017-05-24T10:00:00+00:00","updated_at":"2026-07-13T08:35:56.109624+00:00","url":"https://www.mikebild.dev/de/blog/einfach-schlagen-elegant-statt-prozess/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/652dfbe1c347508153752ae47b8269f074b3251a6d4cccbc07851cd602483f7d/einfach-schlagen-elegant-statt-prozess-vorlesen.mp3","audio_duration_secs":627,"text":"Ein Change Board misst nicht, wie riskant eine Änderung ist. Es misst, wie groß sie geschnitten wurde. Für die Freigaberunde, das Design Review und das wöchentliche Integrations-Meeting gilt dasselbe: Sie reagieren auf die Form, die ein Entwurf der Arbeit gegeben hat, und nicht auf ihren fachlichen Wert.\n\nDie üblichen Vorschläge gegen zu viel Prozess setzen deshalb an der falschen Stelle an – noch ein Gremium, straffere Freigaben, ein umgebautes Ticket-Board. Damit wird Reibung verwaltet, statt sie loszuwerden. Die Frage davor ist ergiebiger: Warum braucht diese eine Änderung überhaupt drei Teams, zwei Reviews und ein Approval-Meeting? Sehr oft steckt die Antwort im Entwurf und nicht in der Organisation. Nicht immer, aber oft genug, dass es sich lohnt, dort zuerst nachzusehen.\n\n## Overhead ist teuer, bevor er sichtbar wird\n\nBevor ich zum Entwurf komme, lohnt ein Blick auf die Rechnung. Martin Fowler hat in seinem Text zu YAGNI (\"You Aren't Gonna Need It\") vorgezogene, spekulative Komplexität sauber in Kostenarten zerlegt: Es gibt build cost – das Bauen des Features, das man heute nicht braucht. Es gibt delay cost – das, was man in derselben Zeit nicht am eigentlichen Problem gearbeitet hat. Es gibt carry cost – jede Zeile spekulative Flexibilität muss ab sofort mitgetragen, verstanden, getestet und umgangen werden. Und es gibt repair cost, wenn die vorgebaute Annahme sich als falsch herausstellt.\n\nDer Punkt, der in Diskussionen fast immer untergeht: Ein großer Teil dieser Kosten ist Koordinationskosten. Ein flexibler, konfigurierbarer, \"für später\" ausgelegter Entwurf braucht ein Design Review. Er braucht ein Config-Ticket. Er kreuzt Teamgrenzen und braucht deshalb Abstimmung. YAGNI ist deshalb kein Faulheitsprinzip, sondern ein Designprinzip – und nebenbei ein Prozessspar-Prinzip. Weniger vorgebaute Komplexität heißt weniger, worüber man sich abstimmen muss.\n\nEin kleines Beispiel, das ich in Varianten immer wieder sehe:\n\n```python\n# Over-engineered: a pluggable strategy, a factory, and a config object\n# for ONE rule that exists today. This needs a design review, a config\n# ticket, and a feature-flag rollout before it ships.\nclass DiscountEngine:\n    def __init__(self, strategy: DiscountStrategy, config: DiscountConfig):\n        self.strategy = strategy\n        self.config = config\n\n    def apply(self, price: Money, customer: Customer) -> Money:\n        return self.strategy.compute(price, customer, self.config)\n\n\n# YAGNI: the one rule you actually have today. One PR, no coordination,\n# no ticket for a config value nobody has asked for yet.\ndef apply_discount(price: Money, is_returning_customer: bool) -> Money:\n    return price * 0.9 if is_returning_customer else price\n```\n\nDie untere Variante ist nicht \"schludrig\". Sie ist ehrlich. Sie beschreibt exakt die eine Regel, die es heute gibt. Und sie kostet in der Auslieferung fast nichts – keine Runde durchs Gremium, kein Flag, kein Meeting. Wenn morgen eine zweite Discount-Regel dazukommt, refactore ich – dann, mit echter Information, statt heute auf Verdacht.\n\n## Der eigentliche Hebel: Schnittgröße\n\nDer Discount ist die kleine Bühne. Die große ist die Frage, wie groß eine Änderung ist, bevor sie live geht. Und genau hier steckt der Zusammenhang, den ich in Reviews am liebsten aufmale.\n\n```mermaid\nflowchart TB\n    A[\"One large change<br/>crossing three teams\"] --> B[Design Review]\n    B --> C[Cross-team Ticket]\n    C --> D[Merge Conflict]\n    D --> E[Change Board]\n    E --> F[Coordination Meeting]\n    F --> G[Release]\n\n    A2[\"Same value, cut into three<br/>small independent changes\"] --> H[\"Context A<br/>own pipeline\"]\n    A2 --> I[\"Context B<br/>own pipeline\"]\n    A2 --> J[\"Context C<br/>own pipeline\"]\n    H --> K[Release]\n    I --> K\n    J --> K\n```\n\nDie Kernaussage der Grafik ist schlicht: Der Koordinationsaufwand hängt nicht am Feature-Wert. Er hängt an der Schnittgröße und daran, wie viele Teamgrenzen ein Schnitt kreuzt. Ein großer Change, der drei Teams berührt, erzeugt dicke Koordinationskanten – Reviews, Merge-Konflikte, Change Board, Abstimmungsrunden. Derselbe fachliche Wert, in drei kleine, unabhängige Änderungen zerlegt, erzeugt fast keine Querkanten. Jede Änderung bleibt in ihrem eigenen Bounded Context und geht durch ihre eigene Pipeline.\n\nDas ist keine Theorie. Die State-of-DevOps-Reports der letzten Jahre – die Arbeit rund um Forsgren, Humble und Kim – zeigen dasselbe empirisch. High Performer arbeiten mit wenigen aktiven Branches, integrieren mindestens einmal täglich in den Trunk und kennen keine langen Integrations- oder Freeze-Phasen. Sie ersetzen Merge- und Koordinations-Overhead durch kleine Batches. Trunk-Based Development ist genau das: den Schnitt so klein machen, dass die aufwendige Koordination gar nicht erst entsteht.\n\nUnd der Teil, der Skeptiker überrascht: Kleine Deployments sind nicht riskanter, sondern sicherer. Dieselben Daten zeigen, dass hohe Deployment-Frequenz und kurze Lead Time for Changes mit einer niedrigeren Change Fail Rate und kürzerer Wiederherstellungszeit korrelieren. Ein kleiner Schnitt ist leichter zu verstehen, leichter zu reviewen und im Fehlerfall leichter zurückzudrehen. Ein großer Schnitt braucht die schwere Approval-Zeremonie – weil er sie tatsächlich verdient hat. Man baut sich den Prozess, den man durch die Größe erzwingt.\n\n## Wenn Koordination bloß Symptom ist\n\nEin Muster, das sich in Projekten hartnäckig hält: Zwei Teams stimmen sich in einem wiederkehrenden Integrations-Meeting ab, weil Team A einen Endpoint bereitstellt, von dem Team B abhängt. Jede Änderung wird vorher besprochen, jede Integration gemeinsam getestet. Der Prozess ist real – aber er kompensiert nur, dass niemand die Erwartung zwischen den Teams explizit gemacht hat.\n\nConsumer-Driven Contracts drehen das um. Der Consumer beschreibt genau, was er braucht – nicht mehr. Der Provider verifiziert diesen Vertrag in seiner eigenen Pipeline, unabhängig. Das Abstimmungs-Meeting verschwindet, weil die Abstimmung im Code steht:\n\n```javascript\n// The consumer declares only what it actually needs. No cross-team\n// integration meeting, no shared end-to-end test suite to schedule.\npact\n  .given(\"customer 42 exists\")\n  .uponReceiving(\"a request for the customer name\")\n  .withRequest({ method: \"GET\", path: \"/customers/42\" })\n  .willRespondWith({\n    status: 200,\n    body: { name: like(\"Ada\") },\n  });\n\n// The provider replays this contract in ITS OWN pipeline and fails fast\n// if it ever breaks the expectation — independently, no meeting required.\n```\n\nWerkzeuge wie Pact machen das seit einigen Jahren praktikabel. Der Effekt ist derselbe wie beim kleinen Schnitt: Ein Stück Koordination, das vorher als Meeting existierte, wird zu ausführbarer Spezifikation – und der Prozess drumherum ist nicht mehr nötig.\n\n## Governance ohne Gremium\n\nDasselbe Muster gilt auf Architekturebene. Viele schwergewichtige Governance-Prozesse – das Architektur-Gremium, das jede Änderung absegnet – existieren, weil niemand eine leichtgewichtigere Art gefunden hat, Architekturregeln durchzusetzen. Neal Ford und Rebecca Parsons prägen für die Alternative einen schönen Begriff: fitness functions. Statt einmal groß vorab zu entwerfen und dann per Gremium zu bewachen, formuliert man die Architekturziele als automatisch prüfbare Regeln in der Deployment-Pipeline.\n\n```yaml\n# Architecture rules as executable guardrails in the pipeline,\n# not as a slide reviewed once a quarter by a committee.\nfitness_functions:\n  - name: modules_stay_decoupled\n    rule: \"no cyclic dependencies between packages\"\n  - name: p95_latency_budget\n    threshold_ms: 300\n  - name: public_api_is_stable\n    rule: \"no breaking change without a new version\"\n```\n\nIst die Regel verletzt, wird der Build rot – sofort, nachvollziehbar, für alle gleich. Das ersetzt keine Architekturarbeit; es ersetzt das Ritual, mit dem man sie sonst durchsetzt. Verwandt dazu sind Fowlers Ideen der \"Sacrificial Architecture\" und des \"MonolithFirst\": erst einfach und notfalls wegwerfbar bauen, Komplexität nur dann einziehen, wenn die Realität sie erzwingt. Evolutionäre Architektur ist die konsequente Weigerung, Prozess-Overhead für eine Zukunft zu bezahlen, die man noch nicht kennt.\n\n## Wo die These an ihre Grenze kommt\n\nDie Gegenrede ist berechtigt. Drei ehrliche Einschränkungen, damit aus einer guten Heuristik keine Ideologie wird.\n\nErstens: Einfach ist nicht dasselbe wie simplistisch. YAGNI gilt für spekulative Features und vorgezogene Flexibilität – nicht für innere Qualität. \"Wir lassen die Tests und das Design weg, dann sind wir schneller\" ist die Fehllesart, gegen die Fowler ausdrücklich anschreibt. Der Unterschied ist der zwischen accidental und essential complexity, den schon Brooks gezogen hat. Weniger spekulative Struktur: ja. Weniger Sorgfalt im Kern: nein. Die kleine Discount-Funktion von oben braucht ihren Test genauso wie die große Engine – nur eben genau einen, für die eine Regel, die es gibt.\n\nZweitens: Overhead ist nicht immer Design-Verschulden. Compliance-Anforderungen sind real. Regulatorische Gates sind real. Echte Abhängigkeiten zwischen Teams, die sich nicht wegschneiden lassen, sind real. Deshalb steht oben bewusst \"oft\" und nicht \"immer\". Es geht nicht darum, jeden Prozessschritt abzuschaffen. Es geht darum, ihn zu befragen: Kompensierst du gerade eine Anforderung von außen – oder eine Komplexität, die wir uns selbst gebaut haben?\n\nDrittens: Ein kleinerer Schnitt kann Komplexität auch nur verschieben. Aus einem Modul zwei Services zu machen tauscht Code-Kopplung gegen verteilte Kopplung und Netzwerk ein. Das ist manchmal richtig, aber es ist nie gratis. Genau darum sind Contract Tests der Ersatz für den vollen End-to-End-Integrationszirkus – und genau darum lohnt Fowlers \"MicroservicePremium\" als Merksatz: Verteilung muss man sich verdienen, sie ist kein Default. Wer klein schneidet, ohne den Schnitt entlang echter fachlicher Grenzen zu legen, hat am Ende mehr Koordination, nicht weniger.\n\n## Wie ich es konkret angehe\n\nDie Reihenfolge, die sich dabei bewährt hat, beginnt nicht beim Prozess.\n\n```mermaid\nflowchart LR\n    A[\"Spot the heavy<br/>process step\"] --> B[\"Ask: what complexity<br/>is it compensating?\"]\n    B --> C[\"Cut the change<br/>smaller\"]\n    C --> D[\"Make the expectation<br/>explicit as a contract\"]\n    D --> E[\"Turn the gate into a<br/>fitness function\"]\n    E --> F[\"Drop the step<br/>that is now redundant\"]\n```\n\nZuerst suche ich den teuersten Prozessschritt – das Meeting, das alle nervt, das Approval, das immer blockiert. Dann frage ich nicht \"wie machen wir es effizienter\", sondern \"welche Komplexität fängt es auf\". Meistens finden wir dahinter einen zu großen Schnitt, eine unausgesprochene Erwartung oder eine Governance, die niemand automatisiert hat. Dann schneiden wir kleiner, machen die Erwartung als Contract explizit, gießen das Gate in eine fitness function – und lassen den Schritt, der jetzt nichts mehr auffängt, ersatzlos weg.\n\nDas Ergebnis ist selten spektakulär und fast immer spürbar: kürzere Zyklen, weil weniger auf Freigaben wartet. Weniger Reibung, weil weniger über Teamgrenzen abgestimmt werden muss. Höhere Qualität, weil kleine Änderungen leichter zu prüfen und im Fehlerfall leichter zurückzudrehen sind. Einfach und elegant statt Prozess-Overhead – das fällt als Nebenprodukt eines besseren Entwurfs ab und ist keine Sparmaßnahme.\n\n## Fazit\n\nProzess ist teuer, und meistens ist er teuer aus gutem Grund: Er fängt Reibung auf, die real da ist. Aber die interessantere Frage ist fast nie, wie man den Prozess effizienter macht. Sie lautet, warum die Reibung überhaupt entsteht. Sehr oft ist die Antwort ein Entwurf, der zu groß, zu spekulativ oder zu implizit ist.\n\nKleiner schneiden schlägt mehr koordinieren. Explizite Verträge schlagen wiederkehrende Abstimmung. Automatisierte Guardrails schlagen Gremien. Und YAGNI schlägt jede Flexibilität, die man heute baut und morgen umgeht. Das ist keine Aufforderung zur Schludrigkeit – innere Qualität bleibt nicht verhandelbar. Es ist die Einladung, den Prozess-Overhead nicht als Naturgesetz zu nehmen, sondern als Symptom zu lesen. Wer das Problem an der richtigen Stelle klein macht, braucht die schwere Maschinerie drumherum gar nicht erst.\n\nWo der Prozess selbst gebaute Komplexität kompensiert, kann ein einfacherer Entwurf ihn tatsächlich überflüssig machen. Wo Regulierung, Betrieb oder echte Teamabhängigkeiten die Ursache sind, bleibt diese Rechnung offen. Genau diese Unterscheidung ist für mich wichtiger als die pauschale Forderung nach weniger Prozess.\n\n## Weiterführende Quellen\n\n- [Martin Fowler – Yagni](https://martinfowler.com/bliki/Yagni.html)\n- [Martin Fowler – Is Design Dead?](https://martinfowler.com/articles/designDead.html)\n- [Sacrificial Architecture (InfoQ, 2014)](https://www.infoq.com/news/2014/11/sacrificial-architecture/)\n- [Building Evolutionary Architectures / Fitness Functions (O'Reilly, 2017)](https://www.oreilly.com/library/view/building-evolutionary-architectures/9781491986356/ch02.html)\n- [Neal Ford – Building Evolutionary Architectures](https://nealford.com/books/buildingevolutionaryarchitectures.html)\n- [Pact – Dokumentation](https://docs.pact.io/)"},{"locale":"de","translation_key":"html5-css3-ecmascript-baseline","slug":"html5-css3-ecmascript-baseline","title":"HTML5, CSS3 und ECMAScript als Baseline","summary":"Im Frühjahr 2017 tragen CSS Grid, Flexbox, fetch und natives ES2015 so weit, dass die erste Architekturfrage im Frontend neu gestellt gehört: Wie weit komme ich ohne Framework?","tags":["Software","Architektur"],"published_at":"2017-05-12T10:00:00+00:00","updated_at":"2026-07-14T17:01:38.042661+00:00","url":"https://www.mikebild.dev/de/blog/html5-css3-ecmascript-baseline/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/381654c4b3bf48e47d9e5e1d6ba07216dbf82047b70635d780f0a4e57071ecb5/html5-css3-ecmascript-baseline-vorlesen.mp3","audio_duration_secs":694,"text":"# HTML5, CSS3 und ECMAScript als Baseline\n\nBaseline meint hier etwas Bestimmtes: die Menge an HTML-, CSS- und JavaScript-Fähigkeiten, die in allen Browsern eines Projekts ohne eine einzige Abhängigkeit läuft. Kein `npm install`, kein Framework, kein Plugin – nur das, was die Plattform von Haus aus mitbringt. Diese Menge ist keine feste Größe. Sie hängt davon ab, welche Browser ein Projekt tatsächlich bedienen muss, und sie verschiebt sich mit jedem Browser-Release. Wer sie kennt, kann eine Frage präzise beantworten, die sonst reflexhaft beantwortet wird: Wofür genau brauche ich eine Abhängigkeit – und wofür nicht?\n\nDiese Frage lohnt sich gerade jetzt besonders, denn die Baseline hat sich in den letzten Monaten so weit nach oben geschoben wie lange nicht.\n\n## Ein ungewöhnliches Frühjahr\n\nIm März sind Chrome 57, Firefox 52 und Safari 10.1 innerhalb weniger Wochen mit CSS Grid Layout erschienen. Dass ein großes Layout-Feature praktisch zeitgleich und ohne Präfixe in drei großen Browsern landet, habe ich in dieser Form noch nicht erlebt. Sonst zog sich so etwas über Jahre – man denke an die drei verschiedenen Flexbox-Syntaxen, die sich lange nebeneinander gehalten haben. Grid ist von Tag eins an in der finalen Syntax nutzbar.\n\nGrid ist aber nur der sichtbarste Teil. Wer die Zielbrowser auf aktuelle Versionen von Chrome, Firefox, Safari und Edge eingrenzen kann, hat im Mai 2017 ohne jede Abhängigkeit zur Verfügung:\n\n- Flexbox und CSS Grid für Layout, dazu `@supports` für saubere Feature-Queries im Stylesheet\n- CSS Custom Properties (seit letztem Jahr breit unterstützt, IE11 ausgenommen)\n- ES2015 nativ: Klassen, Arrow Functions, Destructuring, Template Literals, Promises\n- `async`/`await` aus ES2017 in den aktuellen Versionen der Evergreen-Browser\n- `fetch` als eingebauten HTTP-Client, seit Safari 10.1 auch dort\n- Custom Elements v1 und Shadow DOM v1 in Chrome und Safari\n- Service Worker in Chrome und Firefox – Safari und Edge fehlen hier noch, das gehört zur Ehrlichkeit dazu\n\nVor zwei, drei Jahren war jeder einzelne Punkt dieser Liste ein Grund, eine Bibliothek zu installieren. Genau deshalb ist mir die Frage wieder wichtig geworden. In einem Code-Review bin ich kürzlich durch ein Frontend gegangen, das jQuery, ein Grid-System, eine AJAX-Hilfsbibliothek und einen Klassen-Emulator mitschleppte – zusammen deutlich über 100 KB, bevor die erste eigene Zeile lief. Für jede dieser Abhängigkeiten gab es 2013 einen guten Grund. 2017 erledigt die Plattform alle vier Aufgaben selbst. Niemand hatte die Entscheidung je zurückgenommen, weil niemand sie je als Entscheidung betrachtet hatte.\n\n## Layout gehört jetzt der Plattform\n\nDas Beispiel, an dem ich das durchspiele, ist bewusst gewöhnlich: eine Produktübersicht, Karten in einem Raster, Daten von einer HTTP-Schnittstelle. Der Klassiker, für den man sonst Bootstrap samt jQuery-Abhängigkeit installiert.\n\nDas Raster zuerst. Mit Grid ist das Layout eine Handvoll Zeilen, und der Fallback für ältere Browser ist keine zweite Codebasis, sondern eine Schicht darunter:\n\n```css\n/* baseline for every browser: a simple flex wrap */\n.products {\n  display: flex;\n  flex-wrap: wrap;\n}\n\n.product-card {\n  flex: 1 1 240px;\n  margin: 8px;\n}\n\n/* enhancement for browsers with grid support */\n@supports (display: grid) {\n  .products {\n    display: grid;\n    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));\n    grid-gap: 16px;\n  }\n\n  .product-card {\n    margin: 0;\n  }\n}\n```\n\nZwei Dinge daran finde ich bemerkenswert. Erstens: `repeat(auto-fill, minmax(240px, 1fr))` ersetzt das, wofür Grid-Systeme jahrelang Klassen wie `col-md-4` und eine Media-Query-Kaskade gebraucht haben – ohne eine einzige Media Query. Zweitens: `@supports` macht die Browser-Matrix zu einer Design-Entscheidung statt zu einem Kompatibilitäts-Hack. IE11 und der aktuelle Edge bekommen das Flexbox-Raster, moderne Browser das Grid. Die Seiten sehen nicht pixelgleich aus, und das ist in Ordnung – die Vorstellung, jede Browser-Version müsse identisch rendern, hat uns jahrelang unnötig viel Code gekostet.\n\nEhrlich bleiben muss man bei Edge: Der unterstützt bislang nur die alte Grid-Syntax mit `-ms`-Präfix, die noch aus IE10-Zeiten stammt. Wer Edge im Zielkorb hat, behandelt ihn beim Grid vorerst wie IE11 und fährt den Fallback. Genau dafür ist die `@supports`-Query da.\n\n## Daten laden ohne Bibliothek\n\nDer zweite Baustein ist der Datenabruf. Wofür früher `$.ajax` oder eine eigene XHR-Kapselung nötig war, reicht heute `fetch` – und mit `async`/`await` liest sich der Kontrollfluss endlich wie synchroner Code. Wie mühsam dieselbe Aufgabe vor drei Jahren mit Callback-Ketten war, habe ich damals [in einem eigenen Beitrag](https://www.mikebild.dev/de/blog/control-flow-vor-async-await/) festgehalten; die Distanz zwischen diesen beiden Welten ist erstaunlich kurz.\n\n```js\nasync function loadProducts() {\n  const response = await fetch('/api/products', {\n    headers: { 'Accept': 'application/json' }\n  });\n\n  // fetch resolves on HTTP errors too, so check explicitly\n  if (!response.ok) {\n    throw new Error('Request failed with status ' + response.status);\n  }\n\n  return response.json();\n}\n```\n\nDer Kommentar im Code markiert die Stolperstelle, über die ich in Reviews am häufigsten stolpere: `fetch` lehnt das Promise bei einem 404 oder 500 nicht ab, sondern nur bei Netzwerkfehlern. Wer von jQuery kommt, erwartet das Gegenteil. Solche Eigenheiten muss man einmal lernen – aber man lernt dabei die Plattform, nicht die Meinung einer Bibliothek, und dieses Wissen veraltet deutlich langsamer.\n\nFür IE11 gilt: kein `fetch`, kein Promise, kein `async`/`await`. Wer ihn bedienen muss, kompiliert mit Babel und lädt zwei kleine Polyfills. Das ist ein Build-Schritt, den ich sonst gern vermeide – aber er ist überschaubar, gezielt und vor allem befristet. Der Polyfill fliegt raus, sobald IE11 aus der Matrix fällt. Eine Framework-Abhängigkeit fliegt erfahrungsgemäß nie raus.\n\n## Komponenten direkt im Browser\n\nDer dritte Baustein ist der interessanteste, weil er am dichtesten an dem liegt, wofür man sonst zu einem Framework greift: wiederverwendbare Komponenten. Custom Elements v1 sind in Chrome und Safari angekommen, und damit lässt sich die Produktliste als eigenes HTML-Element definieren:\n\n```js\nclass ProductList extends HTMLElement {\n  async connectedCallback() {\n    this.textContent = 'Loading products ...';\n\n    try {\n      const products = await loadProducts();\n      this.render(products);\n    } catch (error) {\n      this.textContent = 'Products are currently unavailable.';\n    }\n  }\n\n  render(products) {\n    this.innerHTML = '<div class=\"products\"></div>';\n    const container = this.querySelector('.products');\n\n    products.forEach(product => {\n      const card = document.createElement('article');\n      card.className = 'product-card';\n      card.textContent = product.name;\n      container.appendChild(card);\n    });\n  }\n}\n\ncustomElements.define('product-list', ProductList);\n```\n\nIm Markup steht danach schlicht `<product-list></product-list>`, und der Browser ruft die Lifecycle-Methoden selbst auf. Kein virtueller DOM, kein Data-Binding, keine Render-Schleife – für eine Komponente dieser Größe braucht es das alles nicht. Firefox und Edge benötigen dafür noch das Polyfill aus dem webcomponents.org-Projekt, und das ist nicht gratis: Es bringt spürbar Gewicht mit und muss in der Browser-Matrix mitgetestet werden. Wer heute produktiv auf Custom Elements setzt, sollte diese Kosten kennen und nicht nur die Chrome-Demo.\n\nAm Rand notiert: Native ES-Module im Browser stehen ebenfalls kurz bevor – Safari 10.1 kann `<script type=\"module\">` bereits, bei den anderen liegt es hinter Flags. Für den Moment bleibt das Bundling beim Build; aber auch diese Lücke schließt sich gerade.\n\n## Die Prüfreihenfolge\n\nAus diesen Bausteinen ergibt sich eine Reihenfolge, die ich inzwischen bei jeder Frontend-Anforderung durchgehe – nicht als Dogma, sondern als Prüfweg, der Abhängigkeiten zu begründeten Entscheidungen macht statt zu Reflexen:\n\n```mermaid\nflowchart TD\n  A[Anforderung im Frontend] --> B{Kann die Plattform das?<br/>caniuse gegen die Zielbrowser}\n  B -- ja, in allen Zielbrowsern --> C[Baseline nutzen<br/>keine Abhängigkeit]\n  B -- ja, bis auf Ausnahmen --> D{Fallback per @supports<br/>oder Polyfill vertretbar?}\n  D -- ja --> E[Gezielt nachrüsten<br/>Polyfill ist befristet]\n  D -- nein --> F[Bibliothek für genau<br/>diese eine Lücke]\n  B -- nein --> F\n  F --> G{Bilden mehrere Lücken<br/>zusammen ein Muster?}\n  G -- ja --> H[Framework – mit klarem Wofür]\n  G -- nein --> C\n```\n\nDer entscheidende Punkt ist der letzte Knoten. Ein Framework ist in diesem Bild nicht verboten – es steht nur am Ende der Prüfung statt am Anfang. Wer den Weg durchlaufen hat, kann das Wofür präzise benennen: „Wir brauchen React, weil wir zwanzig Ansichten mit geteiltem Zustand haben und das Data-Binding von Hand nicht mehr beherrschbar ist\" ist eine Architekturentscheidung. „Wir nehmen React, weil man das heute so macht\" ist keine.\n\n## Die ehrliche Gegenseite\n\nDamit das nicht wie ein Plädoyer für Frontend-Askese klingt: Es gibt gute Gründe, 2017 weiterhin Abhängigkeiten zu installieren, und die gehören auf den Tisch.\n\nDie Browser-Matrix ist der größte. Wer ein internes System für einen Konzern baut, in dem IE11 per Gruppenrichtlinie gesetzt ist, hat eine andere Baseline als jemand, der eine Website für ein technikaffines Publikum betreibt. Für die IE11-Welt bedeutet der Plattform-Ansatz: Babel, mehrere Polyfills, doppelte Layout-Pfade, doppeltes Testen. Ab einem gewissen Punkt ist eine Bibliothek, die diese Unterschiede wegabstrahiert, schlicht die billigere Lösung – und genau dafür ist jQuery auch in diesem Jahr noch legitim:\n\n- wenn IE-Versionen im Zielkorb sind, deren Eigenheiten jQuery seit Jahren zuverlässig glattzieht\n- wenn ein bestehendes Plugin-Ökosystem – Datepicker, Tabellen, Upload-Widgets – produktiv im Einsatz ist und ein Neubau keinen fachlichen Wert schafft\n- wenn ein Team eine große, gewachsene jQuery-Codebasis pflegt und ein Technologiewechsel mehr Risiko brächte als Nutzen\n\nAuch die Polyfill-Rechnung muss ehrlich sein. Ein `fetch`-Polyfill ist klein; das Web-Components-Polyfill ist es nicht. Wer fünf Plattform-Features nachrüstet, hat am Ende womöglich mehr Kilobytes geladen als mit einer kompakten Bibliothek, die alles mitbringt – und trägt die Testlast für jede Kombination selbst. Die Baseline-Frage lautet eben nicht „Plattform um jeden Preis\", sondern: Was läuft ohnehin überall, und was kostet der Rest wirklich?\n\nUnd schließlich: Für große, langlebige Anwendungen mit viel geteiltem Zustand löst die Plattform das Kernproblem nicht. HTML, CSS und ECMAScript sagen nichts darüber, wie Zustand und Darstellung konsistent bleiben, wenn dreißig Komponenten dieselben Daten zeigen. Dieses Problem ist real, und Frameworks adressieren es zu Recht. Nur ist es eben ein spezifisches Problem – nicht jede Website hat es, und eine Produktübersicht mit drei Ansichten hat es ziemlich sicher nicht.\n\n## Eine Materialsammlung als Nebenprodukt\n\nBeim Sortieren dieses Themas ist bei mir im April eine öffentliche Materialsammlung entstanden: [introduction-html5-css3-ecma](https://github.com/MikeBild/introduction-web-plattform) auf GitHub. Dort liegt der Plattform-Bestand in Abschnitten beieinander – HTML5-Markup und die APIs von Geolocation über Canvas, Web Worker und WebSockets bis Server-Sent Events, dazu CSS3-Selektoren und -Animationen, die JavaScript-Grundlagen um Prototypen und Closures und die ES2015+-Syntax bis zu Promises, `async`/`await` und Generatoren. Nichts davon ist exotisch; der Wert liegt für mich im Nebeneinander. Erst wenn der Bestand einmal aufgeschrieben vor einem liegt, sieht man, wie viel davon im eigenen Projekt gerade doppelt vorhanden ist – einmal nativ im Browser und einmal als Abhängigkeit im Bundle.\n\n## Unterm Strich\n\nDie Baseline aus HTML5, CSS3 und aktuellem ECMAScript ist 2017 kein Bastel-Kompromiss mehr, sondern ein tragfähiges Fundament: Grid und Flexbox für Layout, `fetch` und `async`/`await` für Daten, Custom Elements für Komponenten im Kleinen. Wer damit anfängt, senkt drei Kosten auf einmal – weniger Abhängigkeiten, die gepflegt und aktualisiert werden wollen, weniger Build-Komplexität, und eine niedrigere Einstiegshürde für jeden, der neu ins Projekt kommt und erst einmal nur Webstandards können muss.\n\nVor allem aber verändert die Baseline die Qualität der Framework-Entscheidung. Sie fällt nicht mehr am Projektanfang aus Gewohnheit, sondern später, gezielt, mit einem benennbaren Wofür. Manchmal lautet die Antwort dann trotzdem React oder Angular – und das ist völlig in Ordnung, weil jetzt klar ist, welches Problem damit gelöst wird und welches die Plattform längst selbst löst. Öfter, als ich noch vor zwei Jahren gedacht hätte, lautet die Antwort aber: Es braucht gar keins.\n\n## Weiterführende Quellen\n\n- [MikeBild/introduction-html5-css3-ecma](https://github.com/MikeBild/introduction-web-plattform) – die erwähnte Materialsammlung zu HTML5, CSS3 und ECMAScript\n- [MDN: CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout) – Referenz und Einführung in das Grid-Modell\n- [MDN: Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) – Dokumentation zu `fetch`, Request und Response\n- [Grid by Example](https://gridbyexample.com/) – Rachel Andrews Beispielsammlung zu CSS Grid\n- [Can I use](https://caniuse.com/) – Browser-Support-Tabellen für die eigene Zielbrowser-Matrix"},{"locale":"de","translation_key":"rxjs-push-und-pull","slug":"rxjs-push-und-pull","title":"RxJS: Push und Pull endlich auseinanderhalten","summary":"Wer Producer und Consumer benennt, erkennt sofort, ob Daten gezogen oder geschoben werden, und wählt zwischen Funktion, Iterator, Promise und Observable ohne Raten.","tags":["Software","Reactive"],"published_at":"2017-04-12T10:00:00+00:00","updated_at":"2026-07-14T20:56:00.987422+00:00","url":"https://www.mikebild.dev/de/blog/rxjs-push-und-pull/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/57453e2c7e2175ce6b7e57162944164916b730b7aaf9493ad6f79b9f06abf7a0/rxjs-push-und-pull-vorlesen.mp3","audio_duration_secs":487,"text":"# RxJS: Push und Pull endlich auseinanderhalten\n\nWer ein kaltes Observable wie ein geteiltes Promise behandelt, schickt seine HTTP-Anfrage so oft los, wie jemand `subscribe` aufruft. Drei Komponenten am selben kalten Stream bedeuten dann drei Requests – ohne Fehlermeldung, ohne Warnung, exakt nach Definition.\n\nDer Grund dafür hat zunächst weniger mit Operatoren zu tun als mit einer Frage: Wer entscheidet, wann ein Wert fließt – der Producer oder der Consumer? Vor `map`, `switchMap` und `debounceTime` wird meist gefragt, welcher Operator der richtige ist. Diese Frage kommt zu früh. Push und Pull liefern das Grundmodell, zu dem später Cold, Hot und Multicasting kommen.\n\n## Die eine Frage, die alles ordnet\n\nJede Datenquelle in JavaScript lässt sich über ihre Richtung beschreiben. Es gibt nur zwei.\n\nBei einem Pull-System holt sich der Consumer die Werte aktiv. Er ruft etwas auf und bekommt eine Antwort. Eine Funktion ist genau das: Du rufst sie, sie liefert. Ein Iterator ist dasselbe in mehreren Schritten, denn `iterator.next()` zieht den nächsten Wert heraus. Der Consumer bestimmt das Tempo.\n\nBei einem Push-System dreht sich das um. Jetzt entscheidet der Producer, wann etwas geschickt wird, und der Consumer weiß vorher nicht, wann der nächste Wert kommt. Ein Klick-Event, eine WebSocket-Message, ein Timer: All das schiebt, sobald es so weit ist. Der Consumer reagiert nur noch.\n\nDas klingt akademisch, hat aber direkte Folgen für den Code. Bei synchronem Pull bestimmt der Consumer den nächsten Abruf und kann dabei blockieren; ein asynchroner Iterator muss das nicht tun. Bei Push entscheidet der Producer, wann er liefert, und der Consumer reagiert darauf. Genau hier scheitern viele Migrationen von „Daten abfragen“ zu „auf Daten reagieren“.\n\n## Vier Produzenten, zwei Richtungen\n\nDie offizielle RxJS-Dokumentation ordnet die vier wichtigen Produzenten in ein Raster ein. Ich male es in Architektur-Diskussionen als Erstes ans Whiteboard, weil danach die meisten Fragen schon beantwortet sind.\n\n| Producer | Anzahl Werte | Richtung | Auswertung |\n| --- | --- | --- | --- |\n| Function | genau ein Wert | Pull | lazy |\n| Iterator / Generator | null bis viele | Pull | lazy |\n| Promise | genau ein Wert | Push | eager |\n| Observable | null bis viele | Push | lazy |\n\nLies die Tabelle als zwei Achsen. Die eine Achse fragt: ein Wert oder mehrere? Die andere fragt: zieht der Consumer oder schiebt der Producer? Das Observable ist die einzige Quelle, die mehrere Werte schiebt und dabei trotzdem lazy bleibt. Diese Kombination macht es so mächtig und für Einsteiger so verwirrend, weil sie keine direkte Entsprechung im klassischen JavaScript hat.\n\nEin Promise ist der nächste Verwandte, deckt aber nur eine Zelle daneben ab: ein Wert, geschoben, sofort gestartet. Wer das verinnerlicht, hört auf, ein Observable wie ein Promise mit mehr Methoden zu behandeln.\n\n## Ein Observable ist eine Funktion mit mehreren Ausgängen\n\nAm schnellsten wird das im Code klar. Mein `introduction-rxjs`-Material beginnt bewusst beim `Observable`-Konstruktor, bevor es Operatoren zeigt. Er zwingt dich, Producer und Consumer selbst zu benennen.\n\n```ts\nimport { Observable } from 'rxjs';\n\n// The producer decides on its own when values flow.\nconst ticks$ = new Observable((observer) => {\n  let n = 0;\n  const id = setInterval(() => observer.next(n++), 1000);\n\n  // Cleanup function: runs on unsubscribe or on complete.\n  return () => clearInterval(id);\n});\n\n// The consumer only reacts, it does not actively pull.\nconst sub = ticks$.subscribe({\n  next: (v) => console.log('value', v),\n  error: (e) => console.error('error', e),\n  complete: () => console.log('done'),\n});\n```\n\nDer Block in `subscribe` ist der Observer mit seinen drei Kanälen: `next` für Werte, `error` für den Abbruch mit Fehler, `complete` für das saubere Ende. Das ist das vollständige Vokabular eines Push-Consumers. Mehr gibt es nicht, und mehr braucht man auch nicht.\n\nZum Vergleich dieselbe Idee als Pull-Quelle. Hier passiert nichts, solange niemand zieht.\n\n```ts\nfunction* naturals() {\n  let n = 0;\n  while (true) yield n++; // The value is produced only when pulled.\n}\n\nconst it = naturals();\nit.next().value; // 0  – the consumer pulls\nit.next().value; // 1  – and sets the pace\n```\n\nBeide Quellen liefern eine unendliche Folge natürlicher Zahlen. Der Unterschied liegt allein in der Kontrolle. Beim Generator entscheidest du mit jedem `next()`, wann die Eins nach der Null kommt. Beim Observable entscheidet der Timer, und du bekommst die Werte einfach zugestellt.\n\n## Lazy heißt: ohne subscribe passiert nichts\n\nDie folgenreichste Spalte der Tabelle ist „Auswertung“. Das hier konstruierte kalte Observable ist lazy. Es führt seinen Producer-Code erst aus, wenn `subscribe` aufgerufen wird, und für jedes `subscribe` von vorn. Heiße Observables und geteilte Quellen verhalten sich anders. Ein Promise ist dagegen eager: Es startet seine Arbeit in dem Moment, in dem es erzeugt wird, ganz ohne `then`.\n\nAn diesem Unterschied entstehen die meisten Fehler beim Umstieg.\n\n```ts\n// eager: the request goes out immediately, even without then.\nconst preise = fetch('/api/preise');\n\n// lazy: nothing happens until someone calls subscribe.\nconst preise$ = new Observable((observer) => {\n  fetch('/api/preise')\n    .then((res) => res.json())\n    .then((data) => {\n      observer.next(data);\n      observer.complete();\n    })\n    .catch((err) => observer.error(err));\n});\n```\n\nDamit lässt sich der Fall vom Anfang auflösen. Ein Team baut eine Suche um. Vorher gab es ein geteiltes Promise, das einmal lief und dessen Ergebnis sich mehrere Komponenten teilten. Nach der Umstellung auf ein Observable abonnieren drei Komponenten denselben Stream. Plötzlich gehen drei HTTP-Anfragen raus statt einer. Niemand hat einen Fehler gemacht im klassischen Sinn, das Observable verhält sich exakt nach Definition: lazy und kalt, also pro Subscription eine eigene Ausführung. Wer das Promise-Verhalten 2017 zurückhaben wollte, teilte den Stream mit `publishReplay` und `refCount` oder setzte ein `Subject` davor. `publishReplay` ist inzwischen veraltet; heute drückt `shareReplay({ bufferSize: 1, refCount: true })` dieselbe Absicht direkter aus. Bewusst entscheiden muss man das Multicasting weiterhin. Erst wenn man Push, Lazy und Cold getrennt benennt, sieht man, warum hier drei Requests entstehen.\n\n## Zeit sichtbar machen mit dem Marble-Diagramm\n\nBei Push-Systemen hängt alles am zeitlichen Verlauf, und genau das macht sie schwer zu lesen. Ein Marble-Diagramm zeichnet diese Zeit auf eine Linie. Jede Murmel ist ein gepushter Wert, das `|` ist `complete`, das `X` wäre ein `error`.\n\n```text\nsubscribe                         unsubscribe\n   |                                   |\n   v                                   v\nticks$: ---0----1----2----3----4----5--|\n              (the producer pushes every 1000 ms)\n```\n\nDie Linie macht zwei Dinge sofort sichtbar, die im Text untergehen. Erstens: Die Werte erscheinen nach der inneren Logik des Producers, hier dem Intervall, und eben nicht auf Abruf. Zweitens: Es gibt zwei Ränder, die Subscription und die Unsubscription. Zwischen diesen Rändern existiert der Stream, davor und danach nicht. Wer Marble-Diagramme liest, hört auf, über einzelne Werte nachzudenken, und beginnt über die Lebensdauer des Streams nachzudenken.\n\nFür die Richtung selbst genügt ein kleines Schema. Es zeigt, wer wen antreibt.\n\n```mermaid\nflowchart LR\n  subgraph Pull\n    C1[Consumer] -- ruft next ab --> P1[Producer]\n  end\n  subgraph Push\n    P2[Producer] -- schiebt next --> C2[Consumer]\n  end\n```\n\n## Der Fehler, den fast jeder einmal baut\n\nAus der Lazy-Eigenschaft folgt eine Pflicht, die im Material ein eigenes Kapitel hat, nämlich Disposable. Wenn ein `subscribe` einen Producer startet, dann muss irgendwer ihn auch wieder beenden. Beim `ticks$` oben ist das offensichtlich: Der `setInterval` läuft ewig weiter, solange niemand `unsubscribe` aufruft.\n\n```ts\nconst sub = ticks$.subscribe((v) => console.log(v));\n\n// Without this line the timer ticks forever,\n// even after the component is long gone.\nsub.unsubscribe();\n```\n\nIn einer Single-Page-Anwendung kann daraus ein echtes Leck werden. Eine Komponente abonniert einen Event-Stream, der Nutzer navigiert weg, die Komponente verschwindet aus dem DOM, aber ein nicht beendetes Abo hält Listener und referenzierte Objekte am Leben. Beim nächsten Öffnen kommt ein zweites Abo dazu, dann ein drittes. Die Symptome sind doppelt ausgeführte Side Effects und wachsender Speicherverbrauch. Die Subscription ist die Grenze, an der ein Stream Besitz und Lebensdauer bekommt; je nach Quelle endet sie durch `complete`, `error` oder ein bewusstes Unsubscribe.\n\n## Was bleibt\n\nPush und Pull ist kein theoretisches Detail, sondern das Raster, an dem du jede Entscheidung in RxJS aufhängst. Brauche ich einen oder mehrere Werte? Zieht mein Consumer oder schiebt mein Producer? Startet die Arbeit sofort oder erst beim Abonnieren? Und wer beendet den Stream wieder? Diese vier Fragen klären die meisten Operator-Diskussionen, bevor sie entstehen.\n\nDie Reihenfolge in meinem Begleitmaterial – das ich auch mit Partnern wie [Grossweber](https://grossweber.com/) einsetze – folgt genau dieser Logik. Erst Observable, Observer und Notification, also das Push-Vokabular. Dann Scheduler und Disposable, also Zeit und Lebensdauer. Operatoren kommen zuletzt, weil sie nur Werkzeuge auf diesem Fundament sind. Wer mit der Operatorliste anfängt, lernt Vokabeln ohne Grammatik.\n\n## Weiterführende Quellen\n\n- RxJS-Dokumentation, Kapitel Observable mit der Push/Pull-Tabelle: https://rxjs.dev/guide/observable\n- [RxJS: `publishReplay` und heutige Alternativen](https://rxjs.dev/api/operators/publishReplay)\n- [RxJS: `shareReplay`](https://rxjs.dev/api/index/function/shareReplay)\n- Begleitmaterial der Schulung, Repository `introduction-rxjs`: https://github.com/MikeBild/introduction-rxjs"},{"locale":"de","translation_key":"nodejs-async-io-architektur","slug":"nodejs-async-io-architektur","title":"Node.js: Async I/O erklärt Architektur","summary":"Die Rechnung „ein Thread mal 200 Verbindungen“ zeigt, welche Systeme zu Node.js passen und welche Arbeit besser in eigene Prozesse gehört.","tags":["Software","Node.js","Backend"],"published_at":"2017-03-24T10:00:00+00:00","updated_at":"2026-07-14T20:54:32.790854+00:00","url":"https://www.mikebild.dev/de/blog/nodejs-async-io-architektur/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/c9eed85f57845819b6b32bfdc67178f86cfba4c2a12fff5387324699eb973f6a/nodejs-async-io-architektur-vorlesen.mp3","audio_duration_secs":712,"text":"# Node.js: Async I/O erklärt Architektur\n\nFünfzig Millisekunden sind keine auffällige Zahl. Ein `JSON.parse` über ein paar Megabyte, eine synchrone Template-Renderung, etwas Hashing – 50 ms CPU-Zeit fallen in keinem Profiler unangenehm auf. Jetzt die zweite Zahl: 200 gleichzeitige Verbindungen. In Node.js läuft sämtlicher JavaScript-Code auf einem einzigen Thread. Enthält jede dieser 200 Anfragen einen synchronen 50-ms-Block, wartet die letzte Antwort nicht 50 Millisekunden, sondern 200 × 50 ms = 10 Sekunden. Nicht weil die Maschine überlastet wäre – CPU und Netz langweilen sich –, sondern weil sich alle Anfragen denselben Thread teilen und der Reihe nach durch denselben Engpass müssen.\n\nDiese kleine Rechnung ist der komplette Architektur-Vortrag über Node.js in einem Absatz. Wer sie einmal wirklich verstanden hat, kann die meisten Systementscheidungen rund um Node ableiten: welche Dienste dorthin gehören, welche nicht, und warum die Skalierungsantwort „mehr Prozesse“ heißt. Wie sich das im Einzelnen auswirkt, zeigen die folgenden Abschnitte.\n\n## Ein Thread, viele Verbindungen\n\nNode beantwortet die Frage „Wie bediene ich viele gleichzeitige Verbindungen?\" anders als die klassischen Server. Apache mit PHP oder ein Java-Servlet-Container geben jeder Anfrage einen eigenen Thread oder Prozess; blockiert einer, stört das die anderen kaum. Node dreht das Modell um: Es gibt genau einen Thread für JavaScript, und der darf nie warten. Alles, was dauert – ein Netzwerkaufruf, ein Dateizugriff, ein DNS-Lookup –, wird an das Betriebssystem oder an einen kleinen internen Threadpool abgegeben. Der JavaScript-Thread registriert lediglich einen Callback und wendet sich der nächsten Aufgabe zu.\n\nOrganisiert wird das von libuv, der C-Bibliothek, auf der Node aufsetzt. Sie fragt den Kernel über epoll (Linux), kqueue (macOS) oder IOCP (Windows), welche der offenen Operationen fertig sind, und arbeitet die zugehörigen Callbacks in einer festen Reihenfolge ab – das ist der Event-Loop. Der Loop durchläuft Phasen: Timer, anstehende Callbacks, Polling auf I/O, `setImmediate`, Close-Callbacks. Dazwischen schiebt sich die Microtask-Verarbeitung mit `process.nextTick` und Promise-Auflösungen. Dateisystem, DNS und Teile von Krypto laufen nicht über den Kernel-Mechanismus, sondern über den erwähnten Threadpool – standardmäßig vier Threads, einstellbar über `UV_THREADPOOL_SIZE`.\n\n```mermaid\nflowchart LR\n  subgraph proc[Node-Prozess]\n    JS[JavaScript<br/>ein einziger Thread] --> Loop[Event-Loop<br/>libuv]\n  end\n  Loop --> Kernel[Kernel<br/>epoll / kqueue / IOCP]\n  Loop --> Pool[Threadpool<br/>fs, dns, crypto]\n  Kernel -. Callback bereit .-> JS\n  Pool -. Callback bereit .-> JS\n```\n\nFür den Alltag reichen zwei Merksätze. Erstens: I/O ist in Node praktisch gratis, weil das Warten woanders stattfindet – im Kernel oder im Threadpool. Zweitens: CPU-Zeit im JavaScript-Thread ist die teuerste Ressource des ganzen Systems, weil sie exklusiv ist. Jede Millisekunde, die eine Anfrage rechnet, ist eine Millisekunde, in der alle anderen Anfragen stillstehen.\n\n## Ein blockierender Aufruf blockiert alle\n\nMir ist das zum ersten Mal in einem Produktionsvorfall wirklich klar geworden, nicht beim Lesen der Dokumentation. Ein Reporting-Endpoint nahm JSON-Dokumente entgegen, im Normalfall wenige Kilobyte. Eines Tages begann ein Client, Exporte mit rund 30 MB zu schicken. Der Code sah harmlos aus:\n\n```js\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n  let body = '';\n  req.on('data', chunk => { body += chunk; });\n  req.on('end', () => {\n    // synchronous: the event loop stops while parsing\n    const report = JSON.parse(body);\n    res.end(JSON.stringify({ items: report.items.length }));\n  });\n});\n\nserver.listen(3000);\n```\n\n`JSON.parse` über 30 MB braucht mehrere hundert Millisekunden. In dieser Zeit passiert im Prozess sonst nichts: keine neuen Verbindungen, keine laufenden Antworten, keine Timer. Auch der Health-Check-Endpoint antwortete nicht mehr, der Load-Balancer nahm die Instanz aus der Rotation, das Monitoring meldete den Dienst als tot – dabei lief der Prozess einwandfrei und hat schlicht gerechnet. Der Vorfall war nach einer Stunde verstanden, aber die Lektion war größer als der Vorfall: In Node gibt es keine „eine langsame Anfrage\". Es gibt nur langsame Anfragen, die alle anderen mitnehmen.\n\nDas Fehlermodell unterscheidet sich damit grundlegend von Thread-pro-Anfrage-Servern. Dort äußert sich ein CPU-Fresser als ein langsamer Request in der Statistik. In Node äußert er sich als Latenz-Spitze über das gesamte System – und zwar auch für Anfragen, die mit dem Verursacher nichts zu tun haben.\n\n## Welche Systeme dazu passen – und welche nicht\n\nNimmt man das Modell ernst, sortieren sich Architekturentscheidungen fast von selbst. Node ist stark, wenn der Prozess überwiegend wartet und nur kurz rechnet:\n\n- API-Gateways und Proxies, die Anfragen prüfen, anreichern und weiterleiten\n- REST-APIs vor Datenbanken, bei denen die eigentliche Arbeit im Storage stattfindet\n- Aggregatoren, die mehrere Backends parallel abfragen und Ergebnisse zusammensetzen\n- Push- und Realtime-Dienste mit vielen offenen, meist stillen Verbindungen\n\nAll diese Systeme haben denselben Charakter: Tausende Verbindungen, von denen im Moment fast alle auf etwas warten. Genau dafür ist ein Event-Loop gebaut – die wartenden Verbindungen kosten fast nichts, ein Thread genügt für alle.\n\nUmgekehrt gehört Arbeit mit ernsthafter CPU-Last nicht in den Request-Pfad eines Node-Prozesses: Bildverarbeitung, PDF-Erzeugung, das Verschlüsseln großer Dateien, aufwendige Berechnungen über Datensätzen. Nicht weil V8 langsam wäre – der JIT-Compiler ist erstaunlich schnell –, sondern weil jede dieser Millisekunden allen Anfragen gleichzeitig gehört.\n\nIn einem Projekt haben wir an dieser Linie ein Gateway geschnitten: Node übernahm Authentifizierung, Routing und das Zusammensetzen von Antworten aus drei Backends. Die Thumbnail-Erzeugung für hochgeladene Bilder, anfangs mitten im Upload-Handler, wanderte in einen separaten Prozess mit eigener Queue – per `child_process.fork` gestartet und über Messages angebunden. Die Upload-Latenz fiel, aber der eigentliche Gewinn war ein anderer: Die 99. Perzentile aller übrigen Endpoints beruhigte sich, weil kein Bild mehr den gemeinsamen Thread besetzte. Der Event-Loop hatte uns die Grenze diktiert, an der das System zu trennen war – und es war eine gute Grenze.\n\n## Backpressure: auch Warten will organisiert sein\n\nAsync I/O heißt nicht, dass Daten von allein in der richtigen Geschwindigkeit fließen. Wer eine 2-GB-Exportdatei mit `fs.readFile` lädt, um sie an den Client zu schicken, hält 2 GB im Speicher – pro Anfrage. Streams lösen das, indem sie Daten in Stücken durchreichen:\n\n```js\nconst fs = require('fs');\nconst zlib = require('zlib');\nconst http = require('http');\n\nhttp.createServer((req, res) => {\n  res.setHeader('Content-Encoding', 'gzip');\n  fs.createReadStream('./export.csv')\n    .pipe(zlib.createGzip())\n    .pipe(res);\n}).listen(3000);\n```\n\nDas Interessante an `pipe` ist nicht die kompakte Schreibweise, sondern die eingebaute Flusskontrolle. Kommt das Ziel nicht hinterher – liefert `write()` also `false` –, pausiert der lesende Stream, bis das `drain`-Event signalisiert, dass wieder Platz ist. Dieses Wechselspiel heißt Backpressure. Ohne diese Bremse liest die Platte mit ein paar hundert MB/s, während ein Mobilfunk-Client mit einem Bruchteil davon empfängt – die Differenz sammelt sich als Buffer im Heap, und der Prozess wächst, bis der Speicher endet.\n\nBackpressure ist damit die zweite Stelle, an der das Laufzeitmodell zur Architekturfrage wird: Wer Uploads, Exporte oder Eventströme über Node führt, muss Datenfluss als etwas Begrenzbares entwerfen – mit Streams als Standardwerkzeug und `pipe` als Verbindungsstück, nicht mit „alles in eine Variable und dann senden\".\n\n## Skalieren heißt: mehr Prozesse\n\nEin Node-Prozess nutzt für JavaScript einen Kern. Auf einer Maschine mit acht Kernen liegen also sieben brach, solange nur ein Prozess läuft. Die Antwort der Plattform ist das `cluster`-Modul: Ein Master-Prozess startet pro Kern einen Worker, alle teilen sich denselben Port, der Master verteilt eingehende Verbindungen reihum.\n\n```js\nconst cluster = require('cluster');\nconst os = require('os');\n\nif (cluster.isMaster) {\n  os.cpus().forEach(() => cluster.fork());\n  cluster.on('exit', worker => {\n    console.log(`worker ${worker.process.pid} died, forking a new one`);\n    cluster.fork();\n  });\n} else {\n  require('./server');\n}\n```\n\n```mermaid\nflowchart TB\n  In[eingehende Verbindungen<br/>Port 3000] --> M[Master-Prozess<br/>Round-Robin-Verteilung]\n  M --> W1[Worker 1<br/>eigener Event-Loop]\n  M --> W2[Worker 2<br/>eigener Event-Loop]\n  M --> W3[Worker N<br/>eigener Event-Loop]\n```\n\nJeder Worker hat seinen eigenen Event-Loop und seinen eigenen Heap. Das hat zwei angenehme Nebenwirkungen und eine unbequeme Konsequenz. Angenehm: Ein abgestürzter Worker reißt nur sich selbst mit, der Master startet ihn neu; und ein blockierter Worker blockiert nur noch ein Achtel des Systems statt alles. Unbequem: Es gibt keinen gemeinsamen Speicher. Sessions, Caches, Zähler – alles, was bisher bequem in einer Modul-Variablen lag, muss raus aus dem Prozess, etwa in Redis oder die Datenbank. Aus meiner Sicht ist das kein Verlust, sondern ein früher Zwang zu einem Zustand, den man für horizontale Skalierung über Maschinen hinweg ohnehin braucht. Wer mit `cluster` auf acht Worker kommt, kommt später fast ohne Änderung auf acht Maschinen.\n\nWichtig ist die Einordnung: `cluster` mildert das Blockier-Problem, es löst es nicht. Die 50-ms-Rechnung vom Anfang gilt in jedem Worker unverändert. Für echte CPU-Arbeit bleibt die saubere Antwort ein eigener Prozess mit Queue davor – `cluster` ist Lastverteilung, kein Freibrief für Rechenarbeit im Request-Pfad.\n\n## async/await: neue Syntax, dasselbe Modell\n\nSeit wenigen Wochen – Node 7.6, erschienen im Februar 2017 – laufen `async`/`await` ohne Flag. Auf Node 6 LTS, das viele Produktionssysteme fahren, braucht es dafür weiterhin Babel. Nach Jahren von Callback-Pyramiden und Promise-Ketten liest sich derselbe Ablauf plötzlich wie synchroner Code:\n\n```js\nasync function loadDashboard(userId) {\n  const user = await fetchUser(userId);\n  const orders = await fetchOrders(user.id);\n  return { user, orders };\n}\n\n// independent calls: run them concurrently instead\nasync function loadDashboardFast(userId) {\n  const [user, orders] = await Promise.all([\n    fetchUser(userId),\n    fetchOrders(userId)\n  ]);\n  return { user, orders };\n}\n```\n\nSynchron ist daran nichts. An jedem `await` gibt die Funktion den Thread frei; der Event-Loop bedient andere Callbacks und setzt die Funktion fort, sobald das Promise aufgelöst ist. Genau deshalb gehören zwei Dinge in denselben Gedanken. Erstens: Zwei nacheinander stehende `await`-Zeilen laufen sequenziell, auch wenn sie unabhängig sind – für Parallelität bleibt `Promise.all` zuständig, wie im zweiten Beispiel. Zweitens, und das halte ich für die eigentliche Falle der neuen Syntax: `await` macht Wartezeiten kooperativ, aber CPU-Arbeit zwischen zwei `await`-Punkten blockiert exakt wie vorher. Ein `JSON.parse` über 30 MB wird nicht höflicher, weil davor ein `await` steht. Wer vom Callback über das Promise zu `async`/`await` gewechselt ist, hat deutlich besseren Code – und ein unverändertes Laufzeitmodell. Die Syntax ist neu, die Rechnung bleibt.\n\nLauffähige Beispiele zu all dem – Event-Loop, Streams, Express, Async-Pattern vom Callback bis zum Stream – sammle ich in einem öffentlichen Repository: [MikeBild/introduction-nodejs](https://github.com/MikeBild/introduction-nodejs). Die Beispiele sind bewusst klein gehalten; jedes zeigt genau eine der hier beschriebenen Grenzen.\n\n## Unterm Strich\n\nDer Event-Loop ist ein brauchbarer Architektur-Test, und zwar ein billiger. Für jedes geplante Feature lässt sich fragen: Wartet dieser Code, oder rechnet er? Wartende Arbeit – Datenbank, HTTP, Dateien, offene Verbindungen – passt in den Node-Prozess, in fast beliebiger Menge. Rechnende Arbeit gehört in eigene Prozesse, hinter eine Queue, mit `cluster` und `child_process` als Bordmitteln. Streams mit funktionierendem Backpressure halten den Speicher flach, wo große Datenmengen fließen.\n\nBemerkenswert finde ich, wie viel Architektur aus einer einzigen Laufzeit-Eigenschaft folgt. Die Trennung von Gateway und Bildverarbeitung, zustandslose Prozesse, Queues vor CPU-Arbeit – nichts davon steht in einem Framework-Handbuch, alles davon steckt in der Rechnung 200 × 50 ms. Plattformen erziehen ihre Systeme, ob man das will oder nicht. Bei Node ist die Erziehung streng, aber sie zeigt in eine Richtung, die sich auch jenseits von Node auszahlt: kleine Prozesse, die überwiegend warten, nichts Wichtiges im lokalen Speicher halten und ihre Datenflüsse begrenzen. Wer die 10 Sekunden vom Anfang einmal in einem echten Dashboard gesehen hat, vergisst diese Richtung nicht mehr.\n\n## Weiterführende Quellen\n\n- Beispiel-Repository „Introduction to NodeJS\": https://github.com/MikeBild/introduction-nodejs\n- The Node.js Event Loop, Timers, and process.nextTick(): https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick\n- Backpressuring in Streams: https://nodejs.org/en/learn/modules/backpressuring-in-streams\n- libuv Design Overview: https://docs.libuv.org/en/v1.x/design.html\n- Cluster-Modul (Node.js-Dokumentation): https://nodejs.org/api/cluster.html"},{"locale":"de","translation_key":"babel-node-express-http","slug":"babel-node-express-http","title":"Babel Node Express: moderne Syntax, altes HTTP","summary":"Babel übersetzt Syntax, kein Ausführungsmodell – wer das trennt, weiß, warum babel-node in die Entwicklungsschleife gehört und nicht in den Betrieb.","tags":["Software","Node.js","Backend"],"published_at":"2016-12-20T10:00:00+00:00","updated_at":"2026-07-14T17:17:26.234673+00:00","url":"https://www.mikebild.dev/de/blog/babel-node-express-http/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/00ec79caf10ee98fa18e0fa86cada992ddffdf45f4e9abaa02fb3c24069157f2/babel-node-express-http-vorlesen.mp3","audio_duration_secs":769,"text":"# Babel Node Express: moderne Syntax, altes HTTP\n\n```text\n$ node src/server.js\n/app/src/server.js:1\n(function (exports, require, module, __filename, __dirname) { import express from 'express';\n                                                               ^^^^^^\nSyntaxError: Unexpected token import\n    at Object.exports.runInThisContext (vm.js:76:16)\n    at Module._compile (module.js:542:28)\n```\n\nSo quittiert Node 6 eine Datei, die mit einem `import` beginnt. Die Meldung ist kurz, die Verwirrung dahinter verlässlich: Dieselbe Zeile steht in gefühlt jedem zweiten Tutorial dieses Jahres, sie läuft im Frontend-Build ohne Murren – nur die Runtime, die den Server am Ende tatsächlich ausführen soll, kennt das Schlüsselwort nicht. ES2015 ist seit anderthalb Jahren verabschiedet, V8 hat einen großen Teil davon eingebaut, und trotzdem scheitert der Start an der ersten Zeile der ersten Datei.\n\nDer Anlass für diesen Beitrag ist ein kleines Repository, das ich Anfang Dezember zusammengesteckt habe: [babel-node-expressjs](https://github.com/MikeBild/babel-node-expressjs), eine bewusst schlichte Express-App, durchgehend in ES2015+ geschrieben und über Babel lauffähig gemacht. Am selben Tag entstand ein zweites, [babel-node-rx-ping-monitor](https://github.com/MikeBild/babel-node-rx-ping-monitor), das RxJS durch dieselbe Toolchain schiebt – das hat aber ein eigenes Thema und verdient einen eigenen Text. Hier geht es um die Trennlinie, die beim Aufsetzen sichtbar wurde und die in Diskussionen erstaunlich oft verwischt: Babel verändert die Sprache, nicht das Ausführungsmodell. Die Syntax ist 2016 modern geworden. Das HTTP darunter ist dasselbe geblieben.\n\n## Was Node 6 und 7 schon von selbst können\n\nBevor Babel ins Spiel kommt, lohnt ein nüchterner Blick darauf, was die Plattform ohne jedes Werkzeug beherrscht. Node 6 ist seit Oktober die aktive LTS-Linie, Node 7 die aktuelle Entwicklungslinie, und beide bringen über V8 bereits einen erheblichen Teil von ES2015 nativ mit:\n\n- Klassen samt `extends` und `super`\n- `const` und `let` mit echtem Block-Scoping\n- Template-Literals, Arrow Functions, Default-Parameter\n- Destructuring für Objekte und Arrays\n- Promises und Generatoren\n\nWer nachsehen will, was die eigene Node-Version im Detail abdeckt, findet auf node.green eine Matrix pro Version und Feature. Die Liste ist länger, als viele annehmen – und genau deshalb ist die pauschale Ansage „für ES2015 brauchst du Babel“ inzwischen schief. Für den Großteil der Sprache braucht man es schlicht nicht mehr.\n\nZwei prominente Lücken bleiben. `async`/`await` existiert in Node 7 nur experimentell hinter der Flagge `--harmony-async-await` – für Code, der einen Server tragen soll, ist das kein Fundament, sondern ein Ausblick. Und `import`/`export` fehlt vollständig: Die Modul-Syntax ist zwar Teil der Spezifikation, aber wie ein Loader in Node aussehen soll und wie ES-Module mit dem gewachsenen CommonJS-Ökosystem zusammenspielen, ist ungeklärt. Ein natives ES-Modulsystem ist nicht in Sicht. Wer heute `import` im Backend schreibt, schreibt Syntax für eine Runtime, die es so noch gar nicht gibt – und braucht deshalb einen Übersetzer.\n\n## Die App: Express 4 in heutiger Schreibweise\n\nDer Server im Repository tut absichtlich wenig – eine JSON-Route, eine Route für URL-encodierte Formulardaten, beides im README vorgeführt:\n\n```js\nimport express from 'express';\nimport bodyParser from 'body-parser';\n\nconst app = express();\nconst port = process.env.PORT || 3000;\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: false }));\n\napp.get('/', (req, res) => {\n  res.json({ message: 'hello' });\n});\n\napp.post('/', (req, res) => {\n  const { msg } = req.body;\n  res.json({ received: msg });\n});\n\napp.listen(port, () => {\n  console.log(`server listening on port ${port}`);\n});\n```\n\nInteressant ist nicht, was dieser Code tut, sondern wie er aussieht: `import` statt `require`, Arrow Functions statt `function`, `const` statt `var`, Destructuring am Request-Body, Template-Literal im Log. Das ist die Schreibweise, die sich dieses Jahr im Frontend endgültig durchgesetzt hat, und es gibt keinen guten Grund, im Backend eine ältere Sprachstufe zu pflegen als im Rest des Projekts. Einheitliche Syntax senkt die Reibung, wenn dieselben Leute vormittags React-Komponenten und nachmittags Express-Routen anfassen.\n\nAm Rand sieht man hier auch ein Stück Express-4-Geschichte: Das Body-Parsing ist keine eingebaute Funktion mehr, sondern kommt als eigenes Paket `body-parser` dazu und wird pro Format als Middleware eingehängt. Wer von Express 3 kommt, stolpert zuerst genau an dieser Stelle – und das hat mit Babel nichts zu tun, mit HTTP dafür umso mehr.\n\nAuf der Leitung ändert sich dadurch exakt nichts. Ein POST auf `http://localhost:3000` mit einem URL-encodierten Formularfeld – im README steht der passende Einzeiler – schickt dieselben Bytes wie gegen jede Express-App der letzten drei Jahre, und die Antwort ist derselbe HTTP-Response mit denselben Headern. Middleware-Kette, Body-Parsing, Statuscodes, Content-Negotiation – das komplette HTTP-Verhalten ist von der Syntaxfrage unberührt. Das klingt banal. Es ist aber der Kern des Themas, denn genau hier entstehen die Missverständnisse.\n\n## Was babel-node im Entwicklungsmodus tut\n\nDamit die Datei überhaupt startet, braucht es zwei Dinge: eine Übersetzungsvorschrift und ein Werkzeug, das sie anwendet. Die Vorschrift steht in der `.babelrc`:\n\n```json\n{\n  \"presets\": [\"es2015\"]\n}\n```\n\nDas Preset `es2015` ist der etablierte Weg mit Babel 6. Ganz frisch gibt es daneben `babel-preset-env`, das über ein `targets`-Feld nur noch das transpiliert, was die Ziel-Node-Version tatsächlich nicht kann – dazu gleich mehr. Das Werkzeug für die Entwicklung heißt `babel-node` und liegt der `babel-cli` bei. Es startet einen normalen Node-Prozess, hängt sich in den `require`-Mechanismus ein und übersetzt jede geladene Datei im Speicher, unmittelbar bevor V8 sie sieht. Kein `dist/`-Ordner, kein Zwischenschritt, zusammen mit nodemon ergibt das eine angenehm kurze Schleife:\n\n```json\n{\n  \"scripts\": {\n    \"dev\": \"nodemon --exec babel-node src/server.js\",\n    \"build\": \"babel src --out-dir dist --source-maps\",\n    \"start\": \"node dist/server.js\"\n  }\n}\n```\n\nDatei speichern, nodemon startet neu, babel-node übersetzt, der Server läuft. Für die Entwicklung ist das genau richtig, weil die Rückmeldung zählt und der Prozess ohnehin ständig neu startet. Wichtig ist nur, sich klarzumachen, was da passiert: Die Übersetzung ist in den Programmstart hineingezogen worden. Jeder Start bezahlt sie erneut.\n\nDerselbe Mechanismus trägt übrigens auch die Tests: `babel-register`, in mocha eingehängt, übersetzt die Testdateien nach demselben Prinzip beim Laden. Auch das ist für die Entwicklungsschleife gedacht und dort völlig in Ordnung – ein Testlauf ist ein kurzlebiger Prozess, bei dem ein paar hundert Millisekunden Anlauf nicht ins Gewicht fallen. Die Grenze verläuft also nicht zwischen „mit Babel“ und „ohne Babel“, sondern zwischen kurzlebigen Werkzeugprozessen und dem einen Prozess, der lange laufen und nach einem Absturz schnell wieder da sein muss.\n\n```mermaid\nflowchart LR\n  subgraph DEV[Entwicklung]\n    S1[src/server.js<br/>ES2015+] --> BN[babel-node<br/>übersetzt im Speicher] --> P1[Node-Prozess]\n  end\n  subgraph PROD[Produktion]\n    S2[src/server.js<br/>ES2015+] --> BC[npm run build<br/>babel-cli] --> D[dist/server.js<br/>ES5 + CommonJS] --> P2[node dist/server.js]\n  end\n```\n\n## Was der bequeme Weg in Produktion kostet\n\nDie Versuchung liegt nahe, `babel-node` einfach auch in Produktion zu verwenden – ein Skript weniger, ein Ordner weniger, dieselbe Kommandozeile überall. Die Babel-Dokumentation rät selbst ausdrücklich davon ab, und die Gründe sind handfest:\n\n- Der Prozessstart wird spürbar langsamer, weil jede Datei beim Hochfahren erst durch den Transpiler muss – bei jedem Deployment, bei jedem Neustart nach einem Absturz, bei jedem Prozess im Cluster erneut.\n- Der Speicherverbrauch steigt, weil Babel samt Parser, Presets und Cache dauerhaft im Serverprozess mitläuft, obwohl er nach dem Start nichts mehr beiträgt.\n- Stacktraces zeigen auf übersetzten Code, den nie jemand geschrieben hat; ohne sauber verdrahtete Sourcemaps zeigt die Zeilennummer im Fehlerreport ins Leere.\n- Der Debugger arbeitet gegen den erzeugten Code, Breakpoints landen neben der gemeinten Zeile, und das Verhalten hängt an der installierten Babel-Version auf der Zielmaschine.\n\nMir ist der Punkt in einem Projekt dieses Jahr konkret begegnet: Ein Kollege hatte einen kleinen internen Service mit `babel-node` deployt, und wochenlang fiel das niemandem auf. Aufgefallen ist es erst, als der Prozess unter Last neu startete und der Supervisor ihn mehrfach hintereinander hochzog – jeder Neustart mehrere Sekunden Transpilierung, in denen der Port zwar offen, der Service aber nicht ansprechbar war. Der Fehler stand in keiner Zeile Anwendungscode. Er steckte in der Entscheidung, ein Entwicklungswerkzeug in den Betrieb mitzunehmen.\n\n## Erst bauen, dann starten\n\nDie erwachsene Variante trennt die Übersetzung vom Start. `npm run build` ruft die `babel-cli` auf, übersetzt `src/` einmal nach `dist/` und legt Sourcemaps daneben. Was dort ankommt, ist unspektakuläres ES5 mit CommonJS – aus dem `import` am Dateianfang wird genau das, was Node seit Jahren versteht:\n\n```js\n'use strict';\n\nvar _express = require('express');\n\nvar _express2 = _interopRequireDefault(_express);\n\nfunction _interopRequireDefault(obj) {\n  return obj && obj.__esModule ? obj : { default: obj };\n}\n```\n\nMan muss diesen erzeugten Code nicht schön finden, aber man sollte ihn einmal gelesen haben. Er nimmt der Modul-Syntax jede Magie: `import` ist nach der Übersetzung ein synchrones `require` beim Programmstart, mit einer kleinen Verpackung für den Default-Export. Keine neue Ladelogik, kein anderes Auflösungsverhalten, kein Unterschied zur Laufzeit.\n\nDas Artefakt in `dist/` hat zwei angenehme Eigenschaften. Erstens braucht die Zielmaschine kein Babel mehr – `node dist/server.js` genügt, die devDependencies bleiben zu Hause. Zweitens ist der Startpfad wieder der langweilige, den Node seit Jahren geht: Prozess starten, Module laden, Port öffnen. Die Übersetzung passiert einmal pro Build statt einmal pro Start, und genau dort gehört sie hin. Dass zwischen „es läuft auf meiner Maschine per babel-node“ und „es läuft als gebautes Artefakt“ ein Unterschied besteht, merkt man sonst erst im unpassendsten Moment.\n\nPraktisch folgt daraus auch, wo gebaut wird: in der Pipeline, nicht auf der Zielmaschine. Gebaut und getestet wird einmal, das Ergebnis wird ausgeliefert, und eine Installation ohne devDependencies lässt Babel samt Presets auf dem Server komplett weg. Die Reihenfolge im README des Repos – build, test, dann erst run – ist insofern keine Formsache, sondern die Kurzfassung dieses Betriebsmodells.\n\n## Sprache oben, Ausführungsmodell unten\n\nDamit zur eigentlichen Trennlinie. Babel arbeitet ausschließlich auf der Ebene der Sprache: Es liest Syntax, die V8 noch nicht versteht, und schreibt sie in Syntax um, die V8 versteht. Alles darunter bleibt unangetastet – der Event Loop, das Modulsystem zur Laufzeit, Streams, Sockets, das komplette HTTP.\n\n```mermaid\nflowchart TB\n  B[Babel] -->|verändert nur diese Ebene| L1\n  L1[Sprache: import, Klassen,<br/>Arrow Functions, Destructuring] --> L2[Laufzeitumgebung: Event Loop,<br/>CommonJS-require, Streams]\n  L2 --> L3[HTTP: Verbindungen, Header,<br/>Request und Response]\n```\n\nDiese Trennung klingt selbstverständlich, wird aber regelmäßig verwischt, sobald die neue Syntax nach mehr aussieht, als sie ist. Drei Beispiele aus Gesprächen der letzten Monate. Ein `import` oben in der Datei wirkt deklarativ und statisch – nach der Übersetzung ist es ein gewöhnliches `require`, das beim Start synchron ausgeführt wird, in der Reihenfolge der Zeilen. Eine Arrow Function in der Route wirkt leichtgewichtig – sie läuft auf demselben einen Thread wie alles andere, und eine teure JSON-Serialisierung darin blockiert den Event Loop exakt so wie 2013. Und die `async`-Vorboten aus Node 7 wirken wie Concurrency – tatsächlich sind sie nur eine andere Schreibweise für Promise-Ketten, an Timeouts, Fehlerpfaden und Lastverhalten ändern sie nichts. Wer einen Express-Server mit moderner Syntax betreibt, betreibt denselben Server. Die Fragen, die im Betrieb zählen – wie lange darf ein Request dauern, was passiert bei einem abgebrochenen Body, wer beendet den Prozess sauber –, beantwortet kein Preset.\n\nUmgekehrt hilft die Trennung auch beim Sparen. Weil Node 6 den Großteil von ES2015 nativ ausführt, muss Babel gar nicht mehr die ganze Sprache übersetzen. Genau da setzt das frische `babel-preset-env` an: Man nennt ihm die Zielumgebung, und es wählt nur die Transformationen aus, die dort wirklich fehlen.\n\n```json\n{\n  \"presets\": [\n    [\"env\", { \"targets\": { \"node\": 6 } }]\n  ]\n}\n```\n\nFür Node 6 bleibt davon im Wesentlichen die Modul-Syntax übrig. Der erzeugte Code bleibt näher am Original, Klassen bleiben echte V8-Klassen statt ES5-Prototypen-Nachbauten, und der Build wird schneller. Je besser die Plattform wird, desto dünner darf die Übersetzungsschicht sein – bis sie eines Tages vielleicht ganz verschwindet. Darauf wetten würde ich beim Thema Module allerdings noch nicht.\n\n## Was ich daraus mitnehme\n\nDie beiden kleinen Repos waren an einem Nachmittag zusammengebaut, aber die Trennlinie, die sie zeigen, trägt weiter als der Code. Babel ist ein Übersetzer für Syntax, kein neues Ausführungsmodell – und beide Richtungen dieser Aussage sind nützlich. In die eine Richtung: Die moderne Schreibweise kostet im Betrieb nichts, wenn man sie im Build bezahlt statt beim Prozessstart; `babel-node` gehört in die Entwicklungsschleife, `node dist/` in die Produktion. In die andere Richtung: Die moderne Schreibweise löst auch nichts, was auf der HTTP-Ebene zu lösen wäre. Timeouts, Error Handling, Body-Grenzen und Neustartverhalten sehen in ES2015 exakt so aus wie in ES5, nur hübscher.\n\nWenn im nächsten Jahr `async`/`await` ohne Flagge ankommt, wird sich dieselbe Frage neu stellen, mit denselben Antworten. Die Syntax wird wieder ein Stück moderner. Das HTTP darunter bleibt das alte – und das ist keine schlechte Nachricht, denn es bedeutet, dass sich zwanzig Jahre Wissen über Server nicht mit jedem Preset erneuern müssen.\n\n## Weiterführende Quellen\n\n- Repository: https://github.com/MikeBild/babel-node-expressjs\n- Express-Dokumentation: https://expressjs.com/\n- babel-preset-env: https://github.com/babel/babel-preset-env\n- babel-node in der Babel-Dokumentation: https://babeljs.io/docs/babel-node"},{"locale":"de","translation_key":"api-denken-vor-framework-denken","slug":"api-denken-vor-framework-denken","title":"API-Denken vor Framework-Denken","summary":"Wer Operationen, Daten und Fehlerfälle vor der Framework-Wahl festlegt, kann das Frontend später fast beliebig tauschen – umgekehrt bekommt man eine API, die ein Framework nachbildet.","tags":["Software","GraphQL","API"],"published_at":"2016-12-12T10:00:00+00:00","updated_at":"2026-07-14T16:37:07.719359+00:00","url":"https://www.mikebild.dev/de/blog/api-denken-vor-framework-denken/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0bacf706b5df62ef57f675eb7df31f0b18e3c014f935815ef531087b586bceb6/api-denken-vor-framework-denken-vorlesen.mp3","audio_duration_secs":752,"text":"# API-Denken vor Framework-Denken\n\n„Angular oder React?\" gilt in diesem Jahr als die Architekturfrage für neue Web-Projekte. Sie ist keine. Sie ist eine Werkzeugfrage – und sie wird regelmäßig gestellt, bevor jemand die Frage beantwortet hat, die tatsächlich Architektur ist: Was sind eigentlich unsere Operationen und unsere Daten? Diese Reihenfolge ist verkehrt herum, und sie ist gerade besonders verführerisch. 2016 ist das Jahr der Framework-Debatten: Angular 2 ist seit September final, Vue 2 erschien Ende September, React steht bei Version 15, und die Vergleichsartikel dazu füllen Konferenzprogramme, Blogs und Team-Meetings.\n\nDer Streit ist unterhaltsam, aber er verdeckt etwas Einfaches: Das Framework rendert nur, was eine API hergibt. Wer die API zuerst entwirft – Ressourcen oder Schema, Namen aus der Fachsprache, Fehlerfälle, Berechtigungen –, kann das Frontend danach fast frei wählen und später sogar wechseln. Wer das Framework zuerst wählt, bekommt mit hoher Wahrscheinlichkeit eine API, die den Datenfluss genau dieses Frameworks nachbildet. Und diese API bleibt, wenn das Framework längst abgelöst ist.\n\n## Was eine API festlegt – und was ein Framework\n\nEin Frontend-Framework entscheidet, wie Komponenten gerendert werden, wie Zustand im Client verwaltet wird und wie sich das Team organisiert, das die Oberfläche baut. Das ist nicht wenig, aber es ist austauschbar. Migrationsgeschichten von Backbone nach Angular oder von Angular 1 nach React gibt es genug – in diesem Jahr, mit dem harten Schnitt zwischen Angular 1 und Angular 2, mehr denn je. Ein Framework-Wechsel ist teuer, aber er ist ein lokales Event: Er betrifft den Client und sonst niemanden.\n\nEine API legt etwas anderes fest, und zwar für alle Beteiligten gleichzeitig:\n\n- welche Operationen es gibt und wie sie heißen,\n- welche Daten zusammengehören und welche bewusst getrennt bleiben,\n- welche Fehlerfälle fachlich erwartbar sind und wie sie aussehen,\n- wer welche Operation auslösen darf.\n\nDiese vier Punkte überleben jede Framework-Mode. Sie bilden den Vertrag zwischen Fachseite, Backend und sämtlichen Clients – dem Web-Frontend von heute, der Mobile-App vom nächsten Jahr, dem Partner-System von übermorgen. Ein Vertrag, der sich ändert, zieht Änderungen bei allen Vertragspartnern nach sich. Genau deshalb gehört er an den Anfang, nicht ans Ende.\n\nDer vierte Punkt verdient dabei einen zweiten Blick, weil er beim Framework-zuerst-Vorgehen am zuverlässigsten unter die Räder kommt. Berechtigungen wirken aus Sicht der Oberfläche wie eine Anzeige-Angelegenheit: Der Button wird ausgeblendet, das Menü gekürzt, fertig. Aus Sicht der API sind sie eine Zusicherung – die Aussage, dass eine Operation von einem bestimmten Aufrufer schlicht nicht ausgelöst werden kann, egal welcher Client anklopft. Diese Zusicherung lässt sich nur im Vertrag geben, nicht in der Komponente. Wer sie beim Entwurf ausspart, holt sie später unter Zeitdruck nach, meist nachdem der erste Aufruf aufgetaucht ist, den kein Button je ausgelöst hat.\n\n## Die falsche Reihenfolge im Projektalltag\n\nWie sich die verkehrte Reihenfolge anfühlt, habe ich in diesem Frühjahr in einem Projekt erlebt: Bestellverwaltung für einen Handelskunden, Web-Oberfläche zuerst, Mobile „irgendwann später\". Die ersten drei Wochen gingen in die Framework-Evaluation – Angular 2 war noch Release Candidate, React mit Redux die Alternative, dazu die üblichen Nebenkriegsschauplätze um TypeScript und JSX. Die API stand auf keiner Agenda. „Machen wir, wenn das Frontend steht\", hieß es, und das war ehrlich gemeint.\n\nAls das Frontend stand, gab es dann auch eine API. Sie hatte einen Endpoint `/api/app-state`, der beim Laden den kompletten Redux-Store befüllte. Sie hatte Feldnamen, die aus den Reducern stammten, nicht aus der Fachsprache. Fehler kamen als HTTP 500 mit einem Text, weil der Client ohnehin nur eine rote Meldung anzeigte. Berechtigungen wurden im Frontend geprüft, weil das dort gerade bequemer war. Nichts davon war böser Wille – jede einzelne Entscheidung war aus Sicht des Frontends vernünftig. In Summe war die API ein Abdruck des Redux-Datenflusses.\n\nEin halbes Jahr später kam das Mobile-Team. Es konnte mit `/api/app-state` nichts anfangen, brauchte kleinere Zuschnitte, andere Error Handling, echte Autorisierung auf dem Server. Das Backend bekam eine zweite API neben der ersten, und ab da wurden beide gepflegt. Die Framework-Frage war damals übrigens zugunsten von React entschieden worden – es hätte für das Ergebnis keinen Unterschied gemacht, wenn es Angular geworden wäre. Die teure Entscheidung war nicht das Framework. Es war die Reihenfolge.\n\n## Ressourcen zuerst: ein Beispiel\n\nWie sieht die andere Reihenfolge aus? Sie beginnt mit einem Gespräch, in dem kein Framework vorkommt. Mit der Fachseite am Tisch werden die Begriffe eingesammelt, die dort ohnehin täglich fallen: Bestellung, Kunde, Kreditlimit, Stornierung. Aus diesen Begriffen entsteht ein erster Ressourcen-Entwurf – hier als REST-Routen notiert:\n\n```http\nGET    /customers/{id}\nGET    /customers/{id}/orders\nPOST   /orders\nGET    /orders/{id}\nPOST   /orders/{id}/cancellation\n```\n\nZwei Dinge an diesem Entwurf sind wichtiger, als sie aussehen. Erstens: `POST /orders/{id}/cancellation` statt `DELETE /orders/{id}`. Eine Stornierung ist im Handel keine Löschung, sondern ein fachlicher Vorgang mit eigenen Regeln – sie kann abgelehnt werden, sie kann Gebühren auslösen, sie taucht in der Historie auf. Der Endpoint trägt den Namen aus der Fachsprache, nicht den aus dem HTTP-Lehrbuch. Zweitens: Der Fehlerfall ist Teil des Vertrags. Wenn eine Bestellung das Kreditlimit überschreitet, ist das kein Serverfehler, sondern eine erwartbare fachliche Antwort:\n\n```json\n{\n  \"order\": null,\n  \"failure\": {\n    \"code\": \"CREDIT_LIMIT_EXCEEDED\",\n    \"message\": \"Customer credit limit exceeded\",\n    \"creditLimit\": 5000,\n    \"openAmount\": 5240\n  }\n}\n```\n\nDieses JSON kann man ausdrucken und mit der Fachseite besprechen. „Stimmt der Fehlercode? Fehlt ein Feld? Darf der Außendienst das überhaupt sehen?\" – solche Fragen lassen sich an einem Vertragsdokument klären, lange bevor eine Zeile Frontend existiert. An einem Redux-Reducer oder einem Angular-Service lassen sie sich nicht klären, weil die Fachseite ihn nie zu Gesicht bekommt.\n\n## Dasselbe als Schema gedacht\n\nSeit anderthalb Jahren gibt es für diese Vertragsarbeit ein zweites Vokabular: GraphQL, im Sommer 2015 von Facebook als Spezifikation samt Referenzimplementierung veröffentlicht. Mit Relay gab es von Anfang an einen Client, seit Mitte dieses Jahres arbeitet das Meteor-Team mit Apollo an einer zweiten, bewusst framework-neutralen Client-Familie. Was mich an GraphQL für den Entwurfsschritt interessiert, ist weniger der Query-Mechanismus als die Schema-Kurznotation. Sie zwingt dazu, genau die Dinge aufzuschreiben, um die es beim API-Entwurf geht:\n\n```graphql\ntype Order {\n  id: ID!\n  customer: Customer!\n  items: [OrderItem!]!\n  status: OrderStatus!\n}\n\nenum OrderStatus {\n  PLACED\n  APPROVED\n  REJECTED\n  CANCELLED\n}\n\ntype OrderFailure {\n  code: String!\n  message: String!\n}\n\ntype PlaceOrderResult {\n  order: Order\n  failure: OrderFailure\n}\n\ntype Mutation {\n  placeOrder(input: PlaceOrderInput!): PlaceOrderResult\n  cancelOrder(id: ID!): CancelOrderResult\n}\n```\n\n`placeOrder` und `cancelOrder` heißen wie die Vorgänge, über die die Fachseite spricht. `PlaceOrderResult` macht sichtbar, dass eine Bestellung fachlich scheitern kann, ohne dass technisch etwas kaputt ist – dieselbe Unterscheidung wie im JSON-Beispiel oben, nur diesmal im Typsystem verankert. Ob am Ende REST-Ressourcen oder ein GraphQL-Schema den Vertrag bilden, ist für die Reihenfolge zweitrangig. Beides sind Notationen für dieselbe Denkarbeit: Operationen, Daten, Fehlerfälle, Berechtigungen – vor dem Framework.\n\n```mermaid\nflowchart TD\n  subgraph FF[\"Framework zuerst\"]\n    F1[Framework-Wahl] --> F2[Datenfluss des<br/>Frameworks] --> F3[API bildet den<br/>Datenfluss nach] --> F4[Jeder neue Client<br/>braucht eine neue API]\n  end\n  subgraph AF[\"API zuerst\"]\n    A1[Fachsprache:<br/>Operationen und Daten] --> A2[API-Vertrag:<br/>Ressourcen oder Schema] --> A3[Frontend frei wählbar:<br/>Angular, React, Vue]\n  end\n```\n\n## Woran man eine framework-geformte API erkennt\n\nDie verkehrte Reihenfolge hinterlässt Spuren, die sich in Code-Reviews zuverlässig wiederfinden. Ein paar Signale, auf die ich inzwischen achte:\n\n- Endpoints, die exakt einer Bildschirmseite entsprechen (`/api/dashboard`, `/api/app-state`)\n- Feldnamen aus dem Client-Store statt aus der Fachsprache\n- Fehler ausschließlich als HTTP 500 mit Freitext, weil der Client ohnehin nur eine Meldung einblendet\n- Berechtigungsprüfungen, die nur im Frontend existieren\n- Datenformate, die die interne Struktur einer bestimmten Client-Bibliothek voraussetzen\n\nJedes dieser Signale ist für sich genommen harmlos und im Moment seiner Entstehung sogar effizient. Zusammen bedeuten sie: Diese API hat genau einen legitimen Konsumenten, und der ist zufällig das Framework, das gerade im Projekt steckt. Der zweite Konsument – Mobile-App, Partner-Anbindung, Batch-Import – zahlt dann den vollen Preis.\n\n## Backend-for-Frontend als ehrlicher Kompromiss\n\nNun wäre es unehrlich, so zu tun, als hätten alle Clients dieselben Bedürfnisse. Ein Web-Frontend will oft breite, verschachtelte Antworten; eine Mobile-App über Mobilfunk will kleine, vorverdichtete Zuschnitte. Wer beiden dasselbe generische Format aufzwingt, macht beide langsam. Für dieses Spannungsfeld hat sich seit dem letzten Jahr ein Muster mit eigenem Namen etabliert: Backend for Frontend, kurz BFF. Sam Newman hat es beschrieben, SoundCloud hat es in der eigenen Architektur vorgemacht – pro Client-Typ eine dünne, dem jeweiligen Frontend gewidmete Schicht, dahinter die eine fachliche API.\n\n```mermaid\nflowchart LR\n  Web[Web-Client<br/>React oder Angular] --> BW[BFF Web]\n  Mob[Mobile-Client<br/>iOS und Android] --> BM[BFF Mobile]\n  BW --> API[Fachliche API:<br/>Orders, Customers]\n  BM --> API\n```\n\nDer Punkt, der das Muster für mich ehrlich macht: Die Kopplung an den Client wird nicht geleugnet, sondern benannt und eingezäunt. Das BFF darf client-spezifisch sein, darf Antworten zuschneiden, darf sogar dem Datenfluss eines Frameworks schmeicheln – es ist die einzige Stelle im System, an der das erlaubt ist. Die fachliche API dahinter bleibt sauber und framework-frei. Verwechselt man beide Ebenen, landet man wieder beim `/api/app-state`-Endpoint, nur diesmal mit gutem Gewissen.\n\nWichtig ist außerdem, wem so eine Schicht gehört. Bei SoundCloud pflegt das jeweilige Client-Team sein BFF selbst – das Web-Team seins, das Mobile-Team seins. Das passt zur Logik des Musters: Wer den Zuschnitt braucht, verantwortet ihn auch, und die fachliche API dahinter muss nicht jede Client-Laune mitverhandeln. Übernimmt stattdessen das Backend-Team alle BFFs, wird aus dem Kompromiss schnell wieder ein Flaschenhals, und der Druck wächst, die Zuschnitte doch in die fachliche API zu drücken.\n\n## Vertragsarbeit ist Arbeit mit der Fachseite\n\nOb Ressourcen oder Schema: Der Entwurf taugt nur so viel wie das Gespräch, aus dem er stammt. Für REST-APIs hat sich Swagger als Beschreibungsformat durchgesetzt – offiziell heißt die Spezifikation seit der Gründung der OpenAPI Initiative Ende letzten Jahres OpenAPI, im Alltag sagt weiterhin jeder Swagger. Der eigentliche Wert liegt nicht im Tooling, sondern darin, dass es ein Dokument gibt, das in einem Review neben den Fachkonzepten liegen kann. Ein GraphQL-Schema leistet dasselbe, in kompakterer Form.\n\nIch habe dieses Jahr selbst in diese Richtung experimentiert: graphql-pouch, ein kleines Open-Source-Projekt, das aus einer GraphQL-Schema-Notation eine lauffähige API über PouchDB erzeugt, inklusive CouchDB-Synchronisation. Der Ansatz dort ist bewusst „Frontend-First\" – ohne Backend-Migrationen schnell zu einem typisierten Datenmodell kommen. Interessanterweise bestätigt gerade dieses Experiment die These: Auch wenn die Runtime dem Frontend entgegenkommt, ist das erste Artefakt die Schema-Notation. Man schreibt Typen und Operationen auf, bevor irgendetwas rendert. Das Schema ist der Vertrag; alles andere ist Erzeugnis.\n\nDie Vertragsarbeit selbst bleibt dabei unbequem, und das ist gut so. Wenn die Fachseite beim Namen `cancelOrder` die Stirn runzelt, weil im Haus niemand von „Stornierung\", sondern alle von „Rückabwicklung\" sprechen, dann ist das genau die Diskussion, die man im Dezember führen will – nicht im Juni, wenn drei Clients den Namen bereits fest verdrahtet haben.\n\n## Unterm Strich\n\nDie Framework-Frage darf Spaß machen, und die Antworten dieses Jahres – Angular 2, React 15, Vue 2 – sind allesamt vertretbar. Aber sie ist die zweite Frage. Die erste lautet: Welche Operationen gibt es, wie heißen sie in der Fachsprache, welche Fehlerfälle sind erwartbar, wer darf was? Wer diese Frage in einem Vertragsdokument beantwortet – als Ressourcen-Entwurf oder als Schema –, macht die Framework-Wahl beinahe risikofrei und den späteren Wechsel bezahlbar. Wer sie überspringt, wählt das Framework trotzdem – nur dass es dann heimlich die API mitentwirft, und dieser Teil der Entscheidung lässt sich später nicht mehr per npm install korrigieren.\n\n## Weiterführende Quellen\n\n- [graphql-pouch auf GitHub](https://github.com/MikeBild/graphql-pouch)\n- [GraphQL – Introduction und Schema-Dokumentation](https://graphql.org/learn/)\n- [Sam Newman: Pattern – Backends For Frontends](https://samnewman.io/patterns/architectural/bff/)\n- [Phil Calçado: The Back-end for Front-end Pattern (BFF) bei SoundCloud](https://philcalcado.com/2015/09/18/the_back_end_for_front_end_pattern_bff.html)\n- [OpenAPI Initiative](https://www.openapis.org/)"},{"locale":"de","translation_key":"tyrian-rx-react-ui-datenfluss","slug":"tyrian-rx-react-ui-datenfluss","title":"Tyrian Rx React: UI als Datenfluss","summary":"Ein Nachbau der Elm-Architektur mit RxJS und React – Actions als Strom, scan() faltet das Model, Side Effects bleiben am Rand – und was dieser Proof of Concept über gut alternde UI-Architektur verrät.","tags":["Software","Reactive"],"published_at":"2016-10-12T10:00:00+00:00","updated_at":"2026-07-14T16:35:20.035699+00:00","url":"https://www.mikebild.dev/de/blog/tyrian-rx-react-ui-datenfluss/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/8e7ccdd7685d30b639110526bce8b1d0ddb9a8d315e0a5635afba923104e0cdd/tyrian-rx-react-ui-datenfluss-vorlesen.mp3","audio_duration_secs":792,"text":"# Tyrian Rx React: UI als Datenfluss\n\nWenn in einer Oberfläche jede Komponente ihren eigenen State mutiert, verliert das System als Erstes die Zeitachse. Ein Klick hier, ein Callback dort, ein `setState` irgendwo dazwischen – und drei Wochen später kann niemand mehr sagen, **wann** der State gekippt ist, der den Fehler ausgelöst hat. Der Debugger zeigt das Ergebnis, aber nicht die Geschichte. Man sieht: `count` ist 7, obwohl er 3 sein müsste. Man sieht nicht: welche Folge von Events aus der 3 eine 7 gemacht hat, in welcher Reihenfolge zwei Antworten vom Server eintrafen, ob der Benutzer schneller geklickt hat als das Netzwerk geantwortet.\n\nGenau gegen diesen Verlust der Geschichte ist die Elm-Architektur gebaut. Und weil man eine Architektur erst versteht, wenn man sie einmal selbst nachgebaut hat, habe ich das in den letzten Wochen gemacht: die Elm-Architektur mit RxJS und React – als Proof of Concept, nicht als Framework. Das Repository liegt unter [github.com/MikeBild/reactish-elmish](https://github.com/MikeBild/reactish-elmish), und schon das README warnt in der zweiten Zeile: *Don't use in production!* Diese Warnung ist ernst gemeint, und ich komme am Ende darauf zurück. Der Wert des Experiments liegt woanders.\n\n## Die Elm-Architektur, auf das Skelett reduziert\n\nElm – seit Version 0.17 vom Mai dieses Jahres ohne Signals, dafür mit Subscriptions – zwingt jede Anwendung in dieselbe Form:\n\n- ein Model, das den gesamten State der Anwendung als einen Wert hält\n- eine `update`-Funktion, die aus altem Model und einer Message ein neues Model errechnet\n- eine `view`-Funktion, die aus dem Model die Darstellung erzeugt\n- Subscriptions für alles, was von außen hereinkommt: Timer, WebSockets, Browser-Events\n\nKein Teil davon ist optional, kein Teil kennt einen Seitenausgang. Der Compiler lässt schlicht nichts anderes zu. State entsteht nirgendwo nebenbei; er entsteht ausschließlich dadurch, dass `update` eine Message verarbeitet. Damit ist die Geschichte des States identisch mit der Liste der Messages – und die Frage „wann ist das passiert?\" hat wieder eine Antwort: bei Message Nummer 34, zwischen 33 und 35.\n\nDas Bemerkenswerte an dieser Form ist, wie wenig sie mit der Sprache Elm zu tun hat. Model, Update, View – das ist eine Faltung über eine Event-Folge plus eine Projection. Beides sind Konzepte, die es in jeder Sprache gibt. Die Frage, die mich nicht losließ: Wie viel von der Klarheit bleibt übrig, wenn man den Compiler weglässt und die Form freiwillig in JavaScript nachbaut?\n\n## Der Nachbau: Actions als Strom\n\nDer Kern des Nachbaus passt in wenige Zeilen. Jede Benutzerinteraktion wird zu einem Wert auf einem Strom, und eine einzige `update`-Funktion faltet diesen Strom zum Model. Im Repository steckt das hinter einer kleinen API aus `init`, `update`, `view` und `subscriptions` – hier die Rohform ohne Verpackung:\n\n```javascript\nimport Rx from 'rx'\n\n// every user interaction becomes a value on this stream\nconst actions$ = new Rx.Subject()\n\nfunction update (model, action) {\n  switch (action.type) {\n    case 'INCREMENT':\n      return { count: model.count + 1 }\n    case 'DECREMENT':\n      return { count: model.count - 1 }\n    case 'TICK':\n      return { count: model.count + action.step }\n    default:\n      return model\n  }\n}\n\n// fold the action history into the current model\nconst model$ = actions$\n  .startWith({ type: 'INIT' })\n  .scan(update, { count: 0 })\n```\n\nEine Randnotiz zur Wahl der Bibliothek: Der Prototyp benutzt das klassische `rx`-Paket, also Version 4 mit `onNext` und `dispose`. RxJS 5 steht als Release Candidate bereit und wird die Namen an die ES-Observable-Vorschläge angleichen (`next`, `unsubscribe`), aber für ein Experiment wollte ich die stabile Version, deren Operator-Dokumentation vollständig ist. Am Konzept ändert das nichts – Methodenketten auf Observables funktionieren in beiden Welten gleich.\n\nDer entscheidende Operator ist `scan`. Wer `reduce` über Arrays kennt, kennt `scan` fast: Es ist dieselbe Faltung, nur dass sie nicht auf ein fertiges Array wartet, sondern bei jedem neuen Element den Zwischenstand herausgibt. `reduce` faltet eine abgeschlossene Liste zu einem Endwert. `scan` faltet eine Liste, die nie endet – und genau das ist eine Benutzeroberfläche: eine Event-Folge ohne Schlusspunkt. Das Model zu einem Zeitpunkt ist nichts anderes als die Faltung aller Actions bis zu diesem Zeitpunkt. Diese eine Einsicht ist der halbe Artikel: **State ist der linke Fold über die Ereignisgeschichte.**\n\n## React rendert nur noch\n\nReact kommt in diesem Aufbau eine bewusst langweilige Rolle zu: Es projiziert das aktuelle Model in den DOM und meldet Interaktionen zurück auf den Action-Strom. Kein Fetch in `componentDidMount`, keine State-Logik in Handlern – die Komponente folgt dem `model$`-Strom und sonst nichts:\n\n```javascript\nimport React from 'react'\n\nclass CounterView extends React.Component {\n  componentDidMount () {\n    // the view follows the model stream, nothing else\n    this.subscription = model$.subscribe(model => this.setState({ model }))\n  }\n\n  componentWillUnmount () {\n    this.subscription.dispose()\n  }\n\n  render () {\n    if (!this.state) return null\n    const { count } = this.state.model\n    return (\n      <div>\n        <span>{count}</span>\n        <button onClick={() => actions$.onNext({ type: 'INCREMENT' })}>+</button>\n        <button onClick={() => actions$.onNext({ type: 'DECREMENT' })}>-</button>\n      </div>\n    )\n  }\n}\n```\n\nDass hier trotzdem `setState` auftaucht, ist kein Stilbruch, sondern der Übergabepunkt: Irgendwo muss der Strom in Reacts Render-Zyklus münden, und `setState` ist in React 15 nun einmal die Tür. Wichtig ist, dass es die **einzige** Stelle ist, an der `setState` vorkommt – als Brücke, nicht als State Management. Im Repository ist diese Brücke in zwei Varianten verpackt, einmal als Higher-Order-Component `withElmish` für die Komposition mit zustandslosen Functional Components, einmal als Basisklasse `ReactComponent`, von der man erbt und `init`, `update`, `view` überschreibt.\n\nAn dieser Stelle weicht der Nachbau übrigens bewusst von Elm und von Redux ab: Er hält den State pro Komponente statt in einem zentralen Store. Jede „smarte\" Komponente bekommt ihre eigene kleine Elm-Schleife, „dumme\" Komponenten bleiben zustandslose Funktionen. Ob das eine gute Idee ist, hängt vom Zuschnitt ab – für die Beispielsammlung im Repository (Counter, Formular-Validierung, optimistische UI-Updates, ein Bestellprozess als lang laufender Saga-Strom) war es angenehm, weil jedes Beispiel für sich lebt. Für eine große Anwendung würde ich die Frage neu stellen.\n\n## Side Effects als Ströme am Rand\n\nDer interessanteste Teil ist der, den Counter-Beispiele gern unterschlagen: Was passiert mit allem, das nicht aus einem Klick entsteht? Timer, HTTP-Antworten, Server-Push. In Elm sind das Subscriptions und Tasks. Im Nachbau sind es – natürlich – Observables. Die `subscriptions`-Funktion bekommt ein Kommando aus `init` oder `update` und antwortet mit einem Strom, dessen Werte wieder als Messages in `update` landen:\n\n```javascript\nconst stop$ = actions$.filter(action => action.type === 'INTERVAL_STOP')\n\nfunction subscriptions (cmd) {\n  switch (cmd) {\n    case 'INTERVAL_START':\n      return Rx.Observable\n        .interval(1000)\n        .map(() => ({ type: 'TICK', step: 1 }))\n        .takeUntil(stop$)\n  }\n}\n```\n\nDie Laufzeitschicht abonniert diesen Strom selbst; die Komponente ruft nirgendwo `subscribe` auf. Damit bleiben Side Effects dort, wo sie hingehören: am Rand, als eigene Ströme, die man mit denselben Operatoren komponiert wie alles andere. `takeUntil` beendet den Timer deklarativ, `merge` fasst mehrere Quellen zusammen, `filter` zerlegt einen Strom in Teilströme. Der Lifecycle einer Side Effect ist keine Sonderlogik mehr, sondern ein Datenfluss-Ausdruck.\n\nHier zeigt sich auch ein echter Unterschied zu Elm, kein nachgebauter: Elm-Subscriptions kennen nur *next* – es kommt die nächste Message, sonst nichts. Fehler und Abschluss laufen als gewöhnliche Message-Inhalte durch `update`, und für verkettete asynchrone Effects gibt es Tasks mit `andThen`. Ein Rx-Observable dagegen trägt drei Signale im Vertrag: *next*, *error*, *complete*. Ein Strom kann scheitern, und ein Strom kann fertig sein – beides ist Teil des Typs, nicht Konvention. Für Dinge wie AJAX-Long-Polling gegen ein CouchDB-Change-Feed oder EventSource-Push (beides als Beispiel im Repository) ist das die natürlichere Beschreibung.\n\nDer gesamte Kreislauf, als Bild:\n\n```mermaid\nflowchart LR\n  U[Benutzer-Ereignis] --> A[\"actions$ (Strom)\"]\n  SUB[\"subscriptions:<br/>Interval, HTTP, Push\"] --> A\n  A --> S[\"scan(update, initialModel)\"]\n  S --> M[\"model$ (Strom)\"]\n  M --> V[\"React-View<br/>rendert das Model\"]\n  V --> U\n```\n\nEine Richtung, ein Kreis. Alles, was passiert, passiert als Wert auf einem Strom – und ist damit beobachtbar, filterbar, protokollierbar. Ein `actions$.subscribe(console.log)` an der richtigen Stelle ersetzt eine Menge Debugger-Sitzungen.\n\n## Redux, Elm, RxJS – dreimal dieselbe Idee\n\nWer bis hierhin mitgelesen hat und Redux kennt, hat die Pointe längst gesehen: `update` ist ein Reducer. `(model, action) => model` und `(state, action) => state` sind dieselbe Signatur mit anderen Namen. Das ist kein Zufall – Dan Abramov hat nie einen Hehl daraus gemacht, dass Redux die Elm-Architektur für JavaScript destilliert. Der Unterschied liegt darin, was jede Variante der Idee erzwingt und was sie nur empfiehlt.\n\nRedux macht die Faltung mit weniger Mathematik und mehr Konvention: ein Store statt eines Model-Stroms, `dispatch` statt `onNext`, Middleware statt Operator-Ketten. Dass Reducer rein bleiben und Side Effects draußen, steht in der Dokumentation – erzwingen kann es niemand. Dafür bekommt man ein Ökosystem: DevTools mit Time-Travel, Bindings, Konventionen, die ein Team ohne Diskussion übernehmen kann. Interessanterweise wächst gerade mit redux-observable eine Middleware heran, die Rx-Ströme als Side-Effect-Schicht in Redux zurückholt – Actions rein, Actions raus, dazwischen Observable-Operatoren. Die beiden Welten nähern sich also ohnehin an.\n\nElm erzwingt die Form im Compiler. Es gibt keine Möglichkeit, State an `update` vorbeizuschleusen, keine vergessene Mutation, keine unbehandelte Message-Variante – der Typcheck findet sie. Das ist die härteste, aber auch die unnachgiebigste Variante: Man bekommt die Garantien nur zusammen mit der Sprache.\n\nUnd RxJS? RxJS macht etwas explizit, das bei beiden anderen implizit bleibt: die **Zeit**. Ein Observable ist eine Folge von Werten auf einer Zeitachse, und die Operatoren sprechen offen darüber – `debounce` verhandelt über Abstände, `takeUntil` über ein Ende, `scan` über Geschichte. In Redux ist Zeit ein Side Effect der Dispatch-Reihenfolge; in Elm versteckt sie die Runtime. Im Rx-Nachbau steht sie im Code. Wer einmal gesehen hat, dass „State\" nur der aktuelle Stand einer Faltung über der Zeitachse ist, liest danach auch Redux-Code anders. CycleJS treibt denselben Gedanken übrigens noch konsequenter: Dort ist die gesamte Anwendung eine Funktion von Strömen nach Strömen, React inklusive Rendering ersetzt. Und wer die entgegengesetzte Schule sehen will, findet sie in MobX, das Mutation nicht verbannt, sondern beobachtbar macht – ein anderer Vertrag, eine andere Diskussion.\n\n## Was der Eigenbau lehrt – und was nicht\n\nNach ein paar Wochen mit dem Prototyp und seinen sechzehn Beispielen ist meine Bilanz zweigeteilt. Gelernt habe ich mehr als aus jedem Blogartikel über Redux, und zwar Dinge, die unabhängig von der Bibliothek gelten:\n\n- State als Faltung zu begreifen macht Fehlerbilder erklärbar: Nicht „der State ist falsch\", sondern „diese Action-Folge erzeugt dieses Model\" – eine überprüfbare Aussage.\n- Eine einzige Richtung im Datenfluss ist keine Ästhetik, sondern der Grund, warum man das System noch lesen kann, wenn es gewachsen ist.\n- Side Effects sind dann beherrschbar, wenn sie einen expliziten Lifecycle haben – egal ob der Task heißt, Subscription oder Observable.\n- `update` als Pure Function ist trivial testbar; der Test für den Delayed-Counter im Repository braucht weder DOM noch Browser.\n\nWas der Eigenbau **nicht** ist: ein Produktionsersatz. Die Warnung im README steht dort aus Überzeugung. Es fehlt alles, was eine Architektur erst im Alltag trägt – durchdachte Error Handling über Komponentengrenzen, Werkzeuge, Dokumentation jenseits eines README, und vor allem: andere Leute, die den Code kennen. Ein Framework, das eine Person an ein paar Abenden gebaut hat, ist eine Lernmaschine, kein Fundament. Wer die Elm-Architektur in JavaScript produktiv will, nimmt Redux und bekommt Konventionen samt Community dazu; wer die Garantien will, nimmt Elm und bezahlt mit dem Sprachwechsel. Der Nachbau dazwischen hat genau einen Zweck: verstehen, warum beide funktionieren.\n\nDazu kommt eine Beobachtung aus dem Bauen selbst: Die Versuchung, aus dem Proof of Concept „noch schnell\" ein richtiges Framework zu machen, ist enorm. Jedes Beispiel legt eine weitere Abstraktion nahe, jede Abstraktion einen weiteren Konfigurationspunkt. Ich habe bewusst dagegen gehalten – minimal-invasiv, React-Rendering plus Rx-Komposition, keine Schicht mehr als nötig. Auch das ist eine Lektion: Der Abstand zwischen „lehrreicher Prototyp\" und „schlechtes Framework\" beträgt ungefähr zwei Wochenenden.\n\n## Unterm Strich\n\nWarum altert diese Form so gut? Weil sie fast keine Annahmen über ihre Umgebung trifft. Model, Update, View – das setzt weder eine Sprache voraus noch eine Bibliothek noch ein Rendering-Verfahren. React 15 kann morgen durch etwas anderes ersetzt werden, `rx` Version 4 durch Version 5, und die Architektur bleibt dieselbe, weil sie aus zwei Zutaten besteht, die älter sind als das Web: einer Faltung und einer Projection. Frameworks kommen und gehen in diesem Umfeld schnell genug, dass ich das nicht als Floskel meine, sondern als Auswahlkriterium.\n\nUnd die Frage vom Anfang – wann ist das passiert? – hat in dieser Form immer eine Antwort. Die Ereignisgeschichte ist kein Nebenprodukt, das man mit Logging rekonstruiert, sondern die primäre Datenstruktur der Anwendung. Alles andere, das Model eingeschlossen, ist eine Ableitung davon. Wenn ich in Reviews künftig vor einer UI sitze, deren State niemand mehr erklären kann, ist das mein erster Vorschlag: nicht mehr Werkzeuge, sondern eine Richtung.\n\n## Weiterführende Quellen\n\n- Das besprochene Repository: [github.com/MikeBild/reactish-elmish](https://github.com/MikeBild/reactish-elmish)\n- Die Elm-Architektur im offiziellen Guide: [guide.elm-lang.org/architecture](https://guide.elm-lang.org/architecture/)\n- Der `scan`-Operator interaktiv als Marble-Diagramm: [rxmarbles.com/#scan](https://rxmarbles.com/#scan)\n- Redux-Dokumentation: [redux.js.org](https://redux.js.org/)\n- redux-observable, Rx-Ströme als Redux-Middleware: [redux-observable.js.org](https://redux-observable.js.org/)"},{"locale":"de","translation_key":"graphql-pouch-lokale-daten","slug":"graphql-pouch-lokale-daten","title":"GraphQL-Pouch: lokale Daten mit Schema","summary":"Ein Open-Source-Experiment aus dem Sommer 2016: eine GraphQL-Runtime, die aus einer Schema-Kurznotation eine komplette CRUD-API über PouchDB erzeugt – inklusive Synchronisation über das CouchDB-Replikationsprotokoll.","tags":["Software","GraphQL","API"],"published_at":"2016-07-26T10:00:00+00:00","updated_at":"2026-07-14T16:33:18.446465+00:00","url":"https://www.mikebild.dev/de/blog/graphql-pouch-lokale-daten/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/6811b4979ee5f1ff106d5596ccc25cacfe54f56e3b265bd6fff909ff5bb601c7/graphql-pouch-lokale-daten-vorlesen.mp3","audio_duration_secs":754,"text":"# GraphQL-Pouch: lokale Daten mit Schema\n\n```graphql\ntype Post implements Node {\n  id: ID!\n  rev: String\n  title: String\n  body: String\n  published: Boolean\n}\n```\n\nFünf Felder, ein Interface, keine einzige Zeile Resolver-Code. Diese Datei ist das vollständige Backend eines kleinen Blogsystems – Datenhaltung, HTTP-Endpoint und durchsuchbare API-Dokumentation inklusive. Man übergibt sie an `graphql-pouch`, und wenige Sekunden später antwortet unter `http://127.0.0.1:3000/graphql/blog` eine laufende GraphQL-API mit generierten Queries und Mutationen: `post`, `allPosts`, `upsertPost`, `deletePost`. Gespeichert wird nicht in einem entfernten Datenbankserver, sondern lokal in PouchDB – und auf Wunsch synchronisiert der Prozess seine Dokumente über das CouchDB-Replikationsprotokoll mit anderen Knoten.\n\nDas ist die Kurzfassung von GraphQL-Pouch, einem Open-Source-Projekt, das ich in diesem Monat auf GitHub und npm veröffentlicht habe. Es ist ausdrücklich ein Experiment. Ich wollte GraphQL nicht nur aus Blogposts kennen, sondern von innen – und die beste Methode, eine Technologie von innen kennenzulernen, ist bei mir seit Jahren dieselbe: etwas Kleines, Echtes damit bauen und es so lange benutzen, bis die unbequemen Stellen sichtbar werden.\n\n## Ein Jahr GraphQL, viele offene Fragen\n\nZur Einordnung: Die GraphQL-Spezifikation ist gerade ein Jahr öffentlich. Facebook hat sie im Juli 2015 zusammen mit `graphql-js` als Referenzimplementierung freigegeben, intern läuft die Technik dort schon seit 2012. Drumherum gibt es bislang eine überschaubare Werkzeuglandschaft: Relay als Client-Framework, GraphiQL als interaktive Oberfläche zum Erkunden einer API, `express-graphql` als HTTP-Anbindung für Node.js. Wer heute einen GraphQL-Server baut, schreibt Typdefinitionen und Resolver von Hand gegen `graphql-js` – für jedes Feld eine Funktion, die sagt, woher die Daten kommen.\n\nBeim dritten selbstgeschriebenen Resolver fiel mir auf, wie mechanisch diese Arbeit für einfache Fälle ist. Ein Typ `Post` mit fünf Feldern, dahinter eine Dokumentdatenbank: Lesen per Schlüssel, Liste aller Dokumente, Schreiben, Löschen. Das ist immer dasselbe Muster, und Muster, die immer gleich sind, kann eine Maschine erzeugen. Die eigentlich interessante Arbeit steckt im Schema – in der Frage, welche Typen, Felder und Beziehungen die Anwendung braucht. Daraus wurde die These des Experiments: Wenn das Schema die einzige Quelle ist, wie weit trägt eine Runtime, die den Rest generiert?\n\nDer zweite Strang kam aus einer anderen Richtung. In mehreren Frontend-Projekten habe ich erlebt, wie die Backend-Entwicklung zum Engpass wird: Das Team wartet auf Endpoints, auf Datenbankmigrationen, auf Deployments – und baut in der Zwischenzeit Attrappen, die später mühsam wieder ausgebaut werden. Ein Backend, das aus einer Schemadatei entsteht und ohne Infrastruktur lokal läuft, dreht diese Reihenfolge um. Das Frontend-Team definiert den Datenvertrag selbst, arbeitet sofort gegen eine echte API und verhandelt später, was davon ein „richtiges\" Backend übernehmen muss.\n\n## Von der Kurznotation zur laufenden API\n\nGraphQL-Pouch liest die Schema-Kurznotation – dieselbe knappe Schreibweise, in der die GraphQL-Dokumentation ihre Beispiele notiert – und baut daraus zur Laufzeit ein vollständiges, ausführbares Schema mit `graphql-js`. Für jeden Typ entstehen dabei generierte Wurzelfelder samt Resolvern gegen PouchDB. Der Parser dafür geht auf Matthew Muellers Projekt `graph.ql` zurück, dessen Vorarbeit mir viel Zeit gespart hat.\n\nStandardmäßig sind die Relay-Konventionen aktiv: ein `Node`-Interface mit globalen IDs, Connections mit `edges` und `node` für Listen, `clientMutationId` in den Mutations-Payloads. Das war eine bewusste Entscheidung, denn Relay ist im Moment der anspruchsvollste GraphQL-Client, und wer dessen Konventionen erfüllt, erfüllt die einfacheren Fälle nebenbei. Wer sie nicht will, schaltet sie mit `--no-relay` ab und bekommt schlichte Listen.\n\nEine Query gegen das generierte Blog-Schema sieht so aus:\n\n```graphql\nquery BlogFrontpage {\n  allPosts {\n    edges {\n      node {\n        id\n        rev\n        title\n        published\n      }\n    }\n  }\n}\n\nmutation PublishPost {\n  upsertPost(input: {\n    id: \"hello-graphql\",\n    title: \"GraphQL over local data\",\n    published: true,\n    clientMutationId: \"1\"\n  }) {\n    post {\n      id\n      rev\n    }\n  }\n}\n```\n\nIm Entwicklungsmodus (`graphql-pouch --development`) liefert der Server unter dem Endpoint automatisch GraphiQL aus. Das klingt nach einem Nebenschauplatz, war im Alltag aber der größte Einzelgewinn: Die API ist ab der ersten Minute interaktiv erkundbar, mit Autovervollständigung und eingebauter Dokumentation aus den Schema-Kommentaren. Kein Postman, kein cURL-Gefummel – Query eintippen, Ergebnis sehen.\n\nDarüber hinaus bringt die Runtime einige Dinge mit, die aus dem Experiment fast unbemerkt ein benutzbares Werkzeug gemacht haben:\n\n- mehrere Schemas parallel unter eigenen URL-Pfaden (`/graphql/blog`, `/graphql/cms`)\n- JWT-Authentifizierung per Startparameter, inklusive CLI-Kommando zum Signieren von Tokens\n- Ausliefern statischer Dateien, sodass eine React-Anwendung direkt daneben wohnen kann\n- Migration von Schemadateien, eigenen Funktionen und statischen Inhalten über die Kommandozeile\n\n## Warum PouchDB darunterliegt\n\nDie Wahl der Datenbank war die eigentliche Architekturentscheidung des Projekts. PouchDB ist eine JavaScript-Implementierung der CouchDB-Ideen: dokumentorientiert, revisionsbasiert, und – das ist der entscheidende Punkt – mit dem CouchDB-Replikationsprotokoll als eingebautem Synchronisationsmechanismus. Im Node.js-Prozess speichert PouchDB über LevelDB direkt ins Dateisystem. Es gibt keinen Datenbankserver, keinen Verbindungsstring, keine Migrationen. `npm install -g graphql-pouch`, starten, fertig – der Zustand liegt als Dateien neben dem Prozess.\n\nFür ein Werkzeug, das Frontend-Entwicklung vom Backend entkoppeln soll, ist diese Selbstgenügsamkeit kein Komfortmerkmal, sondern der Kern. Jede Infrastrukturabhängigkeit, die ein Entwickler erst installieren muss, ist eine Hürde vor der ersten Query.\n\nInteressant wird es, sobald mehr als ein Knoten im Spiel ist. Mit `graphql-pouch --remote http://user:pass@couch.example.com` repliziert die lokale PouchDB gegen eine entfernte CouchDB – in beide Richtungen. Mehrere Instanzen hinter einem Load Balancer teilen sich so denselben Datenbestand, ohne dass eine davon der „Master\" wäre. Der Preis ist bekannt und im CouchDB-Umfeld gut dokumentiert: Es gibt keine einzelne Quelle der Wahrheit, nur eventuelle Konsistenz. Jeder Knoten ist jederzeit verfügbar, aber nicht jeder Knoten sieht jederzeit denselben Stand.\n\n```mermaid\nflowchart LR\n  SDL[Schema-Datei<br/>Kurznotation] --> RT[graphql-pouch<br/>Laufzeitumgebung]\n  RT --> GEN[Generierte Felder<br/>allPosts, upsertPost, deletePost]\n  UI[GraphiQL /<br/>Relay-Client] --> GEN\n  GEN --> P[(PouchDB<br/>LevelDB im Dateisystem)]\n  P <-->|CouchDB-<br/>Replikationsprotokoll| C[(CouchDB<br/>entfernter Knoten)]\n```\n\nDass ich diese Eigenschaft nicht als Makel, sondern als Merkmal behandle, hat mit der Zielgruppe zu tun: Frontends. Eine Oberfläche, die auf Bestätigung eines entfernten Servers wartet, fühlt sich zäh an. Relay bringt mit seinen optimistischen Updates ohnehin ein Modell mit, das Änderungen sofort anzeigt und später mit der Serverantwort abgleicht. Eventuelle Konsistenz auf der Datenebene und optimistische Updates auf der Client-Ebene sind zwei Ausprägungen desselben Gedankens – die Architektur von GraphQL-Pouch nimmt diesen Gedanken ernst, statt ihn zu verstecken.\n\n## Die Revision steht im Schema – mit Absicht\n\nWer das `Post`-Beispiel oben aufmerksam liest, stolpert über das Feld `rev`. Das ist die Dokumentrevision aus der CouchDB-Welt, und man kann mit guten Gründen fragen, ob so ein Speicherdetail in einer API sichtbar sein darf. Ich habe mich dafür entschieden, und zwar nach einem konkreten Fehlversuch: In einer frühen Version habe ich die Revision intern behandelt und Schreibzugriffe einfach durchgereicht. Das funktioniert genau so lange, wie niemand gleichzeitig schreibt. Sobald zwei Clients dasselbe Dokument ändern – oder ein replizierter Knoten eine ältere Fassung zurückspielt –, überschreibt der Letzte stillschweigend den Ersten. Der verlorene Stand fällt erst auf, wenn ein Nutzer ihn vermisst, und dann ist er nicht mehr rekonstruierbar.\n\nMit sichtbarer Revision dreht sich das um. Ein `upsertPost` mit veralteter Revision scheitert kontrolliert, weil PouchDB den Konflikt erkennt:\n\n```mermaid\nsequenceDiagram\n  participant A as Client A\n  participant B as Client B\n  participant API as graphql-pouch\n  participant DB as PouchDB\n  A->>API: upsertPost(id, rev: \"1-abc\", ...)\n  API->>DB: put(document)\n  DB-->>API: ok, rev: \"2-def\"\n  B->>API: upsertPost(id, rev: \"1-abc\", ...)\n  API->>DB: put(document)\n  DB-->>API: 409 conflict\n  API-->>B: error instead of silent overwrite\n```\n\nDer Client muss dann neu lesen und entscheiden, was mit den konkurrierenden Änderungen passiert. Das ist unbequemer als ein Schema ohne `rev`, aber die Unbequemlichkeit ist ehrlich: Sie zeigt ein Problem an dem Ort, an dem es entsteht, statt es in die Zukunft zu verschieben. Bei lokalen, replizierten Daten ist der Schreibkonflikt kein Randfall, den man wegabstrahieren kann – er ist der Normalfall, der nur selten eintritt.\n\n## Wenn generiertes CRUD nicht mehr reicht\n\nGenerierte Endpoints tragen erstaunlich weit, aber nicht beliebig weit. Irgendwann braucht eine Anwendung eine Query mit Fachlogik, eine Validierung vor dem Schreiben oder Daten aus einer fremden Quelle. Für diese Fälle hat GraphQL-Pouch eine Fluchttür: eigene Funktionen in JavaScript, die sich unter dem Namen eines Schema-Felds registrieren und den generierten Resolver ersetzen. Zusammen mit der Nutzung als npm-Modul lässt sich das direkt in eine bestehende Express-Anwendung einbetten – das Begleit-Repository `graphql-pouch-as-library` zeigt genau diesen Aufbau:\n\n```javascript\nconst express = require('express');\nconst expressGraphQL = require('express-graphql');\nconst graphqlPouch = require('graphql-pouch');\n\nconst schemaDefinition = `\ntype Post implements Node {\n  id: ID!\n  rev: String\n  title: String\n  body: String\n  published: Boolean\n}\n\ntype Query {\n  postsByAuthor(author: String!): [Post]\n}\n`;\n\n// custom resolver replaces the generated CRUD implementation\nconst customFunctions = {\n  postsByAuthor: (ctx, input) => {\n    legacyBlogService\n      .fetchPostsByAuthor(input.author)\n      .then(posts => ctx.success(posts));\n  },\n};\n\nconst mySchema = graphqlPouch.schema('blog', schemaDefinition, true, customFunctions);\n\nconst app = express();\napp.use('/graphql', expressGraphQL({\n  schema: mySchema.schema,\n  graphiql: true,\n}));\napp.listen(3000);\n```\n\nDieses Muster hat sich im Experiment als der wichtigste Befund herausgestellt. Die Generierung deckt den mechanischen Teil ab, und die eigenen Funktionen übernehmen den fachlichen – ohne dass man das Fundament wechseln muss. GraphQL zeigt hier seine Stärke als Fassade: Hinter demselben Schema können ein generierter PouchDB-Zugriff, ein Aufruf an einen bestehenden REST-Dienst und eine handgeschriebene Berechnung nebeneinander existieren, und kein Client merkt den Unterschied.\n\n## Was das Experiment nicht kann\n\nZur Ehrlichkeit eines Experiments gehört die Liste der offenen Enden, und die ist bei GraphQL-Pouch nicht kurz:\n\n- Events fehlen. PouchDB liefert einen Änderungs-Feed, aus dem sich Benachrichtigungen an Clients speisen ließen – das steht auf der Roadmap, ist aber nicht gebaut.\n- Ein Batching- und Caching-Mechanismus für Resolver fehlt ebenfalls; verschachtelte Queries erzeugen mehr Datenbankzugriffe als nötig.\n- Die JWT-Unterstützung authentifiziert, autorisiert aber nicht – Rollen oder Feldrechte gibt es nicht.\n- Generiertes CRUD bleibt generisch: `upsertPost` sagt nichts darüber, ob ein Beitrag veröffentlicht, zurückgezogen oder redigiert wird. Eine fachlich gute API braucht benannte Operationen, und die muss weiterhin ein Mensch entwerfen.\n\nDer letzte Punkt ist der wichtigste. Die Generierung nimmt einem die Schreibarbeit ab, nicht die Entwurfsarbeit. Ein Schema, das nur aus Typen mit CRUD besteht, ist eine Datenbank mit hübscherem Protokoll – nützlich für Prototypen, Demos und die frühe Frontend-Phase, aber kein Ersatz für eine durchdachte Schnittstelle.\n\n## Was ich daraus mitnehme\n\nNach einigen Wochen mit dem eigenen Werkzeug bleiben drei Beobachtungen. Erstens: Der Ansatz, das Schema zuerst zu schreiben und alles Weitere daraus abzuleiten, verändert Gespräche. Über eine Schemadatei mit Kommentaren lässt sich mit Frontend-Kollegen konkret verhandeln, lange bevor irgendein Server steht – das Schema wird zum Vertrag, nicht zur Nachdokumentation. Zweitens: Lokale Daten mit Synchronisation verlagern die Komplexität, sie beseitigen sie nicht. Was an Infrastruktur wegfällt, kommt als Revisions- und Konfliktdenken im Datenmodell zurück, und es ist besser, wenn die API das offenlegt. Drittens: Ein Wochenend-Experiment, das man ernsthaft zu Ende baut – mit CLI, Tests, Dokumentation und Veröffentlichung auf npm –, lehrt mehr über eine Technologie als jede Einführung, weil es einen zwingt, auch die Ränder anzufassen: Fehlermeldungen, Authentifizierung, Betrieb mit mehreren Knoten.\n\nOb GraphQL sich durchsetzt, kann ich im Sommer 2016 nicht beurteilen. Aber die Idee, einen typisierten Datenvertrag zwischen Client und Server zu stellen und beide Seiten daran auszurichten, wirkt auf mich tragfähiger als vieles, was ich in zehn Jahren API-Entwicklung mit REST-Konventionen verhandelt habe. Das Experiment hat sich schon deshalb gelohnt.\n\n## Weiterführende Quellen\n\n- GraphQL-Pouch auf GitHub: https://github.com/MikeBild/graphql-pouch\n- Beispiel zur Einbettung als Bibliothek: https://github.com/MikeBild/graphql-pouch-as-library\n- Offizielle GraphQL-Einführung: https://graphql.org/learn/\n- PouchDB-Replikationsleitfaden: https://pouchdb.com/guides/replication.html\n- CouchDB-Replikation im Überblick: https://docs.couchdb.org/en/stable/replication/intro.html"},{"locale":"de","translation_key":"definition-of-done-als-qualitaets-gate","slug":"definition-of-done-als-qualitaets-gate","title":"Definition of Done als Qualitäts-Gate, nicht als Bürokratie","summary":"Der automatisierbare Kern einer Definition of Done gehört in ein grünes Gate aus Lint, Build und Test. Fachliche Abnahme und andere Urteile bleiben gemeinsame Qualitätsarbeit.","tags":["Software","Delivery"],"published_at":"2016-06-24T10:00:00+00:00","updated_at":"2026-07-13T08:35:40.529374+00:00","url":"https://www.mikebild.dev/de/blog/definition-of-done-als-qualitaets-gate/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/541e0bc46bdf2627beb07c9b4b5cbae7e1a2602f97dae5bc4e11018f42bd563d/definition-of-done-als-qualitaets-gate-vorlesen.mp3","audio_duration_secs":606,"text":"```console\n$ make verify\nlint    ✓  0 warnings\nbuild   ✓\ntest    ✗  2 failing, coverage 61 % (threshold 80 %)\n\nDefinition of Done: rot\n```\n\nDieses Rot lässt sich nicht verhandeln. Niemand kann es abhaken, niemand muss es im Review interpretieren, und jeder im Team reproduziert es in Sekunden auf der eigenen Maschine. Die ausgedruckte Zwölf-Punkte-Liste neben dem Board leistet das nicht. Steht dort \"alle Tests grün\" und setzt jemand ein Häkchen, dann ist damit nicht gesagt, dass die Tests grün sind – nur, dass jemand es glaubt oder behauptet.\n\nAn diesem Unterschied hängt alles Weitere. Was sich an einer Definition of Done als Kommando formulieren lässt, gehört in ein Gate, das den Merge blockiert, solange es rot ist. Was menschliches Urteil braucht, bleibt ehrlich als solches benannt, klein und sichtbar – und wird nicht so behandelt, als wäre es Code.\n\nDas klingt zunächst nach einer rein technischen Verschiebung. Tatsächlich schlägt sie bis ins Geschäftsergebnis durch: kürzere Zyklen, weniger Reibung im Team, höhere und vor allem verlässlichere Qualität. Wer Qualität an ein automatisiertes Gate koppelt, streitet nicht mehr im Review darüber, ob etwas fertig ist. Die Pipeline sagt es.\n\n## Warum das Ritual scheitert\n\nDie klassische Definition of Done als Checkliste hat ein strukturelles Problem: Sie prüft zum spätestmöglichen Zeitpunkt und mit dem unzuverlässigsten Prüfinstrument, das wir haben – einem müden Menschen am Sprintende. Wenn ein Punkt lautet \"alle Tests grün\", dann bedeutet das Abhaken dieses Punkts nicht, dass die Tests grün sind. Es bedeutet, dass jemand glaubt, dass sie es sind, oder es zumindest behauptet.\n\nGenau hier beginnt die Ticket-Schlacht. Weil die Checkliste nicht bindet, wird der Streit ins Soziale verlagert. Ist das jetzt \"done\" oder \"done done\"? Zählt das Refactoring noch dazu? Hat der Product Owner das schon abgenommen? Jede dieser Fragen kostet Zeit, erzeugt Reibung und – das ist das Schlimmste – vermittelt eine Sicherheit, die es gar nicht gibt. Ein abgehakter Punkt fühlt sich an wie eine Garantie, ist aber nur eine Absichtserklärung.\n\nMartin Fowler hat den technischen Gegenentwurf schon lange vorher beschrieben. Selbsttestender Code und Continuous Integration bilden ein Fundament, in dem jeder Commit einen automatischen Build- und Testlauf auslöst. Ein roter Build ist ein Stopp – \"stop the line\". Das ist kein Vorschlag, über den man diskutieren kann. Es ist ein Zustand. Genau diese Eigenschaft will ich für die Definition of Done: Sie soll ein Zustand sein, kein Konsens.\n\n## Die Definition of Done als Commit-Stage\n\nDer entscheidende gedankliche Schritt kam für mich über die Deployment Pipeline von Jez Humble und David Farley. Ihr Modell macht Qualität zu einem automatisierten Durchlauf. Die erste Stufe, die Commit-Stage, kompiliert den Code, führt Unit-Tests aus, lässt Linter und statische Analyse laufen. Erst wenn diese Stage grün ist, starten spätere Stufen überhaupt. Alles andere ist blockiert.\n\nWenn ich das ernst nehme, dann lässt sich eine Definition of Done fast eins zu eins auf diese Commit-Stage abbilden. Was in der Checkliste stand, wird zu Schritten in der Pipeline:\n\n```yaml\ncommit_stage:\n  fail_fast: true            # any red step blocks the merge\n  steps:\n    - name: compile\n    - name: lint             # static analysis, style rules\n    - name: unit_test\n    - name: coverage_check    # fail below an agreed threshold\n    - name: contract_test     # verify integration boundaries\ngate:\n  rule: merge_blocked_unless(commit_stage == \"green\")\n```\n\nDas Interessante an dieser Darstellung ist, was sie erzwingt. Ein Punkt, den ich nicht als Schritt formulieren kann, gehört nicht in den automatisierten Teil der Definition of Done. Ich kann \"code compiles\" ausführen. Ich kann \"no lint errors\" ausführen. Ich kann \"coverage above threshold\" ausführen. Ich kann \"der Code ist elegant\" nicht ausführen – das ist ein menschliches Urteil und bleibt im Review, wo es hingehört.\n\nDiese Trennschärfe ist der eigentliche Gewinn. Die Definition of Done zerfällt in zwei sauber getrennte Teile: ein hartes, ausführbares Gate und einen kleinen, ehrlich benannten Rest aus menschlichen Prüfungen. Kein Vermischen mehr, keine Scheingenauigkeit.\n\n## Ein Kommando, lokal und in der CI\n\nDamit das Gate im Alltag trägt, braucht es eine Eigenschaft, die oft übersehen wird: Der Entwickler muss es lokal genauso ausführen können wie die CI. Wenn die Pipeline andere Dinge prüft als das, was ich vor dem Push laufen lassen kann, dann verliere ich den schnellen Rückkopplungskreis und bekomme rote Builds erst nach dem Push. Das ist Reibung, und sie ist vermeidbar.\n\nDeshalb bündele ich den ausführbaren Kern der Definition of Done in genau einem Target. Der Name ist zweitrangig, die Idee zählt:\n\n```makefile\n# One command is the executable Definition of Done.\n# Developers run it before push; CI runs the exact same target.\nverify: lint build test\n\t@echo \"Definition of Done: green\"\n\nlint:\n\teslint . --max-warnings 0\n\nbuild:\n\tnpm run build\n\ntest:\n\tnpm test -- --coverage\n```\n\nDas Merge-Gate in der CI ruft kein eigenes Skript auf. Es ruft dasselbe `verify`. Damit gilt: Was lokal grün ist, ist auch in der CI grün, und umgekehrt. In einem Satz: Der automatisierbare Teil der Definition of Done ist ein Kommando; die vollständige Vereinbarung bleibt mehr als dieses Kommando.\n\nAls Git-Hook wird daraus ein leichtes Sicherheitsnetz, das den langsamen Weg über die CI gar nicht erst nötig macht:\n\n```bash\n#!/usr/bin/env sh\n# .git/hooks/pre-push\n# Run the executable DoD before anything leaves the machine.\nif ! make verify; then\n  echo \"Push blocked: Definition of Done is red.\"\n  exit 1\nfi\n```\n\nMan sieht sofort, warum das die Zyklen verkürzt. Der Entwickler bekommt das Rot in Sekunden auf der eigenen Maschine, nicht Minuten später aus der Pipeline und schon gar nicht Tage später im Sprint-Review. Fehler werden dort gefangen, wo sie am billigsten zu beheben sind: direkt nach ihrer Entstehung.\n\n## Der Weg durch das Gate\n\nNebeneinandergestellt springt der Unterschied ins Auge. Auf der einen Seite das Ritual, auf der anderen das Gate:\n\n```mermaid\nflowchart TD\n    A[Commit] --> B{Ritual oder Gate?}\n    B -->|Ritual| C[12-Punkte-Checkliste]\n    C --> D[manuelles Abhaken]\n    D --> E[Review-Meeting]\n    E --> F[Merge<br/>Hoffnung, kein Beweis]\n    B -->|Gate| G[Commit Stage:<br/>lint, build, test, contract]\n    G --> H{alles grün?}\n    H -->|ja| I[Merge]\n    H -->|nein| J[blockiert<br/>zurück zum Entwickler]\n```\n\nDer linke Pfad endet in Hoffnung. Der rechte endet in einem Beweis oder in einer klaren Blockade. Und die Blockade ist kein Vorwurf an eine Person, sondern eine sachliche Rückmeldung des Systems. Das entlastet auch die Teamdynamik enorm – nicht ein Kollege sagt \"das ist nicht fertig\", sondern das Gate sagt es, reproduzierbar und für alle gleich.\n\nEmpirisch stützt sich diese Haltung auf die State-of-DevOps-Reports von 2014 und 2015, an denen unter anderem Nicole Forsgren, Gene Kim und Jez Humble mitgearbeitet haben. Ihr Befund widerlegt den verbreiteten Reflex, Tempo gehe auf Kosten der Qualität. High-Performer koppeln hohe Deploy-Frequenz mit niedriger Change-Fail-Rate. Tempo und Qualität sind kein Trade-off – vorausgesetzt, die Prüfungen laufen automatisiert statt manuell. Genau das ist der Business-Case für das ausführbare Gate: Es macht schnell und sicher zugleich möglich.\n\n## Auch Grenzen lassen sich als Gate prüfen\n\nEin häufiger Einwand: Unit-Tests prüfen nur die eigene Einheit, aber die richtig teuren Fehler entstehen an den Integrationsgrenzen zwischen Services. Stimmt. Und auch dafür gibt es einen ausführbaren Weg statt eines Abnahme-Meetings. Consumer-Driven Contracts, wie Fowler und Ian Robinson sie beschrieben haben und wie Pact sie handhabbar macht, verwandeln die Frage \"passen unsere Schnittstellen zusammen?\" in ein Signal, das grün oder rot ist.\n\n```javascript\n// A consumer-driven contract turns an integration\n// boundary into an executable check.\nprovider\n  .given(\"an order with id 42 exists\")\n  .uponReceiving(\"a request for order 42\")\n  .withRequest({ method: \"GET\", path: \"/orders/42\" })\n  .willRespondWith({\n    status: 200,\n    body: { id: 42, status: \"shipped\" }\n  });\n```\n\nDer Contract-Test wird Teil derselben Commit-Stage. Damit wandert eine weitere Prüfung, die früher in Meetings und Abstimmungsketten stattfand, in die Pipeline. Weniger Termine, mehr Beweise. Der Hebel liegt überall dort, wo Abstimmung nur deshalb nötig ist, weil niemand die Übereinkunft ausführen kann – solche Koordination lässt sich durch ausführbare Übereinkünfte ersetzen.\n\n## Ehrlich bleiben: was das Gate nicht kann\n\nAn dieser Stelle muss ich gegen mein eigenes Argument arbeiten, sonst wird es unredlich. Ein grünes Gate ist nicht dasselbe wie Qualität. Es ist der Nachweis, dass die vereinbarten Prüfungen ausgeführt wurden und durchgelaufen sind – nicht der Nachweis, dass diese Prüfungen aussagekräftig sind. Eine hohe Coverage mit schwachen Assertions ist grün und trotzdem wertlos. Tests, die nichts wirklich behaupten, geben eine Scheinsicherheit, die gefährlicher ist als offen zugegebene Unsicherheit.\n\nDas Gate misst also die Ausführung von Prüfungen, nicht deren Güte. Die Güte der Prüfungen selbst bleibt eine menschliche, fachliche Verantwortung. Wer das verwechselt, ersetzt das alte Checklisten-Ritual nur durch ein Coverage-Ritual.\n\nEbenso ehrlich: Nicht jeder Punkt einer Definition of Done ist automatisierbar. \"Dokumentation aktualisiert\", \"vom Product Owner abgenommen\", \"Barrierefreiheit manuell geprüft\" – das bleibt menschlich. Der Fehler wäre, so zu tun, als würde alles zu Code. Der richtige Umgang ist Trennung: das automatisierbare Kern-Gate hart und blockierend machen, den manuellen Rest klein, sichtbar und bewusst als menschliche Entscheidung stehen lassen.\n\nUnd noch eine Abgrenzung, die in der Praxis viel Reibung spart: Die Definition of Done ist nicht dasselbe wie Akzeptanzkriterien. Die Definition of Done ist projektweit und stabil, ein Qualitätsstandard, der für jede Story gilt. Akzeptanzkriterien sind pro Story, sie beschreiben das fachlich Gewollte dieser einen Anforderung. Wer beides vermischt, bekommt genau die aufgeblähten, ständig neu verhandelten Listen zurück, gegen die dieser Artikel geschrieben ist.\n\n## Fazit\n\nDie Definition of Done ist eine gute Idee, die in vielen Teams an ihrer Form scheitert. Rein mechanisch als Checkliste am spätesten Punkt abgehakt, erzeugt sie Reibung und Scheinsicherheit statt Qualität. Ihr automatisierbarer Kern gehört deshalb in ein Gate, das lokal und in der CI dasselbe prüft. Gemeinsame Qualitätskriterien und fachliche Abnahme verschwinden dadurch nicht; sie werden nur nicht als automatischer Beweis ausgegeben.\n\nDer Weg dorthin ist konzeptionell einfach und genau deshalb elegant. Bilde den automatisierbaren Kern der Definition of Done auf die Commit-Stage einer Pipeline ab. Bündele ihn in einem `verify`-Kommando. Blockiere den Merge, solange es rot ist. Trenne diesen harten Kern sauber vom kleinen manuellen Rest und tu nicht so, als wäre alles Code. Und bleib ehrlich darüber, dass grün \"geprüft\" heißt, nicht \"gut\".\n\nDas Geschäftsergebnis dieser Verschiebung ist real und messbar. Kürzere Feedback-Zyklen, weniger Meetings über den Zustand des Codes, weniger soziale Reibung im Team und eine Qualität, die nicht auf Hoffnung beruht, sondern auf einem reproduzierbaren Zustand. Definition of Done wird vom Bürokratie-Ritual zum stillen, verlässlichen Türsteher. Und der beste Türsteher ist der, über den niemand mehr reden muss.\n\n## Weiterführende Quellen\n\n- Martin Fowler: *Continuous Integration* und *SelfTestingCode*, martinfowler.com\n- Jez Humble, David Farley: *Continuous Delivery*, 2010 – Deployment Pipeline und Commit-Stage\n- Puppet Labs: *State of DevOps Report* 2014 und 2015 (Forsgren, Kim, Humble)\n- Ken Schwaber, Jeff Sutherland: *The Scrum Guide* – Definition of Done\n- Martin Fowler, Ian Robinson: *Consumer-Driven Contracts*, martinfowler.com; Tool: Pact\n- Michael Nygard: *Release It!*, 2007 – Stability Patterns als nicht-funktionale Prüfziele"},{"locale":"de","translation_key":"react-komponenten-als-schnittstellen","slug":"react-komponenten-als-schnittstellen","title":"React: Komponenten als Schnittstellen","summary":"Warum Props der öffentliche Vertrag einer React-Komponente sind – und was sich ändert, wenn man sie wie eine API entwirft statt wie eine Parameterliste.","tags":["Software","Frontend"],"published_at":"2016-03-12T10:00:00+00:00","updated_at":"2026-08-17T11:32:14.2772+00:00","url":"https://www.mikebild.dev/de/blog/react-komponenten-als-schnittstellen/","audio_url":null,"audio_duration_secs":null,"text":"# React: Komponenten als Schnittstellen\n\nEine React-Komponente ist kein Template, dem jemand etwas Logik beigemischt hat. Diese Lesart ist verbreitet, weil JSX auf den ersten Blick wie eine Template-Sprache aussieht – und sie erzeugt genau die Komponenten, die ein halbes Jahr später niemand mehr anfassen will: Markup mit eingestreuten Bedingungen, fünfzehn Props ohne erkennbare Ordnung, und irgendwo tief innen ein Ajax-Aufruf. Eine Komponente ist eine Schnittstelle. Props sind ihr öffentlicher Vertrag, State ist ein privates Implementierungsdetail, und das Render-Ergebnis ist die Erfüllung des Vertrags. Wer Props so entwirft, wie man eine gute API entwirft – minimal, in der Sprache der Fachdomäne benannt, ohne durchgereichte Interna –, bekommt Komponenten, die Personalwechsel und Moden überleben.\n\nSeit React 0.14 ist das keine bloße Interpretation mehr, das Framework selbst spricht diese Sprache: Eine Komponente darf eine schlichte Funktion sein, die Props entgegennimmt und Elemente zurückgibt. Kein `createClass`, keine Klasse, kein Lifecycle – eine Funktionssignatur. Deutlicher lässt sich „Schnittstelle\" kaum ausdrücken.\n\n## Props sind der Vertrag, State ist ein Detail\n\nIn einem Abrechnungsprojekt, an dem ich gerade arbeite, rendern wir eine Liste offener Rechnungen. Die kleinste Einheit ist eine Zeile, und sie ist bewusst eine zustandslose Functional Component:\n\n```jsx\n// InvoiceRow.js - a stateless functional component (React 0.14)\nconst InvoiceRow = ({ invoice, isSelected, onSelect }) => (\n  <tr className={isSelected ? 'selected' : ''}\n      onClick={() => onSelect(invoice.id)}>\n    <td>{invoice.number}</td>\n    <td>{invoice.customer}</td>\n    <td className=\"amount\">{formatAmount(invoice.total)}</td>\n  </tr>\n);\n```\n\nAus Sicht des Aufrufers lautet der Vertrag: Gib mir eine Rechnung, sage mir, ob sie ausgewählt ist, und nenne mir einen Callback für die Auswahl. Mehr nicht. Die Komponente weiß nichts über REST-Endpoints, nichts über einen Store, nichts über die Session des angemeldeten Nutzers. Genau deshalb lässt sie sich in der Detailansicht, im Suchergebnis und im Monatsabschluss gleichermaßen verwenden – und genau deshalb kann ein Test sie ohne Server und ohne Browser-Verrenkungen aufrufen.\n\nDer Gegenspieler des Vertrags ist der State. In den offiziellen Docs steht dazu eine Prüfliste, die ich inzwischen fast wörtlich in Code-Reviews zitiere. Ein Wert gehört nur dann in den State, wenn alle drei Fragen mit Nein beantwortet werden:\n\n- Kommt der Wert über Props herein?\n- Bleibt er über die Zeit unverändert?\n- Lässt er sich aus anderen Props oder State-Werten ableiten?\n\nMir ist aufgefallen, dass die meisten React-Probleme, die ich in Reviews sehe, keine Render-Probleme sind, sondern Vertragsprobleme: Props werden beim Mounten in den State kopiert und laufen danach auseinander, abgeleitete Werte werden gespeichert statt berechnet, und plötzlich gibt es zwei Wahrheiten für dieselbe Rechnung. Wer State konsequent als privates Detail behandelt und alles Vertragliche in Props ausdrückt, bekommt diese Klasse von Fehlern gar nicht erst.\n\n## propTypes: der Vertrag steht im Code\n\nEin Vertrag, der nur im Kopf des Autors existiert, ist keiner. React bringt dafür `propTypes` mit – seit 0.14 direkt im `react`-Paket, egal ob man mit `React.createClass` oder mit ES2015-Klassen arbeitet:\n\n```jsx\nInvoiceRow.propTypes = {\n  invoice: React.PropTypes.shape({\n    id: React.PropTypes.string.isRequired,\n    number: React.PropTypes.string.isRequired,\n    customer: React.PropTypes.string.isRequired,\n    total: React.PropTypes.number.isRequired\n  }).isRequired,\n  isSelected: React.PropTypes.bool,\n  onSelect: React.PropTypes.func.isRequired\n};\n\nInvoiceRow.defaultProps = {\n  isSelected: false\n};\n```\n\nTechnisch sind das nur Warnungen in der Entwicklungsumgebung – kein Compiler, keine Garantie zur Laufzeit im Produktivbetrieb. Trotzdem halte ich `propTypes` für eines der unterschätztesten Werkzeuge im aktuellen React-Ökosystem, aus einem Grund, der mit Typprüfung wenig zu tun hat: Sie sind Dokumentation, die nicht unbemerkt veralten kann. Wenn eine Kollegin `InvoiceRow` zum ersten Mal öffnet, liest sie den Vertrag, bevor sie eine Zeile Implementierung sieht. Und wenn jemand den Vertrag bricht, meckert die Konsole beim nächsten Entwicklungslauf.\n\nNebenbei entschärfen `propTypes` auch ein Team-Problem, das gerade viele Codebasen betrifft: das Nebeneinander von `React.createClass` und ES2015-Klassen. Wir schreiben Neues mit Babel und Klassen beziehungsweise als zustandslose Funktionen, aber ältere Teile der Anwendung stecken noch im `createClass`-Stil – und das wird auch eine Weile so bleiben, denn niemand schreibt eine laufende Anwendung nur wegen einer Syntaxfrage um. Solange jede Komponente ihren Vertrag als `propTypes` deklariert, ist das erstaunlich egal. Der Aufrufer sieht in beiden Fällen dieselbe Schnittstelle, und die Migration einer einzelnen Komponente von einem Stil zum anderen bricht nichts, was der Vertrag nicht sofort melden würde.\n\nInteressant wird es, wenn man `propTypes` als Entwurfswerkzeug benutzt statt als Pflichtübung im Nachhinein. In dem Abrechnungsprojekt schreiben wir die `propTypes` inzwischen zuerst, bevor die Komponente Markup bekommt. Das fühlt sich zunächst umständlich an, zwingt aber zu der einen Frage, um die es geht: Was muss der Aufrufer wirklich liefern? Eine Komponente, deren `propTypes`-Block länger ist als ihr Render-Code, ist fast immer ein Hinweis darauf, dass hier zwei oder drei Komponenten in einer stecken.\n\n## Zerlegen wie in „Thinking in React\"\n\nDie offiziellen Docs enthalten mit „Thinking in React\" einen Text, der genau diese Entwurfshaltung als Methode beschreibt – und der meiner Meinung nach viel zu oft übersprungen wird, weil er nach Einsteigerlektüre klingt. Die Methode ist schlicht: Rechtecke über das UI-Mock zeichnen, jedem Rechteck eine einzige Verantwortung geben, zuerst eine statische Version ohne jeden State bauen, dann den minimalen State identifizieren und ihn im nächstgelegenen gemeinsamen Vorfahren ansiedeln.\n\nÜbersetzt in die Schnittstellen-Sicht heißt das: Jedes Rechteck bekommt einen Vertrag, und die statische Version ist der Beweis, dass der Vertrag trägt, bevor irgendetwas Dynamisches passiert. Der Schritt „minimalen State finden\" ist dann kein React-Trick, sondern das, was man beim Entwurf eines Datenmodells auch tut – jede Redundanz, die man jetzt zulässt, muss man später von Hand synchron halten.\n\nDas ist keine neue Idee. Wer schon einmal ein Modul-Interface geschnitten oder einen Service-Vertrag verhandelt hat, erkennt das Muster sofort wieder. Neu ist, dass React diese Disziplin bis in die kleinste UI-Einheit hinunter bezahlbar macht: Eine Funktion mit drei Props ist billig genug, um sie wegzuwerfen und neu zu schneiden, wenn der Schnitt nicht stimmt.\n\n## Container und Darstellung trennen\n\nIrgendwo müssen die Daten allerdings herkommen. Dan Abramov hat dafür im vergangenen Jahr die Unterscheidung zwischen Container- und Präsentationskomponenten aufgeschrieben, die sich bei uns im Projekt schnell durchgesetzt hat: Präsentationskomponenten kennen nur ihre Props, Container kennen die Datenquelle und reichen Ergebnisse als Props weiter.\n\n```jsx\n// InvoiceListContainer.js - knows where the data comes from\nclass InvoiceListContainer extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { invoices: [], isLoading: true, selectedId: null };\n    this.handleSelect = this.handleSelect.bind(this);\n  }\n\n  componentDidMount() {\n    fetchInvoices().then(invoices =>\n      this.setState({ invoices, isLoading: false })\n    );\n  }\n\n  handleSelect(invoiceId) {\n    this.setState({ selectedId: invoiceId });\n  }\n\n  render() {\n    const { invoices, isLoading, selectedId } = this.state;\n    if (isLoading) return <LoadingHint />;\n    return (\n      <InvoiceList\n        invoices={invoices}\n        selectedId={selectedId}\n        onSelect={this.handleSelect}\n      />\n    );\n  }\n}\n```\n\nDer Container ist bewusst langweilig: Er lädt, er hält den Auswahlzustand, er reicht weiter. `InvoiceList` und `InvoiceRow` bleiben Pure Functions über ihren Props. Der Datenfluss ist damit an jeder Stelle ablesbar – Daten fließen als Props nach unten, Events laufen als Callbacks nach oben:\n\n```mermaid\nflowchart TD\n  C[InvoiceListContainer<br/>State: invoices, isLoading, selectedId] -->|Props: invoices, selectedId, onSelect| L[InvoiceList]\n  L -->|Props: invoice, isSelected, onSelect| R1[InvoiceRow]\n  L -->|Props: invoice, isSelected, onSelect| R2[InvoiceRow]\n  R1 -.->|onSelect mit invoice.id| C\n```\n\nWer Redux einsetzt – und der Aufstieg von Redux ist gerade in vollem Gange –, kennt dieses Muster bereits: `connect` erzeugt nichts anderes als Container. Der Punkt ist aber unabhängig von der Bibliothek. Die Trennung lohnt sich auch in einer Anwendung ganz ohne Store, weil sie die teuren Komponenten (die mit Datenzugriff) von den billigen (die mit reiner Darstellung) trennt. Die billigen sind die, die man wiederverwendet, im Styleguide zeigt und in fünf Minuten testet.\n\n## Komposition über children statt Vererbung\n\nDie zweite Stelle, an der das Schnittstellen-Denken konkret wird, ist Wiederverwendung von Rahmen und Layout. Der Reflex aus der objektorientierten Welt wäre Vererbung: eine `BasePanel`-Klasse, von der Spezialfälle erben. In React habe ich das noch in keinem Fall gebraucht. Stattdessen bekommt der Vertrag einen Platzhalter – `children`:\n\n```jsx\n// Panel.js - a layout component with a slot for arbitrary content\nconst Panel = ({ title, children }) => (\n  <div className=\"panel\">\n    <h2 className=\"panel-title\">{title}</h2>\n    <div className=\"panel-body\">{children}</div>\n  </div>\n);\n\n// usage\n<Panel title=\"Open invoices\">\n  <InvoiceList invoices={invoices} selectedId={selectedId} onSelect={handleSelect} />\n</Panel>\n```\n\n`Panel` weiß nichts über Rechnungen, `InvoiceList` weiß nichts über Panels. Beide Verträge bleiben minimal, und jede Kombination ist am Aufrufort sichtbar, statt in einer Vererbungshierarchie versteckt zu sein. Braucht ein Panel mehrere Einschubstellen – etwa eine Werkzeugleiste neben dem Titel –, ist auch das nur eine weitere Prop, die ein Element entgegennimmt. Elemente sind in React gewöhnliche Werte, und Verträge, die Werte austauschen, sind leichter zu verstehen als Verträge, die Ableitung verlangen.\n\n## Die ehrliche Grenze: Props über viele Ebenen\n\nSo weit die Stellen, an denen die Schnittstellen-Sicht trägt. Es gibt eine Stelle, an der sie im Moment wehtut, und die will ich nicht verschweigen: Props, die über viele Ebenen durchgereicht werden müssen.\n\nDas klassische Beispiel ist der angemeldete Nutzer. Das Nutzermenü ganz unten im Baum braucht ihn, also wandert er als Prop durch Komponenten, die ihn selbst gar nicht verwenden:\n\n```mermaid\nflowchart LR\n  App -->|currentUser| Page\n  Page -->|currentUser| Toolbar\n  Toolbar -->|currentUser| UserMenu\n```\n\n`Page` und `Toolbar` haben `currentUser` nicht in ihrem fachlichen Vertrag – sie transportieren ihn nur. Jede Zwischenebene, die eine fremde Prop durchreicht, verwässert genau die Minimalität, für die ich oben argumentiert habe. Und eine wirklich befriedigende Standard-Antwort darauf gibt es Anfang 2016 nicht. Es gibt Linderung:\n\n- den Baum umbauen und Komposition nutzen – `App` rendert das `UserMenu` selbst und reicht das fertige Element nach unten, statt der Daten\n- weitere Container tiefer im Baum ansetzen, die sich ihre Daten selbst besorgen, bei Redux etwa per `connect`\n- anwendungsweite Daten grundsätzlich in einen Store legen und nur noch lokale Verträge per Props führen\n\nReact hat zwar einen Context-Mechanismus, der genau dieses Problem adressieren soll – aber die Docs sagen dazu wörtlich, das Feature sei experimentell und die API voraussichtlich instabil. Auf so etwas baue ich keine Anwendung, die länger leben soll als die Warnung. Im Projekt tolerieren wir Durchreichen über zwei, drei Ebenen, bauen bei mehr den Baum um und setzen für wirklich globale Dinge auf den Store. Das ist ein Kompromiss, kein State, mit dem ich zufrieden bin. Hier ist das Ökosystem schlicht noch nicht fertig.\n\n## Was ich daraus mitnehme\n\nDie Qualität einer Komponente entscheidet sich nicht in ihrem Render-Code, sondern am Aufrufort. Deshalb stelle ich im Review inzwischen zuerst Fragen an die Props-Liste, nicht an die Implementierung: Verstehe ich den Vertrag, ohne die Datei zu öffnen? Sprechen die Namen die Sprache der Fachdomäne – `invoice`, `onSelect` – oder die Sprache der Technik dahinter? Steckt eine Prop darin, die nur existiert, weil ein tieferes Kind sie braucht? Könnte ein zweiter, ganz anderer Aufrufer diese Komponente verwenden, ohne dass sie es merkt?\n\nTemplates beantworten keine dieser Fragen, Schnittstellen schon. React gibt einem dafür erstaunlich wenig vor – eine Funktion, Props, `children`, dazu `propTypes` als lesbaren Vertrag – und genau diese Kargheit ist der Wert. Die Bibliothek unter der Komponente wird sich weiterdrehen; allein in den letzten anderthalb Jahren haben sich Build-Werkzeuge, Sprachstandard und State-Bibliotheken einmal komplett gedreht. Ein sauber geschnittener Vertrag aus drei Props hat gute Chancen, das alles zu überstehen. Ein Template mit etwas Logik hat sie nicht.\n\n## Weiterführende Quellen\n\n- Thinking in React (offizielle React-Dokumentation): [react.dev/learn/thinking-in-react](https://react.dev/learn/thinking-in-react)\n- React v0.14 – Release-Ankündigung mit stateless functional components: [legacy.reactjs.org/blog/2015/10/07/react-v0.14.html](https://legacy.reactjs.org/blog/2015/10/07/react-v0.14.html)\n- Dan Abramov: Presentational and Container Components (2015): [medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0)"},{"locale":"de","translation_key":"graphql-als-frage-an-das-system","slug":"graphql-als-frage-an-das-system","title":"GraphQL als Frage an das System","summary":"Ein halbes Jahr nach der Spezifikation sortiert dieser Beitrag, was an GraphQL wirklich neu ist – und welche Fragen Anfang 2016 noch niemand beantwortet hat.","tags":["Software","GraphQL","API"],"published_at":"2016-01-12T10:00:00+00:00","updated_at":"2026-07-14T16:06:16.162736+00:00","url":"https://www.mikebild.dev/de/blog/graphql-als-frage-an-das-system/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/6ee310cc30a6bcdec5a63285b0bd1042dd46c04d50d3caaea4246e5d515d0154/graphql-als-frage-an-das-system-vorlesen.mp3","audio_duration_secs":753,"text":"# GraphQL als Frage an das System\n\n„Eine Query Language für APIs\" – so beschreibt Facebook GraphQL in der Spezifikation, die seit Juli 2015 als Working Draft öffentlich ist. Der Begriff führt schnell in die Irre. Wer „Query Language\" hört, denkt an SQL und vermutet eine Query Language für Datenbanken, irgendwie ins Web verlängert: der Client schickt ein SELECT, der Server reicht es durch. Das trifft es nicht, und das Missverständnis ist gefährlich, weil es GraphQL entweder zu mächtig erscheinen lässt (beliebige Queries gegen meine Daten!) oder zu banal (noch ein ORM übers Netz).\n\nGraphQL fragt keine Tabellen ab, kennt keine Joins und hat keine Meinung dazu, wo Daten liegen. Abgefragt wird etwas anderes: ein Typsystem, das der Server veröffentlicht. Der Client formuliert seine Frage in den Begriffen dieses Typsystems, der Server beantwortet genau diese Frage – und woher die Daten kommen, ob aus einer Datenbank, aus drei internen Diensten oder aus einer Datei auf der Platte, bleibt vollständig Sache des Servers. Ein halbes Jahr nach der Veröffentlichung lohnt sich ein sortierender Blick: Was davon ist wirklich neu, und was ist nur neue Syntax für alte Ideen?\n\n## Wer stellt hier eigentlich die Frage?\n\nDer Kern lässt sich in einem Satz fassen: REST beantwortet Fragen, die sich der Server gestellt hat – GraphQL lässt den Client die Frage stellen.\n\nDas klingt polemischer, als es gemeint ist. Ein durchdachtes REST-Design ist eine Sammlung von Antworten: `GET /posts/42` liefert das, was der Entwickler des Endpoints für einen Artikel für relevant hielt. Als der Endpoint entworfen wurde, hat jemand geraten, welche Felder ein Client wohl brauchen wird – und im Zweifel lieber ein paar mehr hineingepackt. Diese Antwort ist eingefroren. Kommt später eine Ansicht dazu, die nur Titel und Autorennamen der letzten zehn Artikel braucht, hat sie zwei Möglichkeiten: den fetten Endpoint aufrufen und das meiste wegwerfen, oder einen neuen, maßgeschneiderten Endpoint beantragen. Beides passiert in echten Projekten ständig, und beides erzeugt Kosten – einmal im Netz, einmal in der Abstimmung zwischen Teams.\n\nGraphQL dreht die Richtung um. Der Server sagt nicht mehr „das sind meine Antworten\", sondern „das sind die Begriffe, in denen du fragen darfst\". Die konkrete Frage – welche Felder, wie tief verschachtelt, in welcher Kombination – formuliert der Client selbst, pro Ansicht, pro Release, ohne Rückfrage beim Server-Team. Das ist die eigentliche Verschiebung, und sie ist organisatorisch mindestens so interessant wie technisch.\n\n## Das Schema als Vertrag und Fachsprache\n\nDamit der Client fragen kann, muss der Server sein Vokabular offenlegen. Das geschieht im Schema, und hier liegt für mich die unterschätzte Qualität von GraphQL: Das Schema ist nicht nur ein Vertrag über Datenformen, es ist eine Fachsprache. Typen benennen Dinge der Domäne, nicht Zeilen einer Tabelle. In der kompakten Schema-Notation, die sich in Beispielen und Vorträgen eingebürgert hat, sieht das etwa so aus:\n\n```graphql\ntype Author {\n  id: ID!\n  name: String!\n  posts: [Post]\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  body: String!\n  author: Author!\n  comments: [Comment]\n}\n\ntype Comment {\n  id: ID!\n  text: String!\n  author: Author!\n}\n\ntype Query {\n  post(id: ID!): Post\n  latestPosts(count: Int): [Post]\n}\n```\n\nMan kann dieses Schema einem Redakteur zeigen und darüber reden, ob ein Kommentar wirklich immer einen Autor hat. Das Ausrufezeichen ist keine Formalie, sondern eine fachliche Aussage: `author: Author!` behauptet, dass es keine verwaisten Kommentare gibt. Ob das stimmt, weiß nicht der Client-Entwickler, sondern derjenige, der die Altdaten kennt. Solche Diskussionen habe ich an Datenbankschemata selten geführt – am GraphQL-Schema entstehen sie fast von selbst, weil es genau an der Grenze zwischen den Teams liegt und beide Seiten es lesen können.\n\nDer Typ `Query` fällt aus der Reihe: Er beschreibt keine Sache, sondern die Entry Points – die Fragen, die das System überhaupt zulässt. Auch das ist eine Design-Entscheidung des Servers. GraphQL öffnet nicht wahllos alle Daten; es öffnet exakt die Wurzeln, die im Schema stehen, und von dort aus die Kanten, die die Typen definieren.\n\n## Die Query: die Form der Antwort ist die Form der Frage\n\nDie zweite Eigenschaft, die im täglichen Arbeiten sofort auffällt: Eine GraphQL-Query ist deklarativ, und die Antwort hat exakt die Gestalt der Frage.\n\n```graphql\n{\n  post(id: \"42\") {\n    title\n    author {\n      name\n    }\n    comments {\n      text\n      author {\n        name\n      }\n    }\n  }\n}\n```\n\nDie Antwort dazu:\n\n```json\n{\n  \"data\": {\n    \"post\": {\n      \"title\": \"GraphQL as a question\",\n      \"author\": { \"name\": \"Ada\" },\n      \"comments\": [\n        { \"text\": \"Nice read!\", \"author\": { \"name\": \"Grace\" } }\n      ]\n    }\n  }\n}\n```\n\nKein Feld zu viel, keines zu wenig, und die Verschachtelung der Antwort spiegelt die Verschachtelung der Frage. Das wirkt zunächst wie eine Annehmlichkeit, hat aber praktische Tiefe: Der Client-Code, der die Antwort verarbeitet, steht direkt neben der Query, die sie beschreibt. Wer die Ansicht ändert, ändert die Query, und die Datenform folgt. Facebooks Relay, seit August 2015 als Open Source verfügbar, treibt genau diesen Gedanken auf die Spitze und lässt jede Komponente ihre Datenanforderungen selbst deklarieren. Man muss Relay nicht einsetzen, um von der Idee zu profitieren – die Query allein erzwingt schon eine Klarheit, die bei „wir nehmen halt, was der Endpoint liefert\" nie entsteht.\n\n## Resolver: der Ort der Wahrheit\n\nBleibt die Frage, wie aus einer deklarativen Frage eine konkrete Antwort wird. Die Referenzimplementierung graphql-js beantwortet sie mit einem einfachen Prinzip: Jedes Feld hat eine Resolver-Function. Sie bekommt das Elternobjekt und die Argumente und liefert den Wert des Feldes – synchron oder als Promise.\n\n```js\nimport {\n  GraphQLObjectType,\n  GraphQLID,\n  GraphQLString,\n  GraphQLList,\n  GraphQLNonNull\n} from 'graphql';\n\nconst postType = new GraphQLObjectType({\n  name: 'Post',\n  fields: () => ({\n    id: { type: new GraphQLNonNull(GraphQLID) },\n    title: { type: new GraphQLNonNull(GraphQLString) },\n    author: {\n      type: authorType,\n      resolve: (post) => db.findAuthorById(post.authorId)\n    },\n    comments: {\n      type: new GraphQLList(commentType),\n      resolve: (post) => db.findCommentsByPostId(post.id)\n    }\n  })\n});\n\nconst queryType = new GraphQLObjectType({\n  name: 'Query',\n  fields: {\n    post: {\n      type: postType,\n      args: { id: { type: new GraphQLNonNull(GraphQLID) } },\n      resolve: (root, args) => db.findPostById(args.id)\n    }\n  }\n});\n```\n\nIn graphql-js baut man das Schema derzeit programmatisch aus solchen Typobjekten zusammen; die kompakte Schema-Notation von oben dient vor allem der Kommunikation. Wichtiger als die API-Details ist der Ort, an dem hier Wahrheit entsteht: im Resolver. Ob `author` aus derselben Datenbank kommt wie der Post, aus einem anderen Dienst oder aus einem Cache – das entscheidet diese eine Funktion, und nur sie. Das Schema verspricht die Form, der Resolver liefert den Inhalt. Diese Trennung macht GraphQL zur Fassade: Man kann dahinter aufräumen, Dienste zusammenlegen oder auseinanderschneiden, ohne dass ein Client es merkt, solange das Schema hält.\n\nIn einem Projekt Ende letzten Jahres habe ich einen kleinen Prototyp mit graphql-js vor zwei bestehende interne Dienste gesetzt – nichts Produktives, ein Experiment über die Feiertage. Die überraschende Erfahrung war nicht die Query-Sprache, sondern wie schnell die Diskussion im Team von Endpoints zu Begriffen wechselte. Statt „welcher Endpoint liefert das Feld\" hieß die Frage plötzlich „gehört das Feld an diesen Typ\". Das ist eine bessere Frage.\n\n## Overfetching und Underfetching: das eigentlich gelöste Problem\n\nWenn man nüchtern fragt, welches konkrete Problem GraphQL löst, lande ich immer wieder bei zweien, die dieselbe Wurzel haben. Overfetching: Der Endpoint liefert mehr, als die Ansicht braucht, und mobile Clients bezahlen das mit Datenvolumen und Akkulaufzeit. Underfetching: Der Endpoint liefert weniger, als die Ansicht braucht, und der Client klappert nacheinander weitere Endpoints ab – jede Runde eine volle Netzwerk-Latenz, im Mobilfunk gern dreistellige Millisekunden.\n\n```mermaid\nflowchart LR\n  subgraph REST[\"REST – drei Runden für eine Ansicht\"]\n    C1[Client] --> E1[\"GET /posts/42\"]\n    C1 --> E2[\"GET /posts/42/comments\"]\n    C1 --> E3[\"GET /authors/7\"]\n  end\n  subgraph GQL[\"GraphQL – eine Frage\"]\n    C2[Client] --> Q[\"POST /graphql<br/>eine Query, ein Roundtrip\"]\n    Q --> R[\"Resolver\"]\n    R --> S1[(\"Datenbank\")]\n    R --> S2[\"interner Dienst\"]\n  end\n```\n\nBeide Probleme verschwinden, weil die Frage vollständig beim Client liegt: Er fragt alles, was er braucht, und nichts darüber hinaus, in einem einzigen Roundtrip. Die Runden zwischen den Datenquellen finden weiterhin statt – aber serverseitig, im Rechenzentrum, wo Latenz billig ist. Genau deshalb hat Facebook GraphQL für seine mobilen Anwendungen gebaut, und genau deshalb ist der Nutzen dort am größten, wo Clients über schlechte Netze sprechen. Wer eine interne API zwischen zwei Servern im selben Rack baut, löst mit GraphQL ein Problem, das er womöglich gar nicht hat.\n\n## GraphiQL: das Fenster ins System\n\nEin Aspekt wird in den Diskussionen um Sprache und Typsystem oft unterschlagen: GraphQL-Server sind introspektierbar. Das Schema ist zur Laufzeit abfragbar – mit einer GraphQL-Query über das Schema selbst. Darauf baut GraphiQL auf, der browserbasierte Explorer, den Facebook zusammen mit der Referenzimplementierung veröffentlicht hat. Man richtet ihn auf einen Endpoint und bekommt:\n\n- Autovervollständigung für Felder und Argumente, direkt aus dem Schema\n- eingeblendete Dokumentation für jeden Typ und jedes Feld\n- Validierung der Query beim Tippen, vor dem ersten Request\n- ein Fenster zum Ausprobieren, ohne eine Zeile Client-Code\n\nDas verändert, wie man eine fremde API kennenlernt. Statt Dokumentations-Wikis zu lesen, die seit drei Versionen niemand gepflegt hat, exploriert man das System selbst – und die Auskunft kann nicht veralten, weil sie aus dem laufenden Server kommt. Mir ist beim Herumprobieren aufgefallen, dass GraphiQL nebenbei die Schema-Qualität diszipliniert: Wenn jeder Feldname sofort sichtbar und autovervollständigbar ist, tut schlechte Benennung sichtbar weh.\n\n## Was Anfang 2016 offen ist\n\nSo weit das Lob. Ehrlicherweise gehört in eine Bestandsaufnahme auch, was die Spezifikation und die junge Community noch nicht beantwortet haben. Vier Punkte beschäftigen mich derzeit:\n\n- Caching ohne URLs\n- das N+1-Problem in Resolvern\n- Berechtigungen pro Feld\n- Versionierung – das Versprechen der „versionless API\"\n\nBeim Caching verliert GraphQL zunächst etwas, das REST geschenkt bekommt. HTTP-Caching lebt von der URL als Cache-Schlüssel: `GET /posts/42` können Browser, Proxy und CDN cachen, ohne den Inhalt zu verstehen. Ein GraphQL-Request ist ein POST gegen einen einzigen Endpoint – für die HTTP-Infrastruktur sehen alle Anfragen gleich aus. Relay beantwortet das clientseitig mit einem normalisierten Cache über Objekt-IDs, was elegant ist, aber eben nur im Client hilft. Für die Zwischenschichten gibt es Stand heute keine überzeugende Antwort.\n\nDas N+1-Problem entsteht direkt aus dem Resolver-Modell. Die Query `latestPosts(count: 10)` mit dem Feld `author` ruft den Author-Resolver zehnmal auf – im naiven Fall zehn einzelne Datenbankabfragen nach einer Liste, die eine einzige Query liefern könnte:\n\n```mermaid\nflowchart TD\n  Q[\"latestPosts(count: 10)<br/>mit Feld author\"] --> P[\"Resolver latestPosts<br/>1 Abfrage\"]\n  P --> A1[\"Resolver author<br/>Post 1\"]\n  P --> A2[\"Resolver author<br/>Post 2\"]\n  P --> An[\"Resolver author<br/>Post 10\"]\n  A1 --> DB[(\"10 einzelne Abfragen<br/>statt einer\")]\n  A2 --> DB\n  An --> DB\n```\n\nFacebook hat dafür im Herbst DataLoader veröffentlicht, ein kleines, frisches Projekt, das Ladevorgänge pro Request sammelt, dedupliziert und gebündelt ausführt. Der Ansatz wirkt tragfähig, ist aber noch kein etabliertes Muster – man muss ihn kennen und bewusst einbauen, sonst produziert das eleganteste Schema miserable Datenbanklast.\n\nBerechtigungen sind die Frage, die mir am meisten Respekt einflößt. Bei REST autorisiert man pro Endpoint, und das Modell ist gut verstanden. In einem Graphen ist potenziell jeder Typ über Kanten von jedem anderen aus erreichbar: Wenn `Comment` ein Feld `author` hat und `Author` ein Feld `posts`, kommt man vom harmlosesten Kommentar zur kompletten Werkliste. Die Konsequenz ist unbequem: Autorisierung muss pro Feld gedacht werden, sinnvollerweise in den Resolvern – und ein verbreitetes, geprüftes Muster dafür existiert schlicht noch nicht.\n\nBleibt die Versionierung. Facebook bewirbt GraphQL als „versionless API\": Statt `/v2/` zu bauen, erweitert man das Schema, markiert alte Felder als veraltet – die Spezifikation sieht Deprecation ausdrücklich vor – und beobachtet, welche Clients sie noch abfragen. Weil jede Query ihre Felder explizit nennt, weiß der Server erstmals genau, was tatsächlich benutzt wird. Auf dem Papier überzeugt mich das; ob es die Disziplin über Jahre trägt, kann Anfang 2016 niemand belegen. Ich notiere es als Versprechen, nicht als Eigenschaft.\n\n## Unterm Strich\n\nWas an GraphQL wirklich neu ist, steckt nicht in der Syntax und nicht im Wort „Graph\". Neu ist die Verteilung der Verantwortung: Der Server definiert die Fachsprache und verantwortet die Wahrheit in den Resolvern, der Client formuliert seine Frage selbst – vollständig, typgeprüft, in einem Roundtrip beantwortbar. Overfetching und Underfetching, die beiden chronischen Reibungspunkte zwischen API-Teams und Client-Teams, verschwinden dabei fast als Side Effect.\n\nDie offenen Fragen sind real: Caching, N+1, Feld-Berechtigungen, das unbewiesene Versionierungs-Versprechen. Keine davon wirkt unlösbar, aber wer GraphQL heute produktiv einsetzt, beantwortet sie selbst und trägt das Risiko dafür. Für mich heißt das: weiter prototypisch arbeiten, das Schema als Gesprächsgrundlage mit Fachleuten ernst nehmen und die Server-Seite klein halten. Die Idee, dass ein Client dem System eine Frage stellt statt vorgefertigte Antworten abzuholen, halte ich unabhängig vom Werkzeug für richtig – und falls GraphQL sich nicht durchsetzt, wird die nächste Technik genau diese Idee wieder aufgreifen müssen.\n\n## Weiterführende Quellen\n\n- GraphQL-Spezifikation (Working Draft): https://spec.graphql.org/\n- GraphQL Learn – offizielle Einführung: https://graphql.org/learn/\n- graphql-js, die Referenzimplementierung: https://github.com/graphql/graphql-js\n- GraphiQL, der Schema-Explorer: https://github.com/graphql/graphiql\n- DataLoader für gebündelte Ladevorgänge: https://github.com/graphql/dataloader"},{"locale":"de","translation_key":"build-skripte-als-produktcode","slug":"build-skripte-als-produktcode","title":"Build-Skripte als Produktcode","summary":"Build-Skripte verdienen die Sorgfalt von Produktcode, weil sie bestimmen, wie reproduzierbar ein System tatsächlich ist.","tags":["Software","Tooling"],"published_at":"2015-10-12T10:00:00+00:00","updated_at":"2026-07-13T08:35:25.355094+00:00","url":"https://www.mikebild.dev/de/blog/build-skripte-als-produktcode/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/067a012c887284d5aeed2ce2eb6492227a4c7000d66979611c23b0238dab8876/build-skripte-als-produktcode-vorlesen.mp3","audio_duration_secs":678,"text":"# Build-Skripte als Produktcode\n\nEin Build-Skript ist keine Sammlung bequemer Abkürzungen für die Kommandozeile. Es ist die Beschreibung sämtlicher Eingaben, aus denen ein auslieferbares Artefakt entsteht: Quellen, Abhängigkeiten in konkreten Versionen, Toolchain, Umgebung. Was dort nicht steht, wird stillschweigend von der Maschine geliehen, auf der gerade gebaut wird.\n\nTrotzdem landen diese Skripte gern in einer Grauzone zwischen Code und Infrastruktur: selten reviewt, fast nie getestet, meist von einer einzigen Person gepflegt. Genau diese Grauzone ist der Grund, warum Releases wehtun.\n\n## Die These\n\nEin Feature ist erst fertig, wenn ein zweiter Mensch es aus dem leeren Verzeichnis heraus bauen, testen und ausliefern kann – ohne dass ich danebensitze. Der Weg dorthin ist kein Nebenprodukt. Er ist das Produkt. Wenn `git clone` plus ein Kommando nicht ausreicht, um dieselbe Artefaktdatei wie auf meinem Rechner zu erzeugen, dann existiert das System eigentlich nur bei mir lokal – und ist damit nicht ausgeliefert, sondern nur vorgeführt.\n\nIch behandle das Build-Skript deshalb mit derselben Sorgfalt wie Produktcode: Es hat einen klaren Vertrag, es wird versioniert, es wird gelesen, und es hat einen definierten Fehlerpfad. Das macht es nicht in jeder Hinsicht so laufzeitkritisch wie den ausgelieferten Dienst. Gemeint ist das Verantwortungsniveau: Andere müssen sich auf sein Ergebnis verlassen können.\n\n## Warum das eine Architekturfrage ist\n\n„Build“ klingt nach Handwerk, nach Nebensache. Tatsächlich entscheidet der Build über zwei Eigenschaften, die sonst nur teuer nachrüstbar sind: Reproduzierbarkeit und Zykluszeit.\n\nReproduzierbarkeit heißt, dass gleiche Eingaben gleiche Ausgaben erzeugen – unabhängig von Maschine, Uhrzeit und Laune des Netzwerks. Ein Build, der auf meinem Laptop grün ist und auf dem CI-Server rot, hat kein Testproblem. Er hat ein Zustandsproblem: Irgendwo fließt undeklarierter Zustand ein – eine global installierte CLI, eine Umgebungsvariable, eine Version, die „latest“ auflöst.\n\nZykluszeit heißt, wie lange es dauert, von einer Änderung zu einer belastbaren Aussage zu kommen. Diese Zeit multipliziert sich mit jeder Person und jedem Tag im Team. Ein Build, der zehn Minuten braucht und alle zwei Läufe scheitert, ist kein Komfortthema. Er ist ein Produktivitätsleck, das man in Stunden pro Woche messen kann.\n\nBeides sind Architektureigenschaften, keine Tool-Details. Deshalb kommt die Werkzeugfrage zuletzt. Davor steht die Klärung: Welche Eingaben gehen in den Build? Welche davon sind deklariert und welche implizit? Was ist das erwartete Artefakt? Erst danach entscheidet sich, ob das ein `npm`-Script, ein Gulpfile oder ein Makefile wird.\n\n## Ein kleines, unspektakuläres Beispiel\n\nDer häufigste Fehler ist nicht das falsche Tool, sondern der undeklarierte Zustand. Ein typisches Frontend-Setup aus dieser Zeit sieht oft so aus:\n\n```json\n{\n  \"scripts\": {\n    \"start\": \"webpack-dev-server --hot\",\n    \"build\": \"webpack -p\"\n  }\n}\n```\n\nDas liest sich harmlos. Der versteckte Vertrag steht aber gar nicht im Skript: Es setzt voraus, dass `webpack` global installiert ist, dass die richtige Node-Version läuft, dass `NODE_ENV` gesetzt ist. Nichts davon ist Teil des Repositories. Der neue Kollege bekommt am ersten Tag einen anderen Build als ich – und niemand hat den Vertrag gebrochen, weil es nie einen gab.\n\nDie Korrektur ist billig und wirkt sofort: Abhängigkeiten lokal binden, den Einstieg auf ein Kommando reduzieren, die eine Umgebungsentscheidung explizit machen.\n\n```json\n{\n  \"scripts\": {\n    \"start\": \"webpack-dev-server --hot --config webpack.dev.js\",\n    \"build\": \"NODE_ENV=production webpack --config webpack.prod.js\",\n    \"test\": \"mocha --recursive\",\n    \"verify\": \"npm run test && npm run build\"\n  }\n}\n```\n\nDer Gewinn ist nicht Eleganz. Der Gewinn ist, dass `npm run verify` jetzt eine überprüfbare Aussage ist: Wenn es grün ist, existiert ein Artefakt, und die Tests, die es absegnen, sind mitgelaufen. Ich habe keinen Build-Server ersetzt. Ich habe nur den Vertrag ins Repository geholt, wo er reviewt werden kann.\n\n## Determinismus ist kein Luxus\n\nDer teuerste Bruch der Reproduzierbarkeit sind Versionen, die sich zur Laufzeit entscheiden. `^1.2.0` in der `package.json` bedeutet: Der Build von heute und der von nächster Woche installieren möglicherweise unterschiedlichen Code, ohne dass sich eine Zeile im Repository geändert hat. Für ein Experiment ist das egal. Für ein Produkt ist es eine offene Flanke.\n\n```bash\n# freeze the exact dependency tree, then commit the lockfile\nnpm shrinkwrap\ngit add npm-shrinkwrap.json\n```\n\nAb hier ist der Abhängigkeitsbaum ein Artefakt wie jedes andere: versioniert, diffbar, im Review sichtbar. Wenn ein Update etwas kaputt macht, sehe ich es als Änderung an einer Datei – und nicht als Geist, der nur auf dem CI-Server erscheint. Das ist der Kern des Ganzen: Zustand, der vorher unsichtbar durch die Ritzen floss, wird zu etwas, das man lesen und ablehnen kann.\n\nWo mir das Sprachökosystem nicht reicht, ziehe ich die Grenze eine Ebene tiefer. Ein schlankes Image, das genau die Toolchain enthält, macht die Umgebung selbst zum versionierten Artefakt.\n\n```makefile\nIMAGE = myapp-build:1.0\n\nbuild:\n\tdocker build -t $(IMAGE) .\n\tdocker run --rm -v $(PWD):/src $(IMAGE) npm run verify\n```\n\nIch benutze Docker hier nicht als Deployment-Strategie und schon gar nicht als Selbstzweck – das Thema Cluster und Orchestrierung lasse ich bewusst weg. Ich benutze es als Reproduzierbarkeits-Werkzeug: Die Frage „welche Node-Version, welches `make`, welche System-Bibliothek?“ hat jetzt eine Antwort, die im Repository steht.\n\n## Ein Kommando pro Absicht\n\nEin Build-Skript ist eine Schnittstelle, bevor es eine Implementierung ist. Deshalb interessiert mich zuerst das Vokabular, nicht der Inhalt. Wenn jedes Projekt im Haus dieselben vier Verben versteht – `install`, `verify`, `build`, `clean` –, dann muss niemand mehr das README lesen, um mitzuarbeiten. Die Absicht steht im Namen, die Mechanik dahinter darf sich pro Projekt unterscheiden.\n\nDas klingt nach Kosmetik, ist aber eine Architekturentscheidung mit Reichweite. Sobald das Vokabular stabil ist, kann ich Werkzeuge dahinter austauschen, ohne dass sich für das Team etwas ändert. Der Wechsel von Grunt auf Gulp, von Gulp auf pures `npm run`, von einem Test-Runner auf einen anderen – all das bleibt hinter `npm run verify` verborgen. Die Grenze, die ich ziehe, trennt Absicht von Mechanik. Genau diese Trennung macht den Build wartbar, während sich die Toolchain unter ihm bewegt.\n\nDer andere Effekt ist, dass das Skript zur Dokumentation wird. Ein Neuzugang muss nicht wissen, dass der Build intern Babel, ein Bundling und einen Uglify-Schritt hat. Er muss `npm run build` kennen. Das verschobene Wissen ist der Punkt: Es steht jetzt im Code und nicht mehr in den Köpfen – und geht damit nicht verloren, wenn jemand das Team verlässt.\n\n## Der Build gehört in die Pipeline, nicht auf meinen Laptop\n\nEin Vertrag, den nur ich einhalte, ist keiner. Deshalb ist die konsequente Fortsetzung, denselben Einstieg auf einem neutralen Server auszuführen – bei jedem Push, ohne Ausnahme.\n\n```yaml\nlanguage: node_js\nnode_js:\n  - \"4\"\ninstall:\n  - npm install\nscript:\n  - npm run verify\n```\n\nDas ist bewusst langweilig. Die CI ruft exakt dasselbe Kommando auf, das ich lokal benutze – nicht eine eigene, parallele Wahrheit. Damit ist der Server kein zweites Build-System, das auseinanderdriften kann, sondern ein unbestechlicher Zeuge für denselben Vertrag. Sobald ein Kollege eine undeklarierte Annahme einbaut, wird die Pipeline rot, bevor der Code in den Hauptzweig kommt. Der teure Fehler – Umgebungsdrift, die erst im Release auffällt – wird zu einem billigen Fehler, der im Pull Request auffällt.\n\nGenau hier werden die Kennzahlen aus der nächsten Schicht überhaupt erst messbar: Zeit bis grüner Build, Anteil roter Läufe, Dauer bis zum reproduzierten Artefakt. Ohne die Pipeline sind das Anekdoten. Mit ihr sind es Zahlen, an denen man eine Verbesserung belegen kann.\n\n## Der Fehlerpfad, nicht der glückliche Pfad\n\nEine Idee zum Build ist erst belastbar, wenn der Fehlerpfad beschrieben ist. Genau hier trennt sich Demo von Betrieb.\n\nDie erste Frage ist Idempotenz. Was passiert beim zweiten Lauf? Ein Build, der ein `dist/`-Verzeichnis füllt, ohne es vorher zu leeren, produziert nach ein paar Wochen Geisterdateien: alte Bundles, die niemand mehr referenziert, aber ausgeliefert werden. Ein sauberer Build beginnt mit `clean`, nicht aus Ordnungsliebe, sondern damit der zehnte Lauf dasselbe ergibt wie der erste.\n\nDie zweite Frage ist das Scheitern selbst. Ein Skript, das mehrere Schritte mit `&&` verkettet, muss beim ersten Fehler abbrechen – und mit einem Exit-Code ungleich null enden. Sonst meldet die CI grün, obwohl der Test-Schritt still weggelaufen ist. Ich habe mehr kaputte Releases auf verschluckte Exit-Codes zurückgeführt als auf falsche Logik.\n\nDie dritte Frage ist Rückbaubarkeit. Kann ich das Artefakt von letzter Woche exakt neu erzeugen, wenn ein Fehler in Produktion auftaucht? Wenn der Build nicht deterministisch ist, ist die Antwort nein – und dann ist ein Rollback keine Entscheidung mehr, sondern ein Ratespiel.\n\n## Die betriebliche Konsequenz\n\nOb die Arbeit wirkt, sehe ich an einfachen Dingen: Wie lange braucht ein neuer Kollege bis zum ersten lokalen Build? Wie oft scheitert die CI an einer Annahme, die nur auf einem Rechner galt? Lässt sich das Artefakt eines alten Releases aus den damaligen Eingaben erneut erzeugen? Ein deklarierter Build verbessert genau diese Fälle. Wie groß der Effekt ist, muss das Team an seinen eigenen Laufzeiten und Fehlern messen.\n\n## Typische Fehler\n\nDer erste Fehler ist, das Werkzeug mit der Lösung zu verwechseln. Gulp ist keine Reproduzierbarkeit. Ein Makefile ist keine Determinismus-Garantie. Diese Werkzeuge können einen sauberen Vertrag ausdrücken, aber sie erzeugen ihn nicht von allein. Ich habe Gulpfiles gesehen, die genauso viel verstecktes Wissen voraussetzten wie das kaputte `npm`-Script davor.\n\nDer zweite Fehler ist, den Build als fertig zu betrachten, sobald er einmal grün war. Ein Build ist lebender Code. Er verrottet mit jeder undeklarierten Annahme, die sich einschleicht – die eine Umgebungsvariable, die „nur bei uns“ gesetzt ist, das Tool, das „eh jeder installiert hat“. Deshalb gehört das Build-Skript in denselben Review wie das Feature, nicht in einen separaten, unbeaufsichtigten Ordner.\n\nDer dritte Fehler ist, Geschwindigkeit gegen Vertrauen zu tauschen. Ein Build, der Tests überspringt, um schneller grün zu sein, verkauft künftige Zykluszeit für heutige Bequemlichkeit. Der Kredit wird immer zurückgefordert, meist im ungünstigsten Moment.\n\n## Worauf ich im Review prüfe\n\nDrei Fragen reichen mir meistens, um zu beurteilen, ob ein Build den Namen Produktcode verdient. Kann ein Mensch, der das Projekt nicht kennt, aus dem leeren Verzeichnis mit einem Kommando ein Artefakt erzeugen? Ist jede Eingabe, die das Ergebnis beeinflusst, im Repository sichtbar – Versionen, Umgebung, Toolchain? Bricht der Build bei einem Fehler sichtbar ab, statt still grün zu melden?\n\nWenn eine dieser Fragen mit Nein beantwortet wird, fehlt kein Tool. Es fehlt ein Teil der Architektur. Und dieser Teil ist meist billiger zu schließen, als das Team glaubt – solange man den Build als das behandelt, was er ist: Produktcode, der bestimmt, ob ein System reproduzierbar existiert oder nur vorgeführt wurde.\n\n## Schluss\n\nAm Ende steht eine praktische Prüfung: Kann ein neuer Rechner aus den versionierten Eingaben dasselbe Artefakt bauen, bricht ein Fehler sichtbar ab und lässt sich ein Release zurücknehmen? Wenn ja, erfüllt das Build-Skript seine Verantwortung. Ob darunter Gulp, Grunt oder ein Shell-Skript läuft, ist zweitrangig."},{"locale":"de","translation_key":"es6-memory-ui-state","slug":"es6-memory-ui-state","title":"ES6 Memory: UI-State begreifen","summary":"Ein Memory-Spiel in frischem ES2015, ohne Framework gebaut, macht sichtbar, welche States eine UI wirklich hat, wo sie liegen sollten und wer sie ändern darf.","tags":["Software","Frontend"],"published_at":"2015-09-24T10:00:00+00:00","updated_at":"2026-07-14T16:53:05.755017+00:00","url":"https://www.mikebild.dev/de/blog/es6-memory-ui-state/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/a79633d3968c180a5c7ce38e984d919228a2dc0ae278c6d423b5f111c66f3bb8/es6-memory-ui-state-vorlesen.mp3","audio_duration_secs":631,"text":"# ES6 Memory: UI-State begreifen\n\nEine einzelne Memory-Karte hat vier unterscheidbare States: verdeckt, aufgedeckt, gefunden – und gesperrt, solange zwei offene Karten gerade verglichen werden. Im DOM landen davon üblicherweise genau zwei, als CSS-Klassen wie `flipped` und `matched`. Der dritte State steckt implizit in einem laufenden `setTimeout`, der vierte ergibt sich aus der Abwesenheit der anderen. Zwei von vier States stehen also nirgends explizit – und genau aus diesen beiden stammen die Fehler, die man in kleinen UIs zuverlässig wiederfindet: die dritte Karte, die sich mitten im Vergleich aufdecken lässt, und das Paar, das nach einem hastigen Doppelklick dauerhaft offen liegen bleibt.\n\nDass mir dieses Zahlenverhältnis – vier States, zwei davon sichtbar notiert – erst richtig aufgefallen ist, als ich ein Spiel gebaut habe, sagt einiges darüber, wie beiläufig wir UI State sonst behandeln.\n\n## Ein Spiel als Prüfstand\n\nSeit Juni ist ECMAScript 2015 final. Klassen, Module, `const` und `let`, Arrow-Functions, Template-Literals – das steht jetzt im Standard, aber es fühlt sich noch ungewohnt an, wie eine fremde Sprache mit vertrauten Vokabeln. Ich wollte die neue Syntax nicht an Folien-Beispielen durchdeklinieren, sondern an etwas Echtem: klein genug für ein paar Abende, groß genug, dass echte Zustandsfragen auftauchen. Ein Memory-Spiel passt genau in diese Lücke. Sechzehn Karten, acht Paare, ein Zugzähler – mehr Fachlichkeit braucht es nicht.\n\nDas Ergebnis liegt als [es6-memory](https://github.com/MikeBild/es6-memory) auf GitHub. Bewusst ohne Framework: kein jQuery, kein React. Nicht aus Prinzipienreiterei, sondern weil ich wissen wollte, was von den Zustandsproblemen übrig bleibt, wenn kein Werkzeug sie versteckt oder abnimmt. Der Build ist trotzdem zeitgemäß: jspm löst die Abhängigkeiten auf, SystemJS lädt die ES2015-Module, Babel übersetzt die neue Syntax für Browser, die noch nicht so weit sind – und ein kleines `node build` bündelt alles zu einer `memory.min.js`, die sich mit einem einzigen `div` in jede bestehende Seite hängen lässt. Passend zur Woche, in der das Repository entstand: Anfang September ist Node 4.0 erschienen, die erste Version nach der Wiedervereinigung mit io.js, mit V8-Rückenwind für einen Teil der neuen Sprachfeatures. ES2015 ist gerade dabei, vom Papier in die Werkzeuge zu wandern, und genau in diesem Moment lohnt sich ein Projekt, das die Sprache pur benutzt.\n\n## Welche States es wirklich gibt\n\nDer erste Gewinn kam vor der ersten Zeile Code: States aufzählen. Für eine Karte sind es drei, nicht vier – das war die erste Korrektur an meinem eigenen Bild vom Spiel:\n\n- verdeckt: die Rückseite ist sichtbar, die Karte reagiert auf Klicks\n- aufgedeckt: das Motiv ist sichtbar, die Karte wartet auf den Vergleich\n- gefunden: das Motiv bleibt sichtbar, die Karte reagiert nie wieder\n\nUnd der vierte State aus dem Einstieg? „Gesperrt\" ist gar kein Kartenzustand. Es ist ein State des Spiels: Solange zwei aufgedeckte Karten verglichen werden – und beim Nicht-Treffer kurz sichtbar bleiben, damit man sie sich merken kann – darf keine weitere Karte umgedreht werden. Dazu kommen der Zugzähler und die abgeleitete Frage, ob das Spiel vorbei ist. Diese Trennung zwischen Karten- und Spielzustand fällt einem nicht ein, solange man in CSS-Klassen denkt. Sie fällt einem sofort ein, wenn man den State als Datenstruktur aufschreiben muss.\n\n```mermaid\nflowchart LR\n  H[hidden] -->|flipCard| R[revealed]\n  R -->|second card<br/>matches| M[matched]\n  R -->|no match<br/>after 800 ms| H\n  M --> E[game over<br/>when all matched]\n```\n\nIn ES2015 liest sich das Modell angenehm direkt. Eine Klasse für die Karte, eine Factory für das Spiel – und zum ersten Mal ohne das übliche Prototypen-Geflecht:\n\n```js\n// card.js\nexport class Card {\n  constructor(id, motif) {\n    this.id = id;\n    this.motif = motif;\n    this.state = 'hidden'; // 'hidden' | 'revealed' | 'matched'\n  }\n}\n\n// game.js\nimport { Card } from './card.js';\n\nexport function createGame(motifs) {\n  const pairs = motifs.concat(motifs);\n  const cards = shuffle(pairs).map((motif, id) => new Card(id, motif));\n  return { cards, locked: false, moves: 0 };\n}\n```\n\nDas ist der komplette State des Spiels: ein Array von Karten mit je einem `state`-Feld, ein `locked`-Flag, ein Zähler. Kein `data-`Attribut, keine Klassenliste, kein verstecktes Timeout, das nebenbei Wahrheit transportiert.\n\n## Wo der State liegt – und wo nicht\n\nDie naheliegende Alternative kenne ich aus genug jQuery-Codebasen der letzten Jahre, auch aus eigenen: Das DOM ist der Zustandsspeicher. Ob eine Karte aufgedeckt ist, entscheidet `classList.contains('flipped')`. Wie viele Karten offen sind, ermittelt ein Selektor. Das funktioniert erstaunlich lange – und kippt dann an immer derselben Stelle: Sobald Timing ins Spiel kommt, gibt es Momente, in denen die Darstellung der Wahrheit hinterherläuft. Die Animation ist noch nicht fertig, die Klasse noch nicht gesetzt, der Selektor zählt falsch. Der Fehler ist dann nicht deterministisch, sondern hängt davon ab, wie schnell jemand klickt.\n\nDer tiefere Punkt: Ein DOM-Knoten vermischt zwei Dinge, die getrennt gehören – was der Fall ist und wie es gerade aussieht. Solange beides identisch ist, merkt man den Unterschied nicht. Interessant wird es genau dann, wenn beides auseinanderfällt, und das tut es bei jedem `setTimeout`, bei jeder Transition, bei jedem Server-Roundtrip. Liegt der State dagegen im Modell, ist er zu jedem Zeitpunkt eindeutig, unabhängig davon, was der Browser gerade zeichnet. Und er ist ohne Browser testbar: `createGame`, zweimal `flipCard`, Assertion auf `state` – das läuft in Node in Millisekunden, ganz ohne DOM-Attrappe.\n\n## Eine Übergangsfunktion statt verstreuter Toggles\n\nDie zweite Entscheidung folgt aus der ersten: Wenn der State an einem Ort liegt, sollte er auch nur an einem Ort verändert werden. Nicht drei Event-Handler, die jeweils ein bisschen Klassenlogik machen, sondern eine einzige Funktion, die alle Spielregeln kennt:\n\n```js\n// game.js\nexport function flipCard(game, cardId, onSettled) {\n  const card = game.cards.find(c => c.id === cardId);\n  if (game.locked || !card || card.state !== 'hidden') return;\n\n  card.state = 'revealed';\n  const revealed = game.cards.filter(c => c.state === 'revealed');\n  if (revealed.length < 2) return;\n\n  game.locked = true;\n  game.moves += 1;\n  const [first, second] = revealed;\n  const isMatch = first.motif === second.motif;\n\n  setTimeout(() => {\n    first.state = second.state = isMatch ? 'matched' : 'hidden';\n    game.locked = false;\n    onSettled();\n  }, isMatch ? 300 : 800);\n}\n```\n\nDie erste Zeile nach dem `find` ist der eigentliche Ertrag des ganzen Umbaus. `game.locked || card.state !== 'hidden'` erledigt beide Fehler aus dem Einstieg in einem Ausdruck: Die dritte Karte während des Vergleichs prallt am `locked` ab, der Doppelklick auf dieselbe Karte am Kartenzustand. In der DOM-Variante waren das zwei getrennte Symptome an zwei Stellen im Code, jedes mit eigenem Workaround. Im Modell sind es zwei Facetten derselben Regel: Aufdecken ist nur erlaubt, wenn das Spiel offen und die Karte verdeckt ist.\n\nMir ist beim Schreiben dieser Funktion noch etwas aufgefallen: Sie ist die Stelle, an der man über das Spiel redet. Als eine Kollegin im Review fragte, ob ein aufgedecktes Paar sofort oder verzögert einrasten soll, konnte ich auf zwei Zeilen zeigen. Die Frage „Wer darf diesen State ändern?\" hat im Kleinen dieselbe Antwort verdient wie im Großen: möglichst genau eine Funktion, und die trägt einen Namen aus der Fachsprache.\n\n## Rendern in eine Richtung\n\nBleibt die dritte Frage: Wie kommt der State auf den Bildschirm? Die Antwort, die sich beim Bauen als tragfähig erwiesen hat, ist fast unangenehm simpel – nach jeder Änderung wird das komplette Brett neu gezeichnet:\n\n```js\n// render.js\nexport function render(game, root) {\n  root.innerHTML = `\n    <p class=\"moves\">Moves: ${game.moves}</p>\n    <ul class=\"board\">\n      ${game.cards.map(card => `\n        <li class=\"card ${card.state}\" data-id=\"${card.id}\">\n          ${card.state === 'hidden' ? '' : card.motif}\n        </li>`).join('')}\n    </ul>`;\n}\n```\n\nTemplate-Literals machen diese Art von Rendering zum ersten Mal angenehm. Vor ES2015 hieß das String-Konkatenation über zwanzig Zeilen oder eine Template-Bibliothek als Abhängigkeit; jetzt ist es ein mehrzeiliger Ausdruck mit Interpolation, direkt in der Sprache. Die Verdrahtung dazu ist ein einziger delegierter Listener:\n\n```js\n// main.js\nimport { createGame, flipCard } from './game.js';\nimport { render } from './render.js';\n\nconst root = document.querySelector('.memory');\nconst game = createGame(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']);\n\nconst update = () => render(game, root);\n\nroot.addEventListener('click', event => {\n  if (!event.target.classList.contains('card')) return;\n  flipCard(game, Number(event.target.dataset.id), update);\n  update();\n});\n\nupdate();\n```\n\nDamit fließt alles in eine Richtung: Ein Klick ist nur noch eine Meldung an die Übergangsfunktion, die Übergangsfunktion ändert das Modell, das Modell wird gerendert. Kein Handler fasst je das DOM an, kein Renderer ändert je den State.\n\n```mermaid\nflowchart LR\n  E[Klick-Event] --> T[flipCard<br/>Übergangsfunktion]\n  T --> S[(Spielzustand<br/>im Modell)]\n  S --> R[render]\n  R --> D[DOM]\n  D -. meldet nur Events,<br/>hält keinen Zustand .-> E\n```\n\nDer reflexhafte Einwand lautet: Alles neu rendern, ist das nicht verschwenderisch? Ich habe es gemessen, statt es zu glauben. Siebzehn Elemente per `innerHTML` zu ersetzen kostet in Chrome deutlich weniger als eine Millisekunde – bei einer Interaktion, die höchstens zweimal pro Sekunde stattfindet. Die Grenze existiert, aber sie liegt weit weg von sechzehn Karten: Bei Hunderten Knoten, Formularfokus oder Scroll-Positionen, die den Neuaufbau nicht überleben, trägt der Ansatz nicht mehr. Genau an dieser Grenze setzt React an, das mit Version 0.13 gerade viel Aufmerksamkeit bekommt: Es behält das Prinzip „State rein, Darstellung raus\" bei und macht nur den Schreibweg ins DOM schlau, indem es Unterschiede berechnet, statt alles zu ersetzen. Wer das Memory-Spiel von Hand gebaut hat, liest die React-Dokumentation anders – als Optimierung eines Modells, das man schon verstanden hat, statt als Magie.\n\n## Was ein Framework abnimmt – und was nicht\n\nDas ist für mich die eigentliche Erkenntnis aus dem Projekt, und sie hat mit ES2015 nur am Rande zu tun. Ein Framework nimmt einem eine Menge ab:\n\n- effizientes Aktualisieren des DOM, wenn das Neuzeichnen zu teuer wird\n- Zerlegung der Oberfläche in komponierbare, wiederverwendbare Teile\n- Verdrahtung von Events, Templates und Daten ohne Eigenbau-Konventionen\n\nWas kein Framework abnimmt, sind die drei Fragen, die dieses kleine Spiel erzwungen hat: Welche States gibt es überhaupt – und welche davon gehören zur Karte, welche zum Spiel? Wo liegen sie – im Modell oder verschmiert über Klassenlisten und Timeouts? Und wer darf sie ändern – eine benannte Übergangsfunktion oder jeder Handler ein bisschen? Wer diese Fragen nicht beantwortet, bekommt mit Framework dieselben Fehler wie ohne, nur besser verpackt. Duplizierter State zwischen Komponente und DOM sieht in JSX ordentlicher aus als in jQuery, bleibt aber duplizierter State. Am Rande: Aus der React-Gemeinde kommt seit dem Sommer mit Redux ein Bibliotheks-Experiment, das genau diese Übergangsfunktion zum zentralen Baustein erklärt – ein Hinweis darauf, dass die Idee nicht am Spielzeugbeispiel endet.\n\n## Was ich daraus mitnehme\n\nDas Spiel selbst ist ein Nachmittagsvergnügen, ein Prototyp mit acht Motiven und einem Zugzähler. Der Wert steckt in dem, was es erzwungen hat. Erstens: States aufzählen, bevor Code entsteht – schon die Inventur hat mein Bild korrigiert, weil „gesperrt\" auf der falschen Ebene vermutet war. Zweitens: Der State gehört ins Modell; das DOM ist eine Projection davon und taugt nicht als Speicher, sobald Timing ins Spiel kommt. Drittens: eine Übergangsfunktion, die alle Regeln kennt, statt Toggles, die über Handler verteilt sind – dort finden Reviews statt, dort steht die Fachsprache, dort verschwinden zwei Bugs in einer Guard-Zeile. Und die neue Sprache? ES2015 hat das Ganze nicht möglich, aber angenehm gemacht: Klassen für das Modell, Module für die Schnitte, Template-Literals für das Rendering. Babel und jspm sorgen dafür, dass es heute schon in echten Browsern läuft. Das nächste größere Frontend werde ich vermutlich nicht ohne Framework bauen – aber ich werde genauer wissen, welchen Teil der Arbeit das Framework wirklich übernimmt und welcher Teil vorher im eigenen Kopf passieren muss.\n\n## Weiterführende Quellen\n\n- Repository es6-memory: https://github.com/MikeBild/es6-memory\n- MDN: Classes (JavaScript-Referenz): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\n- MDN: Template literals: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\n- Babel, der JavaScript-Compiler für ES2015: https://babeljs.io/\n\nDie Links helfen beim Nachschlagen der Sprachfeatures – die Entscheidung, wo State liegt und wer ihn ändert, nehmen sie einem nicht ab."},{"locale":"de","translation_key":"web-messaging-mit-rxjs","slug":"web-messaging-mit-rxjs","title":"Web Messaging mit RxJS","summary":"Wer eingehende Messages hinter einem Observable versteckt, macht den Transport zwischen Browser und Server austauschbar – und merkt dabei, wie weit gewöhnliches HTTP trägt.","tags":["Software","Reactive"],"published_at":"2015-07-24T10:00:00+00:00","updated_at":"2026-07-14T16:51:17.40526+00:00","url":"https://www.mikebild.dev/de/blog/web-messaging-mit-rxjs/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/7f8b231172edbeddaaf2082dbde95bc7884051c166e7000c8fa34cb1b62379a4/web-messaging-mit-rxjs-vorlesen.mp3","audio_duration_secs":797,"text":"# Web Messaging mit RxJS\n\n```js\nvar incoming = Rx.Observable.create(function (observer) {\n  var source = new EventSource('/subscribe/green');\n\n  source.onmessage = function (event) {\n    observer.onNext(JSON.parse(event.data));\n  };\n  source.onerror = function (error) {\n    observer.onError(error);\n  };\n\n  return function () {\n    source.close();\n  };\n});\n\nincoming\n  .map(function (message) { return message.green; })\n  .distinctUntilChanged()\n  .subscribe(function (count) {\n    render(count);\n  });\n```\n\nDas Interessante an diesem Stück Client-Code ist der Teil, der fehlt. Die Konsumseite – die drei Zeilen ab `incoming.map(...)` – weiß nichts über `EventSource`, nichts über HTTP, nichts über Verbindungen. Sie abonniert einen Strom eingehender Messages und verarbeitet ihn mit denselben Operatoren, mit denen sie auch ein Array oder eine Folge von Mausklicks verarbeiten würde. Wie die Messages technisch ins Haus kommen, ist im `create`-Callback eingesperrt. Genau diese Trennung ist der Kern dessen, was ich in den letzten Wochen ausprobiert habe: Messages zwischen Browser und Server nicht als Verbindungsproblem denken, sondern als Strom – mit RxJS als gemeinsamer Sprache auf beiden Seiten.\n\n## Warum nicht gleich WebSockets?\n\nSobald in einem Projekt das Wort „Echtzeit\" fällt, liegt der Griff zu WebSockets nahe – meist in Form von socket.io, das die Verbindungsdetails freundlich wegkapselt. Das ist oft die richtige Wahl, aber sie hat einen Preis, der gern erst später auffällt. WebSockets sind ein eigenes Protokoll mit eigenem Handshake. Ältere Proxies verschlucken das Upgrade, manche Firmen-Firewalls kappen langlebige Verbindungen kommentarlos, Load Balancer brauchen Sonderbehandlung, und die gewohnte HTTP-Werkzeugkiste – Caching, Auth-Header, Access-Logs, curl zum Debuggen – greift nur noch teilweise. socket.io beantwortet einen Teil davon mit Fallbacks, holt sich dafür aber eine ganze Bibliotheksschicht auf Client und Server ins Projekt.\n\nDabei ist die fachliche Anforderung häufig bescheidener, als das Wort „Echtzeit\" klingt: Der Server soll den Browser über Events informieren, überwiegend in eine Richtung, und eine Latenz von Sekundenbruchteilen genügt völlig. Für dieses Profil hat HTTP seit Jahren Antworten, die ohne Protokollwechsel auskommen: Long-Polling, chunked Responses, Server-Sent Events. Alles davon läuft durch jede Infrastruktur, die HTTP kann – also durch praktisch alles.\n\nDie eigentliche Architekturfrage ist deshalb nicht „WebSockets oder nicht?\", sondern: Wie schreibe ich den Anwendungscode so, dass diese Entscheidung später revidierbar bleibt?\n\n## Ein Experiment: alles ist ein Strom\n\nVor knapp zwei Wochen habe ich dazu ein kleines Repository veröffentlicht, [web-messaging](https://github.com/MikeBild/web-messaging). Die README-Zeile beschreibt den Umfang ehrlich: „Message routing and Complex-Event-Streams via HTTP (Transfer-Encoding: chunked)\". Es ist ein Experiment, kein Produkt – eine einzelne `server.js`, eine `index.html`, kein Express, nicht einmal ein Routing-Framework, sondern ein handgeschriebener Mini-Router aus regulären Ausdrücken. Gerade diese Schlichtheit macht sichtbar, worum es geht.\n\nDer Server modelliert alles, was Messages erzeugt, als Observable. Eine simulierte Quelle tickt alle zwei Sekunden und würfelt eine Gruppe; ein `Subject` dient als Eingang für Messages von außen. Beides fließt in einen gemeinsamen Strom:\n\n```js\nvar rx = require('rx');\n\nvar publishChannel = new rx.Subject();\n\nvar simulated = rx.Observable.interval(2000)\n  .map(function (tick) {\n    return { sequence: tick, group: randomGroup() };\n  });\n\nvar events = simulated\n  .merge(publishChannel)\n  .publish()\n  .refCount();\n\nvar totals = events\n  .scan({}, function (acc, message) {\n    acc[message.group] = (acc[message.group] || 0) + 1;\n    return acc;\n  })\n  .publish()\n  .refCount();\n```\n\nZwei Dinge daran haben sich als tragend erwiesen. Erstens `merge`: Dass eine simulierte Zeitquelle und ein von HTTP-POSTs gefüttertes Subject sich zu einem Strom vereinigen lassen, ohne dass irgendwer davon erfährt, ist keine Spielerei – es heißt, dass „woher kommt die Message?\" eine lokale Entscheidung bleibt. Zweitens `publish().refCount()`: Ohne diese beiden Aufrufe wäre der Strom kalt, und jeder Abonnent bekäme seine eigene Simulation mit eigenem Zähler. So aber teilen sich alle Verbindungen dieselbe heiße Quelle, und `scan` führt genau einen Zählerstand über alle Gruppen – State als Strom, nicht als Variable, an der viele Stellen herumschreiben.\n\nDer `publishChannel` wird von der POST-Route gefüttert, und das ist die vielleicht hübscheste Zeile des Experiments: Ein gewöhnlicher HTTP-Request wird zu einem Event im Strom.\n\n```js\nroute.post(/\\/publish\\/([a-z]*)/, function (req, res) {\n  publishChannel.onNext({ group: req.params[0] });\n  res.end();\n});\n```\n\n## Die Antwort als Observer\n\nSpannender als die Erzeugerseite ist die Auslieferung. Wie kommt ein Server-Strom in einen Browser, ohne WebSockets? Die Antwort im Experiment: Die HTTP-Response bleibt einfach offen. Mit `Transfer-Encoding: chunked` darf ein Server beliebig lange häppchenweise schreiben – und damit wird `res` zu einem Observer, der Messages aus dem Strom entgegennimmt:\n\n```js\nroute.get(/\\/subscribe\\/([a-z]*)/, function (req, res) {\n  res.setHeader('Content-Type', 'application/json');\n  res.setHeader('Transfer-Encoding', 'chunked');\n\n  var subscription = totals\n    .map(function (data) {\n      var group = req.params[0];\n      if (!group) return data;\n      var result = {};\n      result[group] = data[group];\n      return result;\n    })\n    .subscribe(function (data) {\n      res.write(JSON.stringify(data) + '\\n\\n');\n    });\n\n  req.on('close', function () {\n    subscription.dispose();\n  });\n});\n```\n\nJede Verbindung ist eine Subscription. Das klingt banal, erledigt aber nebenbei das Problem, das in handgestrickten Publish-Subscribe-Servern regelmäßig zu Speicherlecks führt: die Lebensdauer. Wenn der Browser die Verbindung schließt – Tab zu, Netz weg, Seite neu geladen – feuert `req.on('close')`, die Subscription wird mit `dispose()` beendet, und weil `refCount` mitzählt, stellt die Quelle die Arbeit ein, sobald der letzte Abonnent weg ist. Aufräumen ist keine Sonderlogik mehr, sondern die natürliche Kehrseite des Abonnierens. In einem Projekt einige Jahre zuvor haben wir für genau dieses Aufräumen eine eigene Registry mit Timeout-Heuristiken gepflegt – hier sind es zwei Zeilen.\n\nEin Side Effect dieses Aufbaus, den ich nicht mehr hergeben möchte: Der Strom lässt sich mit Bordmitteln beobachten. Ein `curl http://localhost:8765/subscribe/green` im Terminal, und die Messages tropfen zeilenweise herein – kein Spezialwerkzeug, kein Browser-Plugin, keine Protokoll-Inspektion. Das Repository hat dafür sogar eine eigene Route `/log`, die den ungefilterten Rohstrom vor der Aggregation ausliefert. Beim Entwickeln hatte ich ständig zwei Terminals offen: eines auf `/log` für die Rohereignisse, eines auf `/subscribe/...` für das, was ein Client tatsächlich sieht. Bei einem WebSocket-Aufbau braucht dieselbe Sichtbarkeit bereits eigenen Werkzeugbau oder zumindest die Frame-View der Browser-Entwicklerwerkzeuge.\n\nDer Fluss im Überblick:\n\n```mermaid\nflowchart LR\n  POST[HTTP POST<br/>/publish/:group] --> SUBJ[Subject<br/>publishChannel]\n  SIM[Interval<br/>Simulation] --> MERGE[merge]\n  SUBJ --> MERGE\n  MERGE --> SCAN[scan<br/>Zählerstand je Gruppe]\n  SCAN --> SUBA[Subscription<br/>Verbindung A]\n  SCAN --> SUBB[Subscription<br/>Verbindung B]\n  SUBA --> RESA[chunked Response A<br/>res.write]\n  SUBB --> RESB[chunked Response B<br/>res.write]\n```\n\nAuf der Client-Seite bin ich im Repository übrigens weniger konsequent: Die `index.html` ist eine kleine AngularJS-1.4-Anwendung, die die Chunks noch von Hand aus einem `XMLHttpRequest` klaubt – bei `readyState === 3` den `responseText` an den doppelten Zeilenumbrüchen zerschneiden und die letzte vollständige Zeile parsen. Das funktioniert, ist aber genau die Sorte Transportdetail, die im Anwendungscode nichts verloren hat. Der `Rx.Observable.create`-Wrapper vom Anfang ist die Konsequenz daraus: einmal geschrieben, versteckt er dieses Gefummel, und alles dahinter spricht nur noch Observable. Wer statt roher Chunks Server-Sent Events verwendet – dasselbe Muster, nur als `text/event-stream` formalisiert – bekommt mit `EventSource` sogar Parsing und Wiederverbinden vom Browser geschenkt.\n\n## Reconnect und Backpressure als Streams-Probleme\n\nZwei Themen entscheiden darüber, ob so ein Aufbau ein Wochenend-Experiment bleibt oder Betrieb aushält. Beide lassen sich als Stream-Probleme formulieren, und das ist der zweite Grund, warum sich RxJS hier lohnt.\n\nErstens der Wiederaufbau der Verbindung. Netzverbindungen reißen – die Frage ist nicht ob, sondern wie oft. Mit `EventSource` verbindet der Browser von sich aus neu und schickt per `Last-Event-ID` sogar mit, wo er stehengeblieben ist, sofern der Server IDs vergibt. Beim rohen XHR-Ansatz baut man das selbst – und statt einer Schleife mit Zustandsvariablen wird daraus ein Operator auf dem Strom:\n\n```js\nvar resilient = incoming.retryWhen(function (errors) {\n  return errors.delay(3000);\n});\n```\n\nDer Fehlerfall ist damit kein Sonderpfad mit eigenem Code, sondern Teil derselben Deklaration wie der Erfolgsfall. Wer klügeres Verhalten will – wachsende Wartezeiten, Aufgeben nach n Versuchen – komponiert es aus denselben Bausteinen, statt eine State Machine zu pflegen.\n\nZweitens Backpressure. Der Server im Experiment schreibt so schnell in die Response, wie der Strom liefert. Was, wenn der Abnehmer nicht hinterherkommt – ein Mobilgerät im Funkloch, ein überlasteter Tab? `res.write` gibt in Node ehrlich `false` zurück, wenn der Kernel-Puffer voll ist; das Experiment ignoriert das großzügig, und genau da hört der Spaß auf. Die saubere Antwort ist wieder eine Stream-Antwort, denn RxJS bringt die Werkzeuge mit, die Rate vor dem Draht zu formen:\n\n- `sample` schickt in festen Abständen nur den jüngsten Stand – für Aggregationen wie den Zählerstand hier ideal, denn veraltete Zwischenstände interessieren niemanden.\n- `bufferWithTime` sammelt Messages und verschickt sie paketweise – wenn nichts verloren gehen darf, aber die Frequenz sinken soll.\n- `pausableBuffered` hält den Strom an, bis der Abnehmer wieder Luft hat – echtes Anhalten statt Verwerfen, etwa gekoppelt an das `drain`-Event der Response.\n\nWichtig ist weniger, welcher der drei Wege gewählt wird, als dass die Frage überhaupt eine Antwort im Modell hat. In der Callback-Welt ist „Erzeuger schneller als Verbraucher\" ein Querschnittsproblem, das sich durch den ganzen Code zieht. Im Strom ist es eine Zeile an der richtigen Stelle.\n\n## Der Transport wird austauschbar\n\nDamit zum eigentlichen Architekturgewinn. Wenn die Konsumseite nur ein Observable sieht, ist der Transport eine Implementierung dieses Interfaces – und Implementierungen kann man tauschen. Dieselbe Anwendung, morgen über WebSockets:\n\n```js\nvar incoming = Rx.Observable.create(function (observer) {\n  var socket = new WebSocket('ws://localhost:8765/subscribe/green');\n\n  socket.onmessage = function (event) {\n    observer.onNext(JSON.parse(event.data));\n  };\n  socket.onerror = function (error) {\n    observer.onError(error);\n  };\n\n  return function () {\n    socket.close();\n  };\n});\n```\n\nDie Zeilen ab `incoming.map(...)` bleiben unverändert, ebenso `retryWhen` und alles, was darauf aufbaut. Long-Polling passt in denselben Rahmen: ein Request, der beim Eintreffen einer Message antwortet, per `flatMap` und Wiederholung zu einem endlosen Strom verkettet. Der Wechsel des Transports ist dann ein lokaler Eingriff in einer Datei – keine Operation am offenen Herzen der Anwendung.\n\n```mermaid\nflowchart LR\n  LP[Long-Polling] --> OBS[Observable<br/>gemeinsame Schnittstelle]\n  SSE[Server-Sent Events] --> OBS\n  CH[chunked HTTP] --> OBS\n  WS[WebSocket] --> OBS\n  OBS --> APP[Anwendungscode<br/>map / filter / scan / retryWhen]\n```\n\nMir ist an diesem Punkt aufgefallen, dass die Diskussion „WebSockets vs. HTTP\" in Teams oft deshalb so zäh ist, weil sie als Einbahnstraße geführt wird – als müsste die Entscheidung für immer gelten. Sobald der Transport hinter einem Observable liegt, verliert sie diese Schwere. Man darf mit dem anspruchslosesten Transport anfangen, der die Anforderung erfüllt, und später umziehen, wenn Messungen es verlangen.\n\n## Wann schlichtes HTTP reicht\n\nBleibt die ehrliche Abwägung. Nach diesem Experiment würde ich gewöhnliches HTTP – chunked oder als Server-Sent Events – überall dort wählen, wo drei Bedingungen zusammenkommen:\n\n- Die Messages fließen ganz überwiegend vom Server zum Browser; die Gegenrichtung sind gelegentliche Kommandos, für die ein POST völlig genügt.\n- Latenzen von einigen hundert Millisekunden stören niemanden – Dashboards, Benachrichtigungen, Fortschrittsanzeigen, Feeds.\n- Die vorhandene HTTP-Infrastruktur – Proxies, Auth, Logging, Debugging mit curl – soll ohne Sonderwege weiterarbeiten.\n\nWebSockets verdienen ihren Platz, wo diese Bedingungen kippen: echter bidirektionaler Verkehr mit vielen kleinen Messages in beide Richtungen, kollaboratives Editieren, Spiele, alles mit spürbarer Latenzanforderung. Dann trägt ein POST je Message nicht mehr, und der Protokollwechsel zahlt sich aus. Ein Wermutstropfen der HTTP-Seite gehört ebenfalls auf den Tisch: Browser deckeln die Zahl gleichzeitiger Verbindungen pro Host, sechs sind üblich – wer viele Streams parallel öffnet, muss sie serverseitig zu einem multiplexen. HTTP/2 ist seit Mai als RFC verabschiedet und wird genau dieses Problem entschärfen, aber im Browser-Alltag ist es noch keine Größe, mit der man heute planen kann.\n\nUnd natürlich bleibt das Experiment ein Experiment: keine Authentifizierung, keine Persistenz, keine Messages-IDs für lückenloses Aufholen nach Reconnect, und ein Nachrichtenraum, der genau so lange existiert wie der eine Node-Prozess. Wer mehr braucht, hängt an das Subject eine echte Quelle – eine Queue, einen Log – und genau dafür ist die Stelle ja schon vorbereitet.\n\n## Unterm Strich\n\nDer Wert dieses kleinen Servers liegt nicht im Transport-Trick mit chunked Responses – den gab es lange vor RxJS. Er liegt darin, dass beide Seiten dieselbe Abstraktion sprechen. Auf dem Server sind Simulation, POST-Eingang und Aggregation Observables, die sich mit `merge` und `scan` komponieren lassen; im Browser ist der eingehende Nachrichtenstrom ein Observable, auf dem `map`, `distinctUntilChanged` und `retryWhen` arbeiten. Verbindungsabbruch, Wiederholung, Ratenbegrenzung, Aufräumen – all das, was in Callback-Code als Sonderfall über die Datei verstreut liegt, hat im Strom einen benannten Platz.\n\nES2015 ist seit ein paar Wochen verabschiedet, und vieles am Code oben wird mit Arrow Functions hübscher werden. Am Kern ändert das nichts: Die Entscheidung, eingehende Messages als Strom zu modellieren und den Transport dahinter zu verstecken, ist unabhängig von Syntax und übrigens auch von RxJS selbst – sie würde mit jeder Observable-Implementierung funktionieren. Was ich aus dem Experiment mitnehme, ist deshalb weniger eine Bibliotheksempfehlung als eine Reihenfolge: erst das Nachrichtenmodell als Strom festlegen, dann den anspruchslosesten Transport wählen, der die Anforderung erfüllt – und die Freiheit behalten, ihn zu wechseln, wenn die Wirklichkeit es verlangt.\n\n## Weiterführende Quellen\n\n- [MikeBild/web-messaging](https://github.com/MikeBild/web-messaging) – das besprochene Experiment: Message-Routing und Event-Streams über HTTP mit chunked Transfer-Encoding\n- [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) – die Reactive Extensions für JavaScript mit Dokumentation aller Operatoren\n- [Server-sent events (MDN)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) – `EventSource` und das `text/event-stream`-Format\n- [ReactiveX: Einführung](https://reactivex.io/intro.html) – das Observable-Modell und die Operator-Idee sprachübergreifend erklärt"},{"locale":"de","translation_key":"funktionale-stile-im-alltag","slug":"funktionale-stile-im-alltag","title":"Funktionale Stile im Alltag","summary":"Warum funktionaler Stil im Team-Alltag 2015 nicht Haskell bedeutet, sondern die Disziplin, Pure Functions von I/O zu trennen – und wie ES2015 das endlich bequem macht.","tags":["Software","Architektur"],"published_at":"2015-07-12T10:00:00+00:00","updated_at":"2026-07-14T16:49:16.61261+00:00","url":"https://www.mikebild.dev/de/blog/funktionale-stile-im-alltag/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/5770702d2e3369f179b1c77d169ed73f026dbd79f9f515bb7b55ce5f091b5359/funktionale-stile-im-alltag-vorlesen.mp3","audio_duration_secs":701,"text":"# Funktionale Stile im Alltag\n\nWenn Geschäftslogik und Side Effects ungetrennt im selben Funktionsrumpf stehen, hat das eine sehr konkrete Konsequenz: Jeder Test braucht eine Datenbank. Wer prüfen will, ob eine Rechnung als überfällig gilt, muss vorher Testdaten einspielen, einen Mailer durch eine Attrappe ersetzen und hinterher alles wieder aufräumen. Die Testsuite läuft Minuten statt Sekunden, also läuft sie seltener, also traut sich niemand mehr an genau die Stellen, die eine Änderung am dringendsten nötig hätten. Das ist kein Werkzeugproblem und kein Framework-Problem – es ist ein Stilproblem.\n\nFunktionale Programmierung gilt vielen Kollegen immer noch als akademische Veranstaltung: Haskell, Monaden, Typtheorie. Was ich im Projektalltag darunter verstehe, ist deutlich bescheidener und gleichzeitig wirksamer: Pure Functions als Standardbaustein, Datenfluss statt Zustandsmutation, `map`/`filter`/`reduce` statt Schleifenrümpfen mit Side Effects. Keine neue Sprache, keine neue Runtime – eine Disziplin in der Sprache, die ohnehin schon im Einsatz ist.\n\n## Reine Funktionen als Standardbaustein\n\nEine Pure Function ist schnell erklärt: gleiche Eingabe, gleiche Ausgabe, keine beobachtbare Side Effect. Sie liest nicht die Uhr, schreibt nicht in die Datenbank, verändert keine Variablen außerhalb ihres Rumpfs. Das klingt banal, ist im gewachsenen Code aber die Ausnahme. Typischer ist eine Funktion, die Daten lädt, filtert, umrechnet, speichert und nebenbei noch eine E-Mail verschickt – fünf Verantwortungen in dreißig Zeilen.\n\nAnfang des Jahres habe ich mir Crista Lopes' Sammlung [exercises-in-programming-style](https://github.com/MikeBild/exercises-in-programming-style) geforkt: dieselbe kleine Aufgabe – eine Worthäufigkeitsanalyse – in Dutzenden Programmierstilen, jeder Stil ein eigener Ordner mit Programm und Beschreibung. Beim Durcharbeiten ist mir etwas aufgefallen, das mir vorher so klar nicht war: Stil ist eine Entscheidung, kein Sprachmerkmal. Dieselbe Aufgabe lässt sich in Python monolithisch, objektorientiert oder als Pipeline Pure Functions schreiben. Die Sprache verhindert nichts davon und erzwingt nichts davon. Das gilt für JavaScript und C# genauso.\n\nDie Disziplin besteht darin, die Pure Function zum Normalfall zu machen. Nicht: „Wo könnte ich mal etwas Funktionales einstreuen?\", sondern umgekehrt: Jede Funktion ist rein, bis ein Grund dagegen spricht. Und die Gründe dagegen – I/O, Zeit, Zufall, DOM, Datenbank – sammeln sich dann an wenigen, benannten Stellen statt überall.\n\n## Was ES2015 daran ändert\n\nSeit Juni ist ECMAScript 2015 verabschiedet – die [Spezifikation](https://262.ecma-international.org/6.0/) ist final, und Babel 5 übersetzt den neuen Stand heute schon auf ES5 herunter. Node 0.12 und io.js beherrschen Teile davon nativ, für den Rest bleibt der Transpiler im Build. Für den funktionalen Stil ist das mehr als Kosmetik, denn drei Neuerungen senken genau die Schreibkosten, an denen dieser Stil bisher gescheitert ist:\n\n- Arrow Functions machen kleine Funktionen so billig, dass man sie tatsächlich schreibt – `x => x.amount` statt eines vierzeiligen `function`-Blocks mit `return`.\n- `const` dokumentiert im Code, dass eine Bindung nicht neu zugewiesen wird – die Leserichtung dreht sich: Mutation wird zur markierten Ausnahme.\n- Destrukturierung zerlegt Datenstrukturen ohne Hilfsvariablen, was Funktionen über schlichten Objekten erst angenehm macht.\n\nDer Transpiler ist dabei eine ehrliche Zusatzkosten-Position: Der Build wird um einen Schritt länger, Sourcemaps müssen stimmen, und wer im Browser debuggt, schaut gelegentlich auf generierten ES5-Code statt auf das, was er geschrieben hat. In unserem Fall war das den Tausch wert – aber es gehört auf den Tisch, bevor das Team zustimmt, nicht danach.\n\nVorher war funktionaler Stil in JavaScript möglich, aber syntaktisch teuer. Ein `function (invoice) { return !invoice.paid; }` an jeder Filterstelle ermüdet, und was ermüdet, unterbleibt. Mit Pfeilfunktionen kippt die Abwägung: Die kompakte Form ist jetzt auch die disziplinierte Form. Ich habe in einem laufenden Projekt erlebt, wie allein die Umstellung auf Babel die Zahl kleiner Hilfsfunktionen im Team vervielfacht hat – nicht weil jemand es angeordnet hätte, sondern weil es plötzlich der bequemste Weg war.\n\n## Vom Schleifenrumpf zur Datenleitung\n\nKonkret wird der Unterschied an einem Stück Code, wie es in jedem Backoffice-System steht: Aus einer Liste von Rechnungen sollen die überfälligen ermittelt, Mahnungen erzeugt und die offene Summe berechnet werden. Die verbreitete Form sieht so aus:\n\n```js\nfunction processInvoices(invoices, db, mailer) {\n  let total = 0;\n  for (let i = 0; i < invoices.length; i++) {\n    const invoice = invoices[i];\n    if (!invoice.paid && invoice.dueDate < Date.now()) {\n      total += invoice.amount;\n      db.markAsOverdue(invoice.id);\n      mailer.sendReminder(invoice.customerEmail, invoice.amount);\n    }\n  }\n  return total;\n}\n```\n\nDer Code funktioniert, und genau das macht ihn langlebig – niemand fasst eine Funktion an, die seit zwei Jahren unauffällig ihren Dienst tut. Trotzdem vermischt der Schleifenrumpf vier Dinge: die fachliche Regel (wann ist eine Rechnung überfällig?), die Aggregation (Summe), den Datenbankzugriff und den Mailversand. Dazu liest die Funktion mit `Date.now()` heimlich die Uhr – derselbe Aufruf liefert um Mitternacht ein anderes Ergebnis als um 23:59. Testbar ist das nur mit echter Datenbank, echtem Mailer-Ersatz und eingefrorener Zeit.\n\nDieselbe Logik als Datenfluss, mit ES2015:\n\n```js\nconst isOverdue = (today) => (invoice) =>\n  !invoice.paid && invoice.dueDate < today;\n\nconst toReminder = (invoice) => ({\n  invoiceId: invoice.id,\n  email: invoice.customerEmail,\n  amount: invoice.amount\n});\n\nconst totalAmount = (invoices) =>\n  invoices.reduce((sum, { amount }) => sum + amount, 0);\n\nconst overdueReminders = (today, invoices) => {\n  const overdue = invoices.filter(isOverdue(today));\n  return {\n    reminders: overdue.map(toReminder),\n    total: totalAmount(overdue)\n  };\n};\n```\n\nVier Pure Functions. Die Zeit kommt als Parameter herein statt aus der Uhr, die fachliche Regel steht isoliert in `isOverdue`, und `overdueReminders` beschreibt nur noch, was aus den Daten werden soll – nicht, wie eine Laufvariable hochzuzählen ist. Der Test dafür ist ein Array-Literal und eine Gleichheitsprüfung, keine Datenbank weit und breit. Und wer den Code in einem halben Jahr liest, sieht die Regel auf einen Blick, statt sie aus einem Schleifenrumpf herauszupräparieren.\n\n## Der unreine Rand\n\nDie ehrliche Grenze gehört dazu: `db.markAsOverdue` und `mailer.sendReminder` sind nicht verschwunden. I/O, DOM und Datenbank bleiben unrein – eine Anwendung, die nichts liest und nichts schreibt, ist nutzlos. Der Punkt ist nicht, Side Effects zu verbieten, sondern sie an den Rand zu schieben, wo sie sichtbar und dünn sind.\n\n```mermaid\nflowchart LR\n  DB[(Datenbank)] -->|Rechnungen laden| Edge[Unreiner Rand<br/>I/O, Uhr, Mailer]\n  Edge -->|Daten hinein| Core[Reiner Kern<br/>isOverdue, toReminder,<br/>totalAmount]\n  Core -->|Ergebnis heraus| Edge\n  Edge -->|Mahnungen senden| Mail[Mailserver]\n```\n\nAm Rand sieht der Code dann so aus – Promises sind mit ES2015 Teil der Sprache:\n\n```js\nconst today = Date.now();\n\ndb.loadInvoices()\n  .then((invoices) => overdueReminders(today, invoices))\n  .then(({ reminders, total }) => {\n    reminders.forEach((reminder) => mailer.sendReminder(reminder));\n    log.info(`sent ${reminders.length} reminders, open amount: ${total}`);\n  });\n```\n\nDieser Rand ist bewusst langweilig: laden, Pure Function aufrufen, Ergebnis wegschreiben. Er wird kaum je einzeln getestet, weil er kaum Logik enthält – die Logik steht im Kern, und der Kern kennt weder Datenbank noch Mailer. In einem Projekt haben wir genau nach diesem Schnitt die Integrationstests von einer halben Stunde auf eine Handvoll Randfälle reduziert; alles Fachliche lief als reiner Unit-Test in Sekunden.\n\n## Der Blick aus der .NET-Welt\n\nWem das als JavaScript-Mode erscheint, dem hilft ein Blick in die .NET-Welt, aus der ich ebenfalls komme. Dort heißt derselbe Gedanke seit Jahren LINQ und regt niemanden mehr auf:\n\n```csharp\nvar overdue = invoices\n    .Where(invoice => !invoice.Paid && invoice.DueDate < today)\n    .ToList();\n\nvar reminders = overdue.Select(invoice => new Reminder\n{\n    InvoiceId = invoice.Id,\n    Email = invoice.CustomerEmail,\n    Amount = invoice.Amount\n});\n\nvar total = overdue.Sum(invoice => invoice.Amount);\n```\n\n`Where`, `Select`, `Sum` – das sind `filter`, `map` und ein spezialisiertes `reduce`. In C#-Teams schreibt das seit Jahren jeder, ohne es funktionale Programmierung zu nennen; es ist schlicht die normale Art, mit Auflistungen zu arbeiten. Wer eine `foreach`-Schleife mit Laufsumme in ein Review bringt, bekommt dort die Rückfrage, warum es kein LINQ ist. Diese Beobachtung nimmt dem Thema die Ideologie: Es geht nicht um ein Lager, sondern um eine Ausdrucksform, die sich in einer sehr pragmatischen Umgebung längst durchgesetzt hat – JavaScript zieht mit ES2015 gerade nach.\n\n## Underscore, Lodash, Ramda\n\nFür die Lücken der Standardbibliothek gibt es Werkzeugkästen. Underscore war jahrelang gesetzt, Lodash hat es in Version 3 praktisch abgelöst – gleiche Idee, mehr Funktionen, und verkettete Aufrufe werden seit Lodash 3 lazy ausgewertet, sodass lange Ketten nicht bei jedem Schritt ein Zwischen-Array erzeugen müssen. [Ramda](https://ramdajs.com/) geht seit gut einem Jahr einen Schritt weiter: Alle Funktionen sind automatisch gecurryt, und die Daten kommen als letztes Argument, sodass sich Verarbeitungsschritte zu neuen Funktionen zusammenstecken lassen:\n\n```js\nconst openAmountOf = R.pipe(\n  R.filter(isOverdue(today)),\n  R.map(R.prop('amount')),\n  R.sum\n);\n\nconst total = openAmountOf(invoices);\n```\n\n`openAmountOf` ist eine benannte, wiederverwendbare Pipeline – kein Aufruf, sondern eine Definition. Das ist elegant, und genau hier beginnt die Reibung.\n\n## Wo es im Team reibt\n\nDer funktionale Stil hat im Team-Alltag echte Kosten, und wer sie verschweigt, verliert die Skeptiker zu Recht. Drei Punkte begegnen mir regelmäßig:\n\n- Debugging von Ketten ist mühsamer als Debugging einer Schleife. In einem `for`-Rumpf setzt man einen Haltepunkt und sieht alle lokalen Variablen; in einer `pipe`-Kette aus anonymen Funktionen zeigt der Stacktrace kryptische Namen, und für einen Blick auf Zwischenwerte muss man die Kette aufbrechen oder eine `tap`-Funktion einschieben.\n- Point-free-Schreibweise kippt schnell in Selbstzweck. `R.pipe(R.filter(...), R.map(R.prop('amount')), R.sum)` liest ein geübtes Auge flüssig – drei weitere Kompositionsebenen später liest es niemand mehr, auch der Autor nicht. Im Review hat sich bei uns eine einfache Frage bewährt: Kann der Kollege am Nachbartisch die Zeile ohne Erklärung laut vorlesen und sagen, was sie tut?\n- Das Performance-Argument kommt zuverlässig und ist meistens ein Mythos. Ja, `filter` und `map` erzeugen Zwischen-Arrays, und eine handgeschriebene Schleife ist auf einer Million Elementen schneller. Nur verarbeiten die wenigsten Codestellen eine Million Elemente – sie verarbeiten dreißig Rechnungen, und der eigentliche Engpass ist der Datenbankaufruf daneben. Erst messen, dann optimieren; die zwei heißen Pfade, die es wirklich betrifft, dürfen gern eine kommentierte Schleife bleiben.\n\nDazu kommt eine soziale Komponente: Ein Team, in dem zwei Leute Ramda lieben und fünf es nicht lesen können, hat mit dem Stil nichts gewonnen. Der gemeinsame Nenner – `map`, `filter`, `reduce`, Pure Functions, dünner Rand – trägt weiter als die vollendete Komposition. Die Bibliothek ist verhandelbar, die Disziplin nicht.\n\n## Ausblick: Ströme\n\nWer die Trennung von Kern und Rand einmal verinnerlicht hat, findet die nächste Stufe fast von selbst. [RxJS](https://github.com/Reactive-Extensions/RxJS) behandelt Events – Klicks, WebSocket-Messages, Timer – als Auflistungen über die Zeit, mit demselben Vokabular: `map`, `filter`, `reduce` beziehungsweise `scan` auf Strömen statt auf Arrays. Die Pure Functions aus dem Kern lassen sich unverändert einsetzen; nur der unreine Rand spricht dann eben Observables statt Promises. Für Oberflächen mit vielen gleichzeitigen Event Sources ist das ein spürbarer Gewinn – aber das ist ein eigener Artikel.\n\n## Unterm Strich\n\nFunktionale Programmierung im Alltag von 2015 heißt für mich nicht, die Sprache zu wechseln oder dem Team Kategorientheorie zuzumuten. Es heißt, drei Gewohnheiten zu pflegen: Funktionen sind rein, bis ein Grund dagegen spricht. Daten fließen durch `map`, `filter` und `reduce`, statt in Schleifenrümpfen mutiert zu werden. Und alles Unreine – Uhr, Datenbank, DOM, Netzwerk – steht gesammelt an einem dünnen, langweiligen Rand. ES2015 macht diese Gewohnheiten zum ersten Mal wirklich bequem, LINQ zeigt seit Jahren, dass sie mainstream-tauglich sind, und die Testsuite dankt es sofort: Der Teil des Systems, in dem die Fehler wehtun, braucht plötzlich keine Datenbank mehr. Dafür muss niemand Haskell lernen – nur konsequent bleiben, wenn die nächste Schleife mit Laufsumme im Review auftaucht.\n\n## Weiterführende Quellen\n\n- [exercises-in-programming-style](https://github.com/MikeBild/exercises-in-programming-style) – mein Fork von Crista Lopes' Stil-Sammlung: eine Aufgabe, Dutzende Stile\n- [ECMAScript 2015 Language Specification](https://262.ecma-international.org/6.0/) – der frisch verabschiedete Standard\n- [Array.prototype.reduce (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) – die unterschätzteste der drei Kernfunktionen\n- [Ramda](https://ramdajs.com/) – funktionale Bibliothek mit Currying und Daten-zuletzt-Konvention\n- [RxJS](https://github.com/Reactive-Extensions/RxJS) – Reactive Extensions für JavaScript, derselbe Stil auf Event Streams"},{"locale":"de","translation_key":"container-sind-keine-architektur","slug":"container-sind-keine-architektur","title":"Container sind keine Architektur","summary":"Docker macht Systemgrenzen sichtbar und transportabel – gezogen werden müssen sie weiterhin von Hand, und ein Monolith bleibt auch im Container ein Monolith.","tags":["Software","Platform"],"published_at":"2015-06-12T10:00:00+00:00","updated_at":"2026-07-14T16:47:25.291379+00:00","url":"https://www.mikebild.dev/de/blog/container-sind-keine-architektur/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0df37d999e79d0e8c0b0b274ecd32c888f754777b5859e21039f8424c85e582c/container-sind-keine-architektur-vorlesen.mp3","audio_duration_secs":659,"text":"# Container sind keine Architektur\n\nEin schlecht geschnittener Monolith wird nicht besser, wenn man ihn in einen Container steckt. Er bleibt derselbe Monolith – dieselben verfilzten Abhängigkeiten, dieselbe geteilte Datenbank, dasselbe Deployment, bei dem alles auf einmal rausgeht. Neu ist nur das Dockerfile obendrauf. Trotzdem ist gerade überall dieselbe Gleichsetzung zu hören, auf Konferenzen wie in Projektbesprechungen: Wir führen Docker ein, also machen wir jetzt Microservices. Das eine hat mit dem anderen zunächst nichts zu tun. Docker verpackt Software. Es entwirft sie nicht.\n\nDie Verwechslung ist kein Zufall, und sie ist auch nicht dumm. Sie hat einen Grund, und den lohnt es sich anzuschauen – genauso wie die Frage, was Container tatsächlich leisten. Denn das ist eine ganze Menge. Nur eben etwas anderes als Architektur.\n\n## Warum die Gleichsetzung so gut funktioniert\n\nBeide Themen sind zur selben Zeit groß geworden. Docker steht bei Version 1.6, die 1.7 ist in Arbeit, in anderthalb Wochen beginnt die DockerCon in San Francisco, und nach dem monatelangen öffentlichen Streit zwischen Docker und CoreOS über das „richtige\" Containerformat formiert sich gerade eine Initiative für einen offenen, herstellerneutralen Standard. Bei der Orchestrierung herrscht Wildwuchs: Mesos auf der einen Seite, Dockers eigenes Swarm auf der anderen, und Google arbeitet an Kubernetes, das noch vor der Version 1.0 steht. Parallel dazu ist der Text von James Lewis und Martin Fowler über Microservices seit gut einem Jahr der Referenzpunkt jeder Architekturdiskussion.\n\nBeide Wellen tragen dasselbe Vokabular vor sich her: kleine, unabhängige Einheiten, isoliert, einzeln deploybar. Wer die Texte aber nebeneinanderlegt, sieht die Lücke sofort. Lewis und Fowler reden über fachliche Schnitte, über Teams, über Datenhoheit. Die Docker-Dokumentation redet über Images, Layer und Prozesse. Dass ein Container eine „unabhängige Einheit\" ist, gilt für den Prozess und sein Dateisystem – nicht für die Fachlichkeit, die darin steckt. Ein Container weiß nicht, ob in ihm ein sauber geschnittener Dienst läuft oder ein Gebirge aus zwölf Jahren gewachsenem Code. Ihm ist es auch egal.\n\nDie Gleichsetzung funktioniert, weil sie bequem ist. Ein Dockerfile schreibt sich an einem Nachmittag. Einen Modulschnitt, über den zwei Teams nicht mehr streiten, bekommt man nicht an einem Nachmittag – der braucht Wochen an Gesprächen über Daten, Zuständigkeiten und Schnittstellen, und am Ende steht kein vorzeigbares Werkzeug, sondern nur ein System, das sich leichter ändern lässt. Wenn beides unter demselben Buzzword segelt, gewinnt der Nachmittag. Vorzeigen lässt sich schließlich nur einer von beiden.\n\n## Was ein Container wirklich leistet\n\nAnfang des Jahres habe ich eine kleine .NET-API in einen Container gepackt: Nancy als Web-Framework, selbst gehostet, LiteDB als Dateidatenbank, das Ganze auf Mono, damit es auf Linux läuft. Kein Kundenprojekt, ein Experiment – ich wollte wissen, ob der Weg von Windows-geprägtem .NET-Code zu einem Linux-Container ohne große Verrenkungen begehbar ist. Er ist es. Das Dockerfile war ernüchternd unspektakulär:\n\n```dockerfile\nFROM mono:3.12\n\nCOPY . /app\nWORKDIR /app\n\nRUN nuget restore shop-api.sln && \\\n    xbuild /p:Configuration=Release shop-api.sln\n\nEXPOSE 8080\nCMD [\"mono\", \"src/ShopApi/bin/Release/ShopApi.exe\"]\n```\n\nGenau diese Unspektakularität ist der Punkt. Alles, was der Dienst zum Laufen braucht, steht in dreizehn Zeilen: die Runtime samt Version, der Build-Weg, der Port, das eine Kommando, mit dem der Prozess startet. Vorher stand dieses Wissen verteilt in einer Wiki-Seite („Entwicklungsumgebung aufsetzen, 14 Schritte\"), in den Köpfen von zwei Kollegen und in der Konfiguration eines Build-Servers, den niemand mehr anfassen wollte. Jetzt steht es im Repository, wird mit dem Code versioniert und im Review gelesen.\n\nDas ist der ehrliche Nutzen von Containern, und er ist erheblich:\n\n- Dieselbe Umgebung auf dem Notebook, im CI und auf dem Server – „läuft bei mir\" verliert seinen Schrecken.\n- Ein expliziter Entry Point: genau ein Kommando startet den Prozess, nichts hängt an einem angemeldeten Benutzer oder einer Terminal-Session.\n- Abhängigkeiten stehen im Image statt im Wiki – wer wissen will, was der Dienst braucht, liest das Dockerfile, nicht die Erinnerung des dienstältesten Kollegen.\n- Ein Artefakt, das sich unverändert von Umgebung zu Umgebung schieben lässt, statt auf jeder Maschine neu zusammengebaut zu werden.\n\nMan beachte, was in dieser Liste nicht vorkommt: fachliche Grenzen, Datenhoheit, unabhängige Releases. Das Dockerfile oben verrät nicht, ob `ShopApi.exe` ein fokussierter Dienst ist oder ein Koloss. Es baut beides gleich klaglos.\n\n## Der Monolith zieht nur um\n\nWie wenig die Verpackung am Inhalt ändert, zeigt sich, sobald man einen echten Monolithen containerisiert. Nehmen wir einen Shop, wie er zigfach existiert: Bestellungen, Rechnungen und Katalog in einer Solution, eine gemeinsame Datenbank, ein Deployment. Mit Docker Compose ist die lokale Umgebung dafür schnell beschrieben:\n\n```yaml\nshop-api:\n  build: .\n  ports:\n    - \"8080:8080\"\n  links:\n    - shop-db\nshop-db:\n  image: postgres:9.4\n  environment:\n    POSTGRES_DB: shop\n```\n\nDiese Datei ist nützlich – jeder im Team startet den Stand mit einem Kommando. Aber sie ist vor allem eines: ehrlich. Sie dokumentiert schwarz auf weiß, dass es genau eine deploybare Einheit gibt und eine Datenbank, in die alle Teile hineinschreiben. Wer im Rechnungs-Code eine Zeile ändert, baut und deployt weiterhin den kompletten Shop. Wer das Bestell-Schema migriert, hält weiterhin den Atem an, weil auch der Katalog auf denselben Tabellen sitzt. Der Release-Takt, die Kopplung, die Angst vor der Migration – alles unverändert.\n\n```mermaid\nflowchart LR\n  subgraph before[\"Vorher\"]\n    M1[\"Monolith<br/>Orders + Billing + Catalog\"] --> D1[(\"eine Datenbank\")]\n  end\n  subgraph after[\"Nachher – mit Docker\"]\n    M2[\"Container<br/>Monolith<br/>Orders + Billing + Catalog\"] --> D2[(\"eine Datenbank\")]\n  end\n  before -. \"docker build\" .-> after\n```\n\nDas Diagramm ist absichtlich langweilig. Links und rechts steht dasselbe System. Der Container hat die Struktur sichtbar und transportabel gemacht – erzeugt hat er keine neue. Und Sichtbarkeit ist nicht wenig! Aber sie wird gern mit Veränderung verwechselt, so wie ein Umzugskarton mit Aufräumen verwechselt wird. Erst wenn man ihn packt, sieht man, was sich angesammelt hat. Weggeworfen ist damit noch nichts.\n\n## Grenzen sichtbar machen heißt nicht Grenzen ziehen\n\nDie eigentliche Arbeit heißt Modulschnitt, und sie findet vor jedem Dockerfile statt. Drei Fragen entscheiden, ob ein Schnitt trägt. Wem gehören welche Daten – wer darf die Bestelltabellen ändern, und wer bekommt sie nur über eine Schnittstelle zu sehen? Wie sieht der Vertrag zwischen den Teilen aus – welche Aufrufe sind erlaubt, und wie stabil bleiben sie, wenn sich innen etwas ändert? Und: Was lässt sich unabhängig ausliefern, ohne dass zwei Teams ihre Kalender abgleichen müssen?\n\nNichts davon braucht Docker. Ein sauberer Schnitt lässt sich mitten im Monolithen ziehen, in derselben Solution, im selben Prozess. Zwischen dem Bestell-Modul und dem Rechnungs-Modul steht dann ein bewusst schmaler Vertrag:\n\n```csharp\n// the only allowed path from Orders into Billing –\n// no shared tables, no reaching into internals\npublic interface IBillingService\n{\n    Invoice CreateInvoice(OrderId orderId, Money total);\n}\n```\n\nDazu gehört die unbequemere Hälfte: `Orders` schreibt ausschließlich in seine eigenen Tabellen, `Billing` in seine. Kein Join quer über die Modulgrenze, auch nicht „nur für den Report\". Wenn diese Disziplin eine Weile gehalten hat, ist der Rest Mechanik. Dann – und erst dann – wird aus dem Modul bei Bedarf ein eigener Container, und die Compose-Datei sieht plötzlich nach dem aus, was Lewis und Fowler beschreiben:\n\n```yaml\norders:\n  build: ./orders\n  ports:\n    - \"8080:8080\"\n  links:\n    - orders-db\n    - billing\norders-db:\n  image: postgres:9.4\nbilling:\n  build: ./billing\n  links:\n    - billing-db\nbilling-db:\n  image: postgres:9.4\n```\n\nDer springende Punkt: Diese Datei ist das Ergebnis der Entwurfsarbeit, nicht ihr Ersatz. Wer sie hinschreibt, ohne den Schnitt vorher im Code und in den Daten vollzogen zu haben, bekommt zwei Container, die sich gegenseitig in die Datenbank greifen – denselben Monolithen, jetzt mit Netzwerklatenz dazwischen. Das ist die teuerste Variante eines Monolithen, die ich kenne: verteilt, aber nicht entkoppelt. Jedes Orchestrierungswerkzeug, ob Mesos, Swarm oder demnächst Kubernetes, multipliziert diesen Zustand nur. Es verteilt, was man ihm gibt. Gibt man ihm einen verfilzten Schnitt, verteilt es Verfilzung.\n\n```mermaid\nflowchart LR\n  subgraph om[\"Modul Orders\"]\n    O[\"orders\"] --> ODB[(\"orders-db\")]\n  end\n  subgraph bm[\"Modul Billing\"]\n    B[\"billing\"] --> BDB[(\"billing-db\")]\n  end\n  O -- \"Vertrag:<br/>CreateInvoice(orderId, total)\" --> B\n```\n\nDieses Bild ist der Unterschied. Nicht die Kästen sind interessant, sondern die Pfeile, die fehlen: kein Pfeil von `orders` auf `billing-db`, kein Rückkanal an der Schnittstelle vorbei. Solche fehlenden Pfeile zeichnet einem kein Werkzeug. Die muss man sich erarbeiten, gegen den Widerstand des Tagesgeschäfts, das immer einen guten Grund für die eine kleine Abkürzung hat.\n\n## Der Container als Prüfstein\n\nWenn Container beim Entwurf überhaupt helfen, dann als Prüfstein. Bei dem Mono-Experiment ist mir aufgefallen, dass die unangenehmste Frage nicht „Wie baue ich das Image?\" war, sondern „Was gehört hinein?\". Der Dienst zog Konfiguration aus drei Quellen, erwartete ein Netzlaufwerk und schrieb Logs an einen fest verdrahteten Pfad. Nichts davon war vorher ein Problem gewesen, weil die Maschine, auf der er lief, all das stillschweigend bereitstellte. Der Container stellt nichts stillschweigend bereit. Er zwingt dazu, jede Annahme entweder ins Image zu schreiben oder als Umgebungsvariable an die Oberfläche zu holen. Jede dieser Annahmen war im Grunde eine unsichtbare Kopplung – an eine Maschine, an eine Abteilung, an ein Stück Betriebsfolklore, das nirgends aufgeschrieben war.\n\nDas ist dieselbe Sorte Zwang, die ein guter Modulschnitt ausübt, nur eine Ebene tiefer. Wer für einen Dienst nicht sagen kann, was in sein Image gehört und was von außen kommt, kennt die Grenzen dieses Dienstes nicht – und sollte über Microservices noch gar nicht reden. Insofern taugt die Containerisierung des Monolithen als erster Schritt durchaus: nicht weil sie Architektur wäre, sondern weil sie die Inventur erzwingt, ohne die kein späterer Schnitt gelingt. Man lernt dabei mehr über sein System, als einem lieb ist.\n\nNur sollte man den Schritt dann auch als das behandeln, was er ist. Ein containerisierter Monolith ist ein völlig legitimer Zustand – reproduzierbar gebaut, überall gleich startbar, mit dokumentierten Abhängigkeiten. Für viele Systeme ist das auf Jahre hinaus genug. Verkauft man ihn dagegen als „Microservices-Migration, Phase eins\", hat man ein Versprechen in die Welt gesetzt, das die Verpackung nicht einlösen kann.\n\n## Was ich daraus mitnehme\n\nFür mich hat sich eine Reihenfolge herausgeschält, die sich in Diskussionen bewährt: erst den Monolithen containerisieren und die betrieblichen Vorteile mitnehmen – gleiche Umgebung überall, expliziter Prozess-Einstieg, Abhängigkeiten im Image. Parallel dazu die Grenzen im Code ziehen, wo sie nichts kosten: Module, eigene Tabellen, schmale Verträge wie das `IBillingService`-Beispiel oben. Und erst wenn eine Grenze über mehrere Releases stabil geblieben ist und ein konkreter Grund existiert – anderer Release-Takt, andere Last, anderes Team – wird aus dem Modul ein eigener Dienst mit eigenem Container.\n\nDocker macht auf diesem Weg zwei Dinge hervorragend: Es transportiert die Einheiten, die man geschnitten hat, und es deckt schonungslos auf, wo man noch gar nicht geschnitten hat. Beides ist wertvoll. Keines davon ist Entwurf. Die Standardisierung, die sich gerade um das Containerformat abzeichnet, wird die Verpackung noch selbstverständlicher machen – umso wichtiger wird es, sie nicht mit dem Inhalt zu verwechseln. Ein Dockerfile beantwortet die Frage, wie ein Prozess startet. Wer die Frage beantworten will, wo ein System endet und das nächste beginnt, sitzt weiterhin vor einem Whiteboard, nicht vor einer YAML-Datei.\n\n## Weiterführende Quellen\n\n- [MikeBild/dotnet-docker auf GitHub](https://github.com/MikeBild/dotnet-docker) – das erwähnte Experiment: Nancy, Self-Hosting und LiteDB auf Mono im Container\n- [Microservices – James Lewis und Martin Fowler](https://martinfowler.com/articles/microservices.html) – der Referenztext zu fachlichem Schnitt, Datenhoheit und unabhängiger Auslieferung\n- [Dockerfile-Referenz](https://docs.docker.com/reference/dockerfile/) – die offizielle Beschreibung aller Build-Anweisungen\n- [Docker Compose Dokumentation](https://docs.docker.com/compose/) – Grundlagen zur Beschreibung mehrerer Dienste in einer Datei"},{"locale":"de","translation_key":"programming-styles-architekturvergleich","slug":"programming-styles-architekturvergleich","title":"Programming Styles als Architekturvergleich","summary":"Dieselbe kleine Aufgabe in Dutzenden Programmierstilen gelöst ist der kompakteste Architekturvergleich, den ich kenne – weil jeder Stil eine bewusst gewählte Constraint-Menge ist.","tags":["Software","Architektur"],"published_at":"2015-05-24T10:00:00+00:00","updated_at":"2026-07-14T16:44:07.688862+00:00","url":"https://www.mikebild.dev/de/blog/programming-styles-architekturvergleich/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/3e0c4b9e253f4ddd81cda72221d56929596347f36027544f1df3570028a2557c/programming-styles-architekturvergleich-vorlesen.mp3","audio_duration_secs":673,"text":"# Programming Styles als Architekturvergleich\n\nEin Programmierstil ist keine Geschmacksfrage. Zumindest nicht in der Bedeutung, die Cristina Videira Lopes dem Wort in ihrem Buch „Exercises in Programming Style\" (2014) gibt: Ein Stil ist dort eine Menge von Regeln, die festlegen, welche Mittel erlaubt und welche verboten sind. Keine globalen Variablen. Nur Funktionen, die ihre Eingabe unverändert lassen. Kein direkter Aufruf zwischen Komponenten. Wer in einem Stil schreibt, unterwirft sich einer Constraint-Menge – und genau diese Constraints erzeugen die Eigenschaften des Programms, nicht die persönliche Vorliebe für Einrückung oder Namensgebung.\n\nDas Buch treibt diese Idee mit einem Kunstgriff auf die Spitze, den Lopes von Raymond Queneau geliehen hat. Queneau erzählt in „Exercices de style\" (1947) dieselbe belanglose Alltagsszene auf 99 verschiedene Arten. Lopes macht dasselbe mit einem Programm: Eine einzige, bewusst banale Aufgabe wird in der ersten Auflage in 33 Stilen gelöst. Die Aufgabe ist Wortfrequenzzählung – Term Frequency:\n\n- eine Textdatei lesen (im Repo: „Pride and Prejudice\")\n- den Text normalisieren, also Kleinschreibung und Satzzeichen entfernen\n- Stopwörter wie „the\" und „of\" herausfiltern\n- die Häufigkeit jedes Wortes zählen\n- die 25 häufigsten Wörter ausgeben\n\nJede Lösung ist ein kurzes Python-Skript, alle liefern dieselbe Ausgabe, alle laufen mit demselben Aufruf. Ich habe das begleitende Repository Anfang Mai geforkt und mich Stil für Stil durchgearbeitet – nicht gelesen, sondern getippt, verändert, kaputt gemacht und repariert. Dabei ist mir etwas aufgefallen, das über das Buch hinausgeht: Das ist kein Kuriositätenkabinett. Es ist der kompakteste Architekturvergleich, der mir je begegnet ist. Weil die Aufgabe trivial und konstant ist, bleibt als einzige Variable die Struktur. Man sieht Architekturentscheidungen in Reinform, auf jeweils einer Bildschirmseite.\n\nEin paar der Stile will ich herausgreifen und gegeneinanderstellen.\n\n## Good Old Times: die Abwesenheit von Struktur\n\nDer erste Stil im Buch simuliert die Bedingungen früher Rechner: kaum Speicher, keine benannten Abstraktionen, keine Funktionen – das Programm ist eine einzige Folge von Anweisungen, die sich Zwischenstände auf einer simulierten „Festplatte\" merken muss. Das Ergebnis ist mühsam zu lesen und noch mühsamer zu ändern. Der verwandte monolithische Stil lockert die Speichergrenze, verbietet aber weiterhin jede Abstraktion: eine lange Prozedur, geschachtelte Schleifen, Flags.\n\nInteressant ist daran nicht die Nostalgie, sondern die Ehrlichkeit. Der Monolith ist der Nullpunkt: So sieht Code aus, wenn keine Constraint ihn formt. Und er ist keineswegs ausgestorben – ich habe 2014 in einem Projekt ein gewachsenes Import-Skript übernommen, das exakt diesem Stil folgte, nur eben mit 1800 statt 80 Zeilen. Es funktionierte. Es war nur unmöglich zu testen, weil es keine Stelle gab, an der man es hätte anfassen können, ohne alles anzufassen.\n\n## Pipeline: Datenfluss statt Ablauf\n\nDer Pipeline-Stil erlaubt ausschließlich Funktionen, die ihre Eingabe entgegennehmen und ein Ergebnis zurückgeben. Kein geteilter Zustand, keine Side Effects zwischen den Schritten. Mein Nachbau sieht so aus (Python 2.7, wie im Buch):\n\n```python\nimport re\nimport operator\n\ndef read_text(path):\n    with open(path) as f:\n        return f.read()\n\ndef normalize(text):\n    return re.sub('[^a-z]', ' ', text.lower())\n\ndef tokenize(text):\n    return text.split()\n\ndef remove_stop_words(words):\n    with open('stop_words.txt') as f:\n        stop_words = set(f.read().split(','))\n    return [w for w in words if w not in stop_words and len(w) > 1]\n\ndef count_frequencies(words):\n    counts = {}\n    for w in words:\n        counts[w] = counts.get(w, 0) + 1\n    return counts\n\ndef top_25(counts):\n    ordered = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)\n    return ordered[:25]\n\nfor word, count in top_25(count_frequencies(remove_stop_words(\n        tokenize(normalize(read_text('pride-and-prejudice.txt')))))):\n    print word, '-', count\n```\n\nDie letzte Zeile liest sich wie eine mathematische Formel: Das Programm ist die Komposition seiner Schritte. Jede Funktion ist für sich testbar, jede lässt sich austauschen, solange die Datenform stimmt. Das ist die Architektur jeder Batch- und ETL-Strecke und jeder Unix-Pipe – nur dass dort die Funktionen Prozesse heißen und die Rückgabewerte Dateien oder Streams sind. Die Constraint „kein geteilter Zustand\" kauft Testbarkeit und Parallelisierbarkeit und bezahlt mit dem Verbot, sich zwischendurch etwas zu merken.\n\n## Things: Zustand hinter Türen\n\nDer Stil „Things\" ist die objektorientierte Antwort: Das Problem wird in Dinge zerlegt – ein `DataStorageManager`, ein `StopWordManager`, ein `WordFrequencyManager` – und jedes Ding kapselt seinen Zustand. Von außen sind nur Methoden sichtbar; niemand greift in die Daten eines anderen. Die Constraint lautet: Zustand existiert, aber nur hinter einer Tür, und die Tür hat einen Namen.\n\nAuf 60 Zeilen wirkt das fast übertrieben feierlich. Aber die Analogie auf Systemebene ist offensichtlich: Es ist die Grundidee modularer Systeme und sauberer Serviceschnitte. Die Frage „wem gehört dieser Zustand, und wer darf ihn ändern?\" ist in jedem Architektur-Review, das ich erlebt habe, die ergiebigste Frage überhaupt – und dieser Stil zwingt einen, sie für jedes Datum zu beantworten.\n\n## Hollywood: Don't call us, we'll call you\n\nAb hier dreht sich die Kontrollrichtung um. Im Hollywood-Stil ruft nicht mehr das Programm seine Bausteine – ein Rahmen ruft zurück, was sich vorher registriert hat:\n\n```python\nclass WordFrequencyFramework:\n    def __init__(self):\n        self._load_handlers = []\n        self._work_handlers = []\n        self._end_handlers = []\n\n    def register_for_load(self, handler):\n        self._load_handlers.append(handler)\n\n    def register_for_work(self, handler):\n        self._work_handlers.append(handler)\n\n    def register_for_end(self, handler):\n        self._end_handlers.append(handler)\n\n    def run(self, path):\n        for handler in self._load_handlers:\n            handler(path)\n        for handler in self._work_handlers:\n            handler()\n        for handler in self._end_handlers:\n            handler()\n```\n\nDie fachlichen Teile – Einlesen, Filtern, Zählen – melden sich beim Framework an und warten. Der Ablauf gehört dem Rahmen, nicht mehr der Anwendung. Das ist Inversion of Control in ihrer nacktesten Form, und es ist das Bauprinzip praktisch jedes Web-Frameworks und jeder Plugin-Architektur: Man schreibt keine Hauptschleife mehr, man füllt Lücken, die ein anderer vorgesehen hat.\n\nWer viel JavaScript schreibt, kennt dieses Gefühl aus jedem Node-Programm – dort ist der Callback nicht Stilübung, sondern Alltag, mit allen Folgen für die Lesbarkeit des Kontrollflusses. Ich habe dazu schon einmal aufgeschrieben, [wie sich Kontrollfluss vor async/await bändigen lässt](https://www.mikebild.dev/de/blog/control-flow-vor-async-await/). Die Stilübung macht sichtbar, was man dabei eintauscht: Flexibilität für den Rahmen, Nachvollziehbarkeit für den Leser. Wer wissen will, wann `count_frequencies` läuft, muss den Rahmen verstehen, nicht die Fachlogik.\n\n## Bulletin Board: das schwarze Brett\n\nDer Bulletin-Board-Stil entkoppelt noch eine Stufe weiter. Komponenten rufen einander gar nicht mehr, auch nicht über Registrierung beim Rahmen – sie veröffentlichen Events an ein schwarzes Brett, und wer sich für einen Event-Typ eingetragen hat, wird benachrichtigt:\n\n```python\nclass EventManager:\n    def __init__(self):\n        self._subscriptions = {}\n\n    def subscribe(self, event_type, handler):\n        self._subscriptions.setdefault(event_type, []).append(handler)\n\n    def publish(self, event):\n        event_type = event[0]\n        for handler in self._subscriptions.get(event_type, []):\n            handler(event)\n```\n\nDer Zähler abonniert `word`, der Filter abonniert `valid_word`, die Ausgabe abonniert `print` – und niemand kennt niemanden. Das ist Publish/Subscribe auf 15 Zeilen, das Muster hinter jedem Message-Broker und jeder ereignisgetriebenen Integration. Die Constraint „keine direkten Aufrufe\" kauft maximale Entkopplung: Man kann Teilnehmer hinzufügen, ohne bestehende zu ändern. Bezahlt wird mit dem Verlust des sichtbaren Ablaufs. Beim Durcharbeiten habe ich für diesen Stil zum ersten Mal den Debugger gebraucht – bei 80 Zeilen. Genau dieselbe Erfahrung macht man später im Großen, wenn man in einem ereignisgetriebenen System einer Message hinterherläuft.\n\n## The One: der Wert im Gefäß\n\nDer Stil mit dem schönsten Namen ist eine Monade light: Ein Wert wird in ein Gefäß gelegt, und das Gefäß weiß, wie es Funktionen der Reihe nach auf seinen Inhalt anwendet.\n\n```python\nclass TheOne:\n    def __init__(self, value):\n        self._value = value\n\n    def bind(self, func):\n        self._value = func(self._value)\n        return self\n\nTheOne('pride-and-prejudice.txt') \\\n    .bind(read_text) \\\n    .bind(normalize) \\\n    .bind(tokenize) \\\n    .bind(remove_stop_words) \\\n    .bind(count_frequencies) \\\n    .bind(top_25) \\\n    .bind(print_all)\n```\n\nInhaltlich ist das dieselbe Kette wie im Pipeline-Stil – aber die Verkettung selbst ist jetzt ein Baustein, den man erweitern kann: um Logging bei jedem Schritt, um Error Handling, um verzögerte Ausführung. Wer in ES5-JavaScript schon mit Promise-Bibliotheken gearbeitet hat, erkennt das Muster sofort wieder: `then` ist ein `bind`, das nebenbei Asynchronität wegkapselt. Die Constraint „alles fließt durch ein Gefäß\" kauft einen Ort, an dem Querschnittsbelange wohnen dürfen.\n\n## Sechs Stile, sechs Architekturen\n\nNebeneinandergelegt ergibt sich aus den Übungen eine Zuordnung, die ich seitdem im Kopf behalte:\n\n```mermaid\nflowchart LR\n    A[Monolith<br/>keine Abstraktion erlaubt] --> A2[gewachsene Skripte,<br/>Legacy-Prozeduren]\n    B[Pipeline<br/>nur reine Funktionen] --> B2[Batch, ETL,<br/>Unix-Pipes]\n    C[Things<br/>Zustand nur hinter Methoden] --> C2[Module,<br/>Serviceschnitte]\n    D[Hollywood<br/>Rahmen ruft zurück] --> D2[Frameworks,<br/>Plugin-Systeme]\n    E[Bulletin Board<br/>nur Ereignisse, keine Aufrufe] --> E2[Message-Broker,<br/>Integration]\n    F[The One<br/>alles durch ein Gefäß] --> F2[Fluent APIs,<br/>Promise-Ketten]\n```\n\nJede dieser Architekturen im Großen ist ein Programmierstil im Kleinen – dieselbe Constraint-Menge, nur auf Prozess- statt Funktionsebene. Und in beiden Größenordnungen gilt: Die Eigenschaften, die man sich wünscht, kommen aus dem, was man sich verbietet. Testbarkeit kommt aus dem Verbot geteilten Zustands. Erweiterbarkeit kommt aus dem Verbot direkter Aufrufe. Nachvollziehbarkeit kommt aus dem Verbot versteckter Kontrollflüsse. Nichts davon gibt es geschenkt; jede Constraint hat ihren Preis, und die Übungen machen den Preis auf einer Bildschirmseite fühlbar, statt ihn erst nach zwei Jahren Betrieb zu präsentieren.\n\n## Der unbewusste Stilmix\n\nDie für mich wichtigste Erkenntnis kam allerdings nicht aus einem der Stile, sondern aus dem Kontrast zu meinem eigenen Alltagscode. Der ist – wie vermutlich der meiste Code da draußen – ein Stilmix: ein bisschen objektorientiert, weil die Sprache es nahelegt; ein paar Pure Functions, wo es sich anbot; ein globaler Cache, weil es schnell gehen musste; Callbacks, weil das Framework es verlangt. Nichts davon ist für sich falsch. Das Problem ist, dass der Mix unbewusst entsteht. Niemand hat entschieden, dass dieses Modul dem Pipeline-Gedanken folgt und jenes dem schwarzen Brett – es ist einfach passiert, Commit für Commit.\n\nGenau da liegt für mich der Unterschied zwischen Code, der Struktur hat, und Code, der nur strukturiert aussieht. Architektur ist die Kunst, Constraints bewusst zu wählen – und sie dann auch dort durchzuhalten, wo sie gerade unbequem sind. Eine Constraint, die man aufgibt, sobald sie zwickt, war nie eine; sie war eine Gewohnheit. Seit ich die Übungen durchgearbeitet habe, stelle ich in Code-Reviews gelegentlich eine neue Frage: In welchem Stil sind wir hier eigentlich? Nicht als Fangfrage, sondern weil die Antwort sofort zeigt, ob eine Regel verletzt wurde, die sich das Team gegeben hat – oder ob es die Regel nie gab und wir sie jetzt nachholen sollten.\n\nHilfreich ist der Blick auch in der Gegenrichtung. Wenn ein Modul schwer testbar ist, lautet die Frage nicht „welches Test-Werkzeug fehlt?\", sondern „welche Constraint fehlt?\". Meist ist es dieselbe, die der Pipeline-Stil erzwingt und der gewachsene Code ignoriert.\n\n## Was ich daraus mitnehme\n\nWortfrequenzen zählen ist die langweiligste Aufgabe der Welt, und genau das macht sie zum idealen Prüfstand: Wenn die Aufgabe konstant bleibt, ist alles, was sich zwischen zwei Lösungen unterscheidet, Struktur – und damit vergleichbar. Man kann Architekturstile diskutieren, indem man Systeme mit jahrelanger Geschichte seziert. Oder man vergleicht 33 Skripte à 80 Zeilen, die alle dasselbe tun, und sieht dieselben Kräfte am Werk, nur ohne Nebel.\n\nEin paar Dinge nehme ich konkret mit:\n\n- Stile nicht nach Sympathie beurteilen, sondern nach der Frage, welche Eigenschaft ihre Constraints kaufen und was sie kosten.\n- Beim Lesen fremden Codes zuerst den Stil identifizieren – danach erklärt sich vieles, was vorher wie Willkür aussah.\n- Den eigenen Stilmix gelegentlich explizit machen: Welche Regeln gelten in diesem Modul, und stehen sie irgendwo?\n\nWer das Buch nicht zur Hand hat: Das Repository allein trägt schon weit. Forken, einen Stil pro Abend nachbauen, dabei die Constraints absichtlich verletzen und beobachten, was kaputtgeht. Ich habe aus diesen Abenden mehr über Architektur gelernt als aus manchem dicken Entwurfsmuster-Wälzer – gerade weil kein einziges UML-Diagramm vorkam, sondern nur die Frage: Was verbietest du dir, und was bekommst du dafür?\n\n## Weiterführende Quellen\n\n- Mein Fork mit den durchgearbeiteten Übungen: https://github.com/MikeBild/exercises-in-programming-style\n- Das Original-Repository von Cristina Videira Lopes: https://github.com/crista/exercises-in-programming-style\n- Raymond Queneaus literarische Vorlage „Exercises in Style\": https://en.wikipedia.org/wiki/Exercises_in_Style\n- Python-2-Dokumentation zu `collections` (u. a. `Counter` für die Frequenzzählung): https://docs.python.org/2/library/collections.html"},{"locale":"de","translation_key":"docker-fuer-dotnet","slug":"docker-fuer-dotnet","title":"Docker für .NET, bevor es normal war","summary":"Eine kleine Nancy-API unter Mono in einen Docker-Container zu packen war im Frühjahr 2015 ein Umweg über Linux – und hat mir mehr über .NET-Deployment beigebracht als jedes IIS-Handbuch.","tags":["Software","Platform"],"published_at":"2015-04-24T10:00:00+00:00","updated_at":"2026-07-14T17:05:06.200176+00:00","url":"https://www.mikebild.dev/de/blog/docker-fuer-dotnet/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/9e9092136ee3b807580f4ba10266965c814d180ec55e2485dd4bdccd4c7fb40d/docker-fuer-dotnet-vorlesen.mp3","audio_duration_secs":686,"text":"# Docker für .NET, bevor es normal war\n\nGut 400 Megabyte. Das meldet `docker images` für ein Image, dessen eigentliche Anwendung eine einzige kompilierte Datei von wenigen Kilobyte ist – eine kleine HTTP-API, geschrieben in C#. Die Zahl wirkt absurd, und sie ist es auch. Aber die interessantere Messung ist eine andere: `docker start demo1` braucht unter einer Sekunde, und danach antwortet der Dienst. Ein vergleichbares Deployment auf einem Windows-Server mit IIS hat mich in Projekten regelmäßig einen halben Nachmittag gekostet – Framework-Version prüfen, App-Pool anlegen, Rechte setzen, Dateien kopieren, beten.\n\nDiese beiden Zahlen nebeneinander – 400 Megabyte Platz gegen eine Sekunde Start – beschreiben ziemlich genau, worauf man sich einlässt, wenn man im Frühjahr 2015 .NET-Code in einen Docker-Container steckt. Man tauscht Plattenplatz gegen Wiederholbarkeit. Ich halte das für einen guten Tausch, und ich will erzählen, warum.\n\n## Frühjahr 2015: .NET heißt offiziell Windows\n\nWer heute „.NET\" sagt, meint praktisch immer Windows, IIS und den Microsoft-Stack von oben bis unten. Docker dagegen ist ein Linux-Thema: Docker 1.6 ist gerade erschienen, auf dem Mac läuft der Docker-Daemon in einer kleinen VirtualBox-VM namens boot2docker, und Compose ist eben erst aus Fig hervorgegangen. Die beiden Welten berühren sich kaum.\n\nGanz stimmt das Bild allerdings nicht mehr. Im November hat Microsoft angekündigt, .NET Core als Open Source zu entwickeln, seit Februar liegt die CoreCLR auf GitHub, und das kommende ASP.NET 5 soll ausdrücklich auch auf Linux und OS X laufen. Das ist eine bemerkenswerte Wende – aber im April 2015 ist es eine Ankündigung mit frühen Betas, kein Fundament. Wer heute .NET-Code in einem Linux-Container ausführen will, landet bei Mono, der freien Runtime, die es seit über zehn Jahren gibt und die inzwischen erstaunlich viel vom .NET Framework abdeckt.\n\nGenau das wollte ich ausprobieren. Nicht, weil ein Projekt es verlangt hätte, sondern weil mich die Frage nicht losließ: Wie viel vom üblichen .NET-Deployment-Ritual ist eigentlich nötig – und wie viel davon ist nur Gewohnheit, die am IIS hängt? Ein Wochenende, ein Repository, ein bewusst kleiner Dienst. Wenn das Experiment scheitert, ist wenig verloren; wenn es trägt, weiß ich etwas, das sich mit keinem Blogartikel von anderen ersetzen lässt.\n\n## Der Versuch: eine Nancy-API im Container\n\nDas Ergebnis liegt als Repository unter `dotnet-docker` auf GitHub: eine kleine HTTP-API mit dem Nancy-Framework, selbst gehostet über `Nancy.Hosting.Self`, mit LiteDB als eingebetteter Datenbank. Kein IIS, kein Windows-Dienst, keine Installation – ein Prozess, der einen Port öffnet. Das README nennt es einen „Docker + DotNet Microservice\", und so klein wie das klingt, ist es auch: ein Modul, zwei ernsthafte Endpoints, eine Datei Datenbank.\n\nDas Herzstück ist das Dockerfile. Es beschreibt vollständig, was diese Anwendung zum Laufen braucht – und zwar so, dass keine stille Annahme übrig bleibt:\n\n```dockerfile\nFROM mono:3.10\n\n# Update SSL certs\nRUN mozroots --import --sync\n\n# Copy source files\nADD src ./src\nWORKDIR /src\n\n# Install dependencies via NuGet\nRUN mono /src/NuGet.exe install Nancy\nRUN cp /src/Nancy.1.1/lib/net40/Nancy.dll /src\n\nRUN mono /src/NuGet.exe install Nancy.Hosting.Self\nRUN cp /src/Nancy.Hosting.Self.1.1/lib/net40/Nancy.Hosting.Self.dll /src\n\nRUN mono /src/NuGet.exe install LiteDB\nRUN cp /src/LiteDB.1.0.0/lib/net40/LiteDB.dll /src\n\n# Compile the web service\nRUN mcs nancy.cs modules/webhooks.cs \\\n    -reference:Nancy.dll \\\n    -reference:Nancy.Hosting.Self.dll \\\n    -reference:LiteDB.dll\nEXPOSE 8080\n\n# Run the web service\nCMD [\"mono\", \"/src/nancy.exe\"]\n```\n\nMan sieht dem Dockerfile die Epoche an, und das ist Absicht. Es gibt kein offizielles Microsoft-Image, also startet alles auf `mono:3.10`. Es gibt keine eingebaute Paketverwaltung im Build, also liegt `NuGet.exe` mit im Repository und wird per `mono` aufgerufen. Und weil NuGet die Pakete in Versionsordner legt, werden die DLLs anschließend von Hand an die Stelle kopiert, an der der Compiler sie erwartet. Kompiliert wird mit `mcs`, dem Mono-C#-Compiler, direkt im Image – kein Visual Studio, keine MSBuild-Projektdatei, nur Quelldateien und Referenzen.\n\nDas ist unbequem. Aber jede dieser Zeilen ersetzt eine Annahme, die sonst irgendwo unsichtbar auf einem Server läge: welche Runtime, welche Paketversionen, welche Zertifikate, welcher Port. Mir ist beim Schreiben aufgefallen, wie viele dieser Annahmen ich in Windows-Projekten nie aufgeschrieben, sondern immer nur gewusst habe.\n\n```mermaid\nflowchart LR\n  A[mono:3.10<br/>Basis-Image] --> B[mozroots<br/>SSL-Zertifikate]\n  B --> C[NuGet.exe install<br/>Nancy + LiteDB]\n  C --> D[mcs<br/>kompiliert nancy.exe]\n  D --> E[Image dotnet<br/>ca. 400 MB]\n  E --> F[docker run demo1<br/>mono nancy.exe]\n```\n\n## Der Code: ein Prozess, der einen Port öffnet\n\nDie Anwendung selbst ist bewusst schlicht. Der Entry Point startet einen `NancyHost` und hält den Prozess am Leben:\n\n```csharp\nusing System;\nusing Nancy;\nusing Nancy.Hosting.Self;\n\nclass Program\n{\n    static void Main()\n    {\n        using (var host = new NancyHost(new Uri(\"http://localhost:8080\")))\n        {\n            host.Start();\n            Console.WriteLine(\"Nancy host (http://localhost:8080) started.\");\n            Console.ReadLine();\n        }\n    }\n}\n```\n\nDazu ein Nancy-Modul, das Webhooks in LiteDB ablegt – eine Datenbank, die als einzelne Datei neben der Anwendung liegt und ohne Server auskommt:\n\n```csharp\npublic class WebHookModule : NancyModule\n{\n    public WebHookModule() : base(\"/webhooks\")\n    {\n        Get[\"/\"] = _ =>\n        {\n            using (var db = new LiteDatabase(@\"MyData.db\"))\n            {\n                return db.GetCollection<WebHook>(\"webhooks\")\n                    .FindAll()\n                    .ToArray();\n            }\n        };\n\n        Post[\"/\"] = _ =>\n        {\n            using (var db = new LiteDatabase(@\"MyData.db\"))\n            {\n                db.GetCollection<WebHook>(\"webhooks\").Insert(new WebHook());\n                return HttpStatusCode.Created;\n            }\n        };\n    }\n}\n```\n\nGebaut und gestartet wird mit drei Kommandos, so stehen sie auch im README:\n\n```bash\ndocker build -t dotnet .\ndocker run --name demo1 -p 8080:8080 -i -t dotnet\ndocker start demo1\n```\n\n## Wo es hakte\n\nGlatt lief das nicht, und die Stolpersteine sind lehrreicher als der glückliche Pfad. Der erste Start endete mit einem Container, der sich sofort wieder beendete. Der Grund steht oben im Code: `Console.ReadLine()` hält den Prozess nur am Leben, solange es ein Stdin gibt. Ohne die Flags `-i -t` liefert Docker keins, `ReadLine` kehrt sofort zurück, `Main` läuft aus, der Container ist tot. Deshalb stehen die beiden Flags im README – nicht aus Sorgfalt, sondern als Narbe. Die eigentliche Lektion: Ein Container lebt genau so lange wie sein Prozess. Es gibt keinen IIS, der die Anwendung im Hintergrund festhält; die Anwendung ist selbst dafür zuständig, nicht fertig zu werden.\n\nDer zweite Stolperstein war die Erreichbarkeit. Auf dem Mac läuft der Docker-Daemon in der boot2docker-VM, also antwortet der Dienst nicht auf `localhost`, sondern auf der IP der VM – `boot2docker ip` verrät sie. Und dass die Bindung an `http://localhost:8080` im Container überhaupt von außen erreichbar ist, verdankt der Code einer Eigenheit von Nancys Self-Hosting: Die `HostConfiguration` hat eine Option `RewriteLocalhost`, die standardmäßig aktiv ist und aus `localhost` eine Wildcard-Bindung macht. Das habe ich erst verstanden, als ich im Nancy-Quelltext nachgelesen habe. Wer strikt an `127.0.0.1` bindet, sieht von außen: nichts.\n\nDer Rest war Kleinkram, der sich summiert:\n\n- Frische Mono-Images kennen keine SSL-Stammzertifikate; ohne `mozroots --import --sync` scheitert schon der NuGet-Zugriff auf HTTPS-Quellen.\n- Die Pakete müssen als net40-Assemblies vorliegen, damit Mono 3.10 sie sauber lädt – bei Nancy 1.1 und LiteDB 1.0 kein Problem, bei exotischeren Paketen durchaus.\n- Jedes `RUN` erzeugt eine Image-Schicht; wer beim Experimentieren oft baut, lernt den Build-Cache zu lieben und die Reihenfolge der Zeilen zu respektieren.\n- Die 400 Megabyte bleiben. Ein Basis-Image mit kompletter Mono-Installation ist kein schlankes Fundament, und ein schlankeres gibt es für .NET-Code derzeit nicht.\n\n## Was der Umweg lehrte: Prozess statt IIS\n\nDer eigentliche Gewinn des Experiments liegt nicht im Container, sondern in dem, was der Container erzwingt. Eine .NET-Anwendung, die unter IIS läuft, ist keine Anwendung, sondern ein Gast: Der Webserver besitzt den Prozess, das Konfigurationssystem, den Lifecycle. Die XML-Konfigurationsdatei des IIS beschreibt weniger die Anwendung als ihr Verhältnis zum Wirt. Im Container dreht sich das um. Die Anwendung ist ein gewöhnlicher Prozess, der einen Port öffnet, auf die Standardausgabe schreibt und beendet werden kann, ohne dass etwas aufzuräumen wäre.\n\nDamit ändert sich auch, wo Konfiguration hingehört. Ein Image, das für jede Umgebung neu gebaut werden muss, weil die Einstellungen einkompiliert sind, verfehlt den Zweck. Die Konfiguration muss von außen kommen, und der natürliche Weg dafür sind Umgebungsvariablen – `docker run -e` reicht dann sowohl das Können als auch die Disziplin. In der nächsten Iteration des Entry Point sah das so aus:\n\n```csharp\nstatic void Main()\n{\n    var port = Environment.GetEnvironmentVariable(\"PORT\") ?? \"8080\";\n    var uri = new Uri(\"http://localhost:\" + port);\n\n    using (var host = new NancyHost(uri))\n    {\n        host.Start();\n        Console.WriteLine(\"Nancy host ({0}) started.\", uri);\n        Console.ReadLine();\n    }\n}\n```\n\nDas wirkt banal, ist aber ein Bruch mit Jahren von IIS-Konfigurations-Transformationen und Registry-Einträgen. Interessanterweise beschreibt die Twelve-Factor-Liste von Heroku – seit 2011 öffentlich – genau diese Denkweise: Konfiguration in der Umgebung, Prozesse zustandslos, Logs als Event Stream auf die Standardausgabe, Abhängigkeiten explizit deklariert. Ich hatte das Manifest gelesen und für ein Heroku-Werbedokument gehalten. Erst der Container hat mir gezeigt, dass es eine Beschreibung dessen ist, was übrig bleibt, wenn man einer Anwendung den Wirt wegnimmt.\n\n```mermaid\nflowchart TD\n  subgraph W[Gewohnter Windows-Pfad]\n    W1[Server mit IIS<br/>vorbereiten] --> W2[Framework + App-Pool<br/>konfigurieren]\n    W2 --> W3[XML-Konfiguration<br/>transformieren]\n    W3 --> W4[Dateien kopieren<br/>und hoffen]\n  end\n  subgraph C[Container-Pfad]\n    C1[Dockerfile<br/>beschreibt alles] --> C2[docker build<br/>reproduzierbar]\n    C2 --> C3[docker run -e PORT=8080<br/>Konfiguration von außen]\n  end\n```\n\nDazu kommt die Wiederholbarkeit. Das Image, das auf meinem Rechner entsteht, ist bit für bit das, was auf jedem anderen Docker-Host läuft. „Bei mir geht's\" hört auf, ein Argument zu sein, weil „bei mir\" jetzt eine Datei ist, die man weitergeben kann. Für jemanden, der .NET-Deployments bisher als Abfolge manueller Schritte auf gepflegten Servern kannte, ist das der eigentliche Kulturschock – nicht die Technik, sondern der Wegfall der Ausreden.\n\n## Die ehrliche Einordnung\n\nMan muss trotzdem nüchtern bleiben. Mono ist nicht das .NET Framework. Für Nancy, LiteDB und eine überschaubare API trägt es problemlos; wer WCF-Altlasten, WPF oder tiefe Windows-Abhängigkeiten mitbringt, kommt nicht weit. Wer im Betrieb auf Windows-Servern ausliefert, testet mit einem Mono-Container außerdem eine andere Runtime als die produktive – das darf man wissen und muss es einpreisen. Und die Werkzeugkette ist spürbar zweite Reihe: kein Debugging im Container, Paketverwaltung von Hand, Fehlermeldungen, die Linux-Grundwissen voraussetzen.\n\nIn ein Kundenprojekt würde ich dieses Setup heute deshalb nicht tragen. Dafür ist zu viel Handarbeit im Spiel, und ein Team, das seit Jahren Windows-Server betreibt, wechselt nicht wegen eines gelungenen Prototyps das Betriebsmodell. Als Lernvehikel dagegen ist es kaum zu schlagen: Jeder Handgriff, den das Dockerfile sichtbar macht, ist ein Handgriff, den der IIS bisher versteckt hat.\n\nDie Richtung stimmt trotzdem. Microsoft meint die Öffnung offenbar ernst: CoreCLR und der Compiler liegen öffentlich auf GitHub, ASP.NET 5 wird ausdrücklich für Linux entwickelt, und die frühen Betas laufen heute schon auf Mono. Wenn das hält, was es verspricht, ist der Mono-Umweg ein Übergangspfad – aber eben ein gangbarer, heute, nicht irgendwann. Ich vermute, dass sich die Fertigkeiten aus diesem Experiment eins zu eins übertragen werden: Dockerfiles schreiben, Prozesse statt Wirte denken, Konfiguration über die Umgebung reichen. Die Runtime darunter ist austauschbar; die Denkweise nicht.\n\n## Was hängen geblieben ist\n\nDas Repository ist ein Wegwerf-Experiment, und als solches behandle ich es auch. Trotzdem hat es meine Sicht auf .NET-Deployment dauerhaft verschoben, und zwar an drei Stellen:\n\n- Ein Dockerfile ist die vollständige, ausführbare Liste aller Laufzeitannahmen einer Anwendung – was dort nicht steht, wird stillschweigend vom Host geliehen.\n- Eine Anwendung, die als schlichter Prozess laufen kann, ist die flexiblere Anwendung – jeder Wirt, vom IIS bis zum Container, lässt sich darüberstülpen, umgekehrt gilt das nicht.\n- Konfiguration gehört in die Umgebung, nicht ins Artefakt – ein Build, viele Deployments.\n\nNichts davon setzt Docker voraus. Aber Docker hat mich gezwungen, es aufzuschreiben statt zu wissen, und aufgeschriebene Annahmen kann man diskutieren, prüfen und weitergeben. Die 400 Megabyte zahle ich dafür gern – Plattenplatz ist billig, verlorene Nachmittage vor dem IIS-Manager sind es nicht.\n\n## Weiterführende Quellen\n\n- Das Repository zum Artikel: [MikeBild/dotnet-docker](https://github.com/MikeBild/dotnet-docker)\n- Microsofts Ankündigung: [.NET Core is Open Source](https://devblogs.microsoft.com/dotnet/net-core-is-open-source/)\n- Das offizielle [Mono-Image auf dem Docker Hub](https://hub.docker.com/_/mono)\n- Das [Nancy-Framework auf GitHub](https://github.com/NancyFx/Nancy)\n- [The Twelve-Factor App](https://12factor.net/) – die Denkweise hinter Prozess, Umgebung und Logs"},{"locale":"de","translation_key":"tests-bevor-produkt","slug":"tests-bevor-produkt","title":"Tests, bevor es ein Produkt gibt","summary":"Frühe Tests helfen, ein Problem zu begreifen, auch wenn der Code später komplett ersetzt wird.","tags":["Software","Testing"],"published_at":"2014-12-12T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/de/blog/tests-bevor-produkt/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/6d3ddeee68c181864eba3e7f74b702a8ab456bc38ef66c10043458f43e067b95/tests-bevor-produkt-vorlesen.mp3","audio_duration_secs":621,"text":"# Tests, bevor es ein Produkt gibt\n\nEin Testfall braucht zwei Angaben: eine Eingabe und die Erwartung, was dabei herauskommen soll. Mehr ist nicht nötig, um ein Problem festzunageln, für das noch keine einzige Zeile Code existiert.\n\nDer Reflex bei etwas Neuem geht in eine andere Richtung: sofort bauen. Ein Endpoint, eine Maske, ein Datenmodell – irgendetwas Sichtbares, das man vorzeigen kann. Wer an dieser Stelle einen Schritt langsamer wird und zuerst den Test schreibt, sichert damit keinen Code ab – den gibt es ja noch gar nicht. Der Test zwingt dazu, das Problem in einem einzigen, überprüfbaren Satz zu benennen. Und dieser Satz überlebt fast immer die Implementierung, die ich danach schreibe und ein paar Tage später wieder wegwerfe. Qualitätssicherung wird der Test erst später; am Anfang ist er ein Denkwerkzeug.\n\n## Katas: üben, ohne dass ein Produkt entsteht\n\nDer konkrete Anlass für diesen Text sind Katas. Eine Kata ist eine kleine, klar umrissene Programmieraufgabe, die man nicht löst, um sie loszuwerden, sondern um an ihr zu üben – die String Calculator Kata, die Bowling-Game-Kata, römische Zahlen, FizzBuzz. Man kennt die Lösung oft schon. Trotzdem macht man sie wieder, im Coding Dojo mit dem Team oder allein an einem ruhigen Vormittag, weil es nicht um das Ergebnis geht, sondern um den Weg dorthin.\n\nDas Interessante an einer Kata ist, dass am Ende bewusst kein Produkt steht. Es gibt keinen Kunden, keine Deadline, kein Deployment. Was bleibt, ist die Erfahrung, wie sich ein Problem anfühlt, wenn man es Testschritt für Testschritt aufdröselt. Genau diese Haltung nehme ich mit in echte Projekte. In der frühen Phase eines Features weiß ich oft noch nicht, wie die Lösung aussieht. Ich weiß nur, welches Verhalten am Ende beobachtbar sein muss. Und das lässt sich als Test formulieren, bevor auch nur eine Zeile Produktivcode existiert.\n\nNehmen wir die String Calculator Kata. Die Aufgabe klingt trivial: eine Funktion, die eine Zeichenkette mit Zahlen entgegennimmt und ihre Summe liefert. Der erste Test ist maximal langweilig – und trotzdem die wichtigste Zeile des Tages.\n\n```js\ndescribe(\"String Calculator\", () => {\n  it(\"returns 0 for an empty string\", () => {\n    expect(add(\"\")).to.equal(0);\n  });\n\n  it(\"sums two comma-separated numbers\", () => {\n    expect(add(\"1,2\")).to.equal(3);\n  });\n});\n```\n\nBevor ich `add` schreibe, habe ich zwei Entscheidungen getroffen, die vorher unausgesprochen waren: Der leere Fall ist nicht undefiniert, er liefert die Zahl 0. Und das Trennzeichen ist zunächst das Komma. Zwei kleine Beispiele – und schon ist eine Diskussion möglich, die sonst erst im Code-Review oder, schlimmer, im Betrieb aufgetaucht wäre.\n\n## Der Test als Denkwerkzeug\n\nKent Beck hat das in *Test-Driven Development by Example* auf eine einfache Schleife gebracht: einen Test schreiben, der fehlschlägt, ihn mit dem kleinstmöglichen Schritt grün bekommen, dann aufräumen. Rot, grün, refactor.\n\n```mermaid\nflowchart LR\n  Red[Test schreiben,<br/>er schlägt fehl] --> Green[kleinster Schritt<br/>bis grün]\n  Green --> Refactor[aufräumen,<br/>ohne Verhalten zu ändern]\n  Refactor --> Red\n```\n\nDer entscheidende Effekt ist nicht die Testabdeckung. Es ist das Feedback über das Design. Wenn ich für einen einzigen Testfall drei Objekte aufsetzen, vier Abhängigkeiten stellen und eine halbe Datenbank mocken muss, dann sagt mir der Test etwas über meinen Entwurf, nicht über meinen Testfleiß: Die Grenze sitzt an der falschen Stelle. Ein Test, der schwer zu schreiben ist, ist fast immer ein Hinweis auf eine Kopplung, die ich noch nicht bezahlt, aber schon eingegangen bin.\n\nDeshalb schreibe ich den Test zuerst, auch wenn ich weiß, dass der Code darunter ein Wegwerfstück ist. Der Test ist die Frage, der Code ist nur der erste Antwortversuch. Die Frage ist das Wertvolle. Wenn ich den ersten Antwortversuch nach zwei Tagen komplett ersetze – weil ich das Problem inzwischen besser verstehe –, bleibt die Frage stehen und prüft die neue Antwort genauso streng wie die alte.\n\n## Specification by Example\n\nDer zweite Baustein, der für mich untrennbar dazugehört, ist Specification by Example, so wie Gojko Adzic es beschreibt. Die Idee: Statt eine Anforderung abstrakt zu formulieren („der Rabatt gilt für Neukunden“), schreibt man sie als konkretes Beispiel auf, das gleichzeitig Fachsprache, Erwartung und automatisierbare Prüfung ist.\n\n```gherkin\nScenario: A new customer gets the welcome discount\n  Given a customer with no previous orders\n  When the customer places an order of 100 EUR\n  Then the invoice total is 90 EUR\n```\n\nDieses kleine Szenario leistet mehr, als es aussieht. Es ist in einer Sprache geschrieben, die eine Fachexpertin lesen und korrigieren kann. Es legt die Erwartung auf eine Zahl fest, über die man streiten kann – sind es wirklich 90, oder greift der Rabatt vor oder nach der Mehrwertsteuer? Und es lässt sich an die Ausführung binden, sodass die Beschreibung nicht neben dem Code veraltet, sondern mit ihm mitläuft.\n\nIn der Praxis ist das Beispiel oft der Moment, in dem ein Missverständnis auffliegt. „Neukunde“ hieß für die Entwicklung „noch keine Bestellung“, für den Vertrieb aber „seit zwölf Monaten keine Bestellung“. Solange die Anforderung abstrakt blieb, waren sich alle einig. Erst das konkrete Beispiel mit den 100 EUR hat die beiden Deutungen sichtbar gemacht. Genau dafür schreibe ich Beispiele früh: nicht, um Code zu testen, sondern um Annahmen zu testen, die noch niemand ausgesprochen hat.\n\n## Die Grenze ist die eigentliche Entscheidung\n\nWenn ich einen Test formuliere, treffe ich implizit eine Architekturentscheidung: Ich lege fest, an welcher Grenze ich prüfe. Und diese Grenze bestimmt, was ich später frei ändern kann und was nicht.\n\nPrüfe ich zu tief – auf einzelne Methodenaufrufe, interne Reihenfolgen, private Hilfsstrukturen –, dann klebt der Test an der Implementierung. Jede Umgestaltung, die das Verhalten gar nicht ändert, lässt ihn rot werden. Solche Tests bestrafen Refactoring, statt es abzusichern, und das Team lernt schnell, sie zu meiden oder blind anzupassen. Prüfe ich dagegen an einer sinnvollen Grenze – am beobachtbaren Verhalten der Einheit, an dem, was ein anderer Teil des Systems tatsächlich von ihr sieht –, dann darf sich innen alles ändern, solange außen das Versprechen hält.\n\nDas ist der Punkt, an dem Testen aufhört, eine reine Handwerksfrage zu sein, und zur Entwurfsfrage wird. Die Grenze, an der ich teste, ist dieselbe Grenze, an der ich das System später aufschneiden, austauschen oder ersetzen kann. Ein gut gesetzter Test beschreibt eine Naht im System. Ein schlecht gesetzter Test zementiert ein Detail, das niemanden von außen etwas angeht. Deshalb lohnt sich vor der Tool-Frage – Mocha oder Jasmine, Sinon oder handgeschriebene Stubs – die inhaltliche Frage: Welches Verhalten will ich festhalten, und welches will ich bewusst offen lassen?\n\n## Wann sich das lohnt – und wann nicht\n\nIch will nicht behaupten, dass jede Zeile mit einem Test beginnen muss. Ein Spike, mit dem ich nur herausfinde, ob eine Bibliothek überhaupt taugt, braucht keinen Test – er ist selbst das Experiment und wird danach gelöscht. Ein reiner Durchstich, um ein Layout zu sehen, auch nicht.\n\nDie Abwägung hängt an einer einzigen Frage: Wie gut verstehe ich das Problem schon? Wenn die Aufgabe klar ist und nur noch getippt werden muss, kostet Test-First mehr, als es bringt. Wenn ich dagegen nicht sicher bin, was „richtig“ überhaupt heißt – und das ist in der frühen Produktphase der Normalfall –, dann ist der Test das billigste verfügbare Werkzeug, um Klarheit zu erzwingen. Gerade weil ich weiß, dass der Code Wegwerfware ist, will ich das Wenige, das ich lerne, in einer Form festhalten, die den Code überlebt.\n\nSo gesehen ist Test-First in der Erkundungsphase kein Widerspruch zum Wegwerfen. Es ist die Methode, mit der ich aus einem Wegwerf-Prototyp trotzdem dauerhaftes Wissen herausziehe: die eine Zeile, die das erwartete Verhalten festhält, bleibt, auch wenn alles andere geht.\n\n## Der Fehlerpfad entscheidet über Releasefähigkeit\n\nEs gibt einen Sprung zwischen „läuft in der Demo“ und „läuft im Betrieb“, und genau diesen Sprung machen frühe Tests sichtbar. Im Demo-Modus sieht fast jedes System sauber aus, weil man den Ablauf zeigt, in dem alles gut geht: gültige Eingabe, erreichbarer Dienst, genau ein Durchlauf. Interessant wird es daneben.\n\nWenn ich einen Import baue, ist die spannende Frage nicht, ob er eine korrekte Datei einliest, sondern was bei der halb kaputten passiert. Wird der Lauf wiederholt, entstehen dann Duplikate, oder ist er idempotent? Was passiert bei einem Timeout mitten in der Verarbeitung – bricht er sauber ab oder bleibt das System in einem halben Zustand? Welche Logzeile hilft mir nachts um drei, den Fehler zu verstehen, statt ihn nur zu bemerken? Diese Fragen wirken trocken, aber sie sind der eigentliche Unterschied zwischen einem Prototyp und etwas, das man einem Kunden gibt.\n\nIch schreibe deshalb früh mindestens einen Test für den unangenehmen Fall, nicht nur für den schönen. Ein Test, der prüft, dass eine doppelte Verarbeitung eben nicht zwei Rechnungen erzeugt, sagt mehr über die Tragfähigkeit des Entwurfs aus als zehn Tests für das erwartbare Ergebnis. Und er sagt es zu einem Zeitpunkt, an dem die Änderung noch billig ist.\n\n## Was das messbar bringt\n\nDas alles wäre Folklore, wenn es nur ein gutes Gefühl erzeugte. Der Nutzen ist konkreter. Missverständnisse werden im Beispiel sichtbar, nicht erst in der Abnahme – das verkürzt den teuersten aller Zyklen, den zwischen „falsch verstanden“ und „gemerkt, dass falsch verstanden“. Refactoring wird billiger, weil Tests an der richtigen Grenze das Verhalten absichern, statt die Implementierung einzufrieren; das Team traut sich, aufzuräumen, statt Code zu umgehen. Und die Übergabe wird leichter, weil ein Beispiel in Fachsprache eine bessere Dokumentation ist als jeder Fließtext, der neben dem Code veraltet.\n\nWenn ich einen Effekt herausgreifen müsste, dann diesen: kürzere Rückkopplung. Ein Beispiel, das eine Annahme prüft, verwandelt eine Diskussion, die sonst Wochen später im Betrieb geführt würde, in eine Diskussion von fünf Minuten am Whiteboard. Das ist keine weiche Verbesserung. Es ist der Unterschied zwischen einem Team, das an der Sache arbeitet, und einem, das an seinen Missverständnissen arbeitet.\n\n## Was bleibt, wenn der Code geht\n\nZurück zum Anfang. Der Grund, warum ich Tests schreibe, bevor es ein Produkt gibt, ist nicht Disziplin und auch nicht Vollständigkeit. Es ist, dass der Test die eine Sache festhält, die ich behalten will, während alles andere noch im Fluss ist: das erwartete Verhalten, benannt an einer Grenze, über die man streiten kann.\n\nDer Code der ersten Woche ist fast immer falsch, und das ist in Ordnung – er war nie als Antwort gemeint, sondern als Frage in ausführbarer Form. Wenn ich ihn wegwerfe und neu schreibe, prüft derselbe Test die neue Fassung genauso streng. Genau deshalb üben wir an Katas, ohne je ein Produkt zu bauen: nicht das Ergebnis trägt, sondern das Urteil darüber, welches Verhalten zählt. Und dieses Urteil ist das Einzige, was ein Team wirklich mitnehmen kann, wenn der erste Wurf längst gelöscht ist."},{"locale":"de","translation_key":"flood-it-architektur-lupe","slug":"flood-it-architektur-lupe","title":"Flood-It: ein Spiel als Architektur-Lupe","summary":"Ein Brett aus Zahlen, ein Zug als Pure Function und ein Greedy-Löser zeigen im Kleinen, was in großen Systemen verschwimmt: die Trennung von Kernlogik, Strategie und Darstellung.","tags":["Software","Lernen"],"published_at":"2014-10-24T10:00:00+00:00","updated_at":"2026-07-14T16:38:17.99207+00:00","url":"https://www.mikebild.dev/de/blog/flood-it-architektur-lupe/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/47e2dfa2e2a83c2347aa229f4601fc40333bbac752466758f49c293bbdd0f41e/flood-it-architektur-lupe-vorlesen.mp3","audio_duration_secs":607,"text":"# Flood-It: ein Spiel als Architektur-Lupe\n\n```js\nvar board = [\n  [2, 1, 1, 3],\n  [1, 2, 3, 0],\n  [0, 1, 2, 2],\n  [3, 3, 0, 1]\n];\n\nfunction flood(board, color) {\n  // returns a new board where the top-left region\n  // has captured all adjacent cells of the picked color\n}\n```\n\nMehr Modell braucht Flood-It nicht. Das Spiel ist schnell erklärt: ein Brett aus Farbfeldern, oben links sitzt eine Region, die anfangs aus einem einzigen Feld besteht. Pro Zug wählt man eine Farbe. Die Region nimmt diese Farbe an und schluckt dabei alle orthogonal angrenzenden Felder, die bereits so gefärbt sind. Ziel ist ein einfarbiges Brett – in möglichst wenigen Zügen.\n\nVor gut zwei Wochen habe ich dafür das Repository `kata-flood-it` angelegt, eine frische Kata in JavaScript. Das README besteht bisher aus einer einzigen Zeile, und mehr verspreche ich hier auch nicht: kein fertiges Produkt, sondern ein kleines Experiment. Der Reiz liegt ohnehin nicht im Spiel selbst – Flood-It gibt es längst auf jedem Smartphone. Der Reiz liegt darin, dass so ein winziges Programm wie eine Lupe wirkt. Es gibt keine Datenbank, kein Framework, keinen Netzwerk-Layer, hinter dem sich schlechte Schnitte verstecken könnten. Was übrig bleibt, sind genau drei Dinge: ein Modell, eine Strategie und eine Darstellung. Und die Frage, wo die Grenzen zwischen ihnen verlaufen.\n\n## Das Brett ist eine Entscheidung\n\nDie erste Entscheidung fällt, bevor eine Zeile Spiellogik existiert: Was ist das Brett? Oben steht meine Antwort – ein zweidimensionales Array aus Zahlen. Das wirkt banal, ist es aber nicht. Die naheliegende Alternative sieht man in vielen kleinen Browser-Spielen: Das Brett existiert nur als Sammlung von `div`-Elementen, und die Wahrheit über den Spielzustand steckt in CSS-Klassennamen. Wer wissen will, welche Farbe ein Feld hat, fragt das DOM. Damit ist die Darstellung zum Modell geworden, und jede Logik muss durch sie hindurch.\n\nDie zweite, kleinere Entscheidung: Zahlen statt Farbnamen. Im Modell gibt es kein `\"red\"` und kein `\"#ff0000\"`, nur `0` bis `5`. Welche Zahl welchem Farbton entspricht, ist eine Frage der Darstellung – auf der Konsole vielleicht ein Buchstabe, im Browser eine CSS-Klasse, auf einem Canvas ein Füllstil. Das Modell weiß davon nichts, und genau das macht es tragfähig.\n\nMir ist beim Schreiben aufgefallen, wie viel Diskussionsstoff allein in diesen zwei Zeilen steckt. In einem Review über ein großes System reden wir über dieselben Fragen – wo liegt der führende Zustand, wer darf ihn lesen, wer ihn ändern –, nur verteilt über Dutzende Dateien. Hier passt die ganze Frage auf einen Bildschirm.\n\n## Der Zug als Funktion\n\nDer Kern des Spiels ist ein Flood-Fill: Von oben links aus werden alle zusammenhängenden Felder der alten Farbe eingesammelt und umgefärbt. Klassisch löst man das rekursiv (Tiefensuche) oder mit einer Queue (Breitensuche). Ich habe die Breitensuche gewählt, weil sie ohne tiefe Aufrufstapel auskommt – bei großen Brettern kippt die naive Rekursion in JavaScript irgendwann mit einem Stack Overflow um.\n\n```js\nfunction flood(board, color) {\n  var next = board.map(function (row) { return row.slice(); });\n  var target = next[0][0];\n  if (target === color) return next;\n\n  var queue = [[0, 0]];\n  while (queue.length > 0) {\n    var cell = queue.shift();\n    var row = cell[0];\n    var col = cell[1];\n    if (row < 0 || col < 0 || row >= next.length || col >= next[0].length) continue;\n    if (next[row][col] !== target) continue;\n\n    next[row][col] = color;\n    queue.push([row - 1, col], [row + 1, col], [row, col - 1], [row, col + 1]);\n  }\n  return next;\n}\n```\n\nDie wichtigste Eigenschaft steht in der ersten Zeile: `flood` verändert das übergebene Brett nicht, sondern liefert ein neues. Das kostet ein paar Kopien, und `queue.shift()` ist auf langen Arrays auch nicht die schnellste Operation der Welt – für ein 14×14-Brett ist beides völlig egal. Was ich dafür bekomme, ist erheblich: Ein Zug ist ein Wert. Die Spielhistorie ist schlicht ein Array von Brettern, Undo ist ein Index, der um eins zurückspringt, und ein Replay ist eine Schleife. Nichts davon musste ich extra bauen.\n\nDazu kommt eine zweite Pure Function, die das Spielende feststellt:\n\n```js\nfunction isSolved(board) {\n  return board.every(function (row) {\n    return row.every(function (cell) {\n      return cell === board[0][0];\n    });\n  });\n}\n```\n\nBeide Funktionen kennen weder Züge-Limits noch Buttons noch Punktestände. Sie beantworten genau eine Frage über das Brett. Alles andere – wie viele Züge erlaubt sind, ob das Spiel verloren ist, was danach passiert – gehört woanders hin.\n\n## Tests gegen die Logik, nicht gegen das DOM\n\nBrowser-Oberflächen zu testen ist 2014 mühsam: Man braucht einen echten oder kopflosen Browser, die Läufe sind langsam, und die Tests brechen, sobald sich eine CSS-Klasse ändert. Die Kata zeigt den Ausweg im Kleinen: Wenn die Kernlogik aus Pure Functions in CommonJS-Modulen besteht, laufen die Tests mit Mocha direkt auf Node – in Millisekunden, ohne Browser. Für die Auslieferung bündelt Browserify dieselben Module dann für den Browser. Ein Modulformat, zwei Runtimes.\n\n```js\nvar assert = require('assert');\nvar flood = require('./flood');\n\ndescribe('flood', function () {\n  it('captures adjacent cells of the picked color', function () {\n    var board = [\n      [0, 1],\n      [1, 1]\n    ];\n    assert.deepEqual(flood(board, 1), [\n      [1, 1],\n      [1, 1]\n    ]);\n  });\n\n  it('does not mutate the given board', function () {\n    var board = [\n      [0, 1],\n      [1, 1]\n    ];\n    flood(board, 1);\n    assert.deepEqual(board, [\n      [0, 1],\n      [1, 1]\n    ]);\n  });\n});\n```\n\nDas zweite Beispiel ist mir wichtiger als das erste. Ob eine Funktion ihre Eingabe verändert, ist eine Vertragsfrage, und Verträge gehören in Tests – nicht in Kommentare. In einem größeren Projekt habe ich einmal zwei Tage einem Fehler hinterhergesucht, der genau daher kam: eine Hilfsfunktion, die ein übergebenes Array sortierte und damit still den Zustand des Aufrufers umbaute. Der Test oben kostet sechs Zeilen und schließt diese ganze Fehlerklasse aus.\n\nAuffällig ist auch, was in den Tests nicht vorkommt: kein `document`, kein Selektor, kein simulierter Klick. Wenn die Tests für die Spielregeln einen Browser brauchen, ist das kein Test-Problem, sondern ein Architektur-Befund – dann steckt Logik in der Darstellung.\n\n## Die Strategie ist eine eigene Schicht\n\nFlood-It hat neben den Regeln noch eine zweite fachliche Ebene: Wie spielt man gut? Die naheliegende Heuristik ist gierig – probiere jede Farbe, zähle, wie groß die Region danach wäre, und nimm die Farbe mit dem größten Zuwachs.\n\n```js\nfunction countCaptured(board) {\n  var marked = flood(board, -1);\n  var count = 0;\n  marked.forEach(function (row) {\n    row.forEach(function (cell) {\n      if (cell === -1) count += 1;\n    });\n  });\n  return count;\n}\n\nfunction bestMove(board, colors) {\n  var best = { color: null, captured: -1 };\n  colors.forEach(function (color) {\n    if (color === board[0][0]) return;\n    var captured = countCaptured(flood(board, color));\n    if (captured > best.captured) {\n      best = { color: color, captured: captured };\n    }\n  });\n  return best.color;\n}\n```\n\nZwei Beobachtungen. Erstens: `countCaptured` erfindet keine eigene Traversierung, sondern missbraucht `flood` mit einer Farbe, die im Spiel nicht vorkommt, und zählt die Markierungen. Das geht nur, weil `flood` rein ist – ich kann es gefahrlos „auf Probe\" aufrufen, so oft ich will. Genau dieser Probelauf ist in Systemen mit verstreutem, veränderlichem Zustand unbezahlbar teuer: Wer dort eine Was-wäre-wenn-Frage stellen will, braucht Mocks, Transaktions-Rollbacks oder eine Staging-Umgebung.\n\nZweitens: Die gierige Strategie ist messbar nicht optimal, und das ist keine Schludrigkeit meinerseits. Clifford, Jalsenius, Montanaro und Sach haben 2010 gezeigt, dass Flood-It ab drei Farben NP-schwer ist – eine effiziente optimale Strategie ist also nicht zu erwarten. Für die Architektur heißt das: Die Strategie wird sich ändern. Heute gierig, morgen vielleicht mit zwei Zügen Vorausschau. Deshalb ist sie eine eigene Schicht, die nur über `flood`, `countCaptured` und `isSolved` mit dem Kern spricht. Auch der Zugzähler und das Zug-Limit gehören hierher, nicht in die Regeln und nicht in die Oberfläche – sie sind Spielmodus, nicht Spielgesetz.\n\n## Die Darstellung als austauschbare Haut\n\nGanz außen sitzt die Darstellung. Sie liest das Brett und zeichnet es – mehr nicht:\n\n```js\nfunction render(board, element) {\n  element.innerHTML = '';\n  board.forEach(function (row) {\n    var line = document.createElement('div');\n    row.forEach(function (cell) {\n      var field = document.createElement('span');\n      field.className = 'cell color-' + cell;\n      line.appendChild(field);\n    });\n    element.appendChild(line);\n  });\n}\n```\n\nDer Klick-Handler auf den Farbknöpfen übersetzt ein DOM-Event in einen Aufruf der Kernlogik und rendert das Ergebnis neu. Die Darstellung schreibt nie selbst am Brett herum; sie ist eine Haut, die man abziehen und ersetzen kann. Ein Canvas statt der `div`-Suppe? Nur `render` ändert sich. Eine Konsolen-Version mit Buchstaben statt Farben, um die Kata in Node durchzuspielen? Wieder nur `render`. jQuery habe ich gar nicht erst hereingeholt – für zwanzig Zeilen DOM-Arbeit trägt es nichts bei, und die Versuchung, Zustand in `data`-Attributen zu parken, bleibt draußen.\n\n```mermaid\nflowchart TB\n  subgraph ui[\"Darstellung\"]\n    H[Click-Handler] --> R[render]\n  end\n  subgraph strategy[\"Strategie / Spielmodus\"]\n    G[bestMove] --> Z[Zugzähler +<br/>Zug-Limit]\n  end\n  subgraph core[\"Kernlogik (Pure Functions)\"]\n    F[flood] --> I[isSolved]\n    F --> C[countCaptured]\n  end\n  ui --> strategy\n  strategy --> core\n  ui --> core\n```\n\nDie Pfeile zeigen alle nach innen. Die Kernlogik kennt niemanden, die Strategie kennt nur den Kern, die Darstellung darf beide benutzen. Rückwärts gibt es keinen Weg – `flood` kann gar nicht wissen, ob es gerade von einem Test, vom Greedy-Löser oder von einem Klick aufgerufen wurde.\n\n## Was im Großen verschwimmt\n\nNichts an dieser Aufteilung ist neu. Schichten, reine Kernlogik, dünne Ränder – das steht seit Jahren in jedem Architektur-Buch. Interessant ist, warum es im Großen trotzdem so oft verwischt und im Kleinen so klar bleibt. Meine Beobachtung: In großen Systemen gibt es immer einen bequemen Grund für den kleinen Grenzverstoß. Die Validierung landet im Controller, weil dort das Request-Objekt schon herumliegt. Der Rabatt wird im Template ausgerechnet, weil die Zahl nur dort gebraucht wird. Jede einzelne Abkürzung ist verständlich, und in Summe kann nach zwei Jahren niemand mehr sagen, wo die Geschäftsregeln eigentlich stehen.\n\nDie Kata hat diese Ausreden nicht. Wenn ich in `flood` einen Zugzähler einbaue, sehe ich den Fremdkörper sofort, weil die Funktion vorher sieben Zeilen hatte. Genau das meine ich mit Lupe: Das kleine Programm vergrößert nicht die Lösung, sondern den Verstoß.\n\nEin paar Fragen nehme ich aus dem Spiel direkt mit in die Projektarbeit:\n\n- Was ist unser „Brett\" – die eine Datenstruktur, die den führenden Zustand hält – und wie viele Stellen dürfen sie verändern?\n- Welche Operation ist unser „Zug\", und ist sie als Wert greifbar – nachvollziehbar, wiederholbar, rückgängig zu machen?\n- Können wir eine Entscheidung „auf Probe\" durchrechnen, ohne echten Zustand anzufassen?\n- Laufen die Tests für die Regeln ohne Browser, ohne Datenbank, ohne Netz?\n\nWer diese Fragen für ein großes System nicht beantworten kann, hat kein Tooling-Problem. Es fehlt die Grenze, die in der Kata vier Funktionsnamen groß ist.\n\n## Unterm Strich\n\nDie Kata ist bewusst klein geblieben, und das Repository wird auch keine Bibliothek werden – es ist eine Fingerübung mit Befund. Der Befund: Die Trennung von Kernlogik, Strategie und Darstellung ist keine Frage der Systemgröße und keine Frage des Frameworks. Sie ist in achtzig Zeilen ES5 genauso vorhanden oder abwesend wie in einer Anwendung mit achtzigtausend Zeilen. Der Unterschied ist nur, dass man sie in achtzig Zeilen nicht übersehen kann.\n\nDeshalb lohnt sich so ein Spiel gerade dann, wenn man es eigentlich nicht nötig hat. Nicht als Algorithmus-Training – der Flood-Fill ist an einem Abend geschrieben. Sondern als Prüfstand für die eigenen Gewohnheiten: Wo lege ich Zustand ab, wenn mir niemand eine Struktur vorgibt? Schreibe ich zuerst die Oberfläche oder zuerst den Vertrag? Die Antworten, die man sich bei einem Farbflut-Spiel gibt, sind dieselben, die man später unter Termindruck gibt – nur ehrlicher.\n\n## Weiterführende Quellen\n\n- Repository zur Kata: https://github.com/MikeBild/kata-flood-it\n- Flood Fill (Algorithmus-Überblick): https://en.wikipedia.org/wiki/Flood_fill\n- Clifford, Jalsenius, Montanaro, Sach: „The Complexity of Flood Filling Games\" (2010): https://arxiv.org/abs/1001.4420\n- Mocha (Test-Framework): https://mochajs.org/\n- Browserify: http://browserify.org/"},{"locale":"de","translation_key":"mathparser-parser-als-denkwerkzeug","slug":"mathparser-parser-als-denkwerkzeug","title":"MathParser: Parser als Denkwerkzeug","summary":"Ein Rückblick auf ein eigenes Parser-Demo von 2010 zeigt, warum ein handgeschriebener Ausdrucks-Parser auf wenigen Zeilen mehr über Schichten, Struktur und die Grenze zwischen Syntax und Semantik lehrt als manches große Projekt.","tags":["Software","Architektur"],"published_at":"2014-10-12T10:00:00+00:00","updated_at":"2026-07-14T16:36:34.264841+00:00","url":"https://www.mikebild.dev/de/blog/mathparser-parser-als-denkwerkzeug/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/53b6d4b53816ae7bd654936776c86f1058c99e59c8cb22930ae8b6833f1f01a6/mathparser-parser-als-denkwerkzeug-vorlesen.mp3","audio_duration_secs":695,"text":"# MathParser: Parser als Denkwerkzeug\n\nRund 200 Zeilen C#. Mehr braucht ein vollständiger Parser für Rechenausdrücke nicht – Tokenizer, rekursiver Abstieg, Auswertung, Klammern, Punkt-vor-Strich, brauchbare Fehlermeldungen mit Positionsangabe. Ein durchschnittlicher Controller in einem Geschäftssystem erreicht dieselbe Länge und lehrt dabei fast nichts über Softwareentwurf. Die 200 Parser-Zeilen dagegen enthalten drei sauber getrennte Schichten, eine Grammatik als explizites Strukturmodell und eine Grenze zwischen Form und Bedeutung, an der man sich beim Schreiben mindestens einmal die Finger klemmt. Gemessen an Erkenntnis pro Zeile kenne ich wenig, das dichter ist – und es passt in einen Nachmittag.\n\n## Ein vier Jahre altes Demo-Projekt, neu gelesen\n\nDer Anlass für diesen Text ist ein eigenes Repository: [MathParser](https://github.com/MikeBild/MathParser), ein C#-Demo-Projekt von 2010. Eine Visual-Studio-Solution, darin ein Parser-Projekt, eine zweite Variante namens `ClassicMathParser` und ein Testprojekt. Kein Produkt, keine Bibliothek für andere – ein Demo, geschrieben, um die Sache einmal selbst durchdrungen zu haben.\n\nVier Jahre später habe ich es wieder aufgemacht, eigentlich nur, um aufzuräumen. Hängen geblieben bin ich an etwas anderem: Der Code stellt Fragen, die ich 2010 gar nicht gesehen habe. Warum liegen da zwei Varianten nebeneinander? Warum wertet der Parser sofort aus, statt erst eine Struktur zu bauen? Warum steckt die Behandlung des Minuszeichens genau dort, wo sie steckt? Alte eigene Projekte sind darin unbequem ehrlich: Man diskutiert mit einem früheren Ich, das sich nicht mehr herausreden kann.\n\nGenau deshalb lohnt sich der Rückblick als Artikel. Nicht weil das Repository besonders wäre – sondern weil das Thema als Denkwerkzeug besser altert als die meisten Frameworks jener Zeit.\n\n## Warum ein regulärer Ausdruck hier nicht reicht\n\nDer erste Reflex bei „Rechenausdruck parsen“ ist in Code-Reviews immer wieder derselbe: ein regulärer Ausdruck, vielleicht zwei, dazu ein `Split` auf Operatoren. Für `2+3*4` sieht das kurz sogar gut aus. Für `(1+2)*(3-(4/2))` bricht es zusammen, und zwar nicht wegen handwerklicher Fehler, sondern grundsätzlich: Reguläre Ausdrücke können nicht zählen. Verschachtelte Klammern verlangen ein Gedächtnis über die Tiefe der Verschachtelung, und genau das gibt ein regulärer Ausdruck vom Modell her nicht her. Man kann das theoretisch begründen – reguläre gegen kontextfreie Sprachen –, aber praktisch reicht ein Blick auf die Klammern: Wer `(((` liest, muss sich merken, dass noch dreimal `)))` folgen muss.\n\nMir ist dabei 2010 zum ersten Mal aufgefallen, dass die Wahl des Werkzeugs eine Aussage über die Struktur des Problems ist. Ein regulärer Ausdruck behauptet: „Diese Eingabe ist flach.“ Ein Parser mit Rekursion behauptet: „Diese Eingabe ist ein Baum.“ Rechenausdrücke sind Bäume – `1+2*3` hat eine innere Gliederung, die man der Zeichenkette nicht ansieht. Wer das Falsche behauptet, bezahlt später mit Sonderfällen.\n\n## Drei Schichten, drei Verträge\n\nEin Ausdrucks-Parser zerfällt fast von selbst in drei Schichten, und jede hat einen klaren Vertrag:\n\n- Der Tokenizer macht aus einer Zeichenkette einen Strom von Symbolen: Zahlen, Operatoren, Klammern. Er kennt Zeichen, aber keine Struktur.\n- Der Parser prüft, ob die Symbolfolge der Grammatik entspricht, und baut daraus die Struktur. Er kennt Struktur, aber keine Bedeutung.\n- Die Auswertung gibt der Struktur eine Bedeutung: Sie rechnet. Erst hier existieren Begriffe wie „Ergebnis“ oder „Division durch null“.\n\n```mermaid\nflowchart LR\n  A[\"Eingabe<br/>(1+2)*3\"] --> B[\"Tokenizer<br/>Zeichen zu Symbolen\"]\n  B --> C[\"Token-Strom<br/>( 1 + 2 ) * 3\"]\n  C --> D[\"Parser<br/>rekursiver Abstieg\"]\n  D --> E[\"Struktur<br/>Baum oder direkter Wert\"]\n  E --> F[\"Auswertung<br/>Bedeutung, Ergebnis\"]\n```\n\nDas klingt nach Lehrbuch, hat aber eine sehr praktische Pointe: Jede Schicht kann man einzeln testen, einzeln ersetzen und einzeln erklären. Genau dafür ist in der Solution ein eigenes Testprojekt vorgesehen, und die Tests für den Tokenizer wissen nichts von Grammatik – sie prüfen nur, dass aus `\"12.5+\"` die Symbole `12.5` und `+` werden. Diese Art von Trennung predigt man in großen Systemen ständig; im Parser ist sie kein Vorsatz, sondern die einzig bequeme Bauweise. Das ist der erste Grund, warum ich das Thema ein Denkwerkzeug nenne: Es macht ein Architekturprinzip erlebbar, statt es zu behaupten.\n\n## Die Grammatik zwingt zum Nachdenken über Struktur\n\nBevor der eigentliche Parser entsteht, steht die Grammatik – bei mir damals als EBNF-Skizze auf einem Zettel, in dieser Form:\n\n```text\nExpression := Term   { (\"+\" | \"-\") Term }\nTerm       := Factor { (\"*\" | \"/\") Factor }\nFactor     := Number | \"(\" Expression \")\" | \"-\" Factor\n```\n\nDrei Zeilen, und die interessanteste Eigenschaft steht nirgends explizit: die Operator-Rangfolge. Punkt-vor-Strich ist keine Regel, die irgendwo per `if` geprüft wird – sie steckt in der Schichtung der Grammatik. `Expression` besteht aus `Term`-Bausteinen, `Term` aus `Factor`-Bausteinen. Weil `*` und `/` eine Ebene tiefer gebunden werden als `+` und `-`, binden sie automatisch stärker. Die Klammer wiederum springt von ganz unten zurück nach ganz oben: Ein `Factor` darf eine komplette `Expression` enthalten. Das ist die Rekursion, an der der reguläre Ausdruck vorhin gescheitert ist, hier in einer einzigen Zeile.\n\nBeim Wiederlesen 2014 finde ich das immer noch bemerkenswert: Rangfolge als Struktur statt als Bedingung. Terence Parr behandelt genau diese Denkweise in „Language Implementation Patterns“ von 2010 ausführlich, und Douglas Crockford zeigt in seinem Essay „Top Down Operator Precedence“ von 2007 einen alternativen Weg, bei dem die Rangfolge als Bindungsstärke an den Operatoren selbst hängt. Beide Wege führen zum Ziel; wer beide einmal nachgebaut hat, versteht danach besser, was „Struktur ausdrücken“ überhaupt heißt.\n\n## Rekursiver Abstieg in C#\n\nDie Grammatik übersetzt sich fast mechanisch in Code – pro Regel eine Methode. Zuerst der Tokenizer, hier bewusst schlicht gehalten:\n\n```csharp\npublic enum TokenType { Number, Plus, Minus, Star, Slash, LeftParen, RightParen, End }\n\npublic sealed class Tokenizer\n{\n    private readonly string _input;\n    private int _position;\n\n    public Tokenizer(string input) { _input = input; }\n\n    public Token Next()\n    {\n        while (_position < _input.Length && char.IsWhiteSpace(_input[_position]))\n            _position++;\n\n        if (_position >= _input.Length)\n            return new Token(TokenType.End, 0, _position);\n\n        char current = _input[_position];\n\n        if (char.IsDigit(current))\n        {\n            int start = _position;\n            while (_position < _input.Length &&\n                   (char.IsDigit(_input[_position]) || _input[_position] == '.'))\n                _position++;\n\n            double value = double.Parse(\n                _input.Substring(start, _position - start),\n                CultureInfo.InvariantCulture);\n\n            return new Token(TokenType.Number, value, start);\n        }\n\n        _position++;\n        switch (current)\n        {\n            case '+': return new Token(TokenType.Plus, 0, _position - 1);\n            case '-': return new Token(TokenType.Minus, 0, _position - 1);\n            case '*': return new Token(TokenType.Star, 0, _position - 1);\n            case '/': return new Token(TokenType.Slash, 0, _position - 1);\n            case '(': return new Token(TokenType.LeftParen, 0, _position - 1);\n            case ')': return new Token(TokenType.RightParen, 0, _position - 1);\n        }\n\n        throw new FormatException(\n            string.Format(\"Unexpected character '{0}' at position {1}.\", current, _position - 1));\n    }\n}\n```\n\nZwei Kleinigkeiten mit großer Wirkung: `CultureInfo.InvariantCulture`, weil `double.Parse` auf einer deutschen Maschine sonst das Komma erwartet und `1.5` still zu `15` macht – ein Fehler, den ich nicht im Parser-Demo, aber in echten Systemen mehr als einmal gejagt habe. Und die Positionsangabe im Token, denn ohne sie kann später keine Schicht eine Fehlermeldung erzeugen, die dem Anwender die Stelle zeigt.\n\nDer Parser selbst folgt der Grammatik Zeile für Zeile:\n\n```csharp\npublic sealed class Parser\n{\n    private readonly Tokenizer _tokenizer;\n    private Token _current;\n\n    public Parser(string input)\n    {\n        _tokenizer = new Tokenizer(input);\n        _current = _tokenizer.Next();\n    }\n\n    public double Parse()\n    {\n        double result = ParseExpression();\n        Expect(TokenType.End);\n        return result;\n    }\n\n    // Expression := Term { (\"+\" | \"-\") Term }\n    private double ParseExpression()\n    {\n        double left = ParseTerm();\n        while (_current.Type == TokenType.Plus || _current.Type == TokenType.Minus)\n        {\n            TokenType op = _current.Type;\n            Advance();\n            double right = ParseTerm();\n            left = op == TokenType.Plus ? left + right : left - right;\n        }\n        return left;\n    }\n\n    // Term := Factor { (\"*\" | \"/\") Factor }\n    private double ParseTerm()\n    {\n        double left = ParseFactor();\n        while (_current.Type == TokenType.Star || _current.Type == TokenType.Slash)\n        {\n            TokenType op = _current.Type;\n            Advance();\n            double right = ParseFactor();\n            left = op == TokenType.Star ? left * right : left / right;\n        }\n        return left;\n    }\n\n    // Factor := Number | \"(\" Expression \")\" | \"-\" Factor\n    private double ParseFactor()\n    {\n        if (_current.Type == TokenType.Number)\n        {\n            double value = _current.Value;\n            Advance();\n            return value;\n        }\n\n        if (_current.Type == TokenType.LeftParen)\n        {\n            Advance();\n            double inner = ParseExpression();\n            Expect(TokenType.RightParen);\n            return inner;\n        }\n\n        if (_current.Type == TokenType.Minus)\n        {\n            Advance();\n            return -ParseFactor();\n        }\n\n        throw new FormatException(\n            string.Format(\"Unexpected token at position {0}.\", _current.Position));\n    }\n\n    private void Advance() { _current = _tokenizer.Next(); }\n\n    private void Expect(TokenType type)\n    {\n        if (_current.Type != type)\n            throw new FormatException(\n                string.Format(\"Expected {0} at position {1}.\", type, _current.Position));\n        Advance();\n    }\n}\n```\n\nDas ist rekursiver Abstieg in Reinform: `ParseExpression` ruft `ParseTerm`, `ParseTerm` ruft `ParseFactor`, und `ParseFactor` ruft bei einer Klammer wieder `ParseExpression`. Der Aufruf-Stack der Runtime übernimmt das Klammern-Zählen, das dem regulären Ausdruck gefehlt hat. Man kann Werkzeuge wie ANTLR solche Methoden aus einer Grammatik generieren lassen – für ernsthafte Sprachen würde ich das auch tun. Für das Verstehen ist die Handarbeit durch nichts zu ersetzen.\n\n## AST oder direkte Auswertung – die Frage, die ich 2010 übersprungen habe\n\nDer gezeigte Parser rechnet sofort: `ParseTerm` liefert ein `double`, nicht einen Knoten. Das ist die kürzeste Variante, und für ein Demo völlig in Ordnung. Beim Wiederlesen fällt mir aber auf, was diese Abkürzung kostet: Parser und Auswertung, eben noch zwei Schichten mit eigenen Verträgen, sind hier zu einer verschmolzen. Wer denselben Ausdruck zweimal mit anderen Variablenwerten rechnen will, muss zweimal parsen. Wer den Ausdruck hübsch formatiert ausgeben, vereinfachen oder in eine andere Sprache übersetzen will, kann es gar nicht – die Struktur wurde ja nie festgehalten, sie existierte nur flüchtig im Aufruf-Stack.\n\nDie Alternative ist ein abstrakter Syntaxbaum: `ParseTerm` liefert dann einen `Node`, etwa `BinaryNode(Star, NumberNode(2), NumberNode(3))`, und eine getrennte `Evaluate`-Methode läuft über den Baum. Mehr Code, mehr Allokationen – aber die Struktur wird zum eigenständigen Wert, mit dem sich weiterarbeiten lässt. In meiner Solution liegen bis heute zwei Projektvarianten nebeneinander, und ich vermute stark, dass der Unterschied genau um diese Frage kreiste; sicher sagen kann ich es nach vier Jahren nicht mehr, und das ist selbst eine Lektion über Demo-Projekte ohne Notizen.\n\nDie allgemeine Form der Frage begegnet mir seither ständig: Werte ich sofort aus oder baue ich erst ein Modell? Ein Import, der Zeile für Zeile direkt in die Datenbank schreibt, ist die direkte Auswertung. Ein Import, der erst ein geprüftes Zwischenmodell baut und es dann anwendet, ist der Baum. Beides ist legitim – aber es sollte eine Entscheidung sein, kein Zufall.\n\n## Dasselbe in ES5, zur Probe\n\nUm zu prüfen, ob die Struktur trägt oder nur ein C#-Idiom ist, habe ich den Kern in JavaScript nachgezogen – gleiches Muster, gleiche Namen:\n\n```javascript\n// Expression := Term { (\"+\" | \"-\") Term }\nfunction parseExpression(state) {\n  var left = parseTerm(state);\n  while (state.current.type === 'Plus' || state.current.type === 'Minus') {\n    var op = state.current.type;\n    advance(state);\n    var right = parseTerm(state);\n    left = op === 'Plus' ? left + right : left - right;\n  }\n  return left;\n}\n```\n\nKein Typsystem, keine Klassen, und trotzdem ist es erkennbar derselbe Parser. Das ist kein Zufall: Die Grammatik ist das Entwurfsdokument, der Code nur ihre Übersetzung. Crockfords Essay treibt das in JavaScript noch weiter und baut damit einen Parser für JavaScript selbst – wer wissen will, was `JSON.parse` oder ein Ausdrucks-Feld in einem Formular innen tun, findet dort die Antwort in erstaunlich wenig Code.\n\n## Die Grenze zwischen Syntax und Semantik wird körperlich\n\nDer Moment, der mir vom Nachmittag 2010 am deutlichsten geblieben ist, hängt am Minuszeichen. `3-2` und `-2` enthalten dasselbe Zeichen, aber zwei verschiedene Dinge: einmal einen binären Operator, einmal ein Vorzeichen. Der Tokenizer kann den Unterschied nicht kennen – er sieht nur ein Zeichen. Entschieden wird im Parser, und zwar über den Kontext: Ein Minus an einer Stelle, an der ein `Factor` erwartet wird, ist ein Vorzeichen; ein Minus nach einem fertigen `Term` ist eine Subtraktion. Die Bedeutung „negieren“ kommt dann noch einmal später, in der Auswertung.\n\nDasselbe gilt für Fehler. `2+*3` scheitert im Parser – ein Syntaxfehler, die Eingabe ist schon als Form ungültig. `2/0` dagegen passiert den Parser anstandslos und scheitert erst in der Auswertung – ein semantischer Fehler, die Form war korrekt, die Bedeutung ist es nicht. Wer beide Fehler in derselben Schicht behandelt, hat die Grenze verwischt; wer sie trennt, bekommt zwei präzise Fehlermeldungen fast geschenkt. Diese Unterscheidung – was ist wohlgeformt, was ist gültig, was ist sinnvoll – trage ich seitdem durch jede Schnittstellen-Diskussion, von der Validierung eines XML-Dokuments bis zur Frage, ob ein Web-Service eine 400 oder eine 422 zurückgeben sollte.\n\n## Was ich daraus mitnehme\n\nUnterm Strich hat mir das Wiederlesen des alten Demos drei Dinge klargemacht. Erstens: Kleine, abgeschlossene Probleme sind die besseren Lehrstücke, weil man sie vollständig durchdringen kann – bei einem Parser gibt es keine Stelle, an der man auf Magie verweisen müsste. Zweitens: Die drei Schichten und die Grammatik-Schichtung sind kein Parser-Spezialwissen, sondern Architektur im Kleinen; die Fragen „wer darf was wissen“ und „wo steckt die Struktur“ sind exakt dieselben wie in jedem größeren System. Drittens: Alte eigene Projekte mit vier Jahren Abstand zu lesen ist eine unterschätzte Übung – die offenen Fragen von damals sind heute sichtbar, und die Antworten von heute wären ohne den damaligen Nachmittag nicht da.\n\nWer noch nie einen Parser geschrieben hat: Ein Nachmittag, ein leeres Projekt, die drei EBNF-Zeilen von oben. Kein Generator, keine Bibliothek, kein Blick in fremden Code. Die 200 Zeilen, die dabei herauskommen, sind vermutlich das dichteste Stück Softwareentwurf, das sich in dieser Zeit lernen lässt.\n\n## Weiterführende Quellen\n\n- Mein Demo-Repository: [github.com/MikeBild/MathParser](https://github.com/MikeBild/MathParser)\n- Douglas Crockford: [Top Down Operator Precedence](https://crockford.com/javascript/tdop/tdop.html) (2007)\n- Terence Parr: [Language Implementation Patterns](https://pragprog.com/titles/tpdsl/language-implementation-patterns/) (Pragmatic Bookshelf, 2010)\n- [ANTLR](http://www.antlr.org/) – Parser-Generator, falls es doch eine echte Grammatik werden soll"},{"locale":"de","translation_key":"state-mutation-auf-streams","slug":"state-mutation-auf-streams","title":"State Mutation auf Streams","summary":"Wer State als Faltung über einen Strom von Events berechnet statt ihn direkt zu ändern, bekommt Undo, Replay und Nachvollziehbarkeit fast geschenkt.","tags":["Software","Reactive"],"published_at":"2014-07-12T10:00:00+00:00","updated_at":"2026-07-14T16:34:37.713652+00:00","url":"https://www.mikebild.dev/de/blog/state-mutation-auf-streams/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/10228cff5ded199a1c8a218c7f42eb40effd27666bc1bdf43b2d1cff809224c9/state-mutation-auf-streams-vorlesen.mp3","audio_duration_secs":629,"text":"# State Mutation auf Streams\n\n```javascript\nvar events = [\n  { type: 'ItemAdded', sku: 'A-100', qty: 1 },\n  { type: 'ItemAdded', sku: 'B-200', qty: 2 },\n  { type: 'QuantityChanged', sku: 'B-200', qty: 3 },\n  { type: 'ItemRemoved', sku: 'A-100' }\n];\n\nfunction applyEvent(state, event) {\n  var items = {};\n  Object.keys(state.items).forEach(function (sku) {\n    items[sku] = state.items[sku];\n  });\n\n  if (event.type === 'ItemAdded') { items[event.sku] = event.qty; }\n  if (event.type === 'QuantityChanged') { items[event.sku] = event.qty; }\n  if (event.type === 'ItemRemoved') { delete items[event.sku]; }\n\n  return { items: items };\n}\n\nvar cart = events.reduce(applyEvent, { items: {} });\n// -> { items: { 'B-200': 3 } }\n```\n\nVier Events, eine Funktion, ein Aufruf von `Array.prototype.reduce` – und am Ende steht der aktuelle State eines Warenkorbs. Bemerkenswert ist, was in diesem Code alles fehlt: kein `cart.addItem()`, kein Setter, keine Stelle, an der jemand ein Objekt anfasst und verändert. Der Warenkorb wird nicht gepflegt, er wird berechnet. Die Liste der Events ist die eigentliche Wahrheit, der State nur ihre Zusammenfassung.\n\nDas klingt zunächst wie ein Taschenspielertrick, denn natürlich mutiert irgendwo Speicher. Aber die Blickrichtung dreht sich um, und genau diese Drehung finde ich seit einer Weile spannender als jedes neue Framework: State ist hier kein Ding mit Lebenslauf, sondern das Ergebnis einer Faltung über alles, was bisher passiert ist.\n\n## Eine Faltung, kein Setter\n\nIn der funktionalen Welt heißt dieses Muster `foldl` – eine Linksfaltung. Man nimmt einen Startwert, läuft von links nach rechts über eine Sequenz und verrechnet in jedem Schritt den bisherigen Zwischenstand mit dem nächsten Element. `reduce` in JavaScript ist exakt das, seit ES5 im Sprachstandard und 2014 in jedem aktuellen Browser vorhanden; nur für die verbliebenen IE8-Installationen braucht es noch einen es5-shim.\n\nDie Signatur der Schrittfunktion ist dabei der interessante Teil:\n\n```javascript\n// (state, event) -> state\nfunction applyEvent(state, event) { /* ... */ }\n```\n\nZwei Eigenschaften machen diese Funktion wertvoll. Erstens ist sie deterministisch: Dieselbe Event-Folge und derselbe Startwert ergeben immer denselben State. Zweitens ist sie vollständig: Es gibt keinen zweiten Weg, auf dem sich der State ändern könnte, keine Methode, die an der Faltung vorbei ins Objekt greift. Wer wissen will, warum der Warenkorb aussieht, wie er aussieht, liest die Events. Punkt.\n\nOb `applyEvent` intern ein frisches Objekt baut oder den übergebenen State direkt beschreibt, ist dagegen fast schon Geschmackssache. Im Beispiel oben kopiere ich die Items, weil ich Zwischenzustände später noch brauche. In einer engen Schleife über hunderttausend Events darf die Funktion auch mutieren – solange die Mutation in der Faltung eingesperrt bleibt und nach außen nur das Ergebnis sichtbar wird. Die Disziplin steckt nicht in der Immutability der Objekte, sondern in der einen, einzigen Tür, durch die Änderungen gehen.\n\n```mermaid\nflowchart LR\n  S0[Startzustand<br/>leerer Warenkorb] --> F1((applyEvent))\n  E1[ItemAdded<br/>A-100] --> F1\n  F1 --> F2((applyEvent))\n  E2[ItemAdded<br/>B-200] --> F2\n  F2 --> F3((applyEvent))\n  E3[QuantityChanged<br/>B-200] --> F3\n  F3 --> F4((applyEvent))\n  E4[ItemRemoved<br/>A-100] --> F4\n  F4 --> S[aktueller Zustand<br/>als Projektion]\n```\n\n## Ein kleines Experiment von 2012\n\nAuf die Idee bin ich nicht am Reißbrett gekommen. Im Oktober 2012 habe ich ein winziges Repository namens [statemutatejs](https://github.com/MikeBild/statemutatejs) angelegt. Das README besteht aus einer einzigen Zeile: „simple projection functions, alias foldl, that mutate state on a stream of elements\". Mehr Anspruch hatte das Ding nie – ein Experiment, entstanden aus der Frage, wie sich Projektionsfunktionen anfühlen, wenn man sie konsequent als Faltung über einen Strom schreibt statt als Methoden an einem Objekt.\n\nIch erwähne das nicht, weil daraus eine Bibliothek geworden wäre, die irgendjemand einsetzen sollte. Sondern weil mir beim Herumprobieren etwas aufgefallen ist, das ich damals nur halb verstanden habe: Sobald die Schrittfunktion vom Container getrennt ist, wird austauschbar, worüber gefaltet wird. Ein Array, ein Node-Stream, eine Observable-Sequenz – die Projection-Function bleibt wörtlich dieselbe. Das eine Wort „foldl\" im README war im Rückblick der ganze Punkt des Experiments.\n\nZwei Jahre später sehe ich dasselbe Muster an immer mehr Stellen wieder, und es lohnt sich, die Varianten einmal nebeneinanderzulegen.\n\n## Dasselbe Muster auf Node-Streams\n\nSeit Node 0.10 gibt es die überarbeitete Stream-Schnittstelle – streams2 – und mit ihr den `objectMode`, in dem ein Stream keine Buffer, sondern beliebige Objekte transportiert. Damit löst sich die Faltung vom Array: Die Events müssen nicht mehr vollständig im Speicher liegen, sie dürfen eintreffen, wann immer sie wollen.\n\n```javascript\nvar stream = require('stream');\nvar util = require('util');\n\nfunction StateFold(applyFn, initialState) {\n  stream.Writable.call(this, { objectMode: true });\n  this.state = initialState;\n  this.applyFn = applyFn;\n}\nutil.inherits(StateFold, stream.Writable);\n\nStateFold.prototype._write = function (event, encoding, done) {\n  this.state = this.applyFn(this.state, event);\n  done();\n};\n\n// same projection function as before, no changes needed\nvar fold = new StateFold(applyEvent, { items: {} });\neventSource.pipe(fold);\n\nfold.on('finish', function () {\n  console.log(fold.state); // -> { items: { 'B-200': 3 } }\n});\n```\n\nDas ist bewusst unspektakulär: ein `Writable` im Objektmodus, das pro Event einmal die Schrittfunktion aufruft und den Zwischenstand behält. `applyEvent` ist unverändert die Funktion aus dem ersten Beispiel. Ob `eventSource` eine Datei mit zeilenweise serialisierten JSON-Events ist, ein TCP-Socket oder ein Parser, der Logzeilen in Objekte übersetzt, spielt für die Faltung keine Rolle. Die Backpressure-Mechanik von streams2 sorgt nebenbei dafür, dass ein langsamer Konsument die Quelle bremst, statt Events im Speicher zu stapeln.\n\nIn einem Projekt Anfang des Jahres haben wir genau so eine Auswertung über mehrere Gigabyte an Protokolldaten gebaut: Events aus Dateien lesen, durch eine Handvoll Projektionsfunktionen falten, fertig. Kein Cache, keine Datenbank für die Auswertung selbst – nur Streams und Faltungen. Der Code war so klein, dass die Diskussion im Review länger dauerte als das Schreiben.\n\n## scan() macht die Zwischenzustände sichtbar\n\n`reduce` liefert am Ende genau einen Wert. Auf einem endlosen Strom – Benutzereingaben, Sensordaten, Kursdaten – gibt es aber kein Ende und damit auch kein einzelnes Ergebnis. Die Reactive Extensions für JavaScript, aktuell in Version 2.x, haben dafür den Operator `scan`: dieselbe Faltung, nur dass jeder Zwischenzustand als Element eines neuen Stroms nach außen gereicht wird.\n\n```javascript\nvar cartStates = cartEvents\n  .scan({ items: {} }, applyEvent);\n\ncartStates.subscribe(function (state) {\n  renderCart(state); // every intermediate state, as it happens\n});\n```\n\nWieder dieselbe Projection-Function, kein Zeichen geändert. Bacon.js bietet mit `scan` denselben Operator an, falls einem der Rx-Stil nicht liegt. Interessant wird das im Browser: Wenn jede Benutzerinteraktion ein Event ist und der Anwendungszustand ein `scan` darüber, dann ist die Oberfläche zu jedem Zeitpunkt eine Funktion des bisherigen Event Stream. Ich habe das in einem Prototyp für ein Dashboard ausprobiert, und die ungewohnteste Erfahrung war dabei gar nicht der Code. Es war das Debugging: Statt im Debugger nach dem Objekt zu suchen, das gerade kaputtging, habe ich die letzten zwanzig Events ausgegeben und den Fehler in der Projection-Function gefunden. Der kaputte State war kein Rätsel mehr, sondern das nachvollziehbare Ergebnis einer konkreten Event-Folge.\n\n## Undo, Replay, Nachvollziehbarkeit – Nebenprodukte\n\nUnd damit zum eigentlichen Grund, warum mich dieses Muster nicht mehr loslässt. In klassisch mutierendem Code sind bestimmte Anforderungen teuer, weil der alte State beim Ändern zerstört wird. Wer Undo will, muss Schnappschüsse anlegen oder inverse Operationen pflegen. Wer wissen will, wie es zu einem State kam, braucht Logging, die jemand vorher eingebaut haben muss. In der Faltungswelt fallen diese Anforderungen einfach ab:\n\n```javascript\nfunction stateAt(events, count) {\n  return events.slice(0, count).reduce(applyEvent, { items: {} });\n}\n\nvar current = stateAt(events, events.length);     // state now\nvar undone = stateAt(events, events.length - 1);  // state before the last event\nvar initial = stateAt(events, 0);                 // start over\n```\n\nUndo ist eine Faltung über alle Events bis auf das letzte. Replay ist dieselbe Faltung noch einmal, gern auch schrittweise als Zeitraffer. Und die Nachvollziehbarkeit steckt in der Event-Liste selbst – sie ist das Protokoll, das man sonst mühsam nachrüstet.\n\n```mermaid\nflowchart TB\n  L[Ereignisliste<br/>e1, e2, e3, e4] --> A[Faltung über alle<br/>= aktueller Zustand]\n  L --> B[Faltung über e1 bis e3<br/>= Undo]\n  L --> C[Faltung Schritt für Schritt<br/>= Replay / Zeitreise]\n  L --> D[Liste selbst lesen<br/>= Audit-Protokoll]\n```\n\nEin paar Dinge bekommt man auf diesem Weg praktisch geschenkt:\n\n- Undo und Redo, ohne inverse Operationen zu schreiben\n- Reproduktion von Fehlern, indem man die aufgezeichnete Event-Folge erneut faltet\n- neue Sichten auf alte Daten durch eine zweite Projection-Function über dieselben Events\n- Tests, die nur aus einer Event-Liste und einem erwarteten Endzustand bestehen\n\nDer letzte Punkt ist im Alltag der unterschätzteste. Ein Test für `applyEvent` braucht keinen Mock, keine Datenbank, kein Setup – Eingabeliste rein, Endzustand vergleichen, fertig.\n\n## Vom Spielzeug zur Architekturfrage\n\nNeu ist die Idee natürlich nicht. Martin Fowler hat das Muster schon 2005 unter dem Namen Event Sourcing beschrieben: Der Anwendungszustand wird nicht direkt gespeichert, sondern aus einer Folge von Events rekonstruiert. Greg Young hat es in seinen Arbeiten zu CQRS weitergedacht – die Trennung von Schreibseite, die Events erzeugt, und Leseseite, die Projections darüber baut. Was mir mein kleines JavaScript-Experiment gezeigt hat, ist vor allem, wie kurz der Weg vom `reduce`-Einzeiler zu dieser Architekturfrage ist: Sobald man Events als die Wahrheit behandelt und State als Projection, hat man Event Sourcing im Kleinen bereits gebaut – nur eben im Speicher statt in einer Datenbank.\n\nIch will die Idee dabei nicht größer reden, als sie ist. Wer die Faltung zur Systemarchitektur macht, kauft sich echte Probleme ein. Die Event-Liste wächst unbegrenzt, also braucht es irgendwann Schnappschüsse, damit nicht jeder Start Millionen Events durchfaltet. Die Struktur der Events ändert sich mit der Anwendung, alte Events müssen aber lesbar bleiben – diese Schema-Evolution begleitet einen dauerhaft und ist alles andere als eine Fußnote. Und für einen simplen Verwaltungsdialog, dessen Historie niemanden interessiert, ist ein direktes Update schlicht das ehrlichere Werkzeug. Events aufzuheben lohnt sich dort, wo die Geschichte fachlich etwas bedeutet: Bestellungen, Konten, Verträge, Messreihen.\n\nDeshalb halte ich es im Moment so: im Kleinen konsequent, im Großen vorsichtig. Innerhalb eines Moduls Events zu falten kostet fast nichts und zwingt zu einer sauberen Trennung von „was ist passiert\" und „was folgt daraus\". Ob daraus ein persistenter Ereignisspeicher fürs ganze System werden soll, ist eine deutlich größere Entscheidung, die man nicht nebenbei im Refactoring trifft.\n\n## Was ich daraus mitnehme\n\nDas README von statemutatejs war eine Zeile lang, und trotzdem hat mich das Experiment mehr gelehrt als manches Framework-Handbuch. Die Lehre ist unscheinbar: Wenn Änderungen als Werte vorliegen – als Events, die man aufheben, ansehen und erneut abspielen kann –, dann ist der aktuelle State nur noch eine von vielen möglichen Auswertungen. `reduce` über ein Array, ein `Writable` im Objektmodus, `scan` in RxJS oder Bacon.js: viermal dieselbe Faltung, viermal dieselbe Projection-Function.\n\nSeitdem stelle ich in Code-Reviews eine Frage öfter als früher: Wo entsteht dieser State, und könnten wir die Änderungen stattdessen als Events festhalten? Meistens lautet die Antwort „lohnt hier nicht\", und das ist in Ordnung. Aber in den Fällen, in denen jemand gerade eine Undo-Funktion, ein Audit-Log oder den Abgleich zweier Datenstände von Hand baut, zeigt die Frage fast immer denselben Ausweg: Die gewünschten Eigenschaften stecken schon in den Events. Man muss sie nur falten.\n\n## Weiterführende Quellen\n\n- [MikeBild/statemutatejs](https://github.com/MikeBild/statemutatejs) – das erwähnte Experiment von Oktober 2012\n- [Martin Fowler: Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html) – die Musterbeschreibung von 2005\n- [Node.js 0.10 Stream-API](https://nodejs.org/docs/latest-v0.10.x/api/stream.html) – streams2 inklusive objectMode\n- [MDN: Array.prototype.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) – die Faltung im Sprachstandard\n- [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) – RxJS mit dem scan-Operator"},{"locale":"de","translation_key":"http-apis-klein-stabil-lesbar","slug":"http-apis-klein-stabil-lesbar","title":"HTTP-APIs: klein, stabil, lesbar","summary":"Was der Heroku HTTP API Design Guide taugt, wenn man ihn an eigenen APIs spiegelt – und warum wenige Ressourcen, ein Versionsversprechen und selbsterklärende Fehler mehr bewirken als jedes Framework.","tags":["Software","Architektur"],"published_at":"2014-06-24T10:00:00+00:00","updated_at":"2026-07-14T16:07:55.065953+00:00","url":"https://www.mikebild.dev/de/blog/http-apis-klein-stabil-lesbar/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/0eb071f38aed43b3253c1500f4a27456b2bfa7e8a827019aaf301018da1235cc/http-apis-klein-stabil-lesbar-vorlesen.mp3","audio_duration_secs":676,"text":"# HTTP-APIs: klein, stabil, lesbar\n\nEine HTTP-API, die alle paar Wochen ihre Form ändert, erzieht ihre Clients – nur leider in die falsche Richtung. Nach dem zweiten Bruch baut jedes Client-Team eine Abwehrschicht: einen Mapper, der Felder umbenennt, bevor der Rest des Codes sie zu sehen bekommt. Ein Try/Catch um jeden Datumsparser, weil das Zeitformat schon zweimal gewechselt hat. Prüfungen auf fehlende Felder, auf drei verschiedene Fehlerformate, auf Statuscodes, die mal so und mal so gemeint sind. Nach einem halben Jahr besteht der Client zur Hälfte aus Code, der keine Fachlichkeit abbildet, sondern Misstrauen. Und weil jedes Team diese Schicht für sich erfindet, gibt es sie am Ende viermal, in vier Varianten, mit vier verschiedenen Fehlern.\n\nDie Kosten entstehen also nicht dort, wo die API gebaut wird, sondern verteilt über alle, die sie benutzen. Das macht sie so leicht zu übersehen.\n\nIm Mai hat Heroku seinen HTTP API Design Guide veröffentlicht – ein schmales Dokument auf GitHub, destilliert aus der Arbeit an der Heroku Platform API. Ich habe das Repository Ende Mai geforkt und seitdem Punkt für Punkt an APIs gespiegelt, die ich selbst betreue oder im Review sehe. Nicht alles davon würde ich unterschreiben. Aber die Grundhaltung trifft ziemlich genau das, was ich in eigenen Projekten als tragfähig erlebt habe: Eine gute HTTP-API ist klein, stabil und lesbar. Alles andere ist Zubehör.\n\n## Klein: eine Ressource muss sich ihren Platz verdienen\n\nDer Guide sagt es nicht wörtlich, aber es steht zwischen allen Zeilen: wenige Ressourcen, dafür konsequente Konventionen. Ressourcennamen im Plural (`/orders`, nicht `/order` und schon gar nicht `/getOrders`), möglichst flache Pfade, IDs als kleingeschriebene UUIDs, auf jeder Ressource `created_at` und `updated_at` – ohne dass jemand danach fragen muss.\n\nDas klingt banal, ist es aber nicht. In einem Projekt Anfang des Jahres haben wir eine API übernommen, die über sechzig Endpoints hatte – für eine Fachlichkeit, die mit etwa zehn Ressourcen vollständig beschrieben war. Der Rest waren Bequemlichkeits-Endpoints: `/orders/search`, `/orders/latest`, `/ordersWithCustomer`, jeweils entstanden, weil ein Client-Team eine bestimmte Sicht brauchte und der schnellste Weg ein neuer Endpoint war. Jeder dieser Endpoints hatte sein eigenes Antwortformat, seine eigene Vorstellung von Paginierung und seine eigene Lebensdauer. Keiner ließ sich entfernen, weil niemand wusste, wer ihn noch aufrief.\n\nSeitdem gilt bei mir: Ein Endpoint ist eine Verbindlichkeit, kein Feature. Jede Ressource, die ich veröffentliche, muss ich Jahre tragen. Deshalb frage ich vor jedem neuen Pfad zuerst, ob sich der Anwendungsfall nicht über eine bestehende Ressource plus Query-Parameter ausdrücken lässt. Meistens lautet die Antwort ja – und die API bleibt klein genug, dass ein neuer Entwickler sie an einem Vormittag versteht.\n\nSo sieht der Normalfall aus, auf den sich alles andere beziehen sollte:\n\n```http\nGET /orders/01234567-89ab-cdef-0123-456789abcdef HTTP/1.1\nHost: api.example.com\nAccept: application/json\n\nHTTP/1.1 200 OK\nContent-Type: application/json; charset=utf-8\n\n{\n  \"id\": \"01234567-89ab-cdef-0123-456789abcdef\",\n  \"state\": \"confirmed\",\n  \"total\": 4990,\n  \"currency\": \"EUR\",\n  \"created_at\": \"2014-06-20T08:30:00Z\",\n  \"updated_at\": \"2014-06-21T10:15:00Z\"\n}\n```\n\nNichts daran ist spektakulär. Genau das ist der Punkt: Wer diese eine Antwort gesehen hat, kann die Form jeder anderen Ressource der API erraten. Diese Vorhersagbarkeit ist das eigentliche Produkt.\n\n## Lesbar: der Fehler erklärt sich selbst\n\nDer Teil des Guides, den ich sofort übernommen habe, ist das Fehlerformat. Heroku schlägt für jeden Fehler denselben Body vor: eine maschinenlesbare `id`, eine menschenlesbare `message` und eine `url`, die auf weiterführende Dokumentation zeigt.\n\n```json\n{\n  \"id\": \"rate_limit\",\n  \"message\": \"Account reached its API rate limit.\",\n  \"url\": \"https://docs.example.com/rate-limits\"\n}\n```\n\nWarum mich das überzeugt: Es bedient beide Leser gleichzeitig. Der Client-Code verzweigt über die `id`, ohne Strings zu parsen. Der Mensch, der nachts um zwei im Log liest, versteht die `message`, ohne die Doku zu öffnen. Und die `url` beendet die Raterei, wenn er sie doch öffnen muss.\n\nDer Kontrast zur Praxis ist deutlich. Mir ist in Reviews immer wieder dieselbe Sammlung begegnet: mal ein HTML-Fehlertext vom Proxy, mal `{\"error\": true}`, mal ein Stacktrace im Klartext, mal Status 200 mit einer Fehlermeldung im Body. Jede dieser Varianten zwingt den Client, einen weiteren Sonderfall in seine Abwehrschicht zu schrauben – womit wir wieder beim Anfang wären.\n\nMit Express 4, das seit April draußen ist, lässt sich ein einheitliches Fehlerformat mit sehr wenig Code erzwingen. Der Kern ist eine kleine Fabrik für Fehlerobjekte und genau ein zentraler Error-Handler, der als letzte Middleware registriert wird:\n\n```javascript\n// errors.js - one error shape for the whole API\nfunction apiError(status, id, message, url) {\n  var err = new Error(message);\n  err.status = status;\n  err.id = id;\n  err.url = url;\n  return err;\n}\n\napp.get('/orders/:id', function (req, res, next) {\n  store.findOrder(req.params.id, function (err, order) {\n    if (err) { return next(err); }\n    if (!order) {\n      return next(apiError(404, 'order_not_found',\n        'No order exists with the given id.',\n        'https://docs.example.com/errors#order_not_found'));\n    }\n    res.json(order);\n  });\n});\n\n// registered last, catches everything\napp.use(function (err, req, res, next) {\n  res.status(err.status || 500).json({\n    id: err.id || 'internal_error',\n    message: err.message || 'An unexpected error occurred.',\n    url: err.url || 'https://docs.example.com/errors'\n  });\n});\n```\n\nDer Side Effect, den ich nicht erwartet hatte: Die Liste der Fehler-IDs wird zu einem Katalog der Fachlichkeit. Wenn dort `order_not_found`, `order_already_shipped` und `payment_declined` stehen, liest sich das wie eine Kurzfassung der Domäne. Eine API, deren Fehler sich so lesen, braucht deutlich weniger Prosa-Dokumentation – die URL erzählt die Fachlichkeit im Guten, die Fehler-ID erzählt sie im Schlechten.\n\n## Stabil: Versionierung ist ein Versprechen, kein Header\n\nBeim Thema Versionierung bin ich mit dem Guide nur halb einverstanden. Heroku empfiehlt, die Version über den Accept-Header zu verlangen – `Accept: application/vnd.heroku+json; version=3` – und Anfragen ohne explizite Version abzulehnen. Das ist die sauberste Form: Die URL bezeichnet die Ressource, der Header verhandelt die Repräsentation. So war HTTP gedacht.\n\nNur: In den Projekten, die ich kenne, gewinnt fast immer die Version in der URL, also `/v1/orders`. Und zwar nicht aus Unwissenheit, sondern aus handfesten Gründen. Ein curl-Aufruf zum Nachstellen eines Fehlers braucht keinen zusätzlichen Header. Der Access-Log zeigt auf einen Blick, welche Version ein Client benutzt – wichtig, wenn man wissen will, ob `/v1` endlich abgeschaltet werden kann. Proxies und Router können nach Pfad-Präfix trennen, ohne Header zu inspizieren. Und im Browser lässt sich eine GET-Antwort ohne Werkzeug ansehen. Der Accept-Header ist eleganter; die URL ist ehrlicher gegenüber dem Alltag von Betrieb und Fehlersuche. Ich habe beides im Einsatz und würde heute keinem Team die Header-Variante aufdrängen, das seine Logs liebt.\n\nWichtiger als der Transportweg der Versionsnummer ist ohnehin etwas anderes: was die Version verspricht. Eine Versionsnummer ist die Zusage, dass innerhalb dieser Version nichts bricht. Konkret heißt das für mich:\n\n- Neue Felder und neue Ressourcen dürfen jederzeit dazukommen – Clients müssen Unbekanntes ignorieren.\n- Bestehende Felder ändern weder Namen noch Typ noch Bedeutung.\n- Fehler-IDs und Statuscodes für bestehende Fälle bleiben, wie sie sind.\n- Wird eines davon verletzt, gibt es eine neue Version – und die alte läuft weiter, bis nachweislich niemand sie mehr aufruft.\n\nDiese Entscheidungslogik ist klein genug für ein Diagramm, und ich hänge sie inzwischen tatsächlich an die Wand, wenn ein Team über eine Änderung diskutiert:\n\n```mermaid\nflowchart TD\n  A[Änderung an der API] --> B{Nur additiv?<br/>Neue Felder, neue Ressourcen}\n  B -- ja --> C[Gleiche Version<br/>Clients laufen unverändert weiter]\n  B -- nein --> D{Ändert sich Name, Typ oder<br/>Bedeutung von Bestehendem?}\n  D -- nein --> C\n  D -- ja --> E[Neue Version<br/>alte Version läuft weiter,<br/>bis Logs sie für tot erklären]\n```\n\nDer unbequeme Teil steht im letzten Kasten. Eine neue Version auszurufen ist billig; die alte am Leben zu halten ist die eigentliche Arbeit. Wer das Versprechen nicht halten will, sollte lieber gar keine Versionsnummer vergeben – eine `/v1`, die trotzdem alle zwei Monate bricht, ist schlimmer als gar keine, weil sie Verlässlichkeit signalisiert, die es nicht gibt.\n\n## Zeitstempel und Paginierung – die unterschätzten Kleinigkeiten\n\nZwei Guide-Punkte wirken auf den ersten Blick wie Fußnoten, haben mir aber mehr Debugging-Stunden erspart als manche Architekturentscheidung.\n\nErstens: Zeiten ausschließlich als ISO 8601 in UTC, also `2014-06-20T08:30:00Z`. Ich habe in einem Altsystem einmal drei Zeitformate in derselben API gehabt – Unix-Timestamps in Sekunden, Unix-Timestamps in Millisekunden und ein deutsches Datumsformat mit Punkt. Der Fehler, der daraus entstand, war ein Klassiker: Ein Client interpretierte Sekunden als Millisekunden, und plötzlich lagen alle Bestellungen im Januar 1970. Seit alles konsequent ISO 8601 mit `Z` am Ende ist, ist diese ganze Fehlerklasse verschwunden. Das Format ist sortierbar, eindeutig, und jeder Parser dieser Welt kennt es.\n\nZweitens: Paginierung. Der Guide verweist auf Herokus Range-Header – der Client fragt mit `Range` einen Ausschnitt an, der Server antwortet mit `206 Partial Content` und nennt im `Next-Range`-Header den Schlüssel für die nächste Seite:\n\n```bash\ncurl -i https://api.example.com/orders \\\n  -H \"Range: id 01234567-89ab-cdef-0123-456789abcdef..; max=200\"\n\n# HTTP/1.1 206 Partial Content\n# Content-Range: id 01234567-...;\n# Next-Range: id 89abcdef-...; max=200\n```\n\nTechnisch gefällt mir daran vor allem eines: Es ist Cursor-Paginierung. Der Client blättert ab einem Schlüssel weiter, nicht ab einem Offset – und bekommt deshalb keine Duplikate oder Lücken, wenn zwischen zwei Seiten neue Datensätze entstehen. Das klassische `?page=3` hat genau dieses Problem, und es fällt erst in Produktion auf, wenn die Daten sich schnell genug ändern.\n\nTrotzdem bin ich beim Transportweg wieder pragmatischer als der Guide. Range-Header für etwas anderes als Bytes sind ungewohnt, viele HTTP-Bibliotheken machen den Zugriff auf Antwort-Header umständlicher als nötig, und im Team muss man die Konvention jedem neu erklären. In eigenen APIs bin ich bei Cursor-Paginierung über Query-Parameter gelandet – `?limit=200&after=<id>` – mit einem `next`-Verweis im Body. Dieselbe Eigenschaft, gewöhnlichere Mechanik. Die Idee des Guides übernehme ich, seine Syntax nicht.\n\nGenau das ist übrigens mein Verhältnis zu dem Dokument insgesamt. Es ist eine Sammlung von Entscheidungen, die ein Team für seine Plattform getroffen und öffentlich begründet hat – kein Standard, kein Gesetz. Der Wert liegt darin, dass man beim Lesen für jede eigene API gezwungen ist, Farbe zu bekennen: übernehmen, abweichen, aber nie wieder „haben wir uns nie überlegt“.\n\n## Was ich daraus mitnehme\n\nWer 2014 eine HTTP-API baut, hat das Formatproblem im Grunde gelöst – JSON hat gewonnen, die Verben stehen im RFC, und mit HAL und JSON Schema gibt es lebhafte Diskussionen darüber, wie viel Hypermedia eine API vertragen sollte. Das eigentliche Problem ist sozialer Natur: Eine API ist ein Versprechen an Leute, deren Code man nie sehen wird. Klein, stabil und lesbar sind die drei Eigenschaften, die dieses Versprechen einlösbar machen. Klein, damit man es überblicken kann. Stabil, damit man ihm trauen kann. Lesbar, damit man es ohne Dolmetscher versteht.\n\nDer Heroku-Guide ist dafür die beste Checkliste, die mir bisher begegnet ist – gerade weil er so kurz ist und weil hinter jedem Punkt erkennbar eine echte Plattform steht. Mein Fork liegt seit Ende Mai in meinem GitHub-Konto, und die nützlichste Übung war nicht das Lesen, sondern das Spiegeln: jede eigene API daneben legen und Punkt für Punkt notieren, wo sie abweicht und ob es dafür einen Grund gibt. Bei mir blieben zwei bewusste Abweichungen übrig – Version in der URL, Paginierung per Query-Parameter – und eine unangenehm lange Liste von Stellen, an denen die Abweichung schlicht Nachlässigkeit war. Die arbeite ich gerade ab. Die Clients werden es nicht bemerken, und genau daran erkennt man, dass es die richtige Arbeit ist.\n\n## Weiterführende Quellen\n\n- HTTP API Design Guide (Original von interagent/Heroku): https://github.com/interagent/http-api-design\n- Mein Fork des Guides: https://github.com/MikeBild/http-api-design\n- Heroku Platform API Reference (die API, aus der der Guide entstand): https://devcenter.heroku.com/articles/platform-api-reference\n- RFC 2616 – Hypertext Transfer Protocol HTTP/1.1: https://datatracker.ietf.org/doc/html/rfc2616\n- Express: http://expressjs.com/"},{"locale":"de","translation_key":"was-ich-an-elixir-gesucht-habe","slug":"was-ich-an-elixir-gesucht-habe","title":"Was ich an Elixir gesucht habe","summary":"Nicht die Syntax hat mich zu Elixir gebracht, sondern das Ausführungsmodell der Erlang-VM – Prozesse, Messages und Supervisors, betrachtet mit JavaScript- und C#-Augen.","tags":["Software","Architektur"],"published_at":"2014-05-12T10:00:00+00:00","updated_at":"2026-07-14T16:06:01.869581+00:00","url":"https://www.mikebild.dev/de/blog/was-ich-an-elixir-gesucht-habe/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/72ad512e84aa2d8c31db90f71fc8b1a3ecc2ebbfdf97e63afc9cf6b26735c52e/was-ich-an-elixir-gesucht-habe-vorlesen.mp3","audio_duration_secs":713,"text":"# Was ich an Elixir gesucht habe\n\nEine neue Programmiersprache probiert man aus, weil einem die Syntax gefällt – so lautet die übliche Begründung. Kürzere Schreibweisen, elegantere Lambdas, weniger Zeremonie. Diese Begründung halte ich für falsch herum. An Syntax gewöhnt man sich in zwei Wochen, sie ist der austauschbarste Teil einer Sprache. Interessant wird es dort, wo eine Sprache anders *ausführt*: wie sie Concurrency organisiert, wem Zustand gehört und was passiert, wenn etwas kaputtgeht.\n\nGenau deshalb liegt seit letztem Herbst ein kleines Elixir-Repository auf meinem GitHub-Konto. Nicht, weil mir das Ruby-artige Gewand der Sprache gefallen hätte – das war mir anfangs beinahe egal –, sondern weil unter diesem Gewand die Erlang-VM arbeitet. Und die beantwortet die drei Fragen von oben radikal anders, als ich es aus meinem Alltag mit JavaScript und C# kenne: Prozesse statt Threads, Messages statt geteiltem Zustand, „let it crash\" statt defensivem try/catch an jeder Ecke.\n\n## Ein Blick über den Zaun, mit Zeitkolorit\n\nDer Zeitpunkt für diesen Blick über den Zaun ist günstig. Im Februar hat Facebook WhatsApp für eine Summe gekauft, über die noch immer alle reden – und plötzlich interessiert sich auch die Management-Etage dafür, dass ein erstaunlich kleines Team dort mehrere hundert Millionen Nutzer bedient. Das Backend: Erlang. Die Zahlen, die seit Jahren aus dieser Ecke kursieren – Millionen gleichzeitiger Verbindungen auf einer einzelnen Maschine –, klangen für mich lange wie Folklore. Jetzt schaut man genauer hin, ich auch.\n\nElixir setzt auf genau dieser Maschine auf. José Valim, vielen aus dem Rails-Umfeld bekannt, baut damit eine Sprache, die auf der Erlang-VM läuft, Erlang-Module direkt aufrufen kann und die Werkzeuge der Plattform erbt. Die Sprache ist noch jung: aktuell Version 0.13, auf dem Weg zu 1.0, mit gelegentlichen Brüchen zwischen den Releases. Dave Thomas schreibt bei den Pragmatic Programmers an „Programming Elixir\", bislang als Beta zu haben. Wer heute Elixir anfasst, fasst also bewusst etwas Unfertiges an – die Plattform darunter ist dagegen seit über zwanzig Jahren im Ernstfall erprobt.\n\n## Ein Repository voller Fragen\n\nMein Einstieg war kein Projekt, sondern eine Sammlung kleiner Versuche: [github.com/MikeBild/tryelixir](https://github.com/MikeBild/tryelixir), begonnen im Oktober, gewachsen in Abendstunden. Kein README, keine Architektur, nur Ordner – jeder Ordner eine Frage, die ich der Sprache stellen wollte:\n\n- `actors` – wie fühlen sich `spawn` und `receive` an, das Handwerkszeug der Prozesse?\n- `bankAccount` – kann ein Prozess allein den Zustand eines Kontos verwalten, ganz ohne Lock?\n- `cowboy` – wie spricht man HTTP auf der Erlang-VM, mit dem Webserver Cowboy?\n- `kataTennis` und `kataTennisFSM` – die bekannte Tennis-Kata, einmal klassisch, einmal als endlicher Automat\n- `leveldb` – wie bindet man eine Bibliothek wie LevelDB an?\n\nMehr behaupte ich über das Repository nicht, denn mehr ist es nicht: ein Experimentierkasten. Aber die Konten-Übung darin taugt gut, um zu zeigen, was mich am Ausführungsmodell gepackt hat.\n\n## Prozesse statt Threads\n\nZunächst der Ausgangspunkt. Ein Bankkonto mit nebenläufigen Zugriffen sieht in meinem C#-Alltag ungefähr so aus – geteilter Zustand, geschützt durch ein Lock:\n\n```csharp\npublic class BankAccount\n{\n    private readonly object _sync = new object();\n    private decimal _balance;\n\n    public void Withdraw(decimal amount)\n    {\n        lock (_sync)\n        {\n            if (_balance < amount)\n                throw new InvalidOperationException(\"insufficient funds\");\n            _balance -= amount;\n        }\n    }\n}\n```\n\nDas funktioniert – solange jeder Zugriff durch dasselbe Lock geht, niemand zwei Locks in unterschiedlicher Reihenfolge nimmt und keine Exception den Zustand halb verändert zurücklässt. In Code-Reviews sind das genau die Stellen, an denen ich am längsten hängen bleibe, und die Fehler, die dort durchrutschen, zeigen sich erst unter Last. In JavaScript stellt sich die Frage anders, aber nicht besser: Ein einzelner Thread mit Callbacks schützt zwar vor Race Conditions im Speicher, dafür blockiert eine einzige teure Berechnung alles andere, und ein nicht abgefangener Fehler reißt den ganzen Node-Prozess mit.\n\nDie Erlang-VM organisiert das Problem grundlegend anders. Ihre Prozesse sind keine Betriebssystem-Threads, sondern winzige, von der VM verwaltete Einheiten: wenige Kilobyte beim Start, jeder mit eigenem Heap und eigener Speicherbereinigung, präemptiv geplant. Hunderttausende davon auf einer Maschine sind normal, nicht heldenhaft. Vor allem aber: Es gibt keinen geteilten Speicher zwischen ihnen. Was ein Prozess weiß, weiß nur er.\n\nDasselbe Konto in Elixir ist ein Prozess, der seinen Kontostand als Argument einer Endlosschleife mit sich trägt:\n\n```elixir\ndefmodule BankAccount do\n  def start(initial_balance) do\n    spawn(fn -> loop(initial_balance) end)\n  end\n\n  defp loop(balance) do\n    receive do\n      {:deposit, amount} ->\n        loop(balance + amount)\n      {:withdraw, amount, caller} when amount <= balance ->\n        send(caller, {:ok, balance - amount})\n        loop(balance - amount)\n      {:withdraw, _amount, caller} ->\n        send(caller, {:error, :insufficient_funds})\n        loop(balance)\n      {:balance, caller} ->\n        send(caller, {:balance, balance})\n        loop(balance)\n    end\n  end\nend\n```\n\nKein Lock, kein `synchronized`, keine `volatile`-Grübelei. Der Kontostand kann gar nicht von zwei Seiten gleichzeitig verändert werden, weil ihn nur ein einziger Prozess besitzt und die Messages aus seiner Mailbox der Reihe nach abarbeitet. Concurrency entsteht nicht durch mehr Threads am selben Speicher, sondern durch mehr Prozesse mit je eigenem Zustand – ein Prozess pro Konto, nicht ein Lock pro Konto.\n\n```mermaid\ngraph LR\n  subgraph SHARED[\"Threads und geteilter Zustand\"]\n    T1[\"Thread 1\"] --> L[\"Lock\"]\n    T2[\"Thread 2\"] --> L\n    L --> MEM[\"gemeinsamer Speicher<br/>balance\"]\n  end\n  subgraph MSG[\"Prozesse und Nachrichten\"]\n    P1[\"Prozess A\"] -- \"{:withdraw, 30}\" --> MB[\"Mailbox\"]\n    P2[\"Prozess B\"] -- \"{:deposit, 50}\" --> MB\n    MB --> ACC[\"BankAccount-Prozess<br/>eigener Zustand: balance\"]\n  end\n```\n\n## Messages statt Aufrufe\n\nVon außen betrachtet ist so ein Konto kein Objekt mit Methoden, sondern eine Adresse, an die man Messages schickt:\n\n```elixir\naccount = BankAccount.start(100)\n\nsend(account, {:deposit, 50})\nsend(account, {:withdraw, 200, self()})\n\nreceive do\n  {:ok, new_balance} ->\n    IO.puts \"withdrawal ok, new balance: #{new_balance}\"\n  {:error, reason} ->\n    IO.puts \"withdrawal failed: #{reason}\"\nend\n```\n\nDer Unterschied zu einem Methodenaufruf ist größer, als er aussieht. Ein Aufruf ist synchron, kostenlos im Denken und teuer in den Folgen: Der Aufrufer hängt am Gelingen des Aufgerufenen, teilt sich mit ihm Stack und Schicksal. Eine Message ist asynchron und entkoppelt – ob und wann eine Antwort kommt, ist eine eigene Entscheidung, die im Code sichtbar wird. Beim Umstieg fühlt sich das zunächst umständlich an. Mir ist dabei aber aufgefallen, wie viele Entwurfsentscheidungen ein Methodenaufruf stillschweigend trifft, über die ich vorher nie nachgedacht habe.\n\nWer nicht jedes Protokoll von Hand strickt, greift zur OTP-Bibliothek der Plattform: `gen_server` gießt genau dieses Muster – Zustand in einer Schleife, synchrone und asynchrone Messages, geordnete Start- und Stopp-Semantik – in eine wiederverwendbare Form mit Callbacks. Die Konten-Übung von Hand zu schreiben war trotzdem der richtige Weg: Erst wenn man die `receive`-Schleife einmal selbst gebaut hat, versteht man, was OTP einem abnimmt.\n\n## „Let it crash\" – und wer räumt dann auf?\n\nDer Teil, der mein Denken am stärksten herausfordert, ist der Umgang mit Fehlern. Mein gelernter Reflex aus Jahren mit C# und JavaScript: Fehler dürfen nicht passieren, also verteidige ich mich – null-Prüfungen, try/catch um jede Schicht, Fallback-Werte, Logging und weiterwursteln. Das Ergebnis kenne ich aus etlichen Codebasen, auch eigenen: Der Fehler wird nicht behoben, sondern verschmiert. Irgendwo fängt ein catch-Block zu viel, das Programm läuft mit halb kaputtem Zustand weiter, und der eigentliche Knall kommt Stunden später an einer Stelle, die mit der Ursache nichts mehr zu tun hat.\n\nDie Erlang-Welt zieht daraus einen Schluss, der zunächst fahrlässig klingt: Lass den Prozess abstürzen. Kein defensives Abfangen im Prozess selbst – wenn eine Message nicht zum erwarteten Muster passt oder eine Berechnung scheitert, stirbt der Prozess. Möglich ist das nur wegen der Isolation: Ein sterbender Prozess reißt keinen geteilten Speicher mit, es gibt keinen halb veränderten Zustand, den er hinterlassen könnte. Aufgeräumt wird an anderer Stelle – von einem Supervisor, einem Prozess, dessen einzige Aufgabe darin besteht, andere Prozesse zu beobachten und nach einem Absturz mit frischem, definiertem Zustand neu zu starten. Supervisors überwachen auch andere Supervisors, daraus entstehen Bäume:\n\n```mermaid\ngraph TD\n  APP[\"Application\"] --> SUP[\"Supervisor<br/>Strategie: one_for_one\"]\n  SUP --> A1[\"BankAccount-Prozess<br/>Konto 1001\"]\n  SUP --> A2[\"BankAccount-Prozess<br/>Konto 1002\"]\n  SUP --> A3[\"BankAccount-Prozess<br/>Konto 1003\"]\n  A2 -. \"stürzt ab\" .-> SUP\n  SUP -. \"startet neu,<br/>frischer Zustand\" .-> A2\n```\n\nError Handling wird damit von einer Codestil-Frage zu einer Architektur-Frage. Nicht mehr: Wo fange ich die Exception? Sondern: Welche Einheit darf sterben, und wer startet sie in welchem Zustand neu? Die Antwort steht nicht verstreut in tausend catch-Blöcken, sondern an einer Stelle im Supervision-Baum. Joe Armstrong hat diese Idee in seiner Dissertation ausformuliert – zuverlässige Systeme *trotz* fehlerhafter Software, nicht durch fehlerfreie Software. Beim Lesen musste ich mehrfach an Produktionsvorfälle denken, bei denen uns genau das gefehlt hat: nicht weniger Fehler, sondern ein definierter Weg zurück in einen bekannten Zustand.\n\n## Die Syntax als Zugabe\n\nUnd dann gefällt mir die Syntax am Ende doch – aber als Zugabe, nicht als Grund. Drei Dinge stechen heraus.\n\nPattern Matching ist oben schon zu sehen: Die `receive`-Zweige sind keine if-Kaskade über einen Nachrichtentyp, sondern Muster mit Bedingungen, und die Struktur der Daten dokumentiert sich genau an der Stelle, an der sie verarbeitet wird. Dass `=` in Elixir kein Zuweisungs-, sondern ein Match-Operator ist, hat mich anfangs stolpern lassen und dann überzeugt.\n\nDaten sind immutable. Es gibt kein `balance -= amount`, es gibt nur einen neuen Wert, der in den nächsten Schleifendurchlauf wandert. Was in C# eine Disziplinfrage bleibt – bitte keine geteilten Objekte verändern –, ist hier schlicht nicht ausdrückbar. Ganze Fehlerklassen aus meinen Reviews existieren in dieser Sprache nicht.\n\nDer Pipe-Operator `|>` schließlich macht Transformationsketten lesbar, ohne Zwischenvariablen und ohne von innen nach außen geschachtelte Aufrufe:\n\n```elixir\n\"transactions.csv\"\n|> File.read!\n|> String.split(\"\\n\")\n|> Enum.map(&String.strip/1)\n|> Enum.reject(&(&1 == \"\"))\n|> Enum.map(&String.split(&1, \";\"))\n```\n\nJede Zeile eine Stufe, die Daten fließen von oben nach unten. Die ES5-Entsprechung mit `for`-Schleife und Hilfs-Arrays schreibe ich seit Jahren, ohne darüber nachzudenken – erst die Gegenüberstellung hat mir gezeigt, wie viel Rauschen darin steckt.\n\n## Was in meinen Alltag zurückwandert\n\nElixir wird auf absehbare Zeit nicht meine Produktionssprache. Die Projekte, in denen ich stecke, sind .NET- und Node-Landschaften, und eine Pre-1.0-Sprache schleppe ich dort nicht hinein. Trotzdem war das Experiment kein Selbstzweck, denn einige Denkmuster nehme ich mit über den Zaun zurück:\n\n- Kleine, absturzbereite Einheiten. Ein Node-Dienst, der in Sekunden startet und den ein Prozess-Wächter nach dem Absturz einfach neu hochzieht, ist dem großen Prozess überlegen, der jeden Fehler überleben muss. Schneller Neustart mit frischem Zustand schlägt heroisches Weiterlaufen.\n- Messages statt Aufrufe an den Grenzen. Wo zwei Teile eines Systems unabhängig voneinander leben und sterben sollen, gehört eine Queue dazwischen, kein direkter synchroner Aufruf – die Entkopplung, die Erlang-Prozessen von Haus aus mitgegeben ist, muss ich mir dort mit Infrastruktur erkaufen.\n- Zustand hat einen Besitzer. Auch ohne Erlang-Prozesse kann ein Modul der einzige Ort sein, an dem ein Stück Zustand verändert wird, während alle anderen nur über definierte Messages oder Kommandos mit ihm reden.\n- immutable Daten, wo die Sprache es hergibt – und sei es nur als Konvention im Team.\n\nGenauso wichtig ist, was *nicht* mitkommt. Einen Supervisor in C# oder JavaScript nachzubauen ist verlockend und führt in die Irre: Ohne isolierte Prozesse mit eigenem Heap ist „let it crash\" keine Strategie, sondern Leichtsinn – der abstürzende Thread hinterlässt eben doch geteilten Zustand, und der Neustart beginnt nicht bei null. Das Modell trägt als Ganzes oder gar nicht. OTP in einer anderen Runtime zu imitieren hieße, die Fassade ohne das Fundament zu kopieren.\n\n## Unterm Strich\n\nGesucht habe ich an Elixir keine schönere Sprache, sondern ein anderes Verhältnis zu den zwei Dingen, die mir in Projekten die meiste Arbeit machen: Zustand und Fehler. Gefunden habe ich ein Ausführungsmodell, das beide Probleme nicht besser löst, sondern anders stellt – Zustand hat genau einen Besitzer, Fehler haben einen definierten Bereich, in dem sie sterben dürfen. Dass darüber eine angenehme, junge Sprache liegt, macht das Experimentieren leichter; getragen wird alles von der Erlang-VM darunter.\n\nDas kleine Repository bleibt liegen und wächst weiter, wenn die nächste Frage auftaucht. Und Elixir selbst beobachte ich auf seinem Weg zu 1.0 – nicht, weil ich morgen ein Konto-System darauf bauen werde, sondern weil mir der Blick über diesen Zaun mehr über meine eigenen Werkzeuge beigebracht hat als so manches Framework-Release diesseits davon.\n\n## Weiterführende Quellen\n\n- [github.com/MikeBild/tryelixir](https://github.com/MikeBild/tryelixir) – meine Elixir-Experimente\n- [elixir-lang.org: Getting Started](https://elixir-lang.org/getting-started/introduction.html) – offizieller Einstieg in die Sprache\n- [Erlang/OTP Design Principles](https://www.erlang.org/doc/design_principles/des_princ.html) – Supervision Trees und Behaviours in der offiziellen Erlang-Dokumentation\n- [Joe Armstrong: Making reliable distributed systems in the presence of software errors](https://erlang.org/download/armstrong_thesis_2003.pdf) – die Dissertation hinter „let it crash\""},{"locale":"de","translation_key":"control-flow-vor-async-await","slug":"control-flow-vor-async-await","title":"Control Flow vor `async/await`","summary":"Ein Blick auf die winzige Bibliothek cflow zeigt, wie Node-Entwickler asynchrone Schritte von Hand zu einer Kette verdrahteten und warum der fehlende Fehlerkanal die eigentliche Lektion ist.","tags":["Software","Node.js","Backend"],"published_at":"2014-03-12T10:00:00+00:00","updated_at":"2026-07-13T07:27:27.832717+00:00","url":"https://www.mikebild.dev/de/blog/control-flow-vor-async-await/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/b2520fa45eab43ada9b8eec0c353f6cc6e7139704ebb265c7b81a34ffef94328/control-flow-vor-async-await-vorlesen.mp3","audio_duration_secs":494,"text":"# Control Flow vor `async/await`\n\nNode 0.10 kennt Funktionen, Callbacks und einen Event Loop. Was es nicht kennt, ist ein Befehl, der sagt: „Mach das, warte auf das Ergebnis, mach dann das Nächste.“ Diese Reihenfolge muss man selbst herstellen, Schritt für Schritt, von Hand. Und sobald drei oder vier Schritte aufeinander aufbauen, wird sichtbar, dass „warten“ in einer Single-Thread-Umgebung kein Sprachfeature ist, sondern eine Entwurfsaufgabe.\n\nIch habe mir dafür eine kleine Bibliothek gebaut, `cflow`. Sie ist so klein, dass man sie in einem Rutsch liest, und genau deshalb legt sie den Unterschied offen: zwischen einer verschachtelten Callback-Kette und einer Pipeline, deren Übergänge man einmal modelliert hat.\n\n## Das Problem: Reihenfolge aus Callbacks bauen\n\nEine asynchrone Operation in Node folgt einer Konvention. Sie nimmt als letztes Argument einen Callback, und dieser Callback bekommt als erstes Argument einen möglichen Fehler. Das nennt man error-first oder node-style callback:\n\n```js\nfs.readFile(\"config.json\", function (err, data) {\n  if (err) return handle(err);\n  // continue with data\n});\n```\n\nDas ist für einen Schritt unauffällig. Es wird unangenehm, sobald der nächste Schritt das Ergebnis des vorherigen braucht. Dann landet der zweite Aufruf im Callback des ersten, der dritte im Callback des zweiten, und so weiter:\n\n```js\nloadUser(id, function (err, user) {\n  if (err) return done(err);\n  loadAccount(user.accountId, function (err, account) {\n    if (err) return done(err);\n    loadInvoices(account.id, function (err, invoices) {\n      if (err) return done(err);\n      done(null, summarize(user, account, invoices));\n    });\n  });\n});\n```\n\nDiese Form hat einen festen Namen bekommen: Pyramid of Doom, manchmal auch Callback-Hölle. Der Code wandert nach rechts, die schließenden Klammern stapeln sich, und die eigentliche Absicht – drei Dinge nacheinander laden und zusammenfassen – verschwindet hinter der Mechanik. Das ist nicht nur ein optisches Ärgernis. Jede Ebene wiederholt dieselbe Error Handling, und genau dort schleichen sich Fehler ein.\n\n## Der Fehlerfall, den man fast immer einmal hat\n\nDie error-first-Konvention verlangt eine Disziplin, die das Sprachmittel selbst nicht erzwingt: nach `if (err)` muss ein `return` stehen. Fehlt es, läuft die Funktion weiter:\n\n```js\nloadUser(id, function (err, user) {\n  if (err) done(err);            // Careful: no return\n  loadAccount(user.accountId, function (err, account) {\n    // ...\n  });\n});\n```\n\nIm Fehlerfall passiert hier zweierlei gleichzeitig. `done(err)` wird aufgerufen, der Aufrufer hält das also für erledigt und meldet einen Fehler. Im selben Atemzug greift `user.accountId` auf ein `user` zu, das `undefined` ist, weil ja ein Fehler vorlag. Das wirft eine zweite, ganz andere Ausnahme, oder `done` wird ein zweites Mal aufgerufen – diesmal mit einem irreführenden Ergebnis. Ein Callback, der doppelt feuert, ist besonders gemein, weil die Reihenfolge der Meldungen nicht mehr garantiert ist. Mal kommt erst der echte Fehler, mal erst der Folgefehler. Solche Bugs sind im Log schwer zu lesen, weil die Ursache und ihre Auswirkung zeitlich auseinanderfallen.\n\nDaraus folgt nicht, dass Callbacks schlecht wären. Der Befund ist ein anderer: Wenn jeder Schritt seine Fehlerprüfung und seinen Übergang zum nächsten Schritt selbst von Hand schreibt, dann ist jede dieser Stellen eine Gelegenheit, es falsch zu machen. Was fehlt, ist eine Stelle, die den Kontrollfluss einmal modelliert, statt ihn an jeder Verschachtelung neu zu erfinden.\n\n## Bibliotheken, die den Fluss übernehmen\n\nDamit ist man im Jahr 2014 nicht allein. Caolan McMahons `async` ist der etablierte Werkzeugkasten und bietet genau für diese Muster benannte Funktionen an. `async.series` führt Aufgaben nacheinander aus, `async.parallel` gleichzeitig, und `async.waterfall` reicht das Ergebnis jedes Schritts an den nächsten weiter:\n\n```js\nasync.waterfall([\n  function (next) { loadUser(id, next); },\n  function (user, next) { loadAccount(user.accountId, next); },\n  function (account, next) { loadInvoices(account.id, next); }\n], function (err, invoices) {\n  if (err) return handle(err);\n  // done\n});\n```\n\nDas ist flach statt verschachtelt, und es gibt nur noch einen Fehlerausgang. Parallel dazu reift ein zweiter Ansatz heran: Promises. Die Promises/A+-Spezifikation hat sich durchgesetzt, Bibliotheken wie Q, when.js und bluebird sind verbreitet, und man kann Ketten mit `.then(...)` schreiben. Ein eingebautes `Promise` gibt es in der stabilen Node-Version 0.10 allerdings noch nicht zuverlässig; das kommt erst mit der V8-Aktualisierung der 0.11er-Linie. Wer Promises will, bindet sie heute als Abhängigkeit ein.\n\n## cflow: der Kontrollfluss auf das Nötigste reduziert\n\n`cflow` geht den waterfall-Weg, aber radikal klein. Die gesamte Bibliothek ist eine einzige Funktion:\n\n```js\nvar Flow = function () {\n  this.args = Array.prototype.slice.call(arguments);\n  var next = function () {\n    if (this.args.length > 0) {\n      this.args.shift();\n      this.args[0].apply(next, Array.prototype.slice.call(arguments));\n    }\n  }.bind(this);\n  this.args[0].apply(next);\n};\n```\n\nDer Trick steckt in zwei Zeilen. `Flow` bekommt eine Liste von Funktionen. Jede dieser Funktionen wird mit `this` aufgerufen, das auf `next` gebunden ist – also auf die Fortsetzung. Ein Schritt ruft am Ende seiner Arbeit einfach `this(...)` auf. Das verwirft den aktuellen Schritt (`shift`) und ruft den nächsten mit genau den Argumenten auf, die man `this` übergeben hat. Die Werte fließen so von Schritt zu Schritt weiter.\n\nIn der Anwendung sieht das aus wie eine gerade Liste von Phasen statt wie ein Pyramidenbau:\n\n```js\nvar Flow = require(\"cflow\");\n\nnew Flow(\n  function () {\n    slow(\"A\", this);                 // this is the continuation\n  },\n  function (data) {\n    slow2(data + \"B\", \"!!!\", this);  // data is \"A\"\n  },\n  function (data, data2) {\n    slow(data + \"C\" + data2, this);  // data is \"AB\", data2 is \"!!!\"\n  },\n  function (data) {\n    console.log(data);               // \"ABC!!!\"\n  }\n);\n\nfunction slow(value, callback) {\n  setTimeout(function () { callback(value); }, 200);\n}\nfunction slow2(value, value2, callback) {\n  setTimeout(function () { callback(value, value2); }, 300);\n}\n```\n\nJeder Schritt übergibt `this` als Callback an seine asynchrone Operation. Sobald die fertig ist, wird der nächste Schritt aktiv, und das Zwischenergebnis liegt direkt als Argument vor. Bemerkenswert ist, dass ein Schritt auch mehrere Werte weiterreichen kann – `slow2` gibt zwei zurück, und der folgende Schritt nimmt zwei entgegen. Das ist exakt das Waterfall-Pattern, nur ohne Array, ohne Optionen, ohne Abhängigkeiten. Die `package.json` listet unter `dependencies` schlicht nichts.\n\n## Kette gegen Pipeline\n\nDer Unterschied zwischen den beiden Schreibweisen lässt sich gut nebeneinanderstellen. Die Callback-Kette schachtelt Zustand und Error Handling mit jeder Ebene tiefer ineinander. Die Pipeline legt die Schritte nebeneinander und macht die Übergänge zu einem eigenen, benannten Mechanismus.\n\n```mermaid\nflowchart TB\n  subgraph Kette[\"Callback-Kette (verschachtelt)\"]\n    direction TB\n    a1[\"Schritt 1\"] --> a2[\"  Schritt 2\"]\n    a2 --> a3[\"    Schritt 3\"]\n    a3 --> a4[\"      Ergebnis\"]\n  end\n  subgraph Pipeline[\"Pipeline (modelliert)\"]\n    direction LR\n    b1[\"Schritt 1\"] --> b2[\"Schritt 2\"]\n    b2 --> b3[\"Schritt 3\"]\n    b3 --> b4[\"Ergebnis\"]\n  end\n```\n\nOptisch ist die Pipeline ruhiger. Wichtiger ist aber, was sich strukturell ändert. In der Pipeline existiert der Übergang von Schritt zu Schritt nur an einer einzigen Stelle, nämlich in der Bibliothek. Wenn man dort etwas verbessern will – Logging, ein Timeout, eine zentrale Fehlerweiche – dann hat man genau einen Ort dafür. In der verschachtelten Kette müsste man dieselbe Änderung in jeder Ebene wiederholen.\n\n## Wo `cflow` an seine Grenze stößt\n\nUnd hier liegt die ehrlichste Lektion dieses kleinen Stücks Code. `cflow` modelliert die Reihenfolge sauber, aber es modelliert keinen Fehler. Es gibt keinen error-first-Kanal, keinen Abbruch, kein `try`. Wirft ein Schritt eine Ausnahme oder ruft `this` mit einem Fehlerobjekt auf, dann behandelt `Flow` das nicht – der Fehler wird einfach als nächstes Argument weitergereicht oder fällt durch. Genau das, was die Callback-Konvention mit ihrem `err`-Argument zumindest vorsieht, fehlt hier ganz.\n\nDas ist Absicht, die Konsequenz aus „so einfach wie möglich“. Für eine Demonstration des Kontrollflusses reicht es. Für einen Service, der unter Last läuft, reicht es nicht. Damit benennt die Bibliothek selbst die Grenze, an der man weiterdenken muss: Ein Kontrollfluss ist erst dann vollständig, wenn auch der Fehlerpfad Teil des Modells ist. Wer eine eigene Flow-Funktion baut, sollte den nächsten Schritt deshalb so anlegen, dass ein Fehler die Kette abbricht und an einen einzigen Endpoint geleitet wird, statt blind weiterzulaufen. `async.waterfall` macht genau das vor, indem es bei einem Fehler im ersten Argument sofort zum Abschluss-Callback springt.\n\n## Rückblick aus späterer Zeit\n\n**Redaktionelle Einordnung (Juli 2026):** Der folgende Rückblick wurde nachträglich ergänzt. Der Hauptteil des Artikels beschreibt den Stand von 2014; die Hinweise auf ES2015 und ES2017 gehören nicht zur ursprünglichen zeitlichen Perspektive.\n\nWer diesen Text Jahre später liest, kennt die Auflösung. Mit ES2015 kamen Generatoren, die zusammen mit Bibliotheken wie `co` synchron aussehenden asynchronen Code erlaubten. Und mit ES2017 wurde `async/await` Teil der Sprache. Damit verschwindet die Frage, die diesen Artikel trägt, fast vollständig aus dem Alltag: Die Reihenfolge schreibt man wieder von oben nach unten, der Fehlerpfad ist ein normales `try/catch`, und das Warten ist ein Schlüsselwort.\n\nDas macht die alte Übung aber nicht wertlos. Im Gegenteil. Ein `await` sieht harmlos und synchron aus, doch dahinter steht weiterhin ein nicht-blockierender Aufruf, der Ressourcen halten kann. Die Dinge, die man sich 2014 von Hand klarmachen musste – wo die Reihenfolge erzwungen wird, wo ein Fehler die Kette abbricht, wo ein Timeout fehlt, was bei doppelt gefeuerten Fortsetzungen passiert – sind alle noch da. Sie sind nur unter einer bequemen Syntax verborgen. Wer den expliziten Kontrollfluss einmal selbst gebaut hat, erkennt diese Grenzen auch dann noch, wenn die Sprache sie nicht mehr vor die Augen hält.\n\n## Weiterführende Quellen\n\n- Repository cflow: https://github.com/MikeBild/cflow\n- caolan/async, Dokumentation der Control-Flow-Funktionen: https://github.com/caolan/async\n- Promises/A+ Spezifikation: https://promisesaplus.com/"},{"locale":"de","translation_key":"warum-katas-mehr-sind","slug":"warum-katas-mehr-sind","title":"Warum Katas mehr sind als Fingerübungen","summary":"Eine Kata ist ein Architektur-Labor im Kleinen – weil die Aufgabe konstant bleibt, wird sichtbar, was sonst nur der Entwurf weiß.","tags":["Software","Testing"],"published_at":"2014-01-12T10:00:00+00:00","updated_at":"2026-07-14T16:02:12.984451+00:00","url":"https://www.mikebild.dev/de/blog/warum-katas-mehr-sind/","audio_url":"https://media.mikebild.dev/site/mikebild/assets/1e997fcddd264fe043757155e40937bac1d0bd63218ab692922cd1c30b8173fc/warum-katas-mehr-sind-vorlesen.mp3","audio_duration_secs":643,"text":"# Warum Katas mehr sind als Fingerübungen\n\nEine Kata ist in der Kampfkunst eine festgelegte Abfolge von Bewegungen, die man so oft wiederholt, bis sie ohne Nachdenken abläuft. Dave Thomas hat den Begriff vor gut zehn Jahren in die Programmierung geholt: kleine, scharf umrissene Aufgaben, die man nicht einmal löst, sondern immer wieder – FizzBuzz, der Bowling-Score, Roy Osheroves String Calculator. Auf codekata.com steht eine ganze Sammlung davon.\n\nDer Vergleich mit der Kampfkunst trifft einen Punkt sehr genau und geht an einem anderen deutlich vorbei. Er trifft: Eine Kata findet ohne Ernstfall statt. Kein Kunde wartet, kein Termin drückt, kein Altsystem redet dazwischen. Man kann sich eine einzige Sache vornehmen und ihr die volle Aufmerksamkeit geben. Er hinkt: In der Kampfkunst ist das Ziel der Wiederholung, dass die Bewegung immer gleicher wird. Beim Programmieren wäre das sinnlos. Tippen ist nicht der Engpass, und wer den Bowling-Score zum fünften Mal identisch herunterschreibt, hat beim fünften Mal nichts gelernt.\n\nDie Wiederholung lohnt sich aus einem anderen Grund. Weil die Aufgabe konstant bleibt, kann der Entwurf variieren – und genau dadurch werden Entwurfsentscheidungen sichtbar, die im Projektalltag unsichtbar bleiben. Eine Kata ist kein Tipp-Training. Sie ist ein Architektur-Labor im Kleinen.\n\n## Ein Labor braucht eine Konstante\n\nWer zwei Entwürfe ernsthaft vergleichen will, muss alles andere festhalten. Das ist im Projekt praktisch nie möglich. Dort ändert sich zwischen zwei Lösungsansätzen immer auch das Problem: neue Anforderungen, andere Kollegen, verschobene Prioritäten. Wenn die zweite Lösung besser aussieht als die erste, weiß niemand, ob der Entwurf besser war oder nur die Umstände günstiger. Aus einem Projekt lässt sich deshalb selten sauber ablesen, was eine einzelne Entwurfsentscheidung wirklich gekostet oder gebracht hat.\n\nDie Kata dreht das um. Das Problem ist klein, vollständig bekannt und bleibt exakt gleich. Die Anforderungen stehen fest, bevor die erste Zeile entsteht. Was zwischen zwei Durchläufen variiert, ist ausschließlich der Entwurf: Wo liegt der Zustand? Was ist eine Funktion, was ein Objekt? Welche Grenze trennt Logik von Ein- und Ausgabe? Wenn sich Durchlauf drei leichter testen lässt als Durchlauf eins, dann liegt das nicht an der Aufgabe. Es liegt an einer Entscheidung, die ich getroffen habe – und die ich jetzt benennen kann.\n\nDas klingt banal, ist es aber nicht. Mir ist erst über solche Wiederholungen aufgefallen, wie viele meiner Entwurfsgewohnheiten schlicht Gewohnheiten waren: Dinge, die ich tat, weil ich sie immer so tat, nicht weil sie der Aufgabe dienten. Im Projekt fällt so etwas nicht auf, weil nie jemand dieselbe Aufgabe ein zweites Mal anders löst. In der Kata fällt es sofort auf.\n\n## Zwei Regale voller Versuche\n\nAuf meinem GitHub-Konto liegen zwei solche Sammlungen aus den letzten Jahren. Das ältere Repository heißt schlicht Katas, ist von 2010 und enthält C#-Übungen: eine Tennis-Kata und eine FizzBuzz-Variante, die ich damals mit den Reactive Extensions gebaut habe – nicht weil FizzBuzz das braucht, sondern weil ich wissen wollte, wie sich dieselbe triviale Aufgabe anfühlt, wenn man sie als Strom von Events statt als Schleife denkt. Ein README gibt es nicht, das Repository ist ein persönliches Übungsarchiv und will auch nichts anderes sein.\n\nDas jüngere heißt AppKatas, ist von 2013 und in JavaScript geschrieben. Dort liegen unter anderem eine Calculator- und eine TicTacToe-Kata, beide bewusst als pures JavaScript mit Event-Sourcing umgesetzt, die Module laufen im Browser und unter Node.js, die Tests laufen über Travis. TicTacToe gibt es dort in zwei Ausbaustufen: als reine Browser-Anwendung und als Client-Server-Variante mit einem kleinen Node-Server.\n\nDer Wert dieser Repositories liegt nicht im Code. Den würde ich heute an vielen Stellen anders schreiben. Der Wert liegt darin, dass dieselben Aufgaben mehrfach und unterschiedlich gelöst dort nebeneinanderstehen. Man kann die Entwürfe vergleichen, weil die Aufgabe konstant geblieben ist. Genau das meine ich mit Labor.\n\n## Testbarkeit ist Entwurfsdruck\n\nDie Tennis-Kata sieht harmlos aus: Zähle die Punkte eines Tennisspiels und gib den Spielstand aus – Love, Fifteen, Thirty, Forty, Deuce, Advantage. Beim ersten Durchlauf 2010 habe ich das als eine Klasse mit zwei Zählern und einer großen Methode gebaut, die den Spielstand als Text zusammensetzt. Der erste NUnit-Test dazu sah ungefähr so aus:\n\n```csharp\n[TestFixture]\npublic class TennisGameTests\n{\n    [Test]\n    public void Score_AfterDeuce_ReturnsAdvantage()\n    {\n        var game = new TennisGame();\n        for (var i = 0; i < 3; i++)\n        {\n            game.WinPoint(Player.One);\n            game.WinPoint(Player.Two);\n        }\n        game.WinPoint(Player.One);\n\n        Assert.AreEqual(\"Advantage Player One\", game.Score());\n    }\n}\n```\n\nDer Test funktioniert, aber er verrät etwas: Um einen einzigen Spielstand zu prüfen, muss ich sieben Punkte in der richtigen Reihenfolge einspielen. Der Zustand ist im Objekt eingesperrt, und der einzige Weg hinein führt über die Historie. Bei Deuce ist das noch erträglich. Bei einer Aufgabe mit mehr Zustand wird genau dieses Muster zur Qual – jeder Test beginnt mit einem langen Aufbau, der mit der eigentlichen Behauptung nichts zu tun hat.\n\nDas ist der Moment, in dem Testbarkeit zu Entwurfsdruck wird. Der schwer zu schreibende Test ist kein Test-Problem, er ist ein Symptom. Er zeigt, dass der Entwurf keinen direkten Zugang zu dem Zustand erlaubt, um den es fachlich geht. Im zweiten Durchlauf habe ich den Spielstand als Wert modelliert, den man direkt konstruieren kann, und die Übergangslogik als Funktion von Zustand zu Zustand. Die Tests schrumpften auf drei Zeilen, und nebenbei war die große Textmethode in kleine, benennbare Fälle zerfallen.\n\nIm Projekt hätte ich diesen zweiten Durchlauf nie gemacht. Die erste Version funktionierte ja. Niemand baut ein funktionierendes Stück Software noch einmal, nur um zu sehen, ob der Entwurf auch anders ginge. In der Kata ist genau das der Zweck der Veranstaltung.\n\n## Dieselbe Aufgabe, zwei Entwürfe\n\nAm deutlichsten habe ich den Labor-Effekt bei TicTacToe in AppKatas gesehen. Die naheliegende erste Version in JavaScript sieht so aus, wie vermutlich die meisten sie schreiben würden – ein Spielobjekt, das ein Brett hält und es bei jedem Zug verändert:\n\n```javascript\nfunction Game() {\n  this.board = [null, null, null, null, null, null, null, null, null];\n  this.currentPlayer = \"X\";\n}\n\nGame.prototype.move = function (field) {\n  if (this.board[field] !== null) {\n    throw new Error(\"field already taken\");\n  }\n  this.board[field] = this.currentPlayer;\n  this.currentPlayer = this.currentPlayer === \"X\" ? \"O\" : \"X\";\n};\n```\n\nDas ist völlig in Ordnung und trägt ein kleines Spiel problemlos. Interessant wird es beim zweiten Durchlauf mit einer anderen Grundentscheidung: Das Spiel speichert kein Brett, sondern nur die Liste der Züge. Das Brett wird bei Bedarf aus den Events abgeleitet:\n\n```javascript\nfunction replay(events) {\n  var board = [null, null, null, null, null, null, null, null, null];\n  events.forEach(function (event) {\n    board[event.field] = event.player;\n  });\n  return board;\n}\n\nfunction move(events, field) {\n  var board = replay(events);\n  if (board[field] !== null) {\n    throw new Error(\"field already taken\");\n  }\n  var player = events.length % 2 === 0 ? \"X\" : \"O\";\n  return events.concat([{ player: player, field: field }]);\n}\n```\n\nKein `this`, keine Mutation, kein Konstruktor. `move` nimmt eine Liste und gibt eine neue Liste zurück. Die Konsequenzen dieser einen Entscheidung fallen einem regelrecht in den Schoß: Ein Test ist jetzt eine Liste rein, eine Liste raus – jeder Spielstand lässt sich direkt hinschreiben, ohne Züge einspielen zu müssen. Rückgängig machen ist das Weglassen des letzten Elements. Und die Client-Server-Variante wurde beinahe trivial, weil eine Zugliste sich als JSON verschicken lässt, während ein Objekt mit Methoden und innerem Zustand an der Prozessgrenze auseinanderfällt.\n\n```mermaid\nflowchart TD\n  A[Gleiche Aufgabe:<br/>TicTacToe] --> B[Entwurf 1:<br/>Zustand wird mutiert]\n  A --> C[Entwurf 2:<br/>Zugliste, Brett abgeleitet]\n  B --> D[Test braucht<br/>Zug-Historie als Aufbau]\n  C --> E[Test ist<br/>Liste rein, Liste raus]\n  D --> F[Unterschied ist dem Entwurf<br/>zurechenbar, weil das<br/>Problem konstant blieb]\n  E --> F\n```\n\nDer Punkt ist nicht, dass Ereignislisten besser wären als veränderlicher Zustand. Für ein TicTacToe im Browser ist die erste Version schlicht angemessen, und `replay` bei jedem Zug komplett laufen zu lassen, skaliert erkennbar nicht für große Ereignismengen. Der Punkt ist, dass ich beide Entwürfe an derselben Aufgabe nebeneinander halten kann. Erst dadurch sehe ich, was die Entscheidung kostet und was sie kauft. Im Projekt bekomme ich immer nur einen der beiden Zweige zu sehen – den, für den wir uns entschieden haben. Der andere bleibt Spekulation.\n\nNebenbei zwingt die zweite Version zu einer sauberen Grenze, die in der ersten gern verwischt: Die Spiellogik weiß nichts vom DOM. `replay` und `move` laufen unverändert unter Node und im Browser, die Darstellung ist ein dünner Rand, der Events entgegennimmt und ein Brett zeichnet. Diese Grenze habe ich nicht gezogen, weil ein Prinzip es verlangt, sondern weil der Entwurf sie mir aufgedrängt hat. Solche aufgedrängten Grenzen merkt man sich besser als gepredigte.\n\n## Der Luxus des Wegwerfens\n\nZur Kata gehört ein Schritt, der im Projekt undenkbar ist: Am Ende wird der Code gelöscht. Nicht archiviert, nicht als Basis für den nächsten Durchlauf behalten – gelöscht. Beim nächsten Mal beginnt man leer.\n\nAnfangs kam mir das verschwenderisch vor. Inzwischen halte ich es für den wichtigsten Teil. Solange Code weiterlebt, verteidigt man ihn. Man baut auf ihm auf, umgeht seine Schwächen, gewöhnt sich an seine Form. Erst wenn feststeht, dass er verschwindet, wird man ehrlich zu ihm. Dann probiert man die Entscheidung aus, die man im Projekt nie riskieren würde, weil dort jede Entscheidung sofort Bestandsschutz bekommt.\n\nGenau darin liegt der Unterschied zwischen Üben und Arbeiten. Im Projekt ist Code ein Investitionsgut, und jede Alternative konkurriert mit dem, was schon da ist. In der Kata ist Code Versuchsmaterial. Man darf eine Idee zu Ende denken, feststellen, dass sie nicht trägt, und sie ohne Kosten begraben. Die Erkenntnis überlebt, der Code nicht. Das ist die richtige Reihenfolge.\n\n## Was eine Runde für mich ausmacht\n\nMit der Zeit hat sich bei mir eine einfache Form eingespielt, ganz ohne Rahmenprogramm – eine Stunde, ein Editor, eine Aufgabe:\n\n- Eine bekannte Aufgabe wählen, keine neue. Die Neugier soll dem Entwurf gelten, nicht dem Problem.\n- Vor dem ersten Test eine einzige Entwurfsentscheidung festlegen, die diesmal anders ausfällt als beim letzten Mal.\n- Tests zuerst schreiben und jeden zähen Test als Hinweis auf den Entwurf lesen, nicht als Test-Problem.\n- Am Ende zwei, drei Sätze notieren: Was war leichter, was schwerer, und woran lag es?\n- Den Code löschen.\n\nDie Notizen sind unscheinbar, aber sie sind das eigentliche Ergebnis. Nach ein paar Runden mit derselben Aufgabe steht dort eine kleine, selbst erarbeitete Karteikartensammlung über Entwurfsentscheidungen – belegt an Code, den man selbst geschrieben hat, statt geglaubt aus einem Buch.\n\n## Was hängen bleibt\n\nFingerübung ist das falsche Wort, weil es das Ziel falsch beschreibt. Geübt wird nicht die Hand, geübt wird das Urteil. Eine Kata hält das Problem fest, damit der Entwurf variieren kann, und macht dadurch sichtbar, was eine Entwurfsentscheidung wirklich bewirkt: welche Tests sie leicht oder zäh macht, welche Grenzen sie erzwingt, was sie an einer Prozessgrenze kostet. Das sind genau die Fragen, die in großen Systemen über Jahre nachwirken – nur dass man sie dort nie isoliert beobachten kann.\n\nDeshalb halte ich die halbe Stunde mit FizzBuzz, Tennis oder TicTacToe nicht für vertane Zeit, obwohl dabei nichts entsteht, was jemand benutzt. Es entsteht etwas anderes: die Erfahrung, dieselbe Aufgabe mit zwei Entwürfen gesehen zu haben. Wer die einmal hat, argumentiert in der nächsten Architektur-Diskussion nicht mehr mit Vorlieben, sondern mit Beobachtungen. Das ist mehr, als eine Fingerübung je liefern könnte.\n\n## Weiterführende Quellen\n\n- https://github.com/MikeBild/AppKatas – meine JavaScript-Katas (Calculator, TicTacToe mit Event-Sourcing)\n- https://github.com/MikeBild/Katas – meine älteren C#-Katas (Tennis, FizzBuzz mit Rx)\n- http://codekata.com/ – Dave Thomas' Kata-Sammlung, die den Begriff geprägt hat\n- https://osherove.com/tdd-kata-1 – Roy Osheroves String-Calculator-Kata"},{"locale":"en","translation_key":"von-der-session-zum-system-zwischenfazit","slug":"interim-review-and-system-view","title":"Interim Review and System View: Taking Stock of the Series","summary":"Months after the conversation where it all began, it’s time for an honest assessment: which expectations from the opening came true, which didn’t, what remains open – and why the most exciting question is no longer what the models can do, but what organizations make of it.","tags":["Software","AI","Methodology"],"published_at":"2026-08-17T10:00:00+00:00","updated_at":"2026-08-18T05:16:11.670656+00:00","url":"https://www.mikebild.dev/en/blog/interim-review-and-system-view/","audio_url":null,"audio_duration_secs":null,"text":"The conversation with which [this series began](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/) took place in October of last year; this text takes stock as of August 2026. The opening ended with a resolution: to distrust my own enthusiasm for the time being, look closely and measure every result against more than thirty years of craft. The [last installment](https://www.mikebild.dev/en/blog/tools-that-hold-up-concepts-methods-processes-article/) announced that it would take this resolution at its word. So: which of the expectations came true, which didn’t, what remains open – and what system view has emerged from the individual sessions of the beginning?\n\n*Part 13 of the series “From Session to System” – [the opening post is here](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\n## The enthusiasm survived the test – barely\n\nThe most important thing first, because everything else builds on it: the few days of trial in October have become everyday work, and that is the least spectacular evidence I can offer. I no longer think about these tools, any more than I think about the editor or version control. They are infrastructure. A flash in the pan looks different – you recognize one by the fact that after three months you’re telling stories about it again instead of working with it.\n\nStill, it would be too cheap to simply declare my own perception to be the assessment. In July 2025, the American research institute METR – a nonprofit that measures the capabilities of AI systems with controlled experiments – published a study that has occupied me more than any benchmark: experienced open-source developers were measurably slower with AI support on randomized tasks – by roughly a fifth – and yet afterwards estimated that they had been considerably faster. So exactly the perception I have relied on since the opening can be systematically deceptive. I take that seriously, because it is the same warning I gave myself in the opening: fresh enthusiasm is a poor witness.\n\nThat’s why I check against things that can’t be talked up. What is actually done in the evening? Which of the stalled projects are in operation today? How often did I find errors in reviews that would have slipped through without the shift toward checking? By this standard, the assessment is positive – as an observation, not a measurement; I lack reliable numbers on it. That is exactly why the study remains important for my assessment: as long as I don’t measure with comparable rigor, I have to factor in that my perception may deceive me too. The study does, however, measure tasks that were familiar to the developers, in code they knew well. My biggest gain lies elsewhere – in the projects that would never have been started at all without these tools. That doesn’t refute the study; it’s a different calculation. Both can be true at the same time.\n\n## What came true\n\nThe opening recorded three observations. All three have survived the months since the opening, but none has stayed the way it was.\n\nThe first – generating gets cheap, checking becomes the bottleneck – has turned out to be the load-bearing observation of the entire series. In hindsight, almost every installment is an answer to this one shift: the harness organizes checking around the model, the [house rules](https://www.mikebild.dev/en/blog/what-i-am-critical-of/) defend it against my own convenience, [grounding](https://www.mikebild.dev/en/blog/clean-grounding-ii-grounding-answers/) anchors it in real sources, and [rules in the path](https://www.mikebild.dev/en/blog/ai-agents-per-domain/) make it independent of the checker’s form on the day. What I didn’t see yet in November: the bottleneck keeps moving. First checking was scarce, then cleanly writing down what is supposed to apply – by now it is deciding what gets built at all.\n\nThe second observation – the drawers open up again – came true, with a limitation I didn’t see coming back then. Some of what had been lying around for years is in operation today: smaller than the original idea, and that is not a defeat but a finding. Because what the tools don’t deliver is a judgment on which of the old ideas were worth it. I shut down two projects again after a few weeks – failed faster than would have been possible before, and that is exactly the underestimated gain: cheap implementation makes discarding cheap too.\n\nThe third observation – the tone is always right, even when the content isn’t – was a gut feeling in November. It has since become [a structural explanation](https://www.mikebild.dev/en/blog/clean-grounding-i-why-ai-guesses-so-convincingly/) and then a procedure. The distrust has stayed, but it has moved: from my private vigilance into check steps that don’t depend on whether I’m having a good day. That is perhaps the most compact summary of what these months have done to my way of working – diligence went from being a virtue to being a property of the setup.\n\n## What I expected wrongly\n\nAn assessment that only lists hits is advertising. Two expectations didn’t hold.\n\nThe most expensive misjudgment: that writing things down is enough. For months I put work into ever better instruction files before I honestly drew up the chronicle of these attempts – written rules remain recommendations, no matter how well they are phrased. From this disillusionment came the most important insight of the series: rules that are supposed to apply need a path that enforces them – check before effect, approvals, evidence. If I could take a single sentence away from these months, it would be this one.\n\nThe second misjudgment is more pleasant: I had expected the choice of model to become more important over time – that at some point one model would pull ahead and the question “which one?” would turn into a strategic question after all. The opposite happened. For my tasks, several model changes since the opening felt like quality improvements, and with every jump the choice became [less important, not more](https://www.mikebild.dev/en/blog/good-enough-models/). My way of working hardly noticed the changes. What does make itself felt every time, on the other hand: a badly cut task, a missing piece of context, a rule that only exists in prose. My own share dominates the result – that was there early as a thesis, and by now it concretely decides whether a run holds up: in how the task is cut, in the context provided and in the rules enforced in the path.\n\n## What remains open\n\nThree questions remain unanswered in this interim review.\n\nThe junior question. The opening contained a suspicion: the lever works because three decades of judgment stand behind it – and whether it works the same way for someone without that foundation, I didn’t know. I still don’t know today, and the [critical installment](https://www.mikebild.dev/en/blog/what-i-am-critical-of/) sharpened the suspicion rather than dispelled it: if you get working code before the pain sets in from which understanding arises, you may never build up the substance that checking draws on. A suspicion is still not knowledge. But it is the question I consider more important than any model question.\n\nHomogenization. That teams asking the same model build more similar solutions is something I have recognized several times since that one observation in February, but never measured. It remains a concern without evidence, and I deliberately leave it at that instead of inflating it into a thesis.\n\nUnlearning my own craft. The house rules from February hold up about as well as New Year’s resolutions: better than nothing, worse than claimed. The deliberate run without AI does happen, but less often than I had planned. The pull of the convenient option is real, every day. Exactly this experience made me skeptical, for the second half of the series, of everything that relies on discipline – and receptive to everything that moves diligence into the setup.\n\n## The arc, in hindsight\n\nThe triad of I, We, System was already there as an intention in the opening. What I hadn’t planned is the mechanism that emerged while writing: each level inherits the unsolved problem of the previous one. The discipline of the individual [doesn’t scale to the team](https://www.mikebild.dev/en/blog/my-success-cannot-be-copied/), so the team writes down its rules; written rules bind nobody, so you need knowledge with owners and [a place that survives the session](https://www.mikebild.dev/en/blog/knowledge-that-survives-the-session/); curated knowledge doesn’t yet answer the question of what is binding, so the hard rules move [into the path of a dedicated agent](https://www.mikebild.dev/en/blog/ai-agents-per-domain/); and so that this doesn’t remain a drawing-board design, you need [concepts, methods and processes](https://www.mikebild.dev/en/blog/tools-that-hold-up-concepts-methods-processes-article/) that keep the beginning small.\n\n```mermaid\nflowchart LR\n    subgraph AKT1[\"Act 1 · I\"]\n        S[\"Session<br/>generating gets cheap\"] --> P[\"Way of working<br/>checking becomes the bottleneck\"]\n    end\n    subgraph AKT2[\"Act 2 · We\"]\n        P --> V[\"Team variance<br/>discipline doesn’t scale\"] --> D[\"Instruction files<br/>recommendation instead of rule\"]\n    end\n    subgraph AKT3[\"Act 3 · System\"]\n        D --> W[\"Curated knowledge<br/>with owners\"] --> R[\"Rules in the path<br/>agent per domain\"] --> B[\"System architecture<br/>UI, contracts, approvals\"]\n    end\n```\n\nThe sentence that holds this arc together came up in the installment on curated knowledge: it’s not the model that gets smarter – the organization curates its knowledge.\n\n## Today’s system view\n\nAt the center is the property this series has been about from the start: the separation of proposal and effect, built as a dedicated approval boundary, not as a blanket switch. A workflow engine can hold back external writes until confirmation. A publishing system can tie the promotion of a preview to a human. A knowledge system can leave changes standing as a proposal until a human decides. An order control system can tie execution to approved orders. The same principle, cut differently each time – because the question of what “taking effect” means has to be answered differently in every domain. Published content takes effect differently from an approved knowledge revision, and both differently from a workflow that writes into a third-party system.\n\nWith that, the question the opening asked has shifted too. It was: what can the models do? It is now: what does an organization make of it? Access to an external model API is not the part of this architecture that the organization permanently controls itself. A UI backed by a cleanly cut domain, machine contracts that other systems can rely on, and approval paths that prevent a proposal from taking effect without the intended human decision: an organization has to build these itself, and that is exactly the share that remains its own, independent of any single model.\n\n## Position instead of prediction\n\nI have no basis for judging model capabilities a year from now, productivity curves of entire industries or labor markets, and above all these months have taught me how quickly such statements age. That’s why I’m not formulating a vision, and I explicitly mark what this interim review is: my limited state of experience, not a prediction about inevitable market or organizational developments.\n\nWhat I can stand behind, because it has been confirmed repeatedly over these months: the lasting value lies less in the individual model than in your own knowledge, enforceable rules, clear domains and verifiable processes. That is not a statement about the future but a description of what remained after every model change – and of what was missing every time a result didn’t hold up.\n\nAnd for my own desk, one expectation remains that you can measure me against: the first domain agent that has been in operation long enough for its rejections to tell stories – correct noes, overly tight noes, special cases that deserve a verb of their own. Only then will it show whether the cycle from the last installment holds up or just sounds good.\n\n## Interim review, not a final word\n\nThis series pauses here, for a simple reason: the supply of observations is used up. What would come now would be extrapolation, and there is enough of that. What this interim review lacks is time in operation. When enough new material has come together again, when the noes of the first domain agent have something to tell, I’ll keep writing. Until then, the resolution from the opening applies unchanged: distrust your own enthusiasm, measure against real tasks, check every result against your own craft. Looking closely pays off, and it doesn’t stop.\n\n## Further reading\n\n- [Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity (METR, July 2025)](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/) – the study that puts measured slowdown and perceived speedup side by side\n- [The Anthropic Economic Index](https://www.anthropic.com/economic-index) – ongoing data collection on what AI is actually used for in the economy\n- [Things we learned about LLMs in 2024 (Simon Willison)](https://simonwillison.net/2024/Dec/31/llms-in-2024/) – a sober annual review as an antidote to prediction prose"},{"locale":"en","translation_key":"mcp-http-webhooks-a2a-einfach-erklaert","slug":"mcp-http-webhooks-and-a2a-explained-simply","title":"MCP, HTTP, Webhooks and A2A Explained Simply","summary":"MCP, HTTP with OpenAPI, webhooks and A2A connect systems at different levels. What matters is which responsibility lies at each boundary.","tags":["Software","AI","Architecture"],"published_at":"2026-08-17T10:00:00+00:00","updated_at":"2026-08-17T05:36:19.088608+00:00","url":"https://www.mikebild.dev/en/blog/mcp-http-webhooks-and-a2a-explained-simply/","audio_url":null,"audio_duration_secs":null,"text":"Four connections can all run over HTTP technically and still serve four fundamentally different purposes. An agent application discovers a tool. A fixed program calls a documented endpoint. A service reports an event that has already happened. An independent agent takes on a task with its own lifetime.\n\nMCP, HTTP with OpenAPI, webhooks and A2A describe these boundaries. None of them replaces the domain decision about who may read, write, approve or publish. A product can offer several of these machine interfaces and also have its own web UI for people. It still remains one domain with one authoritative product state and the same domain rules.\n\n## Four questions instead of a ranking\n\nAn interface is an agreed boundary between systems. It defines inputs, results and errors. The transport, however, doesn’t yet answer which responsibility is handed over at this boundary.\n\n| Technique | Guiding question | Typical task |\n| --- | --- | --- |\n| MCP | Which capabilities can an agent application discover and use? | Providing tools and context for an open-ended task |\n| HTTP with OpenAPI | Which known machine command can a client execute? | Calling and checking a stable service contract |\n| Webhook | Which event that has occurred should another system learn about? | Triggering a downstream process promptly |\n| A2A | Which bounded task can an independent agent take on? | Delegating stateful work to another agent system |\n\nThe four options are not ranked, and they don’t sit on the same technical layer. HTTP is a transport protocol, OpenAPI describes an interface, webhooks use HTTP to deliver events, and MCP and A2A each bring their own interaction contracts. An A2A agent can call MCP tools and ordinary HTTP APIs internally.\n\n## MCP provides capabilities for agent applications\n\nMCP stands for Model Context Protocol. With it, an agent application can, for example, discover a knowledge service’s search as a tool; the visibility of this tool is not yet a domain permission and no substitute for a fixed workflow.\n\nA server can run locally as a process or remotely as a web service. The word “server” describes its role in the protocol, not its location.\n\n```json\n{\n  \"mcpServers\": {\n    \"knowledge\": {\n      \"type\": \"http\",\n      \"url\": \"https://knowledge.example.com/mcp\"\n    }\n  }\n}\n```\n\nAfter connecting, the agent application can check the input schema and call the tool. This doesn’t give the model a blanket permission. The host controls which capabilities are visible and which calls require consent. The server authenticates and authorizes the call. The responsible service additionally enforces its domain rules for the operation.\n\nMCP fits open-ended tasks. An agent application can search a knowledge service for approved knowledge, read sources and, depending on the result, decide which next step makes sense. For repeated publications with an identical sequence of steps, this freedom is unnecessary. A stored, approved workflow is easier to check and repeat there.\n\n## HTTP and OpenAPI form an explicit machine contract\n\nHTTP governs request and response. OpenAPI describes the APIs built on top of it in a machine-readable way: paths, methods, inputs, responses and security schemes. People can read the description, programs can generate clients from it, and checks can compare the implementation with the contract.\n\nThe following call is a schematic example:\n\n```http\nPOST /v1/sites/demo/previews HTTP/1.1\nHost: content.example.com\nAuthorization: Bearer <token>\nContent-Type: application/json\n\n{\n  \"revisionIds\": [\"rev-123\", \"rev-456\"]\n}\n```\n\nThe call requests a preview. It says nothing about who reviewed the content from a domain point of view or whether this preview may be published. OpenAPI can make the technical contract precise. The approval rule belongs in the domain and in the controlled process.\n\nIn a publishing system, the HTTP and OpenAPI interface can serve fixed integrations, a remote MCP endpoint can offer selected capabilities to agent applications, and a web UI can carry the human work in the same publishing domain. All three access paths then work with the same revisions, previews, releases and permission boundaries; none of them introduces a second persistence path.\n\n## A webhook reports an event\n\nWith a normal API call, the client actively asks. With a webhook, the event source sends an HTTP request to a previously registered address. That way, the receiver doesn’t have to keep checking whether something has changed.\n\n```http\nPOST /webhooks/knowledge HTTP/1.1\nHost: orchestration.example.com\nwebhook-id: evt-789\nwebhook-timestamp: 1785585600\nwebhook-signature: v1,<signature>\nContent-Type: application/json\n\n{\n  \"type\": \"proposal.approved\",\n  \"data\": {\n    \"space\": \"product-docs\",\n    \"concepts\": [\"integration-options\"]\n  }\n}\n```\n\nThe event type in the example is deliberately generic. In this flow, the webhook only carries the event and the reference to the authoritative state. The receiver checks signature and age, detects duplicate deliveries via the event ID and then reads the state from the responsible system with its own permissions.\n\nDuplicate delivery is part of the normal failure pattern. The receiver has to work idempotently: the same event ID may only take effect once in domain terms. It responds quickly and moves longer work into a stored process. A knowledge service can deliver signed Standard Webhooks for this. A workflow engine can bind such an input – with signature checks and protection against replays – to exactly one versioned workflow, without taking over the knowledge or publishing rules of the systems involved.\n\n## A2A delegates to an independent agent system\n\nA2A stands for Agent2Agent. The protocol connects a calling agent with an independent remote agent system. The client knows its published capabilities, but not its internal plan, memory or tools. The remote agent remains responsible for how it handles the task within its boundaries.\n\nAn Agent Card describes identity, endpoint, capabilities and authentication requirements. A message carries a conversation step made of text, files or structured data. Longer-running work gets a task with its own ID and a lifecycle. Results are returned as artifacts. Follow-up questions and other necessary decisions appear as state transitions of the task.\n\nThat distinguishes delegation from a tool call. With MCP, an agent application calls a described capability. With A2A, one agent hands a goal to another system that can plan on its own, use tools and carry out several steps.\n\n## Web UIs and machine interfaces serve different purposes\n\nA web UI for people is not a fifth kind of integration. MCP, HTTP with OpenAPI, webhooks and A2A connect machines. The web UI and the machine interfaces work with the state of the same domain and don’t introduce a second persistence path.\n\nEach web UI uses the terms and decisions of its own domain for this. In a knowledge service, a pending knowledge change is a change proposal; in a workflow engine, an execution belongs to a specific workflow version.\n\nTwo boundaries follow from this separation:\n\n- A web UI doesn’t become a second domain system with diverging rules.\n- A machine protocol doesn’t become an unintended way around the human decision.\n\n## No protocol grants permissions by itself\n\nAuthentication answers: who is making the request? Authorization answers: what may this identity do? A valid key shouldn’t lump reading, writing and publishing together across the board.\n\nAn agent searching for knowledge only needs read permissions. A step that builds a preview needs the write permissions required for that. A publication may require its own permission and a visibly bound human approval. If an operation is offered via several interfaces, the same domain approval boundaries must apply to it.\n\nReliability doesn’t come from the name of the protocol either. An HTTP call can break off after successful processing, before the response reaches the client. A webhook can arrive more than once. An A2A task can wait a long time for a decision. Every writing step therefore needs a stable identifier, a clear retry rule and a stored state.\n\nFor integrations that write or require approval, three contracts have to fit together:\n\n- The technical contract describes inputs, results and errors.\n- The domain contract defines which system owns knowledge, approval and publication.\n- The operational contract governs time limits, retries, logging and how outages are handled.\n\n## A flow with all four boundaries\n\n```mermaid\nflowchart LR\n    U[\"Human<br/>states a goal\"] --> A[\"Agent application<br/>works on an open task\"]\n    A -->|\"MCP<br/>search and read\"| K[\"Knowledge service<br/>reviewed knowledge\"]\n    A -->|\"MCP or HTTP / OpenAPI<br/>revision and preview\"| C[\"Publishing system<br/>publishing domain\"]\n    K -->|\"signed webhook<br/>approval event\"| S[\"Workflow engine<br/>versioned workflow\"]\n    S -->|\"HTTP / OpenAPI<br/>defined steps\"| C\n    A -.->|\"A2A<br/>delegate a bounded task\"| R[\"Agent system<br/>independent task\"]\n    H[\"Human in the respective web UI\"] -.-> K\n    H -.-> S\n    H -.-> C\n    H -.-> R\n```\n\nThe first run can be supervised. An agent application reads from the knowledge service, generates Markdown and builds a preview in the publishing system. A person sees the results and can still change the order.\n\nAs soon as the sequence repeats reliably, it belongs in a workflow engine as a versioned workflow. The workflow reads a specific approved knowledge revision, creates a content revision and builds a preview. It doesn’t publish automatically just because a webhook started it. The publishing system keeps the approval and release boundary.\n\nA2A comes in when an independent agent system actually takes on a bounded task with its own lifetime. Calling something an “agent” doesn’t turn a simple API call into delegation.\n\n## The decision comes before the protocol\n\nThe table only helps once three questions are answered: which system owns the state? Which identity may change it? Which effect requires a human decision? From these follow the rules for retries and the view in which a person can check the current state.\n\nFirst you decide who owns state and approval. Then comes the protocol.\n\n## Further reading\n\n- [Model Context Protocol: Architecture](https://modelcontextprotocol.io/docs/learn/architecture)\n- [Model Context Protocol: Introduction](https://modelcontextprotocol.io/docs/getting-started/intro)\n- [OpenAPI Specification](https://spec.openapis.org/oas/)\n- [Standard Webhooks](https://www.standardwebhooks.com/)\n- [A2A: Key concepts](https://a2a-protocol.org/latest/topics/key-concepts/)\n- [A2A and MCP compared](https://a2a-protocol.org/latest/topics/a2a-and-mcp/)"},{"locale":"en","translation_key":"a2a-agenten-zusammenarbeit","slug":"a2a-when-agents-work-together","title":"A2A: When Agents Work Together","summary":"Agent Card, Message, Task and Artifact explained clearly: how A2A 1.0 connects independent agent systems, what sets the protocol apart from MCP and when delegating to an independent system pays off.","tags":["Software","AI","Architecture"],"published_at":"2026-07-22T10:00:00+00:00","updated_at":"2026-08-18T18:22:46.983957+00:00","url":"https://www.mikebild.dev/en/blog/a2a-when-agents-work-together/","audio_url":null,"audio_duration_secs":null,"text":"An agent system needs a limited code change in someone else’s repository. It could load tools itself, read the code and draft the change. But it can also hand the job over to an independent system that runs in a different environment, has its own permissions and later reports back a verifiable result.\n\nA2A 1.0 – the abbreviation stands for Agent2Agent – describes, for this second case, how a job is handed over and tracked between independent systems. The published specification of the open protocol covers how a client finds a remote agent, sends it messages, tracks longer-running tasks and receives results. It doesn’t prescribe which language model, which programming language or which framework works internally.\n\n## Independent is the key word\n\nNot every named role is a separate agent. If an application runs three prompts one after the other and manages all tools, credentials and state centrally, then from an architecture perspective, those are three work steps in one agent system. A2A brings little there.\n\nA remote A2A agent, by contrast, is an independent service. Within its job, it decides for itself how it works. The calling agent sees the offered capabilities and the exchanged data, but not automatically the other system’s internal memory, reasoning or tools. This encapsulation separates the permission and task boundaries of both systems: the remote agent works with its own access rights, and only what the job calls for should be exchanged.\n\nIn the protocol, an A2A client makes contact on behalf of the user. The A2A server provides the remote agent. Client and server are communication roles, not classes of systems: for a different job, the same system can take on the other role.\n\n```mermaid\nflowchart LR\n    U[\"User<br/>sets a goal\"] --> C[\"Calling agent<br/>A2A client\"]\n    C -->|\"Read Agent Card\"| S[\"Remote agent<br/>A2A server\"]\n    C -->|\"Message<br/>job and context\"| S\n    S -->|\"Task<br/>state and follow-up questions\"| C\n    S -->|\"Artifacts<br/>results\"| C\n    S --> M[\"Internal models, tools<br/>and data sources\"]\n    C -.->|\"no automatic access\"| M\n```\n\n## The Agent Card is the description, not the permission\n\nBefore a client sends a job, it has to know what the other agent offers and how it can be reached. That is what the Agent Card is for, a JSON document with metadata. The published A2A 1.0 specification describes in it, among other things, identity, supported interfaces and offered skills; as ways to obtain it, it names a standardized address (`https://{domain}/.well-known/agent-card.json`), as well as catalogs or a fixed configuration.\n\nThe following fictional publishing example is reduced to the fields needed here and doesn’t claim to be a complete A2A 1.0 Agent Card.\n\n```json\n{\n  \"name\": \"Publishing Agent\",\n  \"description\": \"Builds previews and prepares approved releases\",\n  \"supportedInterfaces\": [\n    {\n      \"url\": \"https://publishing.example.com/a2a\",\n      \"protocolBinding\": \"HTTP+JSON\",\n      \"protocolVersion\": \"1.0\"\n    }\n  ],\n  \"version\": \"1.0.0\",\n  \"capabilities\": {\n    \"streaming\": true,\n    \"pushNotifications\": true,\n    \"extendedAgentCard\": true\n  },\n  \"defaultInputModes\": [\"text/plain\", \"application/json\"],\n  \"defaultOutputModes\": [\"text/markdown\", \"application/json\"],\n  \"skills\": [\n    {\n      \"id\": \"prepare-publication\",\n      \"name\": \"Prepare publication\",\n      \"description\": \"Creates a preview from approved knowledge\",\n      \"tags\": [\"publishing\", \"preview\", \"content\"]\n    }\n  ]\n}\n```\n\nThe Agent Card is comparable to a public service description. The fact that a skill is listed there doesn’t yet permit a call. Authentication and authorization remain separate security decisions: for every job, the server has to check who is asking and what this client is allowed to do. A public Agent Card should also not reveal internal capabilities or confidential endpoints.\n\n## Message, Part, Task and Artifact\n\nMessage, Part, Task and Artifact denote different building blocks of a job.\n\n| Term | Meaning | Example in delegated work |\n| --- | --- | --- |\n| Message | A conversational turn by the user or the agent | “Analyze this dependency and propose a change.” |\n| Part | A component of a Message or an Artifact | Instruction as text, a file or structured data |\n| Task | A stateful unit of work with a unique ID | The job is waiting for an answer to a question or keeps working |\n| Artifact | A result produced by the agent | Analysis report, prepared change, preview URL |\n\nA Message can be answered immediately with another Message. That fits a short conversation without a lasting work state. If the work has to keep running or be preserved across several conversation rounds, the remote agent responds with a Task.\n\nThe Task is more than a technical request ID. It holds the state of a domain unit of work. The client can read it later, answer a follow-up question or request a cancellation. According to the specification, several Messages can belong to the same conversation context via a `contextId`; a `taskId` denotes the concrete work. A simplified, non-normative example:\n\n```http\nPOST /message:send HTTP/1.1\nHost: agents.example.com\nAuthorization: Bearer <token>\nContent-Type: application/a2a+json\nA2A-Version: 1.0\n\n{\n  \"message\": {\n    \"role\": \"ROLE_USER\",\n    \"messageId\": \"msg-123\",\n    \"parts\": [\n      {\n        \"text\": \"Prepare a limited change proposal. Do not merge it.\"\n      },\n      {\n        \"data\": {\n          \"repository\": \"product-service\",\n          \"scope\": [\"dependency-upgrade\"]\n        },\n        \"mediaType\": \"application/json\"\n      }\n    ]\n  }\n}\n```\n\nThe Parts separate different kinds of content within the same Message: text carries an instruction, a file hands over a document, structured data allows an agreed schema without parsing it out of prose again. The recipient has to check the media type, size, origin and permission of each piece of content.\n\nArtifacts are the work results, not just conversational turns. According to the specification, a Task can deliver several Artifacts, and an Artifact can be extended step by step during a stream. The client should therefore store the Artifact ID and Task ID instead of just copying the last visible text. A typical first response looks like this – the server has accepted, but not finished yet:\n\n```json\n{\n  \"task\": {\n    \"id\": \"task-456\",\n    \"contextId\": \"context-789\",\n    \"status\": {\n      \"state\": \"TASK_STATE_WORKING\",\n      \"timestamp\": \"2026-08-07T10:05:00Z\"\n    },\n    \"artifacts\": []\n  }\n}\n```\n\n## The lifecycle makes longer work visible\n\nA2A is designed for asynchronous tasks. A server can return a Task immediately and keep working in the background. For updates, the specification provides three delivery paths: queries, a continuous stream or push notifications.\n\n```mermaid\nstateDiagram-v2\n    [*] --> SUBMITTED\n    SUBMITTED --> WORKING\n    WORKING --> INPUT_REQUIRED: follow-up question\n    INPUT_REQUIRED --> WORKING: further Message\n    WORKING --> AUTH_REQUIRED: additional approval\n    AUTH_REQUIRED --> WORKING: permission granted\n    WORKING --> COMPLETED\n    WORKING --> FAILED\n    SUBMITTED --> REJECTED\n    WORKING --> CANCELED\n    COMPLETED --> [*]\n    FAILED --> [*]\n    REJECTED --> [*]\n    CANCELED --> [*]\n```\n\nThe diagram simplifies the state space defined in the version 1.0 specification. `INPUT_REQUIRED` means that the agent needs further domain information. `AUTH_REQUIRED` signals an authorization needed during the job; credentials don’t belong in a Message as plain text but go through a separate, previously agreed path. The specification defines `COMPLETED`, `FAILED`, `CANCELED` and `REJECTED` as final states. A client must not revive a final state by blindly retrying, but has to deliberately create a new Task.\n\nPolling, streaming and push solve the same delivery problem in different ways. With polling, the client asks for the Task at sensible intervals – simple, but wasteful during long pauses. With streaming, a connection stays open and the server sends status and Artifact updates as events; after an interruption, the client has to read the stored Task again, because a stream is not an archive. Push notifications spare you the permanent connection, but require a secured HTTP endpoint on the client side, including authentication, protection against internal target addresses and handling of duplicate deliveries.\n\n## Delegation creates no new permission\n\nA2A doesn’t make any security decision for a system. A calling agent should not trust an Agent Card it found just because it is formally correct. Before a job, it has to be clear which provider your own system trusts, which data may leave it and which effects the remote agent can trigger.\n\nThe A2A server has the same obligation: for every job, it has to check who is asking and what this client is allowed to do, and treat Messages as untrusted input. The most important principle behind this: delegation must not create new permissions. Whoever submits a job must not gain more rights in the target system by doing so, and the executing agent must not silently inherit the rights of its client. The job stays limited.\n\nA target system can make this limitation explicit: a delegated job is then bound to an active, human-approved job state. What this state doesn’t allow, even a technically correct A2A call cannot trigger. A human approval step thus remains a domain decision in the target system – an agent must not infer an approval from friendly wording in a Message.\n\n## MCP, A2A and a web UI are different access paths, not labels\n\nMCP provides an agent application with tools and context; responsibility for the open task stays with the application. A2A connects independent agent systems: the client hands over a goal, the remote agent is responsible for the execution and runs its own Task lifecycle. MCP and A2A thus model different responsibilities and lifecycles.\n\n| Question | MCP | A2A |\n| --- | --- | --- |\n| Counterpart | Capability server | Independent agent system |\n| Discoverable description | Tools and context sources | Agent Card with skills and interfaces |\n| Typical work | Select and call a tool | Delegate a goal or subtask |\n| Longer-running state | Modeled by the application | Task lifecycle is a protocol concept |\n| Result | Tool result or resource | Message or one or more Artifacts |\n| Internal implementation | Capability with a defined schema | Remote agent stays independent internally |\n\nOn top of that comes a web UI as an access path for people. These access paths have different jobs, and a system can offer several of them without that turning into several domain models.\n\nFor example, a system can offer limited analysis and change jobs via A2A 1.0, while REST, MCP, A2A and the web UI read the same structured task and result record.\n\n## When A2A makes sense\n\nA2A pays off when several conditions apply at the same time: the agents involved are developed or operated independently. The work may take longer than a single request, needs follow-up questions or produces several results. The client defines the goal and the permitted effect; the remote agent is responsible for the internal execution.\n\nFor a known sequence of fixed steps, a deterministic workflow is usually simpler. Merely different role names, several language models or separate prompts don’t yet justify a distributed agent architecture – they only create an additional network boundary without an additional boundary of responsibility.\n\nThe decision can be anchored in who carries the responsibility for the open task. If it stays in your own application and only needs tools or context, MCP may be enough. If an independent system takes over a limited job with its own Task lifecycle, A2A is the right contract. If you keep these levels apart, you don’t build unnecessary agents – and you recognize the features of the delegation described here: an Agent Card, an authenticated call, a traceable Task and a limited job.\n\n## Further reading\n\n- [A2A Protocol Specification 1.0](https://a2a-protocol.org/latest/specification/)\n- [A2A: Core Concepts](https://a2a-protocol.org/latest/topics/key-concepts/)\n- [A2A: Life of a Task](https://a2a-protocol.org/latest/topics/life-of-a-task/)\n- [A2A and MCP compared](https://a2a-protocol.org/latest/topics/a2a-and-mcp/)\n- [Model Context Protocol: Architecture](https://modelcontextprotocol.io/docs/learn/architecture)\n- [MCP, HTTP, Webhooks and A2A Explained Simply](https://www.mikebild.dev/en/blog/mcp-http-webhooks-and-a2a-explained-simply/)"},{"locale":"en","translation_key":"stuendlich-ist-nicht-echtzeit","slug":"hourly-is-not-real-time","title":"Hourly Is Not Real Time","summary":"A closed hourly report answers different questions than ongoing operational monitoring – and gets simpler as soon as time windows, delays and measurement gaps are modeled explicitly.","tags":["Software","Architecture","Observability","Delivery"],"published_at":"2026-07-20T10:00:00+00:00","updated_at":"2026-08-18T15:35:19.820644+00:00","url":"https://www.mikebild.dev/en/blog/hourly-is-not-real-time/","audio_url":null,"audio_duration_secs":null,"text":"An hourly report doesn’t ask about the current state but about the hour that just closed. Whatever happens at 14:00:00 UTC already belongs to the next time window. So the run only starts once the time window is closed, and it publishes its state a few minutes later. For an alert, that would be far too late. For a reliable summary, it’s exactly the delay you want.\n\nThis timing decision separates the hourly report from ongoing operational monitoring. A closed report answers a different question than monitoring: it records a bounded period as a verifiable state of the observations, while monitoring has to react to new signals. The difference isn’t primarily in Prometheus, Grafana or Markdown. It lies in how quickly a new value has to trigger a reaction and whether the statement in question may still change later.\n\nThe article [“Markdown Reports Instead of Dashboard Mandates”](https://www.mikebild.dev/en/blog/markdown-reports-instead-of-dashboards/) already describes the difference between a fleeting view and a verifiable state. This one is more narrowly about the timing mechanics of a regular product report: closed time windows, late data, retries and the boundary to real operational monitoring.\n\n## Two time axes, two jobs\n\nMonitoring works as close to the event as possible. An error rate rises, an alert is evaluated, someone opens logs and traces. New data keeps changing the display. A report, on the other hand, waits until its period has ended. It can then determine which sources were complete, hash its facts and deliver the same state again later.\n\n```mermaid\nflowchart LR\n    E[\"Event\"] --> M[\"Live metric<br/>seconds to minutes\"]\n    M --> A[\"Alert or investigation\"]\n    E --> W[\"Closed hourly window\"]\n    W --> R[\"Immutable report\"]\n    R --> V[\"Comparison and context\"]\n```\n\nBoth paths may see the same event and still arrive at different results. Monitoring can react at 13:42 to five errors in two minutes. Later, the hourly report records that in the time window from 13:00 to 14:00, five errors occurred across 1,200 executions, which sources were covered and whether the cluster stands out compared with earlier time windows.\n\nA continuously updated UI for the second job would show incomplete intermediate states. While the time window is running, counters are incomplete. A value of zero at 13:01 says almost nothing about the hour. A growing bar invites you to compare unmarked intermediate states with closed hours. Without accounting for the different coverage, that comparison doesn’t hold up.\n\n## The boundaries of the time window\n\nCollection uses half-open UTC intervals. Start included, end excluded. This notation prevents an event at the boundary from ending up in two reports.\n\n```ts\ntype ClosedWindow = {\n  from: string; // inclusive RFC 3339 timestamp\n  to: string;   // exclusive RFC 3339 timestamp\n  bucket: \"hour\";\n};\n\nconst window: ClosedWindow = {\n  from: \"2026-07-18T13:00:00.000Z\",\n  to: \"2026-07-18T14:00:00.000Z\",\n  bucket: \"hour\"\n};\n```\n\nUTC avoids an unpleasant special case: in Europe, the day of the daylight saving time switch doesn’t always have 24 local hours. Storage and collection therefore stay in UTC. The report page can localize a date for its readers later without changing the domain boundary.\n\nBetween the end of the time window and the freshness check, this process provides an explicitly defined buffer. If collection grows more extensive, start time, timeout and check boundary have to be adjusted together. A secretly extended buffer would only make real delays visible later.\n\n## Keeping late data and missing runs apart\n\nAn HTTP call can fail temporarily. A workflow can abort after writing the artifact but before updating its status. A release can succeed even though the response never reaches the client. That’s why a retry must not simply mean “everything again.”\n\nEach run has a unique time window. Cadence-tagged reports are treated here as immutable publications: once an hourly state is published, it doesn’t change anymore. A repeated successful attempt must therefore not make a second, different hourly report visible for the same time window.\n\nOnly after the intended buffer does the distinction between late and missing apply. A late run can still complete successfully and publish the same report. A missing run leaves a gap in the expected sequence of hours. Lateness, measurement gap and closed time window thus remain three separate facts that the report should name separately.\n\n## What follows from a missing observation\n\nA critical case for an hourly report is an hour without data. An observation service should explicitly distinguish four states for this: a source has never been observed, it was checked and the expected content isn’t there, it is access-protected, or it is actually broken. A missing observation must be reported neither as a healthy state nor as the numeric value zero.\n\nFor an hourly report, this means: if there’s no measurement for an hour, there’s no value for that hour. The report then must not claim there were zero events, because that statement would imply a measurement that never took place. Instead, it has to show that the source wasn’t observed in the period in question and the statement remains open. If, on the other hand, the source was checked and the expected content wasn’t found, that state is observed; but that doesn’t automatically mean a general error counter of zero.\n\n## When you would miss Prometheus and Grafana\n\nTools like Prometheus and Grafana support, among other things, ongoing investigation: you can adjust a query during the analysis and shift the time range. This way of working is valuable when the question wasn’t fixed in advance.\n\nA UI for hourly reports, on the other hand, can be geared toward closed report periods. That focus fits as long as the UI is meant to explain closed periods. For an incident analysis, though, warnings would come too late, and hourly resolution isn’t enough to trace a cause down to individual requests. An hourly report replaces neither alerting nor ongoing operational monitoring; it assumes both as separate jobs.\n\n## Four questions before choosing a tool\n\n“Dashboard or report?” is too coarse. Four questions separate the requirements: reaction time, mutability, investigation and resolution.\n\nThe first concerns reaction time. If someone has to act within seconds or a few minutes, the observation belongs in a monitoring and alerting system. If a team can check the state in the next regular work cycle, an hourly or daily report may be enough.\n\nThe second concerns mutability. If the same URL should show new values tomorrow, a live query fits. If exactly the state from July 18 still has to be readable later, you need an immutable artifact or an explicitly stored snapshot.\n\nThe third concerns investigation. If the questions are known in advance – number of releases, errors, source coverage – a limited schema can represent them precisely. If the questions only arise when you look at an anomaly, a query language, variable time ranges and drill-down become important.\n\nThe fourth concerns resolution. An hourly counter can show that something failed more often. It can’t explain which individual request was slow or which log line belongs to a trace. For that investigation, the high-resolution data has to stay in its operational tool.\n\n```yaml\ndecision:\n  reaction_time: next_work_cycle\n  immutable_history: required\n  questions_known_in_advance: true\n  per_request_drilldown: false\nresult: scheduled_report\n```\n\nAs soon as one answer flips, the right tool can change too. A report and a live system may observe the same service, as long as they don’t pretend to do the same job.\n\n## The scheduler is part of the statement\n\nA manually generated report only proves that someone pressed a button at some point. A scheduled run additionally makes visible whether the expected regularity was kept. A check of this regularity therefore has to distinguish between scheduled and manually triggered runs: manual runs must not cover up a missed scheduled hour, otherwise the check counts successes that say nothing about the promise of regularity.\n\nA pause isn’t an error either, if it was explicitly set during a release. But it has to be visible and deliberately lifted after the rollout. A forgotten pause switch isn’t a data problem but a broken promise about regularity.\n\n## What an hourly report has to explain\n\nWithout stated source coverage, an operator can read a measurement gap as a result. An hourly report therefore has to explain for itself what it’s based on. Overview, question, conclusion and next action can be derived from the same semantic report document; a second, separately maintained dashboard dataset isn’t needed for that. A suitable UI shows this answer in decreasing order of importance: first state and exception, then a few signals, then evidence and provenance.\n\nA page with thirty metrics and no question is harder to check than a page with one clear question, one supported state and one named next decision. For this, the fact definition also has to represent data gaps: it should name available, missing and stale sources separately, so that an open statement doesn’t look like an answered one.\n\n```md\n## Data quality\n\nThe source window is complete for four product APIs.\nExternal acquisition data is not connected yet and is shown as unavailable.\nNo value is inferred from missing input.\n```\n\nAggregation needs an explanation too. A weekly median runtime answers a different question than the maximum of the slowest hour. The report names the period, the expected and available sub-windows and the aggregation used. Otherwise, a precise number looks more verified than it is.\n\n## Rolling up over larger periods\n\nDaily, weekly, monthly and yearly reports are built from already closed artifacts. A daily report can build on the immutable hourly states instead of querying the same sources again for each hour, and in doing so show which hourly windows it’s missing. Cadence-tagged reports remain immutable publications; a rollup doesn’t replace an hourly state, it condenses it.\n\n```mermaid\nflowchart TD\n    H[\"24 hourly artifacts\"] --> D[\"Daily report\"]\n    D --> W[\"Weekly report\"]\n    W --> M[\"Monthly report\"]\n    M --> Y[\"Yearly report\"]\n    H --> Q[\"Coverage and missing windows\"]\n    Q --> D\n```\n\nA daily report that’s missing individual hourly windows can still be more helpful than no report at all – but only if it clearly marks itself as incomplete. It must not radiate the same visual certainty as a fully covered period. Data quality belongs next to the metrics, not in a footnote.\n\nA UI can place the latest closed period ahead of further decision horizons and a limited history. Which question each coarser report answers is a design decision. An obvious split: the hour checks the data flow and fresh technical signals. The day answers what needs attention today. The week compares daily patterns and recurring exceptions. The month puts activity patterns, operational risks and measurement gaps in context for the next round of planning. The year condenses only the evidence that can support a strategic decision. Just widening the date filter would be formally correct and weak in substance.\n\nNumbers aren’t just values here either. A fact definition should distinguish counters, stocks, durations, ratios and data volumes, name the unit and specify whether a rollup prefers the sum, the last value or the mean. A machine then doesn’t have to guess from a metric name how the value should be read across several intervals.\n\n## Simple technology needs a clear boundary\n\nThe hourly approach can get by without an additional, permanently running analytics platform if existing systems take over collection, scheduling and publishing. Its questions are fixed before the run, and its result appears as an immutable publication. What matters is the boundary of responsibility: the report collects, closes and publishes; ongoing observation stays with the systems built for it.\n\nThis simplicity only survives if the system stands by its job. A report may show a missing data source instead of secretly building in new data collection. It may point to an external incident view instead of becoming the control room itself. And it may leave a question unanswered if there’s neither a fact nor a connector for it.\n\nHourly here doesn’t mean “almost live.” It means: regular, closed, repeatable and slow enough to verify a complete state. If you have to react faster, you need monitoring and alerting. If you want to trace later what was known in a clear period, you need an hourly report. Both exist side by side, with clearly assigned jobs: monitoring delivers ongoing signals, alerting triggers a reaction from them, and the hourly report preserves the closed, verifiable state of observation.\n\n## Further reading\n\n- [Prometheus Overview](https://prometheus.io/docs/introduction/overview/)\n- [Grafana Dashboards](https://grafana.com/docs/grafana/latest/visualizations/dashboards/)\n- [W3C Trace Context](https://www.w3.org/TR/trace-context/)"},{"locale":"en","translation_key":"claims-klein-belegt-pruefbar","slug":"claims-small-sourced-verifiable","title":"Claims: Small, Sourced, Verifiable","summary":"Claims break wiki pages down into individual statements with subject, predicate, object, confidence, status and a verbatim quote as evidence. This makes agreement and disagreement precise.","tags":["Software","AI","Methodology"],"published_at":"2026-07-20T10:00:00+00:00","updated_at":"2026-08-18T06:39:59.272448+00:00","url":"https://www.mikebild.dev/en/blog/claims-small-sourced-verifiable/","audio_url":null,"audio_duration_secs":null,"text":"“Our publishing is secure, fast and reliable.” The sentence sounds good and is hardly usable as a claim. It contains three judgments, none of them has a criterion, and a source could at most support parts of it. A reviewer would have to accept or reject the whole sentence, even though they might only be able to confirm a documented rollback mechanism as part of reliability.\n\nA knowledge base should therefore store small statements as `subject / predicate / object`. The page text stays readable for people. Beneath it, claims form the units that can be cited, checked, disputed and retired one by one. Confidence and status answer different questions.\n\n## A claim says exactly one thing\n\nThe subject names the thing, the predicate the relationship or property, and the object the concrete value. A good claim can be understood without the rest of the paragraph on the page.\n\n```json\n{\n  \"subject\": \"content-release\",\n  \"predicate\": \"rollback_mechanism\",\n  \"object\": \"switch the active pointer to an immutable revision\"\n}\n```\n\nThe form resembles a simple RDF triple, but it doesn’t force you to model the entire domain as a universal graph. Within a space, a controlled vocabulary emerges that fits its questions. `rollback_mechanism` can make sense where releases are compared; in an HR space it would be meaningless.\n\nClaims that are too large combine several verifiable statements. Claims that are too small lose their meaning. `content-release / uses / pointer` would be atomic, but it doesn’t explain what the pointer is used for. The wording should be narrow enough for a contradiction and complete enough for a reader.\n\n```mermaid\nflowchart TD\n    A[\"Statement from source\"] --> Q{\"one domain<br/>assertion?\"}\n    Q -->|several| S[\"split into several claims\"]\n    Q -->|one| C{\"understandable<br/>without the paragraph?\"}\n    C -->|no| E[\"make the object more precise\"]\n    C -->|yes| V[\"add quote and status\"]\n```\n\n## The quote carries the statement\n\nEvery claim points to one or more sources via citations. A citation contains a verbatim excerpt and, optionally, a locator. A quote check can make sure the quote appears verbatim in the archived source text. A claim whose evidence is only paraphrased or made up should be discarded before it reaches review.\n\n```json\n{\n  \"subject\": \"content-release\",\n  \"predicate\": \"rollback_mechanism\",\n  \"object\": \"switch the active pointer to an immutable revision\",\n  \"confidence\": 0.94,\n  \"citations\": [\n    {\n      \"source_id\": \"source_release_docs\",\n      \"quote\": \"Rollback changes the active release pointer to a previous immutable revision.\",\n      \"locator\": \"Rollback\"\n    }\n  ]\n}\n```\n\nA quote has to support the statement within its scope. If the source only talks about a preview environment, the claim must not turn that into a general production rule. This check can’t be done with string matching alone. The reviewer reads the context.\n\nSeveral citations are useful when a statement is supported jointly by a contract and observed behavior. The API documentation can describe the intended mechanism, a production report can document its actual use. Many weak sources, however, don’t automatically make a claim stronger.\n\n## Confidence is not a truth scale\n\n`confidence` describes how sure the generating synthesis was about its mapping. It can help the reviewer look at uncertain proposals first. It is not a substitute for status and not a probability that a statement is true in the world.\n\n```ts\ntype ClaimStatus = \"proposed\" | \"verified\" | \"disputed\" | \"deprecated\";\n\ntype Claim = {\n  subject: string;\n  predicate: string;\n  object: string;\n  confidence: number;\n  status: ClaimStatus;\n};\n```\n\nA claim with `confidence: 0.99` stays `proposed` until approval. An approved claim with `confidence: 0.78` can be `verified` because a person checked the source and the wording. Later, new evidence can make it `disputed` without reinterpreting the old confidence value.\n\nThis separation prevents a convenient shortcut. A threshold like “approve automatically from 0.9” would confuse model self-confidence with domain authority. It makes more sense to turn every knowledge change into a change proposal, regardless of the value in `confidence`. It is only adopted after human approval.\n\n## Status models the lifecycle\n\n`proposed` is staging and invisible to normal readers. `verified` marks an approved statement. `disputed` makes a traceable conflict visible. `deprecated` keeps an outdated statement in the history without treating it as the current state.\n\nThe lifecycle allows more precise answers than deletion. If a service used a static retry value up to version 2 and shares a budget since version 3, both statements are historically relevant. The old one isn’t removed from all revisions. It gets a status and stays connected to its source.\n\n```mermaid\nstateDiagram-v2\n    [*] --> proposed\n    proposed --> verified: human approval\n    proposed --> [*]: rejection\n    verified --> disputed: conflicting evidence\n    disputed --> verified: conflict resolved\n    verified --> deprecated: superseded\n    disputed --> deprecated: superseded\n```\n\nThe transition from `proposed` to `verified` doesn’t happen automatically but only after a human decision. The visible page text can then explain the current state fluently. The claims beneath it preserve which individual statements carry that explanation and which conflicts are still open.\n\n## Functional predicates make conflicts exact\n\nSome relationships may have several objects at the same time. A system can support several export formats. `supports_format=markdown` doesn’t contradict `supports_format=okf`. Other relationships should have only one current value per subject, such as `primary_database`.\n\nA space can declare such functional predicates. If two different objects for the same subject and predicate meet there, the knowledge base can mark both claims as `disputed` and connect them via `contradicts`.\n\n```json\n{\n  \"settings\": {\n    \"functional_predicates\": [\n      \"primary_database\",\n      \"current_owner\",\n      \"default_retention_days\"\n    ]\n  }\n}\n```\n\nThis rule stays deterministic. A model doesn’t have to decide whether two freely worded paragraphs collide semantically. The controlled predicate states in advance exactly where a single current value is expected.\n\nToo many functional predicates would be harmful. Marking `supports_format` as functional would wrongly put complementary facts in conflict. The vocabulary is therefore a domain decision of the space and belongs in review.\n\n## Breaking a paragraph into claims\n\nA practical example shows the sizing decision. Suppose a source says: “The service runs as a single binary, migrates PostgreSQL on startup, and exposes health and readiness endpoints.” This should not turn into one claim with the object `single binary with migrations and probes`. Three properties change independently of each other.\n\n```json\n[\n  {\n    \"subject\": \"service-runtime\",\n    \"predicate\": \"distribution\",\n    \"object\": \"single self-contained binary\"\n  },\n  {\n    \"subject\": \"service-runtime\",\n    \"predicate\": \"database_migration\",\n    \"object\": \"runs automatically on startup\"\n  },\n  {\n    \"subject\": \"service-runtime\",\n    \"predicate\": \"exposes_probe\",\n    \"object\": \"/health and /ready\"\n  }\n]\n```\n\nIf a sidecar is added later, it affects the distribution claim. The migration and the probes can stay unchanged. A reviewer sees exactly the small diff. An agent can keep using the two confirmed statements while the first one is being checked.\n\nThe cross-check helps: would a change to the object automatically change the other parts of the statement? If not, several claims are appropriate. If a claim would be misleading without its neighboring sentence, it needs a more precise subject or object.\n\nTime and scope belong in the wording too. `uses PostgreSQL` fits a current architecture if the source describes the whole service. If it only refers to the production deployment, the subject should be `service-production-deployment`. Precision often comes more easily from a narrower subject than from a long object text.\n\nA claim is not a complete sentence for blog prose. It may stay machine-readable and terse. The concept page then explains how the three properties work together.\n\n## A concept is more than its claims\n\nClaims alone don’t make a readable explanation. A concept still has a title, a summary, Markdown and relationships to other concepts. The page can explain an example, limitations and the historical context.\n\nThe claims serve a different purpose. They let you:\n\n- trace a single statement back to the original quote;\n- mark a contradiction without rejecting the whole page;\n- check only the statements that actually changed in a new revision;\n- limit search hits and agent answers to visible, approved units.\n\nPage text and the structured layer should be revisioned together. A proposal must not already show new text while its claims are invisible or incomplete for readers. Atomic approval makes the new revision current as a unit.\n\n## Relations connect, claims provide evidence\n\nBesides claims, a knowledge base can know directed relationships between concepts: `related`, `part_of`, `depends_on`, `contradicts` and `supersedes`. A relation answers how two pages are connected. It doesn’t replace a claim or a citation.\n\n```json\n{\n  \"from_slug\": \"content-release\",\n  \"kind\": \"depends_on\",\n  \"to_slug\": \"immutable-revision\"\n}\n```\n\nThe relation enables navigation and context. The documented fact stays as a claim on one of the pages. Otherwise a mere link would carry a domain statement without naming its wording or its source.\n\n`contradicts` can arise as a consequence of the functional predicate logic. `supersedes` fits a traceable replacement where the new term or the new rule replaces the old state. Relations themselves are reviewed and published with the concept revision.\n\n## Revisions answer the question of time\n\nA current claim alone doesn’t explain when it was introduced. A concept history should keep approved, rejected and proposed revisions together with their provenance: which model and which prompt version generated the proposal, which sources were used and which person approved it.\n\nThis information doesn’t make a model the author in a legal or domain sense. It documents which technical synthesis path generated the proposal. Reviewer, note and timestamp explain the human decision. Approval, status and revision together make visible how a statement entered the valid body of knowledge – and how it can leave it again.\n\nThe history allows a time-related question: which statement was visible in March, before the retention rule was changed? A knowledge service that always returns only the current paragraph can’t answer it reliably. Revisions preserve the state at the time without presenting old claims as valid today.\n\nFor teams, this trail becomes especially useful after model or prompt changes. If a new synthesis version proposes noticeably different claims, the affected revisions can be identified and checked specifically. That way, besides the source, you can also trace which model and which prompt version generated the proposal.\n\n## A step beyond “Clean Grounding II”\n\n[Clean Grounding II](https://www.mikebild.dev/en/blog/clean-grounding-ii-grounding-answers/) sorted grounding into conventions, documents and API descriptions. The central question was which material belongs in the scarce context for a specific task and how expensive it would be to retrieve it again. That was a working model for individual sessions.\n\nWhat’s added is a smaller, durable unit between document and context: the claim. An agent doesn’t have to treat a whole page as uniformly binding every time. It can read the current concept revision, check visible claims including their status and open their citations when needed. “Matching document into the context” becomes “matching, approved statement with a way back to the source.”\n\nThe older article [Fuzzy Matching with Explicit Limits](https://www.mikebild.dev/en/blog/fuzzy-matching-with-explicit-limits/) separated a claim with confidence from a fact. The same caution applies here. Confidence helps sort a proposal. Only evidence, review and status determine how the statement appears in the knowledge base.\n\n## Checking claims in review\n\nFor a new proposal, four questions are enough. Does the claim assert exactly one thing? Is it understandable without the surrounding paragraph? Does the quote cover exactly this scope? Would a different new value be recognizable as a clear contradiction?\n\nIf an answer is no, the claim gets split, worded more narrowly or rejected. This is not a formal word exercise. Small claims reduce the effort later. A changed retention rule then doesn’t require a complete rewrite of the page about storage. Only the affected statement and its explanation get adjusted.\n\nOnly statements that matter for search, review, conflicts or provenance get structured. The point is not to map every sentence as a universal ontology. Everything else stays prose; no claim is created for it.\n\n## Further reading\n\n- [W3C RDF 1.1 Concepts](https://www.w3.org/TR/rdf11-concepts/)\n- [W3C PROV-O](https://www.w3.org/TR/prov-o/)\n- [Clean Grounding II](https://www.mikebild.dev/en/blog/clean-grounding-ii-grounding-answers/)\n- [Fuzzy Matching with Explicit Limits](https://www.mikebild.dev/en/blog/fuzzy-matching-with-explicit-limits/)"},{"locale":"en","translation_key":"produkte-berichten-ueber-ihre-api","slug":"products-report-through-their-api","title":"Products Report Through Their API","summary":"Product statistics stay understandable when every system aggregates its own data and offers it through a small HTTP contract with uniform time semantics.","tags":["Software","Architecture","API","Delivery"],"published_at":"2026-07-19T10:00:00+00:00","updated_at":"2026-08-18T06:39:59.272448+00:00","url":"https://www.mikebild.dev/en/blog/products-report-through-their-api/","audio_url":null,"audio_duration_secs":null,"text":"A statistics API is a product feature. That sentence sounds obvious, but while working on cross-product reporting, it only became clear after two worse designs. At first, a central collector was supposed to access several PostgreSQL databases directly. After that, special private reporting endpoints and dedicated keys were on the table. Both would have built the report deeper into the products than its purpose requires.\n\nWhat remained was a smaller contract. A publishing system, a knowledge base and an orchestrator aggregate their own data themselves and offer their view through normal, authenticated HTTP endpoints. A downstream process combines the aggregates for explicitly bounded time windows – it sees neither tables nor Markdown, names, keys or internal IDs.\n\nThis split is not a special trick for dashboards. Every authorized consumer can use the same statistics resources: a capacity report, a quality check, a local analysis or a later export tool.\n\n## Data ownership is more than storage location\n\nWhoever owns a table knows its meaning. A publishing system knows when a revision was created and when a release was actually activated. A knowledge base distinguishes a started ingest from a verified state of knowledge. An orchestrator aggregates its execution data where the runs actually take place. A central collector would have to rebuild these meanings and keep up with every product change.\n\nDirect SQL makes this rebuilding particularly easy – and therefore dangerous. A query works even though it may count an intermediate status that the product itself would never show as complete. A new migration can break the report without the public product API having changed. Database access also bypasses the normal permission check and pulls the credentials of several systems into one place.\n\nWith a product API, the domain aggregation lives where the state change is implemented:\n\n:::process{title=\"Domain aggregation stays in the product\" role=\"primary\" preferredPattern=\"connected-process\"}\n1. Product action · creates a domain-defined state transition\n2. Own data store · keeps the product’s authoritative domain state\n3. Aggregation · translates internal states into bounded domain metrics\n4. Statistics API · delivers authenticated values with time range and meaning\n5. Collector · combines compatible responses without redefining them\n6. Report · explains the frozen shared state\n:::\n\nThe collector may combine the responses, but it may not reinterpret what a successful release or a verified claim is. These terms belong to the product.\n\n## Time is uniform, the domain is not\n\nA shared contract doesn’t mean that all products deliver the same metrics. That would be artificial leveling. The only shared properties are the ones a collector needs for reliable time windows:\n\n- `bucket` determines the resolution: hour, day, month or year.\n- `from` is the inclusive start of the window.\n- `to` is the exclusive end.\n- `tz` makes the time zone explicit, UTC throughout here.\n- `buckets` contains a dense series, including empty intervals.\n- `totals` summarizes exactly the requested window.\n\nThe payload keeps its domain names. A publishing system can, for example, provide site-scoped aggregates for releases, content and reader access, a knowledge base space-scoped aggregates for usage, coverage and reviews, an orchestrator tenant-scoped runtime statistics for executions and connectors. No product has to adopt another product’s terms; all of them have to fulfill the same time contract.\n\n```json\n{\n  \"bucket\": \"hour\",\n  \"tz\": \"UTC\",\n  \"from\": \"2026-07-18T10:00:00.000Z\",\n  \"to\": \"2026-07-18T12:00:00.000Z\",\n  \"buckets\": [\n    { \"ts\": \"2026-07-18T10:00:00.000Z\", \"items_created\": 2 },\n    { \"ts\": \"2026-07-18T11:00:00.000Z\", \"items_created\": 0 }\n  ],\n  \"totals\": { \"items_created\": 2 }\n}\n```\n\nThe half-open notation `[from,to)` prevents double counting. The window from 10 to 11 o’clock contains an event at 10:59:59, but none at 11:00:00. The next window starts exactly there. A retry queries the same time window again and gets the same meaning.\n\n## Measured zero, missing observation, incomplete window\n\nA dense time series also contains empty buckets. That is practical, because the collector doesn’t have to guess or fill in missing hours. A zero is a measured value: the product evaluated the window and found no matching event.\n\nTwo other states have to be distinguished from this. Missing means that there is no observation for the metric – for example, because a source isn’t connected or a ratio cannot be calculated without a base. In the reporting process described here, the downstream report also determines incompleteness: an expected snapshot is missing, or the window had not yet closed at the time of collection. These three cases must not look the same in the report, because they carry different consequences: zero technical errors are reassuring, zero page views can be correct, a missing analytics connection is an open connection and not a measurement.\n\nA product can make the distinction between measured and missing part of the response and label values, for example, with `value_state` and `value_kind`. A ratio without observations carries the state `missing` and is not output as a measured zero:\n\n```json\n{\n  \"metric\": \"engagement_rate\",\n  \"value_kind\": \"ratio\",\n  \"value_state\": \"missing\"\n}\n```\n\nFor someone reading a report, this state matters more than another decimal place. Time window, data state and the meaning of a measurement therefore belong in the contract itself – not in a footnote on the report page.\n\n## Privacy starts with the shape of the response\n\nAggregates should leave out information the purpose doesn’t need. A statistic can count successful, failed and rate-limited reader requests without storing user names, IP addresses, session IDs, Markdown content, URLs, job IDs or credentials in the statistics table. A knowledge base doesn’t have to output source texts through its statistics resources.\n\nSuch a negative list belongs in the documentation and in contract tests. “We currently don’t return any names” is weaker than a schema that has no field for names at all. The collector then cannot accidentally carry a sensitive value over into a JSON artifact or a report page.\n\nTrace data also stays limited to its purpose. W3C Trace Context standardizes `traceparent` and `tracestate` so that a call can be correlated across several services. The W3C recommendation explicitly warns against transporting personal or other sensitive information in these headers. A trace ID connects technical steps; it doesn’t describe a person.\n\n```http\nGET /v1/sites/example/stats/releases?bucket=hour&from=2026-07-18T10:00:00Z&to=2026-07-18T11:00:00Z\nAuthorization: Bearer <site-read-key>\ntraceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\n```\n\n## Zero-config means using existing terms\n\nTelemetry is rarely completely configuration-free. A service needs at least durable storage and information about whether it runs in development, test or production. “Zero-config” is meant more narrowly here: for the reporting process, no special mode is activated in the product, no special key is created and no report target is entered.\n\nThe statistics endpoints can use existing product boundaries: a publishing system, for example, the site and a normal read key, a knowledge base the space and its read scope, an orchestrator the tenant.\n\nOpenTelemetry provides a usable shared vocabulary for this. `service.name` names the logical service, `deployment.environment.name` distinguishes `development`, `staging`, `production` and `test`; as of August 2026, the older key `deployment.environment` is marked as deprecated in the OpenTelemetry conventions. Standardized fields like these prevent one service from treating `prod`, another `live` and a third `production-eu` as the same concept. The product sets these values once for its runtime; the reporting collector doesn’t have to repair labels.\n\nThe shared name alone is not enough, though. If an aggregator reads different field names than an older write path still delivers, successful calls can show up as errors. Such a transition can be made compatible in both directions: the reader understands old and new fields, the writer delivers both for the time being, and tests use real audit rows instead of hand-built ideal objects.\n\n## Bounded queries instead of hidden load\n\nA general statistics API needs hard limits, such as a maximum window length per resolution. Invalid or oversized windows return `422` instead of burdening the product database with an unexpected full evaluation.\n\nThese limits belong to the product contract, because only the product knows its costs. A collector should not try to get around them with many overlapping queries. For a long period, it uses the coarser resolution or works in distinct, non-overlapping pages.\n\nThe same applies to retention. Anonymous raw events can have their own retention period in the product. A report artifact can live longer if its aggregated content is meant for that. Raw event, product aggregate and published report have different lifecycles; they don’t have to end up in one store.\n\n## Existing keys instead of a back door\n\nA dedicated “reporting key” seems tidy at first, but it creates a second security logic. What may this key read? Does it apply to a site, a space or the whole product? Who rotates it? As soon as every product gives a different answer, the supposedly simple collector becomes a special case with far-reaching permissions.\n\nThe statistics APIs should therefore use existing scopes. A read-only key for a site may then read exactly the statistics of the site it was issued for. A read key for the knowledge base stays limited to its space. Without a matching key, each of these endpoints stays closed.\n\nSo the same rule applies to the collector as to other API users: a separate key per product, as narrow as possible; secrets only in the credential store; no keys in the workflow definition, JSON artifact, log or report. The workflow only knows a `credential_ref`; the actual value is inserted at the HTTP call and appears neither in the stored process nor in its result. This separation can be tested: a call without a key must return `401`, a key without a matching scope `403`, a correct key `200`.\n\n## PostgreSQL is internal, not forbidden\n\nRejecting direct database queries doesn’t mean that aggregates have to live outside the product database. For a publishing system or a knowledge base, PostgreSQL may be exactly the right place. Events and domain state can be recorded transactionally there, scoped by site or space and evolved with the same migrations as the rest of the product.\n\nWhat matters is the direction of the dependency. The product may know its own database. An outside collector must not need to know it. Whether a response comes from a precomputed table, a bounded SQL aggregation or a cache remains an internal decision. What counts is that each product can design its internal storage according to its own operating model and, toward the outside, fulfills the same reliable time contract.\n\n## Documentation is part of the contract\n\nA new endpoint is only done when OpenAPI, `llms.txt`, `llms-full.txt`, the README and the detailed product documentation tell the same story. Otherwise, a person finds a scope in the README, a client generates from an older OpenAPI file and an agent reads a third variant.\n\nThat is why the repositories check their generated documents for drift. Contract tests send valid, invalid, oversized and unauthorized windows to the handlers. Integration tests use the real product storage. A binary test makes sure that the shipped file contains the same routes and the same version number as the source. These checks prevent the collector from depending on an outdated or internally known-only response shape.\n\n## APIs make exchange possible\n\nThe immediate effect of this separation shows up in testing. Every product API can be checked against its own schema with a fixed window. The collector gets fixtures without database access. A product release can be rolled back independently at the API level, as long as the published contract is preserved.\n\nA new consumer doesn’t need a new table in the product. Another reporting tool can call the same API just as well. A product may change its internal storage without the statistics resource having to be reinvented.\n\nThat also keeps the products understandable. Each product keeps its role – as a publishing system, knowledge base or orchestrator. Their statistics resources describe their own work as bounded aggregates with domain names. Everything else happens outside their boundaries. As long as the published contract is preserved, one part can be replaced without adjusting the others.\n\n## What has changed since then\n\nThe post [HTTP APIs: Small, Stable, Readable](https://www.mikebild.dev/en/blog/http-apis-small-stable-readable/) described an endpoint in 2014 as a long-term promise to unknown clients. Small resources, unambiguous timestamps, stable meanings and readable errors were meant to prevent every client from building its own defensive layer. These requirements still apply.\n\nWhat’s new is the view of internal product statistics. A statistics path is not built for a specific dashboard but as a bounded projection of the product’s own data. It uses existing keys and scopes, delivers time boundaries and data state along with the values and publishes only aggregates. This keeps the API small, regardless of whether a person, a workflow or an agent calls it.\n\n## Further reading\n\n- [W3C Trace Context](https://www.w3.org/TR/trace-context/)\n- [OpenTelemetry Service Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/resource/service/)\n- [OpenTelemetry Deployment Attributes](https://opentelemetry.io/docs/specs/semconv/registry/attributes/deployment/)\n- [HTTP APIs: Small, Stable, Readable](https://www.mikebild.dev/en/blog/http-apis-small-stable-readable/)"},{"locale":"en","translation_key":"vom-organigramm-zum-arbeitsfluss","slug":"from-org-chart-to-product-ownership","title":"From Org Chart to Product Ownership","summary":"AI makes the path from customer problem to impact more continuous.","tags":["Software","AI","Methodology"],"published_at":"2026-07-18T10:00:00+00:00","updated_at":"2026-08-18T06:39:59.272448+00:00","url":"https://www.mikebild.dev/en/blog/from-org-chart-to-product-ownership/","audio_url":null,"audio_duration_secs":null,"text":"An AI assistant produces a draft – and afterwards the work item waits for approval, review and release just as before. Who carries it from the observed customer problem to measurable impact? No draft generation, however fast, answers this question. AI can make the flow of work from the first customer signal through plan and implementation to review and impact more continuous – if responsibility for problem, decision, review and impact is brought together in one place.\n\nAI doesn’t remove organizational boundaries automatically. It lowers the cost of getting up to speed on the next step. Whether this results in one connected piece of work or merely a faster feed into the same waiting points is decided by the organization, not by the model.\n\n## The flow of work from customer problem to impact\n\nBy flow of work I mean a concrete chain here: a customer signal is observed, it leads to a hypothesis, the hypothesis to a plan, the plan to an implementation, the implementation to a review with domain acceptance, then a release and finally an observable impact that flows back as a signal into the next cycle.\n\n```mermaid\nflowchart LR\n    S[Customer signal] --> H[Hypothesis and plan]\n    H --> E[Design and implementation]\n    E --> Q[Review and acceptance]\n    Q --> R[Release]\n    R --> W[Observe impact]\n    W --> S\n    A[AI: context, variants,<br/>tests and documentation] --> H\n    A --> E\n    A --> Q\n```\n\nThe starting hypothesis is that in organizations built on division of labor, this chain is rarely continuous: one ticket describes the wish, another person decides on the design, a third builds the interface, a fourth checks the release. Each role can do its job very well while the result for the customer still remains incomplete. If you only see a small slice, you can hardly judge whether a new feature solves the customer problem or merely makes a subprocess tidier.\n\nWhat AI mainly changes about this chain is one cost factor: getting up to speed on the next step. An assistant can explain an unfamiliar service, gather existing decisions, sketch a data flow and suggest suitable tests. It doesn’t replace domain knowledge in the process. It lowers the barrier to bringing in domain knowledge from other parts of the organization in time – before a decision is made, not after a finished solution has been delivered.\n\n## Handoffs don’t get shorter automatically\n\nMy thesis is: AI can shorten handoffs if responsibility for problem, decision, review and impact is brought together. This is a hypothesis about organization, not a proven law. If responsibility stays as distributed as before, AI merely speeds up the production of intermediate results that still wait for the same approvals.\n\nThe [post on faster development and unchanged processes](https://www.mikebild.dev/en/blog/ai-in-the-enterprise-faster-development-different-processes/) describes this downside: if an organization just fills the same old process faster, the bottleneck moves. More drafts wait for the same reviewers, and more documents contradict each other. The gain only comes when the freed-up time flows into understanding the whole piece of work.\n\nBringing responsibility together doesn’t mean that one person has to be product manager, designer, security expert and operations lead at the same time. It means that a clearly bounded slice of the product is followed through by the same place: from the observed problem through a hypothesis and a change to feedback from usage. Specialist disciplines remain indispensable. The difference lies in the timing: specialists are brought in earlier and more deliberately instead of receiving a finished solution at the end of a long chain.\n\nThe org chart doesn’t disappear because of this. People need clear responsibilities, development prospects and decisions that don’t get lost between teams. But the continuous flow of work can become more important than the boundaries between the boxes – where responsibility actually has been brought together.\n\n## Vertical slices as a testable hypothesis\n\nVertical work packages make this thesis testable. Instead of breaking a change down by technical layers – first the data model, then the API, then the UI – a small, usable slice is carried through all layers. Such a slice has a clear purpose, a visible impact and a manageable number of open decisions.\n\nThis way of working made sense even without generative AI. One possible obstacle was the effort of getting into unfamiliar parts of the system: a developer knew the frontend, say, but not the rules in the backend. The product team knew the impact for users, not the consequences for operations or the data model. So work packages were cut along responsibilities and then pieced back together over many meetings.\n\n```mermaid\nflowchart TD\n    P[Product problem] --> V[Vertical slice]\n    V --> U[UI]\n    V --> F[Domain logic]\n    V --> D[Data and contracts]\n    V --> B[Operations and observation]\n    U --> X[One verifiable result]\n    F --> X\n    D --> X\n    B --> X\n    K[AI: make dependencies and<br/>suggestions visible] --> V\n```\n\nSmaller vertical slices are a testable organizational hypothesis, not a blanket statement about every team. The hypothesis is that a team with AI support can explore more of this context on its own – which services are affected, which contracts change, which test cases are missing, which documentation needs to be updated. Whether the observations in a concrete context support this hypothesis can be checked using waiting time, number of handoffs, rework and time to user feedback. The values are collected with identical definitions before and after a limited pilot; other process changes have to be recorded, because such a comparison doesn’t prove a clear cause. If the measurement turns out differently than expected, the hypothesis is not confirmed for this context for now – the team hasn’t failed.\n\nA vertical slice must not become a pretext for offloading every specialist discipline onto a few people. Where security, regulation or deep domain knowledge are needed, collaboration remains mandatory. The slice changes the order of involvement, not its necessity.\n\n## Technology becomes an option again\n\nMany technology choices arise from what a team happens to know. That’s understandable: an unfamiliar platform demands research, small experiments and the worry of being left alone with it later. That’s why requirements are sometimes adapted to the existing tools, even though a different path might fit better.\n\nAI changes this calculation. It can search documentation, explain examples from a repository, compare variants and prepare a small prototype. That alone doesn’t turn an unfamiliar technology into a good decision. But it becomes cheaper to make the decision based on a real experiment instead of habit.\n\nA useful investigation keeps several possibilities open:\n\n- What is the smallest change with which we learn something about the customer problem?\n- Which existing systems, data and contracts do we really need to understand?\n- Which assumption does the AI make, and how can it be checked?\n- What impact do we expect after the release, and how would we notice the opposite?\n\nThe answers don’t always have to be documented like an architecture decision. For a small change, a clean pull request with tests and a short rationale is often enough. What matters is that the AI doesn’t just produce more options but helps evaluate options faster and discard bad ideas earlier.\n\n## Creating gets cheaper, review and acceptance become more important\n\nThe most visible result of AI is often a draft: code, a test, a summary, an API description, a release note. The draft can be surprisingly good. But it can also carry a false premise forward with great conviction. The cheaper creating becomes, the more the value of review and domain acceptance grows.\n\nReview here means more than the pull request. It includes the domain check of a requirement, the look at contradictions in existing knowledge, the test under realistic conditions and the question of whether the release improves the product. Quality assurance is therefore not a last gate before rollout. It accompanies the entire slice.\n\n```yaml\nreview_focus:\n  product_question: \"Does this solve the observed customer problem?\"\n  domain_question: \"Which business rule could make this wrong?\"\n  technical_question: \"Which contract or dependency can break?\"\n  quality_signal: \"What evidence would change our decision?\"\n  release_check: \"Can we observe the result and recover safely?\"\n```\n\nThis example is not a new checklist for every little thing. It shows the shift: with AI-assisted drafts, the bottleneck can move from generation to review. What then becomes more important is deciding quickly and reliably what to keep, change or discard from a draft.\n\nThe NBER study “Generative AI at Work” provides a limited empirical hint on this. Among more than 5,000 customer support agents, an AI assistant increased the number of cases resolved per hour by 14 percent on average, with less experienced workers benefiting in particular. I read this finding about the less experienced workers as a hint that AI can spread proven practices – that is my interpretation, not a direct finding of the study. In any case, the study is not evidence of the same effect in every task, let alone in product development. What remains for product work is mainly this: the first draft becomes more accessible. That doesn’t devalue experience. Experience becomes more visible where it counts – in choosing a direction, in recognizing an atypical case and in judging quality.\n\n## Anchoring responsibility technically\n\nIf this thesis is meant seriously – responsibility for problem, decision, review and impact brought together – then it also has to be reflected in the systems through which work flows. Otherwise it remains a good intention. Two examples show what such anchoring can look like.\n\nA request control layer can route HTTP, MCP, A2A, webhooks and chat into the same planning path and bind execution to explicit task authority, budgets, contracts, evidence and review. That is the technical form of this bundling of responsibility: no matter which channel a request arrives through, it goes through the same planning, and execution is bound to explicit authority.\n\nA workflow engine can model recurring work across several systems as an approved, logged workflow and hold back steps with external effects until confirmation. Here too, the design separates preparation and execution from the confirmed external effect: a piece of work may be prepared, checked and repeated, but the step that has an external effect waits for acceptance.\n\nTransferring this to the organization is a hypothesis, not a guarantee. If knowledge can be found, if releases are prepared so that a team can follow a change in a controlled way all the way to its impact, and if product and service information comes from the same verified sources instead of aging in separate copies – then one piece of work can close more gaps at once: a product change delivers test cases, operational information and a draft of the customer documentation at the same time. Recurring support questions show early which product rule or explanation is missing. Errors and follow-up questions flow back into rules, tests and later work packages. Whether these conditions are met, every organization has to check against its own flow of work.\n\n## One complete slice as a test\n\nThe change doesn’t start with a new org chart. It starts with a real, limited product problem. A team takes a piece of work that has several handoffs today and carries it through completely once: understand the customer question, check the assumption, build the change, assess quality, release and look at the impact.\n\n```yaml\nvertical_slice:\n  customer_problem: \"Describe the observed problem\"\n  smallest_change: \"Deliver one useful outcome\"\n  ai_support:\n    - \"Find relevant context\"\n    - \"Prepare tests and documentation\"\n  human_review:\n    - \"Validate domain assumptions\"\n    - \"Accept quality and release risk\"\n  outcome_signal: \"Measure customer use and failures\"\n```\n\nAfter that, the discussion about roles and structure becomes more concrete. Perhaps it turns out that a team can own an interface itself. Possibly a shared source of knowledge is missing. Or a specialist remains a permanent part of the process. What matters is that the organization learns from observed work and not from an abstract restructuring plan – and that it discards the hypothesis where the measurement speaks against it.\n\nAI doesn’t make end-to-end product development easy. It makes it possible more often where responsibility, review and impact belong together and aren’t spread across many stations. Research, drafting, tests, documentation and release preparation move closer together. The org chart stays. But the decision every organization can make now is concrete: take ownership of one selected, limited flow of work end to end once, and measure by its impact whether the hypothesis holds.\n\n## Further reading\n\n- [NBER: Generative AI at Work](https://www.nber.org/papers/w31161)\n- [AI in the Enterprise: Faster Development Needs Different Processes](https://www.mikebild.dev/en/blog/ai-in-the-enterprise-faster-development-different-processes/)"},{"locale":"en","translation_key":"llms-txt-und-llms-full-txt","slug":"llms-txt-docs-for-machines","title":"llms.txt: Docs for Machines","summary":"Context for models, not for ranking: why llms.txt and llms-full.txt help coding agents – and what an MCP server makes of them.","tags":["Software","AI","Methodology"],"published_at":"2026-07-15T10:00:00+00:00","updated_at":"2026-08-18T05:16:11.670656+00:00","url":"https://www.mikebild.dev/en/blog/llms-txt-docs-for-machines/","audio_url":null,"audio_duration_secs":null,"text":"`llms.txt` sits in the root directory of a website, which makes it look like the next signal for search engines – a neighbor of `robots.txt` and `sitemap.xml`, created in the hope of visibility. Exactly this conclusion misses the point. The file was never meant as a ranking signal, and there is no evidence of any ranking effect. Its value doesn’t lie in crawler signals but in providing agents with curated documentation context.\n\nThere are two files, `llms.txt` and `llms-full.txt`. They look like marketing infrastructure, and their value lies somewhere else: in the question of how a model gets clean, curated context without first working its way through navigation bars, cookie banners and JavaScript. Both files are machine-readable self-documentation of a product.\n\n## Two files, one problem\n\nJeremy Howard, co-founder of Answer.AI, published the proposal on September 3, 2024; the description is at `llmstxt.org`. The starting point is a sober observation: models increasingly rely on web content, but their context window is too small to take in an entire website in one go. And turning raw HTML into usable text is tedious and imprecise – between the actual content there is a lot of clutter that only eats up space.\n\nThe answer consists of two building blocks that you should keep clearly apart.\n\n`llms.txt` sits in the root directory of a site and is a curated index in Markdown. The format is deliberately narrow: an H1 heading with the project name, below it a blockquote with a short summary, optionally a few sentences of context, then H2 sections with lists of links. Each link carries a brief description. A separate `## Optional` section marks what a model may drop first when space is tight. This is how compact it looks:\n\n```markdown\n# Orderflow API\n\n> Orderflow is a REST API for creating, tracking, and refunding orders.\n> These docs are written for LLMs and coding agents.\n\nEvery write endpoint accepts an `Idempotency-Key` header, so retries stay safe.\n\n## Core Documentation\n\n- [Quick Start](https://docs.example.com/quickstart.md): Authenticate and create your first order\n- [API Reference](https://docs.example.com/api.md): Endpoints, parameters, and error codes\n- [Webhooks](https://docs.example.com/webhooks.md): Event types and signature verification\n\n## Optional\n\n- [Changelog](https://docs.example.com/changelog.md): Version history and breaking changes\n```\n\n`llms-full.txt` is the second building block and conceptually simpler: the full text of the important pages, concatenated into a single Markdown file. No longer an index, but the whole content in one piece, without HTML noise. An agent or client can load the bundled content with a single request instead of working its way through page by page – whether all of it fits the specific task is another question.\n\nIn addition, Howard suggests also providing individual pages as a clean Markdown version at the same address with `.md` appended – `.../api` becomes `.../api.md`. That’s the glue between index and content: the index points to pages that already exist in the form a model processes best anyway.\n\nThe distinction matters, because a lot gets mixed up here. `robots.txt` governs what a crawler may touch. `sitemap.xml` helps with indexing. `llms.txt` does neither: the file puts things in context and curates them, intended for the moment of inference, not for the crawl. An agent that reads it gets an editorial statement about what matters in a product – not a promise to a search engine. The three files don’t exclude each other; they answer different questions.\n\n```mermaid\nflowchart TD\n    A[Coding agent] -->|knows llms.txt| B[llms.txt<br/>curated index]\n    B --> C{Which page<br/>do I need?}\n    C -->|targeted| D[page.md<br/>clean Markdown version]\n    C -->|everything at once| E[llms-full.txt<br/>entire content]\n    A -.->|alternative without llms.txt| F[Crawl the HTML page<br/>navigation, ads, JS]\n    F -.->|lots of noise| G[Context window full,<br/>content diluted]\n```\n\n## Why this helps\n\nWhen integrating a third-party library, an agent without a Markdown view often loads the complete HTML page or improvises missing signatures. In the first case, it pulls in the menu, the footer and three code examples it doesn’t need at all – a noticeable part of the window is gone before the actual task begins. In the second case, it guesses. In a code review, I noticed that an agent had simply made up an API signature, plausible and wrong, because fetching the exact reference was too expensive for it. Both are symptoms of the same problem: too much noise per token, too little reliable substance.\n\n`llms.txt` addresses exactly this. Curated Markdown without layout ballast means more of the window is left for the actual content. The index also forces a decision: not every page is equally important, and someone with domain knowledge has to name which thirty to a hundred pages make up the core. And when the model needs the exact error message or the exact parameter, it fetches the matching `.md` page instead of improvising.\n\nThe point about curation is often overlooked. A good `llms.txt` isn’t an arbitrary list of links but an editorial statement about what matters in a product. This decision is the actual work – not the file itself.\n\n## Where it pays off\n\nFor a blog or a marketing site, `llms.txt` brings little: there is no evidence of a ranking effect, and if you create the file hoping for better visibility, you’ll be disappointed. Anyone who promises such an effect promises too much.\n\nThe exception is narrow but real: technical documentation and coding agents. An API reference, a component library, an SDK – content that is maintained in Markdown anyway and that an agent in the IDE looks up in a targeted way.\n\nFor pure marketing pages without demonstrable agent usage, the maintenance effort usually doesn’t justify the file; for regularly queried technical documentation, it can pay off. Server logs with requests to `/llms.txt` give you a hint of usage, but they don’t carry the decision on their own: a lack of direct requests doesn’t necessarily prove a lack of usage, for example when the same content is retrieved through other paths such as MCP resources.\n\n## Generated from the source, not maintained by hand\n\nA central risk when using these files is organizational, not technical: two versions of the same content that are maintained separately. The page for humans here, the Markdown version for models there. If `llms-full.txt` lags behind the real docs, you feed models outdated content – and that’s worse than no file at all, because it creates false trust. Without automatic generation from the same source, drift is only a matter of time.\n\nThat’s why both files belong in the build, not in the editor. The build can generate `llms.txt`, `llms-full.txt` and Markdown twins per site and locale from the published state. What matters is the shared source for human-readable and machine-readable outputs; a second, hand-maintained documentation would make drift possible again.\n\nThat’s the second half of the curation work. A human makes the editorial decision about what belongs in the index. The build takes care of generating the files. If you do both by hand, you have taken on a second set of docs that easily deviates from the published state.\n\n## What an MCP server makes of it\n\nUp to this point, `llms.txt` is a static file that someone picks up at some point. MCP adds targeted access to resources and operations on top of the static index. The Model Context Protocol is the open protocol that Anthropic introduced at the end of 2024, through which an agent talks to external tools and data sources in a standardized way.\n\nAs an index, `llms.txt` describes which content exists and where it lives; an MCP server provides resources and operations in a targeted way. With `mcpdoc`, the LangChain team built exactly such a docs server. It receives a list of `llms.txt` addresses and provides the agent with two tools: one that lists the registered sources and one that fetches a specific page from them.\n\nAn MCP docs server designed for this can load context in a targeted way, make calls loggable and restrict access – three improvements over simply downloading the file.\n\nFirst, dosage. Instead of dumping all of `llms-full.txt` into the window, the agent uses the index to request only the one page that fits the task – the range between “no context at all” and “everything at once.”\n\nSecond, traceability. With a docs server like `mcpdoc`, fetching runs through tool calls that you can inspect: which address was loaded and what came back. This doesn’t automatically apply to resource reads; there, you need your own logging on the server side. A direct download of the file doesn’t necessarily leave this trail in the agent workflow. For internal or protected documentation, this auditability can justify the additional operational effort.\n\nThird, access control. You can restrict the server to allowed domains, and for internal or protected docs you put authentication in front of it. If you need permission-bound access, you can offer the documentation as a resource through an authenticated MCP server and check permissions there for every read. This way, the convention also works behind the company firewall: the server points to a private `llms.txt`, and models in the team get curated knowledge without the content being openly available on the web.\n\nIf both come from one product, it can offer a remote MCP interface alongside the generated files. In such a setup, MCP resources are application-managed context that the server offers the client as documentation. Tools stay separate from this: they represent domain operations and should only become visible with the matching scope. Such a system can additionally provide its own `llms.txt` documentation as an MCP resource, so that a client can read the tool model and API boundaries without guessing a web page. So MCP adds targeted access and operations to the static documentation; this access only becomes permission-bound once the server authenticates and authorizes resource reads. The documentation doesn’t replace MCP – without generated, up-to-date machine views, these documentation resources would lack a reliable foundation.\n\n```mermaid\nflowchart LR\n    H[Agent host<br/>Cursor, Claude Code] --> M[MCP docs server<br/>e.g. mcpdoc]\n    M -->|list sources| L[llms.txt<br/>registered indexes]\n    M -->|fetch page| P[only the needed<br/>.md page]\n    P --> H\n```\n\n`llms-full.txt` in particular gains from this combination. You can attach the file directly to an MCP server as a knowledge source – without an embedding pipeline, without a vector database. More accurate than “a replacement for RAG” is to describe it as a tool-based, auditable variant of it: not unpredictable retrieval from a large vector index, but traceable access to curated pages.\n\n## Where it falls short\n\n`llms.txt` is a proposal, not an adopted standard. There is no committee behind it and no guarantee that a particular model reads the file. You provide it; you can’t force it to be consumed.\n\nSize is a real limit. An `llms-full.txt` that is several megabytes in size may, depending on tokenization, model and client limits, not fit completely into the available context and then only gets loaded in fragments – and with that, the advantage of “everything in one request” is gone. For large sites, you stick with the curated index of the truly central pages, complemented by targeted fetching of individual `.md` versions.\n\nAnd finally, the question of trust. As soon as an agent takes over a third-party `llms-full.txt` without checking it, it takes over content it doesn’t control. That’s the same attack surface as with any external data source that ends up in the context – a good reason to go through an MCP server with a domain restriction instead of collecting arbitrary addresses.\n\n## Conclusion\n\n`llms.txt` and `llms-full.txt` are machine-readable self-documentation. The index says what matters and where it lives; the full version delivers the content in one piece; the `.md` mirrors provide individual pages in the form models prefer. None of them is a reliable ranking factor, and if you create the files with that expectation, you’re measuring against the wrong goal. Their value arises where documentation meets agents – with SDKs, API references and coding tools.\n\nTwo decisions follow from this. First: the files are generated from the same source as the documentation for humans, or you leave them out – a hand-maintained duplicate drifts and undermines exactly the trust it’s supposed to build. Second: if you need targeted or permission-bound access, you can offer the documentation as a resource through an authenticated MCP server and check permissions there. In this way, MCP can complement the static views with measured, auditable and – with server-side authorization – permission-bound access; it still depends on the documentation behind it being correct.\n\n## Further reading\n\n- The original proposal and the format description: [llmstxt.org](https://llmstxt.org/)\n- Repository for the proposal: [AnswerDotAI/llms-txt](https://github.com/answerdotai/llms-txt)\n- MCP docs server that reads `llms.txt` as a source: [langchain-ai/mcpdoc](https://github.com/langchain-ai/mcpdoc)\n- Model Context Protocol: [modelcontextprotocol.io](https://modelcontextprotocol.io/)"},{"locale":"en","translation_key":"hilfsmittel-konzepte-methoden-prozesse","slug":"tools-that-hold-up-concepts-methods-processes-article","title":"Tools That Hold Up: Concepts, Methods, Processes","summary":"You cannot install an agent for your own domain – but you can very well learn the way there. Which concepts hold up, which methods keep the start small and which processes keep rules from going stale.","tags":["Software","AI","Methodology","Delivery"],"published_at":"2026-07-15T10:00:00+00:00","updated_at":"2026-08-18T05:16:11.670656+00:00","url":"https://www.mikebild.dev/en/blog/tools-that-hold-up-concepts-methods-processes-article/","audio_url":null,"audio_duration_secs":null,"text":"There is no installation package for an agent that represents a domain in a binding way. You can install available model weights and runtimes; you can implement or connect protocols. Model weights and runtimes alone, however, do not enforce a domain approval and do not produce meaningful domain evidence of who decided what. The binding part only emerges when you engage with your own domain – with its terms, its rules and the people who stand behind both. The way there can be learned, though, and it is less spectacular than many framework debates suggest.\n\n*Part 12 of the series “From Session to System” – [start with the opening post](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nThe [previous post](https://www.mikebild.dev/en/blog/ai-agents-per-domain/) described what such an agent has to be able to do: check plans before they take effect; approvals that no model can talk its way around; evidence that answers the questions of the day after tomorrow. What remained open was the way there. It leads through three kinds of tools: concepts that hold up. Methods that keep the start small. And processes that keep the whole thing alive in operation once attention moves on. One at a time.\n\n## Concepts: none of this is new\n\nIf you go through the list of capabilities from the previous post, you will not find a single AI invention in it. Domain language and domain boundaries – that a system should speak the terms of its domain and that those terms are only unambiguous within a defined context – were described by Eric Evans a good twenty years ago in “Domain-Driven Design” as ubiquitous language and bounded context. Every organization that reviews changes before rolling them out knows the separation of proposal and effect, from the four-eyes principle in accounting to `terraform plan` and `apply`. Validation, authorization and audit are the basic toolkit of any serious business application. And that answers [have to rest on real sources instead of plausible guessing](https://www.mikebild.dev/en/blog/clean-grounding-ii-grounding-answers/) and that [curated knowledge needs a cycle with owners](https://www.mikebild.dev/en/blog/knowledge-that-survives-the-session/) was covered in the middle posts of this series – at its core that, too, is documentation and library work, not magic.\n\nThe only new thing is the consumer: a loop in which a model acts, instead of a UI where people click. For choosing concepts, that is a small shift. Since then, one simple test question has helped me: did this concept hold up before there was AI? Domain boundaries, approval workflows, versioning, audit – yes, for decades. An orchestration framework that has existed for four months – probably not. That is not a dismissal of everything new; somewhere the next concept that holds up is actually emerging right now. But the burden of proof lies with the new, not with the proven.\n\nA natural building block shows that the old concepts carry over directly into agent systems: a workflow engine can separate mission, plan, run and the authority granted for it – and use the same planning path for HTTP, MCP, A2A, webhooks and chat. That is the old separation of proposal and effect, applied consistently to every input channel: no matter where an initiative comes from, it takes the same planning path.\n\nFor the reflex to design the whole organization as an agent landscape right away, there is an old concept as well, and it hits harder than any technical question. John Gall phrased it in the seventies as an observation about systems: “A complex system that works is invariably found to have evolved from a simple system that worked. A complex system designed from scratch never works and cannot be patched up to make it work. You have to start over, beginning with a working simple system.” Twelve connected agents on a whiteboard are the design from scratch. The first process that actually runs and delivers a verifiable result is the beginning of the system.\n\n## Method: take inventory of the rules first\n\nThe first of the three questions from the end of the previous post was: which rules belong in the path, and which may stay prose? The answer does not start with technology, but with an inventory that is less popular than it needs to be. For the inventory, I would first check four places: the wiki, instruction files such as CLAUDE.md or AGENTS.md, code review comments – and heads, as in the knowledge of that one colleague you ask before every price change, just to be safe. This list is not complete; depending on the organization, tickets, policies, configuration or business procedures come on top. The inventory brings the rules into one place and notes four things for each: where is it written? How binding is it meant to be? What happens if it is violated? And how often was it actually violated recently?\n\nThe last column is the most important, because it replaces opinion with findings. In the chronicle of my instruction files, the sobering lesson was that written rules remain recommendations; in the [post about tools](https://www.mikebild.dev/en/blog/agent-model-domain/), that turned into a transition criterion: when the same rule shows up in an instruction file for the third time and has been ignored for the second time, it is a candidate for enforcement in the path. The inventory turns this gut feeling into a list:\n\n```yaml\n# rule inventory, one entry per rule\n- rule: \"Credit notes above 500 EUR require team lead approval\"\n  source: wiki, AGENTS.md\n  violation_impact: money leaves the company\n  violated_recently: twice in Q2\n  decision: enforce   # goes into the path\n\n- rule: \"Use the customer number, not the invoice number, in replies\"\n  source: onboarding notes\n  violation_impact: confusion, no damage\n  violated_recently: unknown\n  decision: prose     # stays a convention\n```\n\nFor classifying them, I consider three questions a solid starting point, and they match the criteria that have gradually emerged in this series: does a violation move money, personal data or effects to the outside? Does someone have to be able to prove afterwards who decided what and when? Was the rule broken repeatedly despite clean documentation – by people or by the model? A yes to any of these questions is my starting point for taking the rule into the path: check, approval, evidence. It remains a starting heuristic, though – where the possible damage is small, a mistake is easy to undo or existing controls catch it anyway, a rule can stay prose even with a yes. Three times no, and it stays prose – as a convention that the model reads and mostly follows, and whose remaining risk has been explicitly accepted.\n\nThe inventory has a second yield that is easy to overlook: it finds dead rules. Requirements that nobody has needed for years, whose reason disappeared long ago, but which are still dragged along in every document. Those go – not into the path, but out entirely. An agent that represents a domain is also an opportunity to declutter the domain itself.\n\n## Method: cut the first domain small\n\nThe second question: how do you cut the first domain without overreaching? The short answer: one process, not one department. A department bundles many states and responsibilities that are never finished at the same time; a process has a verifiable beginning and a verifiable end. “Accounting” is therefore not a cut but a box on an org chart. “Credit notes and dunning stops” is one – a well-delimited process with a beginning, an end and a handful of verbs.\n\nHow you recognize a suitable first candidate:\n\n- The process has a clear beginning and a clear end – no permanent state, no umbrella term.\n- A handful of verbs is enough: at the latest when the tool list reaches double digits during modeling, I would review the cut again.\n- There is already a person responsible for the domain today – the role that approves and decides even without AI.\n- The pain is documented: violations have actually happened in the past and demonstrably caused trouble.\n- The damage potential justifies the effort but stays manageable – credit notes yes, international payments maybe only in the second year.\n\nThe last point deserves a moment. The first domain agent is not just a tool; it is also the piece on which a team builds and operates the three capabilities – check, approval, evidence – for the first time. You choose such first pieces so that mistakes are instructive, not existential.\n\nA small cut also calls for a small transition. Nobody tears down the existing way of working and replaces it with the agent; the prose version remains the prototype from which rules move into the path one by one, as soon as their binding nature has been proven. For this pattern – the new grows along the old until the old is no longer needed – Martin Fowler coined the image of the strangler fig that grows around a tree. Applied to rules: first the 500 euro rule applies as a sentence in the instruction file, then additionally as a check in the path, and at some point the sentence is just documentation of the check. No big switchover day, no risky migration over a weekend.\n\nThe rest of the big sketch does not die in the process – it becomes backlog, sorted by exactly the criteria above. That can feel like a retreat. It is the opposite: the first step that can actually be taken and delivers a verifiable result.\n\n## Processes: owner, change path, rhythm\n\nThat leaves the third kind of tool, and it is the one most easily underestimated. You can learn concepts, you can apply methods – processes you have to sustain in operation. I consider three of them load-bearing.\n\nFirst: every rule has an owner, and that owner sits in the business unit. Engineering owns the enforcement – the code that checks, the gate that waits, the log that writes. But whether 500 euros is the right threshold, whether “goodwill” and “pricing error” take different paths, is decided by the business side that has always carried this responsibility. The discussion about proposing, reviewing and approving rules is not an obstacle on the way to the process. It is the process – if you skip it, you have rules without legitimacy, and they erode at the first conflict.\n\nSecond: rule changes take the same path as rules. Proposal, review, approval, versioning – the same care that is a given for code. That the evidence records the rule version in force was a side detail in the previous post; in operation it becomes the precondition for touching rules at all without reinterpreting the past. Two building blocks show what this can look like: a knowledge system can keep domain guidelines in a versioned charter that people are responsible for, and route changes to the derived knowledge base through a review process. A workflow engine can describe approved procedures as workflows that run repeatably and log every run – work that has not been described and approved is not improvised. Both are expressions of the same principle: the change path is built into the system.\n\nThird, and most important: learn from the noes, at a fixed rhythm. In operation, the agent produces two streams – executions and rejections. For rules that are too narrow or missing, the rejections are often the more fruitful starting point; samples of successful runs are still necessary, because an execution that was waved through can also contain a wrong decision. The rejection log therefore belongs on the table regularly – at first at a fixed interval of a few weeks, later depending on the rejection rate and damage potential – with three questions: which noes were right and stay? Which were too narrow and need an adjusted threshold or a new reason for a credit note? And which special cases come up so regularly that they deserve their own verb? This is the same cycle that [the post about curated knowledge](https://www.mikebild.dev/en/blog/knowledge-that-survives-the-session/) described, just with rules instead of insights: operations deliver candidates, curation turns them into something binding – the organization changes rules and interfaces in the process; the model stays unchanged.\n\n```mermaid\nflowchart LR\n    I[\"Inventory<br/>collect and assess rules\"] --> K[\"Classification<br/>path or prose\"]\n    K --> B[\"Build<br/>verbs · check · approval\"]\n    B --> O[\"Operation<br/>executions and rejections\"]\n    O --> S[\"Review at a rhythm<br/>learn from the noes\"]\n    S --> I\n```\n\nTogether, the three processes deliver what the previous post merely claimed: that such an agent is a product with a lifecycle. A product has owners, a change path and a cadence at which it gets better. If one of these is missing, it decays – faster with rules than with code, because an outdated threshold does not fail a build and therefore has to be caught deliberately through review or operational metrics.\n\n## Fads you can skip\n\nAnd the opposite list? I consider four patterns attention sinks that improve neither check nor approval nor evidence – that is a judgment, not a measurement.\n\nThe multi-agent orchestra from day one: many agents sending each other messages before even one of them enforces a single binding rule – the design from scratch cast in software. Frequent framework switching, where the domain logic sinks a bit deeper into vendor conventions each time; the antidote – domain logic in your own services, the tool layer as a thin adapter – was already in [the post about agent, model and domain](https://www.mikebild.dev/en/blog/agent-model-domain/). The model comparison table as a substitute for strategy, which [this series argued against early on](https://www.mikebild.dev/en/blog/good-enough-models/): whether several models solve your own tasks well enough is shown by a concrete check against exactly those tasks – and where that is the case, the energy belongs in your own share, not in the table. And endless polishing of wording: when the same instruction is reworded for the third time so that the model “finally understands” it, that is not a writing problem. It is the signal that the rule belongs in the path, not in nicer words.\n\nThe test question is always the same, and it keeps the list short: does it help build check, approval or evidence – or does it just feel like progress? Many of the frameworks and agent patterns currently under discussion can be left to mature in peace. They are not going anywhere, and whatever holds up will still be there in a year.\n\n## Where things stand\n\nWith that, the three questions from the end of the previous post are answered, as well as I can after these months: with an inventory that delivers findings instead of opinions, a cut the size of one process, and processes that define owner, change path and rhythm. So I would start with a documented rule violation in a process that has already been cut small – that is where the pain is documented, the cut is small and the result is verifiable. The concepts behind it are old, and that is their most important property: they have held up before.\n\nA good eight months ago, this series began with a session on my computer and the observation that my work was changing; now the path ends, for the time being, at organizations that put rules, knowledge and responsibility into their own agents. The next post checks the expectations from the opening: what came true, what did not – and where does all of this lead?\n\n## Further reading\n\n- [Domain-Driven Design Reference (Eric Evans)](https://www.domainlanguage.com/ddd/reference/) – ubiquitous language and bounded context as design work\n- [John Gall: Systemantics](https://en.wikipedia.org/wiki/John_Gall_%28author%29) – why working complex systems evolve from simple working systems\n- [Martin Fowler: Strangler Fig Application](https://martinfowler.com/bliki/StranglerFigApplication.html) – the pattern for transitions without a big switchover day\n- [Building Effective AI Agents (Anthropic)](https://www.anthropic.com/engineering/building-effective-agents) – the advice to start with the simplest setup that works"},{"locale":"en","translation_key":"eigener-agent-pro-fachdomaene","slug":"ai-agents-per-domain","title":"AI Agents per Domain: Rules, Approvals and Evidence","summary":"How an AI agent enforces domain rules across several tool calls: with case state, checked plans, approvals and traceable execution.","tags":["Software","AI","Methodology","Delivery"],"published_at":"2026-07-14T10:00:00+00:00","updated_at":"2026-11-08T13:00:00+00:00","url":"https://www.mikebild.dev/en/blog/ai-agents-per-domain/","audio_url":null,"audio_duration_secs":null,"text":"An AI agent per domain connects the tools of a field of work with its rules, permissions and case state. What matters is not another chat but an executable path that checks related actions before they take effect. This article shows which responsibility lies with the model, with the tool and with the agent system you operate.\n\nA constructed example: an agent is supposed to refund 740 euros as a goodwill gesture. Anything over 500 euros needs approval from the team lead. The tool call for 740 euros is rejected; two calls for 370 euros each, however, would pass a check that only looks at individual calls. Each call would be allowed on its own, but their combined effect would not. This is exactly the gap a rule over the whole case has to close.\n\n*Part 11 of the series “From Session to System” – [the opening post is here](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nThe example describes a possible weakness, not an observed incident. Whether a model would actually propose two partial amounts is an open question. The architecture still has to prevent this kind of workaround: a rule about a case cannot be expressed as an isolated check of individual calls alone.\n\nThis installment thus keeps two promises the series has left open. The chronicle of my instruction files ended with the finding that only what the environment enforces is a rule. The [last installment](https://www.mikebild.dev/en/blog/agent-model-domain/) closed with the question of why binding rules lead to a dedicated agent tied to the domain – and what that agent has to be able to do. The credit note construction gives the short answer: rules need a place where the context is visible.\n\n## A tool sees the call, not the case\n\nA reminder of where the series stands: the last installment moved the domain from the prompt into the tools – typed operations whose names come from the domain language, whose inputs are validated and whose calls are authorized. The check now runs in the executable path instead of in the prompt: the 500-euro rule went from a recommendation the model can read and weigh to code that decides the same way on every call.\n\nIn this example, the check sees only one call. A tool can also load and check case state; what matters is that this responsibility is implemented explicitly. Without it, three things stay hidden.\n\nThe context. Domain rules are rarely rules about calls – they are rules about cases. “No more than 500 euros in goodwill” means per case, per customer, per period. Two credit notes of 370 euros for the same case violate the rule without any single call violating it. An authorization that only receives the input of the current call cannot notice this – not because the tool is technically incapable, but because it lacks the bound case state.\n\nThe effect. Some errors don’t show in a single step but only in the overall picture – in what will exist after twenty steps. If you only check after execution, you check too late; by then the credit note has already reached the customer.\n\nThe memory. Whether a pattern is suspicious is decided across sessions: the same invoice, three times in two weeks, triggered by two different people. The individual call knows nothing about that, and neither does the individual tool.\n\nWhat the individual tool call lacks, the agent can bring together: the history, a materialized plan and persistent case state – provided these states are stored explicitly and bound to the case. That is why enforcement moves up one level – out of the tool and into the agent that runs the loop. The agent is then no longer an interchangeable accessory but the place where the binding rules of a domain live: an operated software system with a plan, permissions, approvals, evidence and clear ownership.\n\n## From proposal to evidence: five stations\n\nWhat does this enforcement look like? The core idea is old and doesn’t come from the AI world: separate building from executing. If you run infrastructure as code, you know it as `terraform plan` and `terraform apply` – first you get a complete preview of what would change, then you decide separately whether it actually happens. Between proposal and effect sits a check, and it doesn’t look at a single move but at the whole undertaking.\n\nApplied to agents, the path from idea to effect has five stations.\n\nIt starts with the model proposal: a textual or structured output, as eloquent as it is non-binding. Whether the model delivers prose or fully formatted tool calls – at first it only produces a statement of intent without authorized effect. Second, this becomes an executable plan: an ordered sequence of typed operations with concrete parameters, stored as an immutable revision and bound to the checked state; the operations and parameters are machine-readable, while a rationale can remain free text. Third, domain authorization: the plan is checked as a whole against the rules of the domain. This is where two credit notes for the same case stand out, where sum and frequency rules apply, and where it is decided whether the undertaking is allowed, rejected or requires approval. Fourth, where the rules demand it, human approval: a confirmation by a domain role that the model can neither grant nor replace – it may make proposals but may not confirm a human decision itself. And fifth, evidence, in two forms: decision evidence for every rejection and every approval, and execution evidence for every operation actually executed – who, what, when, with what result, under which rule version.\n\n```mermaid\nflowchart LR\n    M[\"Model proposal<br/>textual or structured, non-binding\"] --> P[\"Plan<br/>all planned operations\"]\n    P --> R{\"domain authorization<br/>rules of the domain\"}\n    R -- \"violated\" --> N[\"Rejection<br/>justified and logged\"]\n    R -- \"requires approval\" --> H[\"human approval\"]\n    R -- \"allowed\" --> D{\"bound state<br/>still current?\"}\n    H -- \"confirmed\" --> D\n    H -- \"rejected\" --> A\n    D -- \"yes\" --> E[\"Execution\"]\n    D -- \"no\" --> R\n    E --> A[\"Decision or execution evidence<br/>who · what · when · rule version\"]\n    N --> A\n```\n\nAnyone who works with coding agents knows this on a small scale: first the diff, then the commit. The difference is that there a human looks voluntarily – and on a Friday afternoon sometimes doesn’t. In an agent that is responsible for a domain, the check is not a habit but part of the path. It happens whether anyone remembers it or not.\n\n## A no that stays a no\n\nThe second capability follows directly from the construction at the start. A model that runs into a rejection can rephrase, negotiate, look for detours. That wouldn’t be malice: searching on is exactly the behavior we appreciate elsewhere, when a model tackles a test failure three different ways until the build is green. Instead of trying to train this persistence away, you can give it a limit that is not up for negotiation.\n\nFor that, the approval has to live outside the conversation. An operation that requires approval waits until a human confirms it – and no text in the context, however eloquent, moves this gate, because the gate doesn’t even read the text. The model can propose its two 370-euro credit notes as often as it likes: the sum rule triggers on the plan, the approval stays pending, and the case sits with the responsible human. What matters here is who gives this yes: not “some admin” but a role from the domain – the team lead who decides on 500-euro goodwill payments even without AI. The approval maps an existing domain responsibility; it doesn’t invent a new one.\n\nSketched on the tool definition from the last installment, the extension looks roughly like this. The code block is a simplified, illustrative sketch: the API `defineTool` and the role `billing_team_lead` are freely chosen placeholders.\n\n```ts\nconst issueCreditNote = defineTool({\n  name: \"issue_credit_note\",\n  input: z.object({\n    invoiceId: z.string(),\n    amount: z.number().positive(),\n    reason: z.enum([\"complaint\", \"goodwill\", \"pricing_error\"]),\n  }),\n  approval: {\n    required: ({ input, history }) =>\n      input.amount + history.totalCreditedFor(input.invoiceId) > 500,\n    approvers: [\"billing_team_lead\"],\n  },\n  audit: { record: [\"user\", \"input\", \"approval\", \"result\"] },\n});\n```\n\nThe crucial line is the one with `history`. The approval requirement doesn’t depend on the individual amount but on the sum across the case. The authoritative state lives in the domain, not in the conversation: the agent binds a checked state of the case to the plan and passes it as input to the authorization – exactly the view the isolated single-call check lacks. Binding alone isn’t enough, though: so that parallel calls can’t exceed the 500-euro limit after all, execution has to recheck the bound state against the current domain state beforehand and abort or reauthorize if it has changed in the meantime.\n\n## Evidence instead of memory\n\nThe third capability is the least conspicuous: every execution leaves evidence behind. Who triggered the case, which plan revision was checked, what exactly was executed, with which inputs, what came out, who approved it – and, easy to overlook: which version of the rules applied. Domain rules change. 500 euros becomes 300, an approval path gets rebuilt. When someone asks three months later why a credit note went through back then, the answer has to be able to say: under the rules as of March it was allowed, here is the entry.\n\nSuch a log doesn’t exist because someone remembered to take notes. It exists because the path produces it – rejections included. The no leaves a trace too, and it is precisely the noes that show where rules are too tight or tools are cut too coarsely. Auditability is not a compliance exercise you bolt on afterwards. It is a property of the path, or it doesn’t exist.\n\n## Why per domain\n\nSo far, I have argued why binding rules belong in checkable state transitions and authorization boundaries rather than only in prompt prose. The second part of the question from the last installment is still open: why a *dedicated* agent per domain – and not one big agent that can do everything?\n\nBecause each of the three capabilities requires domain knowledge. A plan check can only evaluate what it understands: that two credit notes belong to the same case, that a customer is in dunning, that “goodwill” and “pricing error” have different consequences – these are terms and relationships of a domain, not generic concepts. The approval needs roles that only exist there. The evidence has to be kept in the language in which someone will ask later. A generic agent can read files and run commands; it cannot know what an inadmissible credit note is.\n\nThen there are the permissions. An agent that carries the tools of all domains may need a correspondingly broad set of permissions if rights are not delegated and limited per call – and with such permanent rights it becomes a worthwhile target. OWASP lists “Excessive Agency” among its top 10 risks for LLM applications: too many tools, too broad permissions, too much autonomy in a single system. With his “lethal trifecta”, Simon Willison named the most toxic combination – access to private data, exposure to untrusted content and the ability to communicate externally, united in one agent. Cutting along domains is therefore also a security decision – but it only becomes an enforceable boundary with separate identities, permissions, states and interfaces: few tools, narrowly scoped permissions, a clear blast radius. The credit note agent cannot trigger deployments, and the deployment agent doesn’t know any customer data.\n\nAnd finally, knowledge. Curated insights, [grounded answers](https://www.mikebild.dev/en/blog/clean-grounding-ii-grounding-answers/), [knowledge that survives the session](https://www.mikebild.dev/en/blog/knowledge-that-survives-the-session/) – all of this always belongs to a particular domain. An agent that is responsible for a domain carries its sources, its conventions, its special cases. Not as a cross-domain grab bag, but as a maintained, manageable collection with owners.\n\nThis also closes the loop to the [variance from the team part of this series](https://www.mikebild.dev/en/blog/my-success-cannot-be-copied/). Back then, the finding was: results vary between people, tasks and sessions, and files with rules change little about that. The domain agent doesn’t solve this problem by making people the same. It moves the line below which variance can do damage. Above it, everything stays different: how someone phrases, explores, delegates, which path a session takes. Below it, everything is the same: whatever takes effect in the end goes through the same authorization, the same approval, the same evidence – for the experienced colleague just as for the intern, on Friday afternoon just as on Tuesday morning.\n\n## What your own agent has to be able to do\n\nWith that, the question from the last installment can be answered compactly. An agent that is supposed to represent a domain in a binding way needs:\n\n- tools in the domain language – typed, validated, authorized\n- the separation of model proposal and effect, with a check of the whole plan instead of individual calls\n- rules about cases: sums, frequencies, relationships across calls and sessions\n- approvals in the path, outside the conversation, by roles of the domain\n- evidence of every execution and every rejection – with plan revision, rule revision, approval decision, caller, result and error status\n- the permissions of the respective caller instead of its own omnipotence – narrowly scoped, domain-specific\n- curated knowledge sources of the domain, with owners and maintenance\n\nNothing on this list is something an experienced team wouldn’t have built long ago: validation, authorization, workflow, audit, permission model. The only new thing is what it’s for – not for a UI where people click, but for a loop in which a model acts. If you build an agent like this, you wrap ordinary, solid software around variable model proposals. That is exactly why the task is doable.\n\nDoable doesn’t mean on the side. What emerges here is an operated software system with a lifecycle, not a weekend project – the counter-calculation from the last installment still applies, from maintenance effort to the risk of building, out of sheer caution, a form with a chat UI. And it doesn’t belong to anyone alone: the rules come from the business side, enforcement comes from engineering, and neither can take over the other’s part. Regardless of the implementation effort, the team has to clarify who may propose, check and approve such rules in the future – that is organizational work.\n\n## Where things stand\n\nThe path of this series can now be told in three stations. Rules as prose: read, weighed, occasionally overruled – recommendations, the kind I spent half a year tightening in vain. Rules in the tool: checked on every call, reliable in detail, blind to the context. And rules in the path: a dedicated agent that knows the domain, checks plans before they take effect, obtains approvals no model can talk its way around, and produces evidence that answers the questions of the day after tomorrow. Only at this stage has the recommendation become a rule that holds even when nobody is looking.\n\nWhat this installment deliberately leaves open: the path there. No installed product automatically ships the rules of a domain – they emerge from engaging with the domain itself, and that immediately raises practical questions. How does a team find out which rules belong in the path and which may stay prose? How do you cut the first domain without overreaching? Which concepts, methods and processes hold up – and which fads can you safely skip? The next installment is about these tools.\n\n## What SubKit contributes\n\n[SubKit](https://subkit.mikebild.dev/de/) is my tool for recurring processes: an assistant designs the workflow, a person checks it and approves its scope. Execution follows the defined steps; permissions and results become traceable. AI clients can use approved workflows as tools via MCP.\n\nThis doesn’t replace modeling the domain. A case-based goodwill limit, shared case state and the handling of parallel requests have to be implemented explicitly in the respective process and the connected systems. SubKit doesn’t automatically supply the business rules for this. The [use cases](https://subkit.mikebild.dev/de/anwendungsfaelle/) show possible starting points; the article [MCP: When Software Offers Capabilities](https://www.mikebild.dev/en/blog/mcp-security-tools-permissions-and-approvals/) explains the role of the interface.\n\n## Further reading\n\n- [Terraform: plan and apply](https://developer.hashicorp.com/terraform/cli/commands/plan) – separating proposal and effect in everyday infrastructure work\n- [OWASP Top 10 for LLM Applications: Excessive Agency](https://genai.owasp.org/llmrisk/llm062025-excessive-agency/) – too many tools, too broad permissions, too much autonomy\n- [Simon Willison: The lethal trifecta](https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/) – why the combination of data access, untrusted content and external communication is dangerous\n- [Domain-Driven Design Reference (Eric Evans)](https://www.domainlanguage.com/ddd/reference/) – domain language and domain boundaries as design work"},{"locale":"en","translation_key":"mcp-softwarefaehigkeiten-agenten","slug":"mcp-security-tools-permissions-and-approvals","title":"MCP Security: Tools, Permissions and Approvals for AI Agents","summary":"How to integrate MCP tools into applications safely: server-side permission checks, human approvals, protection against prompt injection and traceable calls.","tags":["Software","AI","Architecture"],"published_at":"2026-07-13T10:00:00+00:00","updated_at":"2026-11-09T06:23:14.832389+00:00","url":"https://www.mikebild.dev/en/blog/mcp-security-tools-permissions-and-approvals/","audio_url":null,"audio_duration_secs":null,"text":"# MCP Security: Tools, Permissions and Approvals for AI Agents\n\nAn MCP tool can read data, publish a revision or call an external service. That turns a model response into an action with consequences. For developers and operators, the security question is therefore: Who may run which operation, on which data and after which approval?\n\nThe Model Context Protocol standardizes the connection to such capabilities. You still have to enforce the rules of your application yourself. This article shows how, using a constructed publishing example: the same permissions across the web UI, HTTP and MCP, a verifiable approval before publishing, and a traceable way of handling retries and untrusted content.\n\nFor context on the interfaces, here are the [differences between MCP, HTTP, webhooks and A2A](/en/blog/mcp-http-webhooks-and-a2a-explained-simply/).\n\n## Not the app, but the capability\n\nThe Model Context Protocol is an open standard that lets AI applications connect to external systems. The official documentation describes MCP as a connection between AI applications and data sources, tools and workflows. The specification talks about hosts, clients and servers: an LLM application is the host, a client sits inside it, and a server provides context or capabilities.\n\nAt first, this sounds like integration infrastructure. In fact, it contains a bigger shift. An application is then no longer just a UI for humans. It is also a set of addressable capabilities for agents.\n\nThe classic operating path looks like this:\n\n```mermaid\nflowchart LR\n  Human[Human] --> UI[UI]\n  UI --> App[Application]\n  App --> Result[Result]\n```\n\nThe human opens a UI, looks for the right place, fills in fields, clicks preview, clicks publish, then checks the feed and search. The application is the visible bundle of interaction, domain logic and state.\n\nWith an agent, a second path is added:\n\n```mermaid\nflowchart LR\n  Human[Human] --> Agent[Agent]\n  Agent --> Validate[validate_markdown]\n  Agent --> Preview[create_preview]\n  Agent --> Publish[publish_revision]\n  Agent --> Rollback[rollback_release]\n  Agent --> Search[rebuild_search_index]\n```\n\nThe UI doesn’t disappear because of this, and it doesn’t become secondary either. But it’s no longer the only access to the work. An agent doesn’t need to know where the button is. It needs to know which capability exists, which inputs it expects, which results come back and which rules apply.\n\nThat’s the core: MCP makes software capabilities addressable for agents. What it doesn’t do: replace the product domain or push aside its human UI.\n\n## A publishing system as an example\n\nThe following publishing system is a constructed architecture example, not a finished integration and not a customer case. The flow is familiar: Markdown comes in, a preview is built, someone reviews it, and then a revision is published. If something goes wrong, you need a rollback. After the release, the index, feed and cache have to be right.\n\nIn a classic UI, these steps are tied to pages and buttons. For humans, that makes sense: a good GUI shows context, can block invalid input and makes states such as approval status visible. For an agent, the same UI is a detour and a source of errors. It would have to click, wait, read from HTML, interpret, click again. That’s automation at the wrong level.\n\nAs an MCP capability, the same step would look different:\n\n```ts\nconst publishRevision = defineTool({\n  name: \"publish_revision\",\n  description: \"Publish an approved content revision\",\n  inputSchema: {\n    type: \"object\",\n    properties: {\n      site: { type: \"string\" },\n      revisionId: { type: \"string\" },\n      reason: { type: \"string\" }\n    },\n    required: [\"site\", \"revisionId\", \"reason\"]\n  }\n});\n```\n\nThe important part isn’t the specific syntax. The important part is the shift: an operating path becomes a named capability. `publish_revision` isn’t “click the green button.” It’s a domain operation with inputs, a result, permissions and errors.\n\nOnce the operation exists in this form, an agent can work with it. It can call `validate_markdown` first, ask back when there are warnings, request a preview, check the approval status and only then publish. The agent doesn’t operate a screen. The MCP server described here gives it domain tools with an input schema and a permission check.\n\n## Three access paths, one domain\n\nSuch a publishing system can provide a domain-oriented tool surface under `/mcp` that runs through the same publishing domain as REST and the web UI. The MCP tools stay bound to the product scopes.\n\nWhat matters is what this construction is not: MCP isn’t a second system next to the product. The web UI, HTTP and MCP access the same publishing domain with its revisions and permission boundaries. The shared domain logic decides what applies – not the channel the request came through.\n\nThis has a practical consequence for the tool list itself. Tools that the current principal isn’t allowed to use don’t need to appear in the list at all. So the agent only discovers capabilities its scopes allow. And where a human approval is required, the agent doesn’t provide that approval itself – it remains a separate step outside its reach.\n\nThis filtering is more than convenience, but it’s visibility, not the actual protection. An agent that doesn’t see a tool in the list won’t discover it the regular way. Protection against unauthorized calls comes from server-side authorization; the tools stay bound to the scopes of the respective product. That’s why you can’t obtain a missing release permission by switching from the web UI to MCP. The access path changes, the permission doesn’t.\n\n## Tool access is a permission\n\nAn agent that writes text can produce nonsense. An agent that calls tools can produce effects. It can read data, change files, trigger releases or notify external systems. That’s why tool access isn’t a convenience feature but a permission. A tool being discoverable is not yet permission to act; the call remains an authorized operation that the system checks. In a remote MCP setup, these duties are split: according to the MCP specification, getting the user’s consent before a tool call is the host’s job, while the product checks every call on the server side against the principal’s scopes.\n\nThe MCP specification itself says that such capabilities raise security and trust questions: users must be able to understand and control data access and operations, tools must be treated with caution, and hosts must obtain consent before tool calls. Consent and access control therefore belong in the execution path of every tool call.\n\nSo in a production system, a tool definition isn’t enough. It needs a policy next to it:\n\n```ts\ntype ToolPolicy = {\n  tool: string;\n  allowedRoles: string[];\n  requiresApproval: boolean;\n  requiresIdempotencyKey: boolean;\n  maxRuntimeMs: number;\n};\n\ntype ToolAuditEntry = {\n  tool: string;\n  inputHash: string;\n  idempotencyKey?: string;\n  decision: \"allowed\" | \"blocked\" | \"approved\";\n  outcome: \"succeeded\" | \"failed\" | \"unknown\";\n  actorId: string;\n  runId: string;\n};\n```\n\nThis turns “the agent may publish” into a verifiable rule. Who was allowed to make which call? Which input was used? Was an approval required? Was the call executed or blocked? For write operations, there is one more question: What happens if the agent repeats the same call after a timeout? An idempotency key only helps if the server binds it to the operation and its inputs, catches concurrent retries and stores the result reliably. With external side effects, the downstream service also has to recognize retries, or the system has to reconcile the unclear outcome. A key alone doesn’t guarantee a single execution.\n\nMCP standardizes how a tool is discovered and called. It doesn’t make the operation safe from a domain perspective, nor automatically idempotent or auditable. The capability being offered has to carry these properties itself.\n\n## Prompt injection: content must not grant permissions\n\nAn article that gets read in can contain instructions, for example to publish a different revision or to send data to an outside address. Treat such content as untrusted data. A prompt that tells the model to ignore such instructions isn’t sufficient access control. The allowed operations, target addresses and approvals have to be checked outside the document being read.\n\nTool descriptions and labels like “read-only” aren’t proof of how a third-party server actually behaves either. Check which server you connect and which permissions you give it. The [security principles of the MCP specification](https://modelcontextprotocol.io/specification/2025-06-18#security-and-trust--safety) name this trust boundary explicitly.\n\nFor a remote MCP server, securing authentication comes on top: check whether an access token was issued for your server; don’t pass received tokens on to downstream services unchecked. Request only the permissions you need. The official documentation on [MCP Security Best Practices](https://modelcontextprotocol.io/docs/2025-11-25/tutorials/security/security_best_practices) describes these measures and the risks of token passthrough.\n\nFor the publishing example, I would check at least the following cases before going into production:\n\n- A user without publishing permission calls the tool directly: the server rejects it, even if the tool name is known.\n- An approval applies to revision A, but the call names revision B: the server rejects it.\n- A document asks for data to be sent to an outside address: the configured boundary stays in effect.\n- A call runs into a timeout: before another write attempt, its result is clarified or the retry is effectively deduplicated.\n- A failed or rejected operation appears in the history with its actual result.\n\nThis is a checklist for this architecture example, not complete evidence of security.\n\n## The wrong split and the right one\n\nI don’t believe that applications will fall apart into small MCP services and stop being products. A good application bundles more than functions: it bundles understanding, interaction, data model, permissions, feedback and responsibility. But at the edges, capabilities that used to be tied to operating paths become individually addressable.\n\nA capability is well cut when it’s understandable from a domain perspective, technically verifiable and operationally accountable. The wrong split would be a generic `run_sql` or `click_button` – a tool that bypasses the domain rules instead of carrying them. The better split is an operation with domain intent: `publish_revision`, `rollback_release`, `create_preview`. The agent shouldn’t work around the database. It should work within the same rules that apply to the web UI and HTTP.\n\nA standard takes away integration work, but not product responsibility. Anthropic introduced MCP at the end of 2024 to address exactly the problem that every new data source needed its own integration. The specification standardizes the exchange over JSON-RPC and describes resources, prompts and tools. Bad capabilities stay bad, even when they are offered in a standardized way.\n\n## What happens to UIs\n\nThe strongest version of the claim about the future goes like this: when agents operate software, GUIs become secondary. I think that’s wrong.\n\nRoutine paths will shift. If I can tell an agent to review a draft, build a preview and show me only the deviations, I don’t want to click through five forms for that. This is especially true for recurring work that is well described and cleanly bounded.\n\nBut humans need UIs for exploration, control, exceptions and trust. A preview is a GUI. A diff is a GUI. An audit log is a GUI. An approval dialog is a GUI. Precisely when agents execute more, good control UIs become more important. The control UI exists so that a human understands what an agent has done and steps in where their judgment is needed.\n\nSo the control UI and MCP don’t compete for the same job. The control UI is aimed at human operation and control, MCP at agentic calls. Both are subject to the permission boundaries of the same domain.\n\n## What I take away from this\n\nFor me, MCP is less a spectacular technology than a good reason to describe software differently. Not only through the data a system holds, and not only through the UI it offers – but through the work it can do safely, traceably and verifiably.\n\nThat’s an architecture question. If you publish capabilities only as a thin wrapper around internal functions, you’re probably building new risks. A domain split, permissions, idempotency and auditability create a controllable foundation for agents – they are not a quality guarantee.\n\nNot every application needs an MCP server right away. Many systems are better served by a good API, a CLI or a clear UI. Where it fits, though, this holds: software meant to be used by agents has to make its capabilities explicit – and it has to enforce the same permission boundaries across every access path.\n\n## Where SubKit fits in\n\nIn [SubKit](https://subkit.mikebild.dev/de/), AI helps you design a workflow. A person reviews the preview and approves its scope. After that, the defined workflow runs; the AI doesn’t decide on the further path during execution. Every run is checked for permissions and recorded.\n\nMCP is used in both directions: a workflow can serve as a tool for an AI client, and an external MCP server can be connected as a connector. Which external tools may be used is defined separately. The additional access path replaces neither the approval nor the permissions of the calling person.\n\nThis is a concrete product reference, not a claim that SubKit makes every MCP server secure or automatically knows domain rules. The rules of your domain and the permissions of external systems still need to be checked. The article [AI Agents per Domain: Rules, Approvals and Evidence](/en/blog/ai-agents-per-domain/) goes deeper into how such rules can be separated from model decisions.\n\n:::note\n**Context and sources**\n\nThe publishing system and the code snippets are constructed and illustrate architecture decisions. This article uses the MCP specification from June 18, 2025 and the linked Security Best Practices. The security sections were checked against these primary sources on November 9, 2026; this implies no statement about the security of any specific installation. The SubKit section is based on the confirmed product description from November 8, 2026.\n:::\n\n## Further reading\n\n- [Model Context Protocol: Specification 2025-06-18](https://modelcontextprotocol.io/specification/2025-06-18)\n- [Model Context Protocol: Security Best Practices](https://modelcontextprotocol.io/docs/2025-11-25/tutorials/security/security_best_practices)\n- [Model Context Protocol: Introduction](https://modelcontextprotocol.io/docs/getting-started/intro)\n- [SubKit: workflows, approvals and operations](https://subkit.mikebild.dev/de/)"},{"locale":"en","translation_key":"agent-modell-fachdomaene","slug":"agent-model-domain","title":"Agent, Model, Domain","summary":"The model is rented, the agent can be under your own control – what matters is whether the domain lives as prose in the prompt or as a checked interface in the agent.","tags":["Software","AI","Methodology","Delivery"],"published_at":"2026-07-13T10:00:00+00:00","updated_at":"2026-08-17T17:34:45.985779+00:00","url":"https://www.mikebild.dev/en/blog/agent-model-domain/","audio_url":null,"audio_duration_secs":null,"text":"Some time ago, I sat in a meeting at a large enterprise that was supposed to decide on an “agent strategy” for the coming year. On the wall, a slide with three columns: three vendors, with checkmarks for features below them, prices per user, compliance seals. For an hour, the conversation revolved around the question of which agent was the best. At some point I asked a different question: What of all this actually belongs to us afterward? If we switch vendors in three years – what do we take with us? The room went quiet. Not because the question was particularly original, but because the slide had no answer to it.\n\n*Part 10 of the series “From Session to System” – [start here with the opener](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nThe [last episode](https://www.mikebild.dev/en/blog/knowledge-that-survives-the-session/) ended with the question of whom I hand curated knowledge to – and where the generic agent reaches its limits. To answer it, I first have to take apart everything that gets packed into the word “agent.” Because the silent minute in the conference room had a simple reason: the group talked about agents as if they were a device you buy, set up and use. That picture is misleading – and precisely at the point where it gets expensive for the company.\n\n## An agent is software\n\nWhat an agent really is can be said in one sentence. In the fall of 2025, Simon Willison put forward a useful working definition: an agent is a model that runs tools in a loop to achieve a goal. There is nothing more to it. No consciousness, no intent, no magic.\n\nThere is a loop: the model gets a task and the history so far, proposes the next step, the agent executes it, the result flows back – until a stop condition applies. There are tools: functions that the agent offers the model and whose calls it executes. There is context: everything the agent gives the model, from files and search results to instructions. There is state: what persists between steps and beyond the session. And there are permissions: what the agent is allowed to execute at all, with whose rights, with what evidence.\n\nEach of these five things is ordinary software. In episode 3, I described how exactly this frame – the harness – makes the difference between an impressive tool and a useful one. Back then I meant it personally: my machine, my tools, my way of working. Today I read the same sentence organizationally. What applies to my command line applies all the more to the company: the model produces outputs, such as suggestions, classifications and wording. The agent determines the loop, context, state, permissions and tool integration. These parts can be designed.\n\n## What you rent and what you can control\n\nThis division of labor deserves a close look, because economically it describes two completely different things.\n\nA proprietary model that you get through a vendor’s API is rented: it belongs to the vendor, and you have a say in version changes only within the frame set by the API contract and the vendor. You own nothing of it – and that is acceptable as long as several models solve your own, concretely checked tasks well enough. If you build your strategy on “the best model,” you build on something you neither own nor control. I laid out this thought in detail [early in this series](https://www.mikebild.dev/en/blog/good-enough-models/).\n\nThe agent layer, on the other hand, can be under your own control. The loop, the context building, the state, the permissions, above all the tools – all of this can be your own code and your own configuration, versionable, testable and reviewable. The integration is also becoming less proprietary: since December 2025, MCP, together with AGENTS.md and goose, sits with the Agentic AI Foundation under the umbrella of the Linux Foundation. That is no guarantee that every vendor provides the same capabilities in the same way.\n\n```mermaid\nflowchart TB\n    subgraph rented[\"rented – interchangeable\"]\n        M[\"Model<br/>Suggestions · Classification · Language\"]\n    end\n    subgraph owned[\"designable – under your own control\"]\n        A[\"Agent<br/>Loop · Context · State · Permissions\"]\n        W[\"Tools and interfaces<br/>typed operations\"]\n        F[\"Domain<br/>Terms · Rules · Processes\"]\n        A --> W\n        W --> F\n    end\n    A -- \"requests\" --> M\n    M -- \"suggests steps\" --> A\n```\n\nIf the model is rented and the integration increasingly standardized, one particularly important part remains your own: what a company puts into the agent. Its terms, its rules, its processes, its data – in short: its domain. That raises the question of this post. Where does the domain live?\n\n## Option A: the domain as prose\n\nThe obvious place is the prompt. In practice, that means instruction files such as CLAUDE.md or AGENTS.md, system prompts, attached policy documents. They then contain something like: “Credit notes over 500 euros may only be issued by a team lead. Customers in an ongoing dunning process receive no goodwill credit. Price changes apply only from the following month.”\n\nI do not want to belittle this option. It is fast: if there is an approved way to maintain it, the business department can change the text without touching the business application. The changed version is available to the model as soon as the agent loads it. For exploratory work, that is often enough – and at the beginning it is almost always the right way, because you first have to find out which rules are needed at all.\n\nBut it is fragile, and structurally so, not just in its craftsmanship. First, prose is unchecked: nobody validates it, no compiler reports that sentence 12 and sentence 47 contradict each other, no type check notices that “500 euros” meant gross in one place and net in another. Second, for the model, prose is a recommendation, not a reliable enforcement mechanism – that was the central disillusionment of my futile attempts with instruction files: the model can follow instructions, but you cannot enforce compliance with them this way. Third, the session lottery kicks in: the same sentence is heeded today and skipped tomorrow, depending on what else is in the context. And fourth – in a company, this weighs heaviest – you can version the file, but not the behavior. The instruction file alone provides no deterministic, blocking check that prevents a credit note that breaks the rules; without an additional check, the violation only shows up afterward.\n\nProse scales with the amount of knowledge. It does not scale with how binding that knowledge is.\n\n## Option B: the domain as an interface\n\nThe alternative: do not put the domain knowledge next to the agent but build it into its tools. Instead of giving the model generic database and file access and placing the rules next to it as text, the agent gets typed operations whose names come from the domain language and whose inputs are checked:\n\n```ts\nconst issueCreditNote = defineTool({\n  name: \"issue_credit_note\",\n  description: \"Issue a credit note for an existing invoice\",\n  input: z.object({\n    invoiceId: z.string(),\n    amount: z.number().positive(),\n    reason: z.enum([\"complaint\", \"goodwill\", \"pricing_error\"]),\n  }),\n  authorize: ({ user, input }) =>\n    input.amount <= 500 || user.hasRole(\"team_lead\"),\n  execute: (input, ctx) => billing.issueCreditNote(input, ctx.audit),\n});\n```\n\nThe difference is more fundamental than the short code block suggests. The 500-euro rule is no longer a request but code: it is checked on every call, the same in every session, regardless of the model’s mood of the day or the state of its context. It exists exactly once, it has an owner, a review, a test. The AI does the wording; the interface decides what is possible at all.\n\nThis is the logical continuation of two thoughts from the last episodes. [Episode 8](https://www.mikebild.dev/en/blog/clean-grounding-ii-grounding-answers/) was about grounding answers: looking things up instead of guessing, real sources instead of plausible assumptions. A tool is grounded knowledge in executable form – the agent does not have to guess the credit note rules; it can only act within them. And [episode 9](https://www.mikebild.dev/en/blog/knowledge-that-survives-the-session/) was about knowledge that survives the session: a tool definition survives it on its own, because it is part of the system and not part of the conversation.\n\nThe tool names connect directly to Domain-Driven Design: they become the binding domain language. What Eric Evans called “ubiquitous language” a good twenty years ago – a shared, precise language between the business side and development – gets a very tangible form of existence. If `issue_credit_note` and `waive_dunning_fee` are the only verbs the agent knows, the organization has to agree on what exactly these verbs mean. Modeling the tools is domain work, not infrastructure work. The interface can reliably check the inputs and permissions of individual calls; process rules spanning several calls need additional state checks and, where necessary, a check of the planned process.\n\n## The counter-calculation\n\nSo much for the opportunity. The same calculation includes lock-in, maintenance effort, responsibility and over-constraining.\n\nFirst, lock-in. Tool definitions, skill formats and agent configurations follow vendor conventions today. MCP standardizes the transport, not the semantics: the protocol defines how a tool is called, not how my credit note logic is structured. If you pour your domain logic directly into the formats of an agent framework, that is exactly where it will be in three years – and moving costs money. The remedy is an old one: put the domain logic into your own services and build the tool layer as a thin adapter. But you have to do it; it does not happen on its own, and under deadline pressure, the opposite happens regularly.\n\nThen the maintenance effort. Your own tool layer causes ongoing maintenance and operating effort. Business rules change: the 500-euro threshold becomes 300, a new credit reason is added, a role is restructured. Someone has to maintain, prioritize, test and roll that out – next to everything else. The prose option was so tempting partly because it hid this effort. The tool option makes it visible, and visibility at first feels like it makes things more expensive, even though the effort was only somewhere else before: in the corrections afterward.\n\nThird, reviewability and responsibility. Who is liable for a tool definition? The question sounds legal, but it is above all organizational. With purely advisory use, a human can reject the answer. If the agent may execute tools without approval, an error in their authorization can take effect immediately: a wrong upper limit then applies reliably wrong, in every session, for every user. Tool definitions therefore need the same care as any production interface: review, tests, clear ownership, change history. And responsibility shifts noticeably: away from the individual who wrote a prompt, toward the team that defined the tool. That is consistent and right – but an organization has to want it, decide it and bear it.\n\nAnd finally, over-constraining. After the first incident, it is tempting to define away every conceivable deviation until the agent knows only a single, narrow path. Then you have built a form with a chat UI in front of it – more expensive, slower and moodier than the form would have been. The model’s strength lies precisely in the unforeseen: in the special case, in the follow-up question, in the connection between two cases that nobody thought of during the design. If you give the agent tools only for the expected, you could have had classic automation more cheaply. Tools that are too narrow can limit risks, but they can also take away so much room for action that classic automation would be the better fit.\n\n## When generic tools are enough – and when they are not\n\nFor my decision, four criteria matter: the kind of work, the people responsible, the potential for damage and the maturity of the domain knowledge. Generic tools – file access, shell, search – go surprisingly far as long as a few conditions come together:\n\n- The work is exploratory: analyzing, prototyping, researching, migrating – tasks whose result a human reviews anyway.\n- A single person is working who owns the result and can judge it themselves.\n- The potential for damage is small: everything is reversible, nothing leaves the building, no money moves.\n- The domain knowledge is still in flux – it would simply be too early to pour it into interfaces.\n\nConversely, the domain belongs in the agent as soon as the picture flips:\n\n- A process repeats in the team: the same operation, many people, different levels of care and experience.\n- Rules are binding, not recommended – they must also hold at 5 p.m. on a Friday afternoon.\n- There are audit or evidence obligations: who triggered what and when, with what justification?\n- The potential for damage is high: money, personal data, external impact.\n\nIn between, I use a pragmatic transition: the prose option is the prototype of the interface. When the same rule shows up in an instruction file for the third time – and has been ignored for the second time – it is a candidate for a tool for me. That way, the domain moves piece by piece from recommendation into structure, following how binding it actually is rather than a big up-front plan.\n\n## Where things stand\n\nFor me, the series so far shifts responsibility from the session to the system. It started with the session: the experience that the models are good enough for my work and that the difference lies in my own frame – tools, context, way of working. Then came the team: the disillusionment that my success at work cannot be copied by file and that instruction files remain recommendations, however carefully you write them. Then knowledge: clean grounding instead of convincing guessing, curated insights that survive sessions. And now the system: the insight that the model is rented and stays rented – and that the part you can control in the long run lies in the agent. More precisely: in the tools through which the agent touches the domain.\n\nWhat remains open is the question of how binding rules are enforced across individual tool calls. Tools decide what is possible in a single call – beyond that, you need approvals before something takes effect; traceability after it has taken effect; a no that stays a no, even when the model keeps phrasing things politely. Why this ultimately leads to an agent of your own, bound to the domain – and what it has to be able to do – deserves a post of its own.\n\n## Further reading\n\n- [Building Effective AI agents](https://www.anthropic.com/engineering/building-effective-agents) – Anthropic’s distinction between workflows and agents\n- [Writing effective tools for AI agents](https://www.anthropic.com/engineering/writing-tools-for-agents) – tool design for agents from practice\n- [Designing agentic loops](https://simonwillison.net/2025/Sep/30/designing-agentic-loops/) – Simon Willison on loops, tools and stop conditions\n- [Model Context Protocol](https://modelcontextprotocol.io/) – specification and documentation of the tool protocol\n- [Founding of the Agentic AI Foundation](https://www.linuxfoundation.org/press/linux-foundation-announces-the-formation-of-the-agentic-ai-foundation) – MCP, AGENTS.md and goose under the umbrella of the Linux Foundation"},{"locale":"en","translation_key":"wissen-das-die-session-ueberlebt","slug":"knowledge-that-survives-the-session","title":"Knowledge That Survives the Session","summary":"Session knowledge evaporates when no one curates it – why teams should treat their AI working knowledge like code, and why it’s not the model that gets smarter but the organization that learns.","tags":["Software","AI","Methodology","Delivery"],"published_at":"2026-06-23T10:00:00+00:00","updated_at":"2026-08-17T17:34:45.985779+00:00","url":"https://www.mikebild.dev/en/blog/knowledge-that-survives-the-session/","audio_url":null,"audio_duration_secs":null,"text":"Tuesday morning, the third session this week. I’m typing the same explanation for the third time. Our error model distinguishes between expected and unexpected errors; expected errors come back as values, and there should be no try/catch cascades around service calls. The session before knew that. It had understood it, applied it and even cleanly solved an edge case I wouldn’t have thought of myself. Now I’m sitting in a new session again without that explanation and writing it once more, in different words, a bit more impatiently than last time.\n\n*Part 9 of the series “From Session to System” – [the opening post is here](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nThis is session amnesia as an everyday experience. Not as a theoretical problem of context windows and token budgets, but as the quiet annoyance of working with a tool that hears from me for the first time every morning. The vendors are working on it. As of August 2026, there are different storage mechanisms for this: Anthropic’s Memory Tool lets agents store information outside the immediate context window in files and load it again later; Claude Code provides project instructions through hierarchical CLAUDE.md files and personal notes through Auto Memory, both across sessions. Personal Auto Memory starts with the individual person; shared, jointly maintained CLAUDE.md files are a different matter. None of these features solves the variant of the problem that really occupies me on its own.\n\nBecause the team variant is worse. On Wednesday, a colleague tells me he explained our error model to “his” session. I ask how. He explained it differently than I did. Not wrong – differently. Different terms, different examples, one nuance I would leave out, one I’m missing. A third colleague didn’t explain it at all, because he didn’t know there was anything to explain; his session built try/catch cascades, and the pull request looked like it. Four people, four private explanations of the same convention, four slightly different results. This is exactly the variance problem I described in [“My Success Cannot Be Copied”](https://www.mikebild.dev/en/blog/my-success-cannot-be-copied/) – except that here it’s not about ways of working but about knowledge. Each of us feeds our sessions with our own oral tradition of what the team should actually know together. Personal Auto Memory doesn’t change that: it remembers my version of the explanation, not ours. Versioned, jointly maintained CLAUDE.md files would be the place for a shared version – but only if the team curates them deliberately.\n\nSo the core question of this episode is: how does session knowledge become team knowledge – and eventually company knowledge? How does what comes out of a good session get into the next session of another person?\n\n## Two kinds of knowledge\n\nTo talk about this sensibly, a distinction helps me that I carried around only implicitly for a long time: curated knowledge and emergent knowledge.\n\nCurated knowledge is deliberately distilled. Someone sat down and put an experience or a decision into words, someone else proofread it, and the result sits in a place where it gets found. Architecture decisions in ADRs, conventions in a CLAUDE.md or AGENTS.md, a runbook for the deployment edge case that strikes every six months. Curated knowledge is expensive – it costs the time of one person who writes it down and of a second who reviews it. In return, it is addressable: I can point to it, link to it, hand it to a session.\n\nEmergent knowledge comes about on the side. In Tuesday’s session, half a dozen small insights came up: that our test setup has a quirk when mocking the message broker, that a certain library in version 4 has a different default behavior than our docs say, that my prompt framing for refactorings works better when I put the target picture before the constraints. I wrote none of it down. The session ended, and with it everything evaporated that didn’t solidify into code or a commit message. Emergent knowledge is cheap to create – and not reliably available to later sessions unless it was saved.\n\nThe gap between the two is the real problem. Teams today produce more emergent knowledge in AI sessions than ever before – every session is a small lab where someone tries things out, phrases things, fails, readjusts. And almost none of it survives. What survives is the code. But the code contains only the result, not the reasoning, not the discarded wrong turn, not the phrasing that untied the knot.\n\n## Treating knowledge like code\n\nA team’s distilled working knowledge deserves the same treatment as its code. Versioned. Reviewed. With ownership. And with a lifecycle that includes dying. That is where this episode is headed.\n\nAt first that sounds trivial – Docs as Code means treating documentation with the same versioned ways of working as source code, including review and automated checks. But in the AI context, each of these four properties gets a new edge:\n\n- Versioned, because the knowledge is now consumed by machines. When an instruction file changes, the behavior of the sessions that load it can change. Such changes affect the behavior of the system – and behavior changes belong in the history, with a diff and a date and the option to go back.\n- Reviewed, because a wrong convention now misleads not only human readers but also several sessions. A person reading a bad wiki article often notices that something is off. A session can’t recognize the error and will apply the wrong convention, as I described in [“Clean Grounding II: Grounding Answers”](https://www.mikebild.dev/en/blog/clean-grounding-ii-grounding-answers/): whatever is in the context becomes the session’s reality, whether it’s true or not.\n- With ownership, because no one maintains knowledge that belongs to no one. Every convention file, every runbook needs a person who feels responsible. That’s not bureaucracy – it’s the simple answer to the question “Whom do I ask whether this still applies?”\n- With a lifecycle, because outdated knowledge is worse than none. This is the point I see underestimated most often. A session without a matching source can guess or ask; a session with outdated grounding guesses with a citation. It quotes the convention from 2024 that we dropped in the fall, and sounds so well-supported that no one checks.\n\nThe last point deserves its own paragraph because it is counterintuitive. We are trained to see documentation as “better than nothing.” In the AI context, that’s no longer true. Wrong, old, half-baked knowledge in a session’s grounding is actively harmful, because it turns the model’s uncertainty into false confidence. An empty directory forces me to think about what the session needs to know. A full directory that has never been cleaned out fools me into thinking that’s been taken care of. That is why the lifecycle also includes regular checks against the sources: does the convention still apply? Does the runbook still describe the system that is running?\n\n## The cycle\n\nIf you take this distinction seriously – emergent knowledge is created all the time, curated knowledge has an effect – a cycle follows almost inevitably. From these observations I derive four stations.\n\nFirst: learn from real runs. Not from opinions, not from blog posts, but from what actually happened in your own sessions. Which explanation worked? Where does the same follow-up question come up repeatedly? Which error shows up independently in several pull requests? The raw material is lying around – you just have to recognize it as raw material.\n\nSecond: a human curates and approves. This is the decisive station, and it is deliberately not automated. Distilling means selecting, condensing, throwing away. Ten observations become one paragraph; one paragraph may become one line in the convention file; eight of the ten observations are discarded because they were one-offs. The team has to make this decision, because only the team can define what is binding from now on: what is a rule here, what was an exception and what should apply starting tomorrow. And the approval – a second pair of eyes, a real review – turns a private note into a shared commitment.\n\nThird: the distillate flows into the grounding of the next session. It sits in the file every session reads, or in the knowledge source that is pulled in during work. From that moment on, not every colleague has to explain the error model to “his” session orally and differently – the explanation is the same, for everyone, reviewed.\n\nFourth: the next piece of work can get better. Not dramatically, not all at once. Whether the cycle works can be checked with concrete questions: does the follow-up question that kept repeating come up less often? Does the recurring error still show up in new pull requests? And the next runs produce new raw material – ideally at a slightly higher level.\n\n```mermaid\nflowchart LR\n    A[\"Real runs<br/>and experiences\"] --> B[\"Observe and<br/>collect raw material\"]\n    B --> C[\"Human curates,<br/>review approves\"]\n    C --> D[\"Distillate in the grounding<br/>of the next session\"]\n    D --> A\n```\n\nThis is not a framework and not a ceremony. To get started, a regular, short pass is enough, in which the team discusses what stuck, plus the discipline to treat changes to the knowledge files like code changes: branch, review, merge. How much effort is appropriate depends on the team, the scope and the risk.\n\n## It’s not the model that gets smarter\n\nThe point of this cycle only became clear to me over time, and it changed how I see the whole model debate: in this cycle, the model doesn’t get smarter. The organization learns: people select insights, justify them and make them reusable for others. The selected insights show up as versioned changes to the curated knowledge – not in a model retaining more context.\n\nAt the end of the quarter, the model hasn’t automatically retained anything from our sessions as team knowledge. The version on offer may well have changed during that time – that doesn’t mean it knows our error model. What has improved is the layer around it: our curated knowledge, our explanations, the quality of what we give each session. And – this is the decisive difference – this layer belongs to us. We can read it, check it, correct it, roll it back. We can steer it. Which model version a vendor ships and how it behaves is something we can influence far less.\n\nIf you locate the learning ability of your AI work in the model, you have a steering problem: you’re waiting for progress you can’t influence. If you locate it in curation, you have a work problem – more strenuous, but solvable. I consider that the most sober answer to the question of where a team should invest: in the part it owns.\n\n## The anti-patterns\n\nMost of the attempts I’ve seen to capture session knowledge have failed. And in three recognizable ways.\n\nThe prompt collection in the wiki. Someone creates a page: “Our best prompts.” For three weeks people contribute, then never again. After half a year, the page contains outdated prompts without context of use: for models no one uses anymore, for problems no one has anymore, without saying when they work and when they don’t. No one dares to delete, no one wants to maintain. The mistake is already in the form: a prompt without the situation it was distilled for is not knowledge but a souvenir.\n\nThe instruction file dump. I already looked at this from a different angle in “Futile Attempts: Skills, AGENTS.md and the Limits of Recommendation”: convention files that everyone writes something into now and then and from which nothing ever drops out. After a year, there are two thousand lines in which rules contradict each other because the one from March doesn’t know the one from October. The sessions read everything and weight it somehow – the result is a lottery. A knowledge file without deletion discipline is not a knowledge file but a sediment basin.\n\nThe written-down-once. The third variant is the quietest: in a good week, a motivated colleague writes everything down – thoroughly, structured, really useful. Then it’s never touched again. No ownership, no review rhythm, no occasion to update it. Twelve months later, parts of it may be outdated, and because no one knows which ones, no one trusts the rest anymore. The one-time heroic effort is the natural enemy of the cycle: it feels like a solution and prevents exactly the routine that would be one.\n\nAll three patterns lack the same thing: the way back from the real work into the knowledge. They treat writing things down as an event instead of a cycle.\n\n## The opportunity that costs work\n\nAnd still – or precisely because of this – I consider this moment an unusual opportunity. Organizations have been talking for decades about making implicit knowledge explicit. Knowledge management initiatives, wikis, communities of practice: my thesis is that the lack of an immediate consumer contributed to many of these initiatives petering out. Whoever wrote down their knowledge wrote for an abstract “later” and a hypothetical “someone.” The feedback was missing; writing things down remained a sacrifice without visible return.\n\nThat is changing right now. AI sessions form an additional immediate consumer for explicit knowledge. If you distill a convention cleanly today, you can check it in the next session: does the AI behave differently? Does the pull request follow the convention? Does the familiar follow-up question stay away? The feedback loop that was missing in these cases can become much shorter in such workflows. AI thus creates an immediate incentive to make implicit knowledge explicit – and the next session gives early hints about whether what was written down holds up.\n\nI don’t want to hide the criticism of this. Curating costs the time of exactly the people who have the least of it. There is a real risk that the cycle gets out of hand and every line of convention has to pass through its own approval committee. And not all knowledge wants to be frozen – some of it is deliberately in flux, and if you distill it too early, you cement an interim state. The answer to that is moderation, not abstinence: start small, distill only what has repeated itself, and take deleting as seriously as writing.\n\nWhat keeps me busy at the end of this episode is a question one level deeper. Suppose the cycle is in place: the team curates, the knowledge survives the session, the organization learns. Then there is a growing body of distilled conventions, domain terms, decisions – and session after session, I hand it to a generic assistant that knows nothing about my domain and reconstructs everything from the context every time. At some point the question arises of whom I’m actually entrusting this knowledge to: is the generic agent with good grounding enough – or does the domain need a counterpart built for it? Where exactly the generic agent ends is the question of the next episode.\n\n## Further reading\n\n- [AGENTS.md – the open format for agent instructions](https://agents.md/)\n- [Anthropic: Memory Tool – knowledge across sessions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool)\n- [Claude Code: How Claude remembers your project](https://code.claude.com/docs/en/memory)\n- [Ikujiro Nonaka: The Knowledge-Creating Company (Harvard Business Review)](https://hbr.org/2007/07/the-knowledge-creating-company)\n- [Write the Docs: Docs as Code](https://www.writethedocs.org/guide/docs-as-code/)"},{"locale":"en","translation_key":"sauberes-grounding-antworten-erden","slug":"clean-grounding-ii-grounding-answers","title":"Clean Grounding II: Grounding Answers","summary":"My working model for grounding distinguishes conventions, documents and API descriptions. What stays in the scarce context, I prioritize by task and by the cost of fetching it again.","tags":["Software","AI","Methodology","Delivery"],"published_at":"2026-06-03T10:00:00+00:00","updated_at":"2026-08-17T17:34:45.985779+00:00","url":"https://www.mikebild.dev/en/blog/clean-grounding-ii-grounding-answers/","audio_url":null,"audio_duration_secs":null,"text":"A few weeks ago, a colleague and I sat in front of a half-finished piece of integration. The AI was supposed to write a client for an internal API, and it did what it always does: it suggested `customerId`. In our system, the field is called `customer_ref` – for historical reasons that no one defends anymore but everyone knows. We had already explained that to the assistant twice that week. This time I did something different: I didn’t contradict it; I put the OpenAPI description of the API into the context. The next suggestion was right. Not roughly, but exactly – including the somewhat idiosyncratic pagination that no model in the world could have made up, because it was simply a decision of ours. Same model, same day, same task. The difference: it no longer had to guess.\n\n*Part 8 of the series “From Session to System” – [the opening post is here](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nIn the [last episode](https://www.mikebild.dev/en/blog/clean-grounding-i-why-ai-guesses-so-convincingly/), I described why AI guesses so convincingly: a language model uses symbols to refer to symbols, not to my systems. It knows a thousand APIs that look similar to mine – and that is exactly why it invents plausibly. That was the diagnosis. This episode is the constructive side: how do I give the AI my reality? For myself, I call this clean grounding – grounding answers instead of leaving them hanging in the air. And as so often, the core is less a tool than a sorting: what knowledge is there at all, where does it come from, and when does it belong in the context?\n\n## My working model: three layers of knowledge\n\nWhen I look at what gives my answers solid ground in practice, I keep ending up with three layers. This is my sorting for this work, not a general taxonomy of knowledge. The layers differ not only in content but in their character – and that is the real point.\n\n```mermaid\nflowchart TB\n    subgraph Schichten[\"Three layers of knowledge\"]\n        K[\"Conventions<br/>how we work<br/>prescriptive, curated\"]\n        D[\"Documents<br/>runbooks, specs, decisions<br/>descriptive, aging\"]\n        S[\"API descriptions<br/>OpenAPI, GraphQL introspection, schemas<br/>machine-checkable\"]\n    end\n    K --> E[\"Grounding while building<br/>and preparing\"]\n    D --> E\n    S --> E\n    E --> A[\"Checked work result<br/>document, plan, code, configured flow\"]\n```\n\nThe first layer is our **conventions and ways of working**. This is prescriptive knowledge: not “this is how the world is,” but “this is how we do it here.” Error handling belongs to the caller, migrations never run automatically, commit messages explain the why, reviews check the interface first. None of this is in an API description, and none of it can be guessed by a model – these are decisions, not facts. In episode 6, I told how I tried to pack exactly this knowledge into instruction files like AGENTS.md or CLAUDE.md – and where recommendations reach their limits. Giving up was not the lesson. This layer has to be small, dense and curated: a short list of rules the team stands behind can be followed and enforced in review. A long collection of hints competes with itself for attention.\n\nThe second layer is our **documents**: runbooks, specifications, architecture decisions, operations notes. This is descriptive knowledge – it describes what applies here and why it came about this way. A recorded architecture decision can prevent the AI from overriding three-year-old system boundaries with its suggestion. A runbook explains what really needs to be done for a particular alert, instead of what sounds generically sensible. But I’ve learned to approach this layer with a certain skepticism: documents age. They describe the state of back then, not of today. A runbook that no one has touched in two years can mislead the AI just as much as its own guessing – only then the answer sounds even more convincing because it cites “our docs.”\n\nThe third layer is **real API descriptions** – and it’s my favorite, because it has a character the other two lack: tools can read their structure, even if schema and runtime behavior can drift apart. An OpenAPI description, a GraphQL schema queried via [introspection](https://graphql.org/learn/introspection/), a JSON Schema, a database schema – that is not a colleague’s memory of the system but a machine-readable description of structure or API. Introspection shows the schema this environment offers at this point in time: if the field is called `customer_ref`, that’s what it says there. That proves neither correct resolvers nor agreement with other deployments or with data-dependent responses. Depending on the artifact, I can read field names, types or endpoints from it instead of guessing them from conventions or documents.\n\nThe three layers answer different questions, and they don’t replace each other:\n\n- Conventions say **how** something should be built – style, boundaries, responsibilities.\n- Documents say **why** things are the way they are – context and history.\n- The respective API description names fields, types or endpoints. Whether the implementation matches this state and works has to be checked separately.\n\nIf you supply only the third layer, you get code that matches the described contract but doesn’t necessarily work at runtime. If you supply only the first, you get stylistically clean code against an invented API. Only together do they ground an answer.\n\n## Look it up instead of guessing\n\nThe principle behind all three layers is the same, and it’s so unspectacular that it’s easy to read past: **look it up instead of guessing**. The easiest way to understand it is through an analogy everyone knows from the editor: IntelliSense.\n\nWhen I type `customer.` in my editor, the editor doesn’t guess which fields a customer probably has. It looks them up. A type-based editor derives suggestions from the available type definition, not from statistical similarity. Exactly this derivation is what a language model lacks when we let it work without grounding.\n\nAn agent with suitable tools and read permissions can look things up. It can read an OpenAPI file, query a GraphQL schema via introspection, open a type definition in the repository. The [Model Context Protocol](https://modelcontextprotocol.io/) provides tools and context sources for this through a protocol contract. And such an agent can go one step further, beyond IntelliSense: it can **try** endpoints. A read-only call against the real API, a look at the actual response structure, and the next suggestion is based on observed data instead of invention. “This field probably exists” becomes “I have seen this field – in this response, with these permissions, in this environment and at this point in time.” That is a categorical difference, not a gradual one, even if a single response doesn’t prove the behavior for other data, permissions, environments and points in time.\n\nExploratory read access must be authorized; whether it is free of side effects in domain terms has to be clarified beforehand. Such calls are valuable for research. Writing calls “just to try it out” are a topic of their own with their own safeguards – I’ll come to that later in this series. For grounding answers, the reading side is almost always enough.\n\n## Grounding of repeatable workflows belongs at build time\n\nThe second principle took longer to sink in for me, and it’s the one with the biggest consequences: **when** does grounding happen? Wherever a repeatable workflow has an artifact that can be checked in advance, grounding belongs at build and preparation time – not in the critical path of execution. If, on the other hand, the question only arises at runtime, the grounding has to happen there too.\n\nThe diagram above shows this case for an artifact that can be checked in advance.\n\nAt this point I have to place RAG, because it’s the first word in the room as soon as someone says “our own knowledge” and “AI” in the same sentence. Retrieval-Augmented Generation – described in 2020 by [Lewis and colleagues](https://arxiv.org/abs/2005.11401) – means: at query time, matching text passages are searched in a corpus and passed to the model. That is exactly right when the question only arises at runtime and the answer has to come from a body of documents – an assistant that answers questions about the handbook, a search across internal notes, support cases. Such cases correspond to the pattern of retrieval and generation described in the RAG paper.\n\nIt goes wrong when RAG becomes the reflex for everything. Because retrieval at runtime has two properties that hurt in day-to-day work: additional latency and possible changes in results when the index, ranking or search method changes. Every execution searches anew, and what gets found depends on embeddings, rankings and the state of the index – the same workflow can see different text passages today than yesterday and therefore behave differently. For an exploratory question, that’s tolerable. For a workflow that runs every night and whose result people rely on, changing hits can lead to non-reproducible results.\n\nThat is why, for such repeatable workflows, I pull grounding forward. The knowledge – the conventions, the documents, the API descriptions – flows in while something is being **created**: a document, a plan, a piece of code, a configured workflow. This work result is checked, by me or by a colleague, and from then on it is fixed. The later execution doesn’t roll the dice again; it executes what was checked. The difference is the same as between a program that guesses its dependencies from the network on every start and a build with pinned versions: all the uncertainty belongs in the fleeting, creative moment – it doesn’t belong in what then runs again every night.\n\nThis is not a rejection of RAG but a clarification of responsibilities. Search across documents at runtime, where the question arises at runtime. Grounding at build time, where the result is an artifact that is meant to last. In my work, the second case is the more common one – yet it is still discussed in the vocabulary of the first.\n\n## Context economics: what goes last\n\nThe third principle sounds trivial and decides a surprising amount in practice: context is scarce. Yes, the windows have gotten big. But if you work with agent sessions for a while, you know that “big” doesn’t mean “inexhaustible” – long sessions, files read, tool outputs and intermediate states fill every window, and at some point things get trimmed, summarized, left out. Anthropic put this in a nutshell under the term context engineering: context is a finite resource; relevant information is found deliberately and loaded only when needed. A large, unfiltered context is not a mark of quality – the source that is authoritative for the task belongs in it at the time of the work.\n\nFor my grounding, this leads to a prioritization rule: when something has to leave the context under pressure, I first remove material that can be looked up again in a targeted way. A long runbook stays in the context only with the paragraphs that are relevant right now. Small, task-relevant conventions I hold on to longer, because their loss is harder to notice. For a different task, this order can look different; what matters is relevance and the cost of fetching it again, not the name of the layer.\n\nThat’s why I keep convention documents small and tailored to the task. A sprawling document competes with sources and tool outputs for space. Curating here means deciding deliberately what has to stay in the context for the next step.\n\n## What grounding doesn’t do\n\nHonesty includes the counter-calculation, and I don’t want to squeeze it in at the end as if it were a footnote. Grounding doesn’t eliminate guessing. With the OpenAPI description loaded, the next suggestion contained no invented field names or structures. But a language model remains a language model: it can have a correct specification in the context and still draw a conclusion from it that doesn’t hold. It can read two documents together that contradict each other and elegantly bridge the contradiction instead of reporting it. And it can be grounded in an aged runbook – then the answer is cleanly reasoned and still wrong, only harder to recognize as wrong.\n\nSo checking remains mandatory. The grounded work result is a better candidate, not a final verdict. What has changed for me is the kind of checking: I search less often for freely invented fields and more often for wrong conclusions from correct sources. That’s a better problem – the same kind of problem I would have with a human colleague who had conscientiously read up. But it is a problem, and grounding replaces neither consistency checks nor tests – without such checks, wrong conclusions can go undetected.\n\nOne question hasn’t let go of me since. Everything I’ve described here grounds one session: the conventions, the documents, the interfaces flow into one working context, and at the end there is a checked result. But the session ends. The window closes, the context is gone – and with it everything the AI learned in those two hours about our system, our quirks, our corrections. Tomorrow I’ll explain `customer_ref` for the third time, or I’ll have found a way for knowledge to survive the session. What that can look like – without accumulating outdated, unfindable or unsupported entries – is the subject of the next episode.\n\n## Further reading\n\n- [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) – Anthropic’s engineering post on context as a finite resource\n- [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401) – the original RAG paper by Lewis et al. (2020)\n- [GraphQL Introspection](https://graphql.org/learn/introspection/) – how a GraphQL schema provides information about itself\n- [OpenAPI Specification](https://spec.openapis.org/oas/latest.html) – the standard for machine-readable HTTP API descriptions\n- [Model Context Protocol](https://modelcontextprotocol.io/) – an open standard for giving AI tools access to real data sources and systems"},{"locale":"en","translation_key":"ki-im-konzern-schnellere-entwicklung-andere-prozesse","slug":"ai-in-the-enterprise-faster-development-different-processes","title":"AI in the Enterprise: Faster Development Needs Different Processes","summary":"AI shortens research, design and implementation. If handoffs, ticket hierarchies and approvals stay the same, the bottleneck just moves – so large companies have to rethink workflow and governance together.","tags":["Software","AI","Architecture","Delivery"],"published_at":"2026-05-19T10:00:00+00:00","updated_at":"2026-08-17T17:34:45.985779+00:00","url":"https://www.mikebild.dev/en/blog/ai-in-the-enterprise-faster-development-different-processes/","audio_url":null,"audio_duration_secs":null,"text":"If implementation takes two days instead of five, but the change then waits twelve days for reviews, approvals and a shared test window, the product hardly reaches users any sooner. The local work got faster. The overall process did not.\n\nThis is exactly the shift that AI exposes in large companies. A developer can prepare code, tests and a first draft of the documentation in a fraction of the previous time. In research and development (R&D), hypotheses can be tested faster and prototypes shown earlier. At the same time, dependencies between teams, contradictory documentation and long-grown approval rounds stay the same. The bottleneck moves from implementation into the organization.\n\nThis is not an argument against large companies. Their formalities rarely came from a pure love of bureaucracy. Regulation, product liability, changing staff, distributed systems and software that has run for decades all need traceability. It becomes a problem when nobody can tell anymore which formality controls a real risk and which one only administers an old uncertainty.\n\n## AI amplifies the workflow you already have\n\nAt first glance, the productivity numbers don’t add up. Three field experiments at Microsoft, Accenture and another Fortune 100 company with a total of 4,867 developers found that users of a coding assistant completed about 26 percent more tasks; the effect varied with experience and context. A randomized METR study with experienced open-source developers, on the other hand, found 19 percent longer completion times with early-2025 tools. In February 2026, METR reported signs of better results with newer agentic tools, but itself considered the data too uncertain, due to selection effects, to put a number on the size of the benefit.\n\nThe findings contradict each other less than it seems. Task, codebase, experience, tool and acceptance criteria all change the outcome. The [DORA Report 2025](https://dora.dev/research/2025/dora-report/) sums up the organizational part well: AI acts as an amplifier. Good feedback loops, well-maintained internal data and small changes benefit. Unclear ownership and cumbersome processes get amplified too.\n\nA survey result from the [Atlassian State of Developer Experience Report 2025](https://www.atlassian.com/teams/software-development/state-of-developer-experience-2025) points in the same direction: developers reported time saved through AI and, at the same time, weekly time lost to organizational friction. Self-reports like these are not a stopwatch. As a diagnosis, they are still useful: faster code does not remove waiting time.\n\n## The ticket tree is not the product\n\nIn a large company, a product idea can first become an initiative, below it an epic, several features, stories and subtasks. The business description lives in Confluence, an architecture decision in a comment, the acceptance condition in a ticket and the actual rule in the code. Each level makes sense on its own. Together, they create several truths.\n\nThis often leads to a half-agile, half-waterfall approach. The team works in sprints but has to fix the content months in advance for budget, dependencies and committees. Questions end up as ticket comments because the spoken word doesn’t count as reliable. So people write more, without the documentation becoming any more consistent. When several systems are integrated, the number of alignment meetings grows faster than the number of domain decisions.\n\nAI should not fill this apparatus automatically. Otherwise you just get more epics, longer summaries and even more convincing-sounding comments. The better approach starts with a single, small description of the intent. Everything else is derived from it and stays versioned with the change.\n\n```yaml\nchange:\n  id: customer-address-v2\n  outcome: reduce failed deliveries\n  constraints:\n    - preserve existing API clients\n    - keep customer consent auditable\n  owners:\n    product: customer-experience\n    technical: customer-platform\n  evidence:\n    - contract-tests\n    - migration-report\n    - rollback-plan\n  risk: medium\n```\n\nThis is not a new mandatory form. It is an example of a small, versioned change artifact that you can have a meaningful argument about. With read access to an indexed body of code and decisions, an agent may use it to gather the affected repositories, earlier decisions, contracts and tests. It may propose a plan, acceptance examples and documentation changes. Outcome, constraints, risk and owners are still decided by the team.\n\nThe difference from the ticket tree lies in the direction: people don’t maintain five representations of the same change. The different views are generated from a few versioned sources. The ticket points to the artifact, the pull request shows the diff, and the documentation points to the decision. A summary for management may look different from the technical view, but both have to trace back to the same state.\n\n## Integration needs contracts, not more alignment\n\nAI does not automatically make complex integration simple. An agent can read an unfamiliar service quickly and still miss a domain assumption that only the team running it knows. That is exactly why collaboration should depend less on prose and more on verifiable contracts.\n\nIn the example of the changed customer address, the relevant event could exist as a schema:\n\n```json\n{\n  \"$id\": \"CustomerAddressChanged.v2\",\n  \"type\": \"object\",\n  \"required\": [\"customerId\", \"address\", \"consentId\"],\n  \"properties\": {\n    \"customerId\": { \"type\": \"string\" },\n    \"address\": { \"$ref\": \"Address.v2.json\" },\n    \"consentId\": { \"type\": \"string\" }\n  }\n}\n```\n\nThe AI can search the code for producers and consumers, write a compatibility report, add contract tests and prepare test data. The compatibility report has to cite repository, revision and location for every statement – for example, that the CRM already delivers `consentId`, that the shipping service ignores the field and that an old export works with `Address.v1`. That way, the research can be checked before a decision is based on it.\n\nIt doesn’t have to make the decision. Whether an old address may still be processed is a domain question. Whether both versions run in parallel or an adapter is needed is an architecture decision. The agent collects evidence; the teams involved own the contract. This is exactly where [ADRs](https://www.mikebild.dev/en/blog/adrs-decisions-you-still-understand/) and executable specifications are valuable: they don’t record every conversation, only the result and its reasons.\n\n## Documentation is derived, not abolished\n\nConfluence stays useful for explanations, entry points and overviews. It just shouldn’t be the third manually maintained copy of what the ticket and the code also describe. A page needs a named owner, a verifiable link to a contract, ADR or repository, and a visible update date. If that link is missing, an agent may flag the page as possibly outdated, but must not quietly declare it the truth.\n\nAI can generate different views from an approved change: release notes for users, a technical integration note and a short summary for the portfolio. Each text stays verifiable because it points to the same artifacts. People then don’t have to write every sentence three times. They check whether the derived view is right for its readers. This makes the documentation more consistent and the obligation smaller at the same time: what gets recorded is the decision, the contract and the operational consequence – not every intermediate stage of the discussion.\n\n```mermaid\nflowchart LR\n  Idea[Product idea] --> Ticket[Ticket hierarchy]\n  Ticket --> Docs[Separate documentation]\n  Docs --> Meetings[Alignment rounds]\n  Meetings --> Build[Large implementation]\n  Build --> Test[Shared test window]\n  Test --> Approval[External approval]\n\n  Intent[Versioned intent] --> SmallChange[Small change]\n  SmallChange --> Evidence[Tests, contract and diff]\n  Evidence --> Review[Peer Review]\n  Review --> Release[Release]\n  Release --> Feedback[User and operations signal]\n  Feedback --> Intent\n```\n\n## You become agile through the cost of a change\n\nAgility is not a particular board or a number of meetings. The original Agile Manifesto values working software over comprehensive documentation and responding to change over following a plan. Neither statement calls for carelessness. Both call for new information to actually be able to change the state of the work.\n\nWhether AI shortens research, prototyping or test design in a specific value stream has to be measured there. If it does, the cost of small experiments drops. R&D can then work more with hypotheses: What do we want to learn, which smallest experiment delivers evidence, and which result would change our direction? Product development can use the same rhythm.\n\nThe prerequisite is small batches. More code generated in parallel makes the flow worse if review capacity stays the same. The result would be a new kind of inventory – half-finished pull requests instead of half-finished tickets. As with [developer productivity](https://www.mikebild.dev/en/blog/developer-productivity-shorter-cycles/), what counts is therefore not typing speed but the time to reliable feedback. [DORA metrics](https://www.mikebild.dev/en/blog/dora-metrics-what-really-shortens-cycles/) help with the diagnosis; they must not become a target for individual employees.\n\n## Governance without a blanket queue\n\nControl is still necessary, but not every change deserves the same path. A text correction, a backward-compatible API extension and a new permission model have different potential for damage. Good governance makes this difference executable. The NIST AI Risk Management Framework follows the same idea at the level of the AI systems themselves: it structures risk management through governance, measurement and ongoing management instead of a single blanket approval.\n\n```yaml\napproval_policy:\n  - risk: low\n    requires: [tests, policy-checks, peer-review]\n    decision: peer-approved\n  - risk: medium\n    requires: [tests, contract-checks, owner-review, rollback-plan]\n    decision: peer-approved\n  - risk: high\n    requires: [security-review, compliance-review, business-owner, audit-record]\n    decision: manually-approved\n```\n\nThis YAML file, too, is only a sketch, not a finished policy language. Automated checks produce the same evidence for every change. People review where context, liability or effects that are hard to reverse come into play. DORA recommends replacing heavyweight external change approvals with peer review, continuous testing, monitoring and targeted extra review of risky changes. That means less bureaucracy and more precise control at the same time.\n\n```mermaid\nflowchart TD\n  Change[Change with evidence] --> Risk{Risk class}\n  Risk -->|low| Guardrails[Automatic guardrails]\n  Guardrails --> Peer[Peer Review]\n  Peer --> Release[Release]\n  Risk -->|medium| Owner[Domain and technical owner]\n  Owner --> Release\n  Risk -->|high| Specialist[Security, compliance and business]\n  Specialist --> Approval{Approval}\n  Approval -->|yes| Release\n  Approval -->|no| Rework[Rework or discard]\n```\n\nThe EU AI Act makes a second distinction important. Article 4 of [Regulation (EU) 2024/1689](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX%3A32024R1689) on AI literacy has applied since February 2, 2025: providers and deployers must take measures to ensure that people who work with AI systems on their behalf have a sufficient level of AI literacy. Annex III, point 4 of the regulation covers – depending on the intended purpose – among other things systems that evaluate or monitor employees or allocate tasks based on individual behavior or personal traits. A productivity ranking built from process data does not automatically fall under it. But if it is used for HR decisions, performance evaluation or task allocation, it sits in a legally particularly sensitive area. Governance should protect the work, not put people under general suspicion.\n\n## The organization has to follow the workflow\n\nA new assistant alone doesn’t change an org chart. In the long run, though, an organization with many handoffs is a poor fit for a way of working that is supposed to learn in short loops. For value streams with frequent cross-team changes, three structures become more important:\n\n- long-lived, cross-functional product teams that own an outcome from idea to operation and can approve small changes themselves\n- an internal platform that offers secure access to code, documentation, test environments and approved AI models as the default path\n- governance, security and architecture groups that design rules, reference solutions and exceptions instead of waving through every normal change individually\n\nThis matches the pattern I already described for [simpler design and less process](https://www.mikebild.dev/en/blog/simple-design-can-save-process/): first make the change small and its expectations explicit, then remove the process step that this makes unnecessary. A locally measured time saving does not replace this architecture work.\n\nFor the roles involved, the focus shifts:\n\n| Role | New focus |\n| --- | --- |\n| Developers | Slicing tasks, providing context, reviewing generated changes, designing tests and operational signals |\n| Architects | Designing system contracts, automated architecture rules, reversibility and safe default paths |\n| Product owners | Sharpening outcomes, acceptance examples and user feedback instead of managing the ticket backlog |\n| Project management | Reducing dependencies, risks, waiting times and work in progress instead of planning activities in detail up front |\n\nNone of these roles disappears. On the contrary: the cheaper it becomes to generate proposals, the more valuable selection, judgment and responsibility become. The [result of a single AI power user cannot simply be transferred to an enterprise](https://www.mikebild.dev/en/blog/my-success-cannot-be-copied/). Teams need shared review criteria, time to learn and a workflow that makes differences visible.\n\n## Start small and measure the whole cycle\n\nA company-wide transformation program would be a contradictory start. A single value stream with a recurring change whose risk is known works better. There you can map today’s path from request to operation: How long is work being done, how long is it waiting, how often is the same information transferred, and where does rework happen?\n\nA first attempt needs only a few steps:\n\n- define a versioned change artifact and the leading sources\n- give the AI read-only access and log its context in a traceable way\n- generate tests, contract checks and documentation diffs automatically as evidence\n- at first, send only small, reversible changes through the new path\n- compare lead time, waiting time, number of handoffs, rework, change fail rate and time to user feedback\n\nI would not measure generated lines of code, closed tickets or individual prompt activity. Numbers like these reward volume. I would measure the inventory of half-finished work, the share of a predefined sample of documents that contradicts a named contract, ADR or repository state, and the time from opening a review request to the first approval or concrete change request. The share of releases that go through the controlled path measures process coverage, not impact.\n\n## Conclusion\n\nThe cumbersome processes of large companies are not a law of nature, but they are not just past stupidity either. They preserve ownership, knowledge and control where technical means were long insufficient. AI changes this calculation because it can gather context faster, prepare evidence and support recurring checks.\n\nThe gain only materializes when the organization doesn’t fill the freed-up time with more output. Then changes get smaller, contracts replace part of the alignment and versioned artifacts avoid contradictory copies. Approvals follow risk instead of a blanket queue. People keep the decisions where domain knowledge, liability and consequences matter.\n\nThat is how AI can actually make development and R&D more agile: not by filling out the old process faster, but by helping to make its detours unnecessary.\n\n## Further reading\n\n- [DORA – State of AI-assisted Software Development 2025](https://dora.dev/research/2025/dora-report/)\n- [DORA – Capability Catalog](https://dora.dev/capabilities/)\n- [DORA – Streamlining Change Approval](https://dora.dev/capabilities/streamlining-change-approval/)\n- [DORA – Working in Small Batches](https://dora.dev/capabilities/working-in-small-batches/)\n- [DORA – Repository](https://github.com/dora-team/dora.dev)\n- [Microsoft Research – The Effects of Generative AI on High-Skilled Work](https://www.microsoft.com/en-us/research/publication/the-effects-of-generative-ai-on-high-skilled-work-evidence-from-three-field-experiments-with-software-developers/)\n- [METR – Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/)\n- [METR – We Are Changing Our Developer Productivity Experiment Design](https://metr.org/blog/2026-02-24-uplift-update/)\n- [Atlassian – State of Developer Experience Report 2025](https://www.atlassian.com/teams/software-development/state-of-developer-experience-2025)\n- [Manifesto for Agile Software Development](https://agilemanifesto.org/)\n- [NIST – AI Risk Management Framework](https://airc.nist.gov/airmf-resources/airmf/5-sec-core/)\n- [European Commission – AI Literacy: Questions & Answers](https://digital-strategy.ec.europa.eu/en/faqs/ai-literacy-questions-answers)\n- [Regulation (EU) 2024/1689 – Artificial Intelligence Act](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX%3A32024R1689)"},{"locale":"en","translation_key":"sauberes-grounding-warum-ki-raet","slug":"clean-grounding-i-why-ai-guesses-so-convincingly","title":"Clean Grounding I: Why AI Guesses So Convincingly","summary":"Why language models invent plausible things, why more training doesn’t reliably eliminate the problem and what grounding has to do with it.","tags":["Software","AI","Methodology","Delivery"],"published_at":"2026-05-06T10:00:00+00:00","updated_at":"2026-08-17T16:28:14.564928+00:00","url":"https://www.mikebild.dev/en/blog/clean-grounding-i-why-ai-guesses-so-convincingly/","audio_url":null,"audio_duration_secs":null,"text":"A few weeks ago I was sitting in a review of generated code. The assistant had suggested retry logic for our internal HTTP client – a client that exists only at our company, a thin TypeScript layer over `fetch` with a few in-house conventions. The suggestion: `client.withRetry({ backoff: \"exponential\", maxAttempts: 3 })`. Cleanly named, in the style of our codebase, with a comment on why exponential backoff was the right choice here. Plus a short explanation in the chat of how the method relates to our timeout handling.\n\nThe method doesn’t exist. It never existed. Our client configures retries in a completely different place, when the instance is created, not at the call. But the frightening part wasn’t the mistake. I make mistakes too. The frightening part was the quality of the invention: the name fit our conventions perfectly, the signature looked like one of ours, the reasoning was sound from a domain point of view. If a human had suggested the method, I would have said: this person really knows our code well. Except that the suggestion was a complete guess – and was delivered with the same confidence as the twenty correct suggestions before it.\n\n*Part 7 of the series “From Session to System” – [the series opener is here](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nIf you work seriously with Copilot, Claude Code or Cursor, you can run into something like this. At first, I looked at such errors like a bug that should disappear with the next model generation. Today I don’t rely on that. Better models can reduce hallucinations, but they don’t reliably eliminate them – and since that became clear to me, I work differently with these systems.\n\n## The model doesn’t reliably know the limit of its knowledge\n\nTo understand why the invention sounded so convincing, I had to remind myself what a language model actually does: it continues text. From billions of examples it has learned which continuation is likely after a given beginning. That is not a disparaging simplification but the mechanism – and it is astonishingly powerful, as I described [in part 2 of this series](https://www.mikebild.dev/en/blog/good-enough-models/). But it has a property that can’t be argued away: true and false statements both arise as likely continuations; a truth check doesn’t automatically follow from this mechanism.\n\nA human developer – fallible as they are – has a sense of whether they know something or are guessing. If I ask a colleague about a method in our internal library, they answer either “it’s called this” or “I’d have to look it up”. This having-to-look-it-up is metacognition: knowledge about your own knowledge, a sense of your own uncertainty. Exactly this faculty is missing in the model. It has no inner state that distinguishes between “this appeared a thousand times in the training corpus” and “this sounds the way it ought to sound”.\n\nThat’s why the confidence that irritates us so much is not arrogance but an artifact. The tone of a text is part of the continuation. Technical documentation, Stack Overflow answers, code comments – the material the model learned from is overwhelmingly written in a tone of certainty. Nobody documents an API with “I think this method exists”. So the invented method sounds like documentation too. The confident tone is not a signal of correctness. It never was.\n\nTwo papers support parts of this explanation. In 2024, Ziwei Xu and colleagues argued formally that hallucinations cannot be completely eliminated for large language models. And in a publication of its own – available online as of August 2026 – OpenAI describes a second mechanism: training and evaluation incentives can push models toward guessing instead of admitting uncertainty. A model that says “I don’t know” when uncertain can score worse on benchmarks that reward correct answers but don’t properly account for abstentions than one that guesses confidently – just as a multiple-choice test teaches students to tick a box at random when they don’t know instead of leaving the field empty.\n\n## Symbols that refer to symbols\n\nThere is an even deeper level, and it is older than the current models. In 1990 – long before today’s large language models – the cognitive scientist Stevan Harnad formulated the *Symbol Grounding Problem*. His question: how does meaning get into a system that only manipulates symbols according to formal rules? His image: try to learn Chinese exclusively from a Chinese-Chinese dictionary. Every character is explained by other characters, and those in turn by more characters – you go around in circles without ever arriving at the thing itself. Symbols refer to symbols; nowhere does the system touch the world.\n\nI usually hesitate to drag cognitive science papers into everyday debates, because that often creates more fog than clarity. But here the analogy fits uncomfortably well. A language model knows text about the world, not the world. It has read what people have written about HTTP clients, about retries, about exponential backoff – and has learned statistical relationships between tokens from it. In any case, the answer in my opening scene gave no hint of a check against the thing itself: no compiler rejecting the call, no test turning red, no production alerting at three in the morning. Where I as a developer have calibrated my concepts against experience, the model has calibrated its concepts against other concepts. The dictionary explains itself, and it explains itself fluently.\n\nYou don’t have to adopt Harnad’s problem in its full philosophical sharpness to see the practical core: a system whose entire “knowledge” consists of text statistics can’t tell a plausible invention from a fact, because both are made of the same stuff. For the model, `withRetry` was just as real as any method that actually exists – a likely symbol among other symbols.\n\n## Why bigger models mitigate the problem but don’t solve it\n\nThe objection is obvious: the models have gotten better, haven’t they? In my work, at any rate, I now rarely catch current models making things up freely when it comes to public, well-documented knowledge.\n\nBut “more rarely” only means “less often”, not “fundamentally different”. The mechanism stays the same: a bigger model has learned finer statistical relationships – it guesses less often because it has seen more, not because it has stopped guessing. At the point where its material ends, it still produces the most likely continuation, in the same confident tone. The line between knowledge and guesswork moves outward, but it doesn’t disappear, and the model still doesn’t show it to me. That is exactly what makes the remaining cases so treacherous: the rarer the error, the less I expect it – and the more unchecked the suggestion goes through.\n\n## Without internal sources, organization-specific facts remain guesswork\n\nAnd that brings me to the point that occupies me most in my daily work. Everything said so far applies to public knowledge – React, PostgreSQL, the AWS APIs. There I rarely see the model guess – the public material is huge. But the moment I open the door to a specific organization, the ratio flips. Because what counts there isn’t reliably accessible to the model without provided internal sources:\n\n- the internal libraries and services with their actual signatures and quirks\n- the in-house conventions – how errors are handled, how modules are split, what a deployment has to go through\n- the terms of the domain that mean something precise inside the company and something else or nothing at all outside it\n\nThe case from the opening scene showed me how far this goes. The model had never seen our HTTP client, so it invented it – and did so in the way such a client typically looks. That’s why the suggestion was so good: it was the ideal form of an internal HTTP client, distilled from public patterns. Just not ours. Without an internal source, the actual signatures couldn’t reliably be derived by the model; the invention was an obvious move and looked deceptively similar to real knowledge, because the model is so good at continuing the style of a codebase.\n\nIn hindsight, this also explains why my attempts with instruction files went so sobering – I told that story in detail in the last part. Back then I still thought the problem was compliance: the AI doesn’t stick to our rules, so the rules have to be stated more clearly, more strictly, more prominently. But even if an AGENTS.md were followed perfectly, it answers the wrong question. An instruction tells the system how to behave. It can’t give it what it actually lacks: the facts. “Don’t invent methods” is a helpless instruction to a system that doesn’t notice when it invents. The model doesn’t lack the will; it lacks the material. I was working on the motivation of a system that doesn’t have a motivation problem but a knowledge problem.\n\n## Grounding: providing internal facts in the working context\n\nFor this answer to the knowledge problem, I use the term grounding here – anchoring answers in verifiable facts. At its core, the idea is simple. If the model can’t know my reality from training, then I have to give it that reality at the time of the work: the real signature instead of the likely one, the actual schema instead of the typical one, our convention instead of the industry standard. Not as a rule of behavior, but as material. The model should be able to look things up instead of having to guess – roughly the way a good IDE with type information keeps me from typing method names from memory.\n\nHere I use grounding for providing concrete source material in the working context, and I thereby distinguish it from mere instructions that formulate rules of behavior. Grounding is not a product and not a feature you switch on. It is first of all an insight about the division of labor: the model provides language understanding, pattern recognition and synthesis – the facts about my world have to come from my world itself. And, to be honest, it isn’t a complete solution either. A grounded model can still connect the facts it was given incorrectly, and if you have ever tried to dump “simply all the documents” into the context, you know that this brings new problems. The difference lies elsewhere: with a grounded system, I argue about the quality of my sources. Without sources, I check free additions drawn from general patterns.\n\nWith that, the conclusion of this part is settled, even if it saves no one any work: better models and stricter instructions don’t reliably eliminate convincing wrong answers. Grounding provides concrete source material where the system would otherwise have to fill in from general patterns. Which is where the real work begins – because “provide internal facts” is quickly said. Which facts, exactly, in what form, at which point in the workflow? That is not a rhetorical question but the next part.\n\n## Further reading\n\n- [Stevan Harnad: The Symbol Grounding Problem (Physica D, 1990)](https://doi.org/10.1016/0167-2789(90)90087-6) – the original paper with the dictionary argument\n- [Ziwei Xu et al.: Hallucination is Inevitable – An Innate Limitation of Large Language Models (2024)](https://arxiv.org/abs/2401.11817) – the formal argument that hallucination cannot be eliminated for this class of models\n- [OpenAI: Why Language Models Hallucinate](https://openai.com/index/why-language-models-hallucinate/) – why training and evaluation incentives can reward guessing (retrieved in August 2026)\n- [Lilian Weng: Extrinsic Hallucinations in LLMs (2024)](https://lilianweng.github.io/posts/2024-07-07-hallucination/) – a detailed overview of causes, measurement and countermeasures"},{"locale":"en","translation_key":"mein-erfolg-laesst-sich-nicht-kopieren","slug":"my-success-cannot-be-copied","title":"My Success Cannot Be Copied","summary":"A colleague takes over my AI setup and gets different results. Tools, tests and conventions can be transferred; how you cut tasks, how you review and the course of an individual session only to a limited degree.","tags":["Software","AI","Methodology","Delivery"],"published_at":"2026-03-04T11:00:00+00:00","updated_at":"2026-08-17T16:28:14.564928+00:00","url":"https://www.mikebild.dev/en/blog/my-success-cannot-be-copied/","audio_url":null,"audio_duration_secs":null,"text":"In February, a colleague – an experienced developer with good judgment, no beginner – asked me whether he could have my setup. He had watched me work with Claude Code for weeks and wanted the same: the same tools, the same configuration, the same results. I gave him everything. The complete toolchain. My instruction files, grown over months. My prompt collection for recurring tasks, my checklists for reviews, even my notes on which tasks I delegate and which I do not. There was no secret remainder. He really had everything I have.\n\n*Part 5 of the series “From Session to System” – [start here with the opener](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nTwo weeks later, we sat down for coffee, and he was disillusioned. Not frustrated in the sense of “the tool is useless” – he had had some genuinely useful moments. But what he had seen with me, the matter-of-factness with which tasks go out and checked results come back, did not happen for him. For him, the AI went in the wrong direction three times, built things he did not want, and he spent more time cleaning up than he used to spend writing the code himself. His sentence stuck with me: “I have your setup. Why don’t I have your results?”\n\nThe question occupied me longer than any tool problem of the past months. Because the obvious answers are all wrong. It was not the model – we used the same one. Not the configuration – it was identical, file for file. Not a lack of experience as a developer – he is at least as good as I am. What he was missing was not in any of the files I had given him. And that is exactly the point where this series has to make the leap: from me to the team. So far, I have described why the harness matters more than the model and [what makes me uneasy about my own way of working](https://www.mikebild.dev/en/blog/what-i-am-critical-of/). Both were the perspective of an individual. As soon as a second person comes into play, a problem shows up that I had previously only suspected: variance. And on three levels at once.\n\n## First level: the same task, two sessions, two results\n\nThe first level has nothing to do with my colleague yet. I can demonstrate it on my own machine.\n\nI give the same AI the same task twice – under largely the same visible conditions: same prompt, same repository, same instruction files. Session one decides to read the tests first, finds an existing pattern there and extends it cleanly. Session two jumps straight into the production code, considers a helper function unused, removes it “while it is at it” and delivers a solution that runs but is cut differently from everything around it. Both sessions got the same assignment. Both report confidently that they are done. The results differ in structure, style and side effects.\n\nIn my runs, even early decisions differed – for example which file was read first or which pattern served as the model. After that, the subsequent steps diverged too.\n\nFor me alone, that is manageable. I have learned to check results instead of prescribing paths, and in episode 3 I described how much of this the harness catches: tools, feedback loops, check steps. But even here, the mistake of confusing “best practices” with reproducible results becomes apparent: the same success case cannot be repeated exactly. When I show my colleague how great a session went yesterday, I am showing him a single run – even for me, the next one would look different.\n\n## Second level: the knowledge that is in no file\n\nThe second level is the one where my colleague actually failed. And it is more uncomfortable, because it disguises itself as a tool question but is a question of experience.\n\nWhen we talked through his disillusioning two weeks, I noticed: he did the same things I do – just in different places. He delegated, but the wrong tasks. He checked, but looked at the wrong things. He stopped, but too late. Three examples from our conversation:\n\n- He gave the AI a task I would never delegate as a whole – a change across three modules with unclear domain logic – and was surprised by the chaos. I would have cut it into three checkable chunks beforehand. This cut is not in any of my prompts; I make it in my head before I even start typing.\n- He read the AI’s explanations and found them convincing. I hardly read the explanations anymore – I look at the diff, the tests and the places where, in my experience, unwanted side effects occur. Where you look is judgment, not configuration.\n- He had a session make three rounds of fixes before he gave up. I stop after the first failed fix attempt and rephrase the task, because I have learned: once the direction is wrong, steering back costs more than starting over. That is not written down anywhere either – this stopping rule comes from repeated failed attempts.\n\nHow you cut tasks, where you look when reviewing, when you stop – that is tacit knowledge in the classic sense. You acquire it through friction, not through reading. My instruction files are the sediment of this knowledge, but they are not the knowledge itself. They tell the AI what to do. They do not tell my colleague what *he* should do while the AI is working.\n\nThe [METR study from summer 2025](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/) made a related effect measurable: for experienced open source developers, tasks with early-2025 AI tools took 19 percent *longer* on average – even though the participants expected to save time. You can argue about how far the study generalizes; the conditions were special. But the documented finding fits what I saw with my colleague: expected time savings and measured working time can diverge.\n\n## Third level: there is no identical run\n\nThe third level is often overlooked because it sounds so banal: my colleague works on different tasks than I do.\n\nNot fundamentally different – same company, related systems, a similar stack. But his specific task on a specific Tuesday is never my specific task. His module has a different history, different legacy, different unwritten conventions. His bugs sit in different places. Even if he had my judgment and the session lottery went his way: he still could not reproduce my success, because the experimental setup “same task” simply does not exist in real work.\n\nThat fundamentally distinguishes AI tools from almost everything we have introduced in teams before. Formatters and CI pipelines aim for reproducible execution under the same version, configuration and environment; a framework API provides the same contract. With these tools, the rule is: one person finds the good configuration, everyone adopts it, everyone gets the benefit. This exact pattern is what we all have in mind when we say “share the setup” – and this exact pattern does not apply here. The benefit of an AI session comes from the interplay of task, context, person and chance. Three of these four factors are different for every team member.\n\n## What organizations regularly conclude wrongly from this\n\nAt the organizational level, these differences can lead to false productivity assumptions. Because the individual observation “it works for Mike” invites three fallacies.\n\nThe first fallacy: license bought means team productive. An enterprise procures access for all developers, books it as “AI adoption” and expects the productivity leap that the power users showed in the pilot project. But the power users were fast precisely because they had built up tacit knowledge over months. The license buys the tool, not the second level. The [2025 DORA report](https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report) puts it in a formula I have been quoting constantly ever since: AI amplifies what is already there. Teams with good feedback loops and clean architecture get better; teams with weak processes get their weaknesses back amplified.\n\nThe second fallacy: sharing a prompt library is a rollout. That was my own mistake with my colleague, just on a small scale. Prompts and instruction files are sediment – useful, but dead without the practice they came from. A shared prompt collection without shared judgment produces people who read convincing explanations instead of checking diffs. The [2025 Stack Overflow survey](https://survey.stackoverflow.co/2025/ai/) shows the consequences at scale: AI tools are widely used, but trust remains limited, and a frequently cited frustration is code that is “almost right.” Recognizing almost right is exactly the ability that cannot be distributed by file alone.\n\nThe third fallacy: what works in the pilot scales linearly. It does not, because of all three levels of variance at once. A pilot can include motivated power users (person variance), selected tasks that are easy to cut (task variance) and selectively reported success stories – failed sessions may be missing from the management presentation (session variance). If you build a projection for 200 developers from that, you may be calculating with an unrepresentative average.\n\nI put it pointedly because I already used the sentence in [episode 4](https://www.mikebild.dev/en/blog/what-i-am-critical-of/) and here it describes the organizational consequence: the success stories of individuals are real, and they are still not a blueprint. Tools, tests, conventions and acceptance criteria can be copied. My concrete result also arises from task, context, review judgment and the course of the session. No setup file transfers that part.\n\n## Variance is also a source of learning\n\nThis sounds bleaker than I mean it. Because the same variance that prevents copying is a useful diagnostic source for a team.\n\nWhen my colleague and I dissected his two weeks, something remarkable happened: for the first time, I had to say out loud *why* I cut tasks the way I do. Why I ignore explanations and read diffs. Why I stop after one failed fix attempt. That was tacit knowledge that I had not perceived as knowledge myself – for me, it was simply “how you do it.” Only the difference between his way of working and mine made it visible. Exactly where two people do the same thing differently, the tacit knowledge lies in plain sight. You just have to look instead of dismissing the difference as a failure of the slower one.\n\nMy conclusion after that February: if individual experiences are to flow together in a team, the prompts are not the valuable part. The differences are. Two developers, the same class of task, different results – that is not an annoyance; it is a finding. Each of these differences points to an unspoken rule, a heuristic, a piece of judgment that so far existed only in one head.\n\nBy the way, my colleague still works with the setup – now with his own instruction files that differ more and more from mine, and with much better results. Not because he copies me better now, but because he stopped trying. What he took over from me is not the files. It is the questions he asks himself before every delegation.\n\nAnd that brings me to the consequence that every team sets out to draw at this point, mine included: if the decisive knowledge is tacit, then we simply make it explicit. We sit down, spell out the rules that so far existed only in heads and write them down – in exactly the files the AI reads in every session. Task cutting, review rules, stopping criteria, all of it goes in. That has to be enough. Why it is not – and why the AI follows our carefully written rules surprisingly selectively – is what the next episode is about.\n\n## Further reading\n\n- [METR: Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity](https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/)\n- [Google Cloud: Announcing the 2025 DORA Report](https://cloud.google.com/blog/products/ai-machine-learning/announcing-the-2025-dora-report)\n- [Stack Overflow Developer Survey 2025: AI](https://survey.stackoverflow.co/2025/ai/)"},{"locale":"en","translation_key":"was-ich-kritisch-sehe","slug":"what-i-am-critical-of","title":"What I Am Critical Of","summary":"Four observations and one open hypothesis after intense months with AI – from a possible loss of skills to the worry about more uniform solutions, and my practical countermeasures.","tags":["Software","AI","Methodology"],"published_at":"2026-02-10T11:00:00+00:00","updated_at":"2026-08-17T16:28:14.564928+00:00","url":"https://www.mikebild.dev/en/blog/what-i-am-critical-of/","audio_url":null,"audio_duration_secs":null,"text":"On a Thursday evening in January, I almost waved through a pull request that I had commissioned myself. Claude Code had written a database migration, cleanly formatted, with comments, with a rollback path. I read it, nodded, already had the mouse pointer over the merge button – and then, more out of habit than mistrust, I took a look at the affected table in the staging system after all. The migration would have worked. It would just, on the side, have renamed a column that a report accesses, a report the session could not have known about. No drama, quickly found. But the moment before still occupies me today: I had not checked. I had read it the way you read a well-written text – benevolently, going with the flow.\n\n*Part 4 of the series “From Session to System” – [the series opener is here](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nIn the last installment, I described why delegating to AI only works for me with a good harness – with tools, feedback and guardrails around the model. At the end there was an unease that has grown louder with every delegated task. Today I want to take this unease seriously. Not as an alarm – I keep working with these tools every day, gladly and productively. But as what criticism should actually be: looking closely before you carry on. In doing so, I separate four observations from one open hypothesis.\n\n## If you only review, you unlearn building\n\nWhen I rarely write code myself, I now have to distinguish more carefully: am I only missing an API signature, or am I missing practice in the routine? If you need a rarely used library function, you look up its signature – that has always been the case and is not a problem. The problem would be the direction of the movement: if it is no longer just the exception that gets looked up but the routine disappears altogether, the repetition from which fluency arises is missing. Whether and how fast this happens to me, I cannot measure. That is why I deliberately do certain routine tasks without AI and pay attention to where I lack practice.\n\nThe CHI 2025 study by Microsoft Research and Carnegie Mellon surveyed 319 knowledge workers on this. In the self-reports, higher confidence in generative AI was associated with less critical thinking being applied. That is a correlation in a survey, not evidence that skills have already eroded. My worry goes one step further than the study’s result: if you hand off routine work and only deal with the exceptions, you could lose exactly the practice you need for the exceptions.\n\nFor me, this is a creeping risk that I can actively manage. What concerns me more is what the math looks like for people starting their careers. I learned my craft by falling flat on my face often enough: hunting memory leaks myself, building race conditions myself and understanding them myself. If, during the learning phase, you mostly review generated code, you may get fewer opportunities to build up this substance – that is a guess, not a measurement, and the survey cited says nothing about it. Concretely, what would then be missing is the experience that makes good reviewing possible in the first place: being able to judge whether a timeout, a lock or an error handling approach fits your own system, because you have made such decisions yourself and borne their consequences.\n\n## Plausible is not correct\n\nThe scene from the beginning has a name: automation bias. A systematic review by Goddard, Roudsari and Wyatt describes it as the tendency to follow automated recommendations and overlook contradictory cues – the research on it is older than the current language models. In my migration, the clean formatting, the comments and the included rollback path amplified exactly this impression of trustworthiness: I almost approved what I had not checked.\n\nWhether review and the four-eyes principle work systematically worse against such plausible output than against visibly sloppy code, I cannot prove.\n\nIn line with this, Perry and colleagues showed in a controlled study that participants with an AI assistant wrote insecure code more often and at the same time were more convinced that they had written secure code. The study does not examine code reviews. For my review practice, the combination is therefore a warning sign, not evidence of effectiveness.\n\n## “That’s how the AI did it” is not an answer\n\nIn a review, “That’s what the AI suggested to me” is not enough as a justification for me. The sentence explains the origin, but not the decision. Why is the timeout set to thirty seconds here? Why is that right for our system? If no answer follows, the decision is not justified in the review – because the session that chose the value ended long ago and took its reasons, if there were any, with it.\n\nIn a review, there is no third party. There is the person who submits the code and the person who approves it – both with names, both reachable, both still around tomorrow. What the tool suggested is as relevant as the question of which editor the code was typed in. If you open a pull request, you are saying: I stand behind this. If this commitment dissolves because “the AI” is in the room as a diffuse co-author, the review loses its core. Then two people review something nobody feels responsible for.\n\n## Debt that nobody took on\n\nTechnical debt can arise from deliberate shortcuts: we build the quick solution now and clean up later. You knew the shortcuts you took deliberately and their consequences. Next to that, I see a possible second variant: code that works, passes all tests – and that nobody on the team really understands. Not because it is incomprehensible, but because nobody ever had to understand it. It was generated, it ran, it was merged.\n\nIf a team only roughly follows a generated mechanism when it is built in, the next change may require reconstructing assumptions and the reasons behind decisions before the mechanism can be changed safely. Then technical debt may have arisen without anyone having taken it on deliberately – no note, no decision, no “we’ll clean up later.” Such debt can arise unnoticed because no deliberate shortcut was documented. A system that consists to a larger extent of such code is not broken. It is something worse: not understood while fully functional.\n\n## When everyone asks the same model, designs can become more similar\n\nThe last worry is an open hypothesis. A thought experiment makes it tangible: four groups get the same open-ended design task, and all four ask their first question to the same model. How different do the results turn out? If everyone starts with a very similar first answer, that answer can shape the rest of the design. The effect has not been measured and depends, among other things, on the prompt, context, sampling and model. The Microsoft study mentioned does not examine it.\n\nYou can shrug and say: converging on proven patterns is a good thing. That is partly true – I am the last person to find an unusual solution good just because it is unusual. But architectural diversity is not an end in itself; it is a search process. Different designs make alternative assumptions and trade-offs visible. My worry is therefore: if many design decisions run through the same filter, the space of seriously considered alternatives narrows. I cannot measure that.\n\n## Criticism does not mean rejection\n\nAt this point, the text could tip over – into cultural pessimism, into “back then we still did real programming.” That would be convenient and wrong. None of these points is an argument against the tools. Each one is an argument against a particular way of using them: the passive one. Skills do not decay because AI exists but because I stop practicing. Automation bias strikes because I confuse plausibility with correctness. Responsibility diffuses because I let it diffuse. That is the catch: the answer does not lie in the next model release. It lies with me.\n\nI have set up a few rules for myself. No words of wisdom, more like house rules:\n\n- Regularly work deliberately without AI. Not a ritual of renunciation, more like a run without a watch: certain tasks – an algorithm, a data model, a tricky bug fix – by hand, to feel where it snags. Where it snags, I check whether I lack practice or whether I just do not have a rarely used API at hand.\n- An obligation to understand before the merge. Nothing goes into the main branch that I could not explain to a colleague at the whiteboard – line by line for critical spots. Critical spots are, for example, possible data loss, permission checks, concurrency and public APIs. “Roughly followed” does not count.\n- My own judgment first, then the model. For design questions, I write down my position in three sentences before I ask. It does not have to be the better one; it is an anchor against the plausible first answer – deviations then become real information.\n- Name the origin, keep the responsibility. When code was generated, I say so openly in the review – and take it on anyway as if I had typed it.\n\nNone of this is original. The extra review costs me time, but it makes the approval more traceable. And I notice: it takes effort. In everyday work, it is easier to skip it.\n\nBut this is exactly where the reach of this text ends. Everything I have described here are measures of an individual – my rules, my discipline, my house rules. That reaches exactly as far as my self-control does, and on bad days it reaches surprisingly little. A team cannot rely on the private discipline of its members; ten people with ten different sets of house rules do not yet make a shared way of working. What happens to these observations when not one person works like this but an entire team – with different experience, different levels of care and deadline pressure on top – that is the question I have set myself for the next installment.\n\n## Further reading\n\n- [The Impact of Generative AI on Critical Thinking (Microsoft Research / Carnegie Mellon, CHI 2025)](https://www.microsoft.com/en-us/research/publication/the-impact-of-generative-ai-on-critical-thinking-self-reported-reductions-in-cognitive-effort-and-confidence-effects-from-a-survey-of-knowledge-workers/)\n- [Kate Goddard, Abdul Roudsari, Jeremy C. Wyatt: Automation bias – a systematic review of frequency, effect mediators, and mitigators (JAMIA, 2012)](https://academic.oup.com/jamia/article/19/1/121/732254)\n- [Neil Perry, Megha Srivastava, Deepak Kumar, Dan Boneh: Do Users Write More Insecure Code with AI Assistants? (arXiv, 2022)](https://arxiv.org/abs/2211.03622)"},{"locale":"en","translation_key":"gut-genug-modelle","slug":"good-enough-models","title":"Good Enough: The Model Is Rarely the Bottleneck","summary":"For the everyday tasks I work on with AI myself, the choice of model is rarely the first bottleneck. How the task is cut, the context and the verification usually matter more.","tags":["Software","AI","Methodology"],"published_at":"2025-12-09T11:00:00+00:00","updated_at":"2026-07-14T20:56:33.58758+00:00","url":"https://www.mikebild.dev/en/blog/good-enough-models/","audio_url":null,"audio_duration_secs":null,"text":"*Part 2 of the series “From Session to System” – [start with the opening post](https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/).*\n\nEnd of November, an architecture review with a team I support, day two, first coffee break. A developer walks over to me, cup in hand, and asks the question that has come up in every team conversation and every hallway chat at conferences for two years: “Which model do you use?” This time with particular urgency, because November 2025 was wild: GPT-5.1 on the 12th, Grok 4.1 on the 17th, Gemini 3 on the 18th, Claude Opus 4.5 on the 24th. Four flagship announcements in twelve days, plus the usual benchmark screenshots making the rounds on the timelines. His team, he tells me, has been discussing for weeks whether they need to switch.\n\nI used to answer this question seriously, with model names and reasons. Every one of those answers was outdated after six weeks. These days I answer differently: “That is the second question. Let’s talk about the first one.”\n\n## The convergence nobody likes to talk about\n\nLooked at soberly and without vendor loyalty: for the large block of everyday tasks I use AI for, the big models were close enough to each other in my own trials at the end of 2025. Reading and explaining code, proposing a refactoring, designing tests, reviewing a concept paper, summarizing API documentation, sketching a migration path – I got that done in usable quality with GPT-5, Claude Sonnet 4.5 and Gemini. Not equally well in every single run, but well enough that the choice of model was rarely my first construction site.\n\nOf course they are not identical. Every model has its own tone, its own preferences, its own weaknesses, and for individual tasks the differences can be large. Public benchmarks only help me to a limited extent, because they reflect neither my context nor my review criteria and shift quickly with new versions. For an architecture decision, I therefore need measurements on my own tasks rather than a general ranking.\n\nI do not like to be the first to say this in such meetings, because it cools down the discussion everyone was looking forward to. The model comparison is entertaining, it feels like engineering work, and it has the charm that you do not have to change anything about your own way of working. But it answers the wrong question.\n\n## The noise in daily work is larger than the difference between models\n\nWhen a session with Claude or ChatGPT goes wrong for me, it is almost never because of the model. It is because I stated the task unclearly. Because the model did not know the context that was decisive for the solution – the architecture decision from two years ago, the unwritten convention in the team, the reason why this one service is built differently from all the others. Or because I did not check the result and the mistake only surfaced in review.\n\nAn example from a team conversation at a large enterprise, anonymized as always: two colleagues, the same model, the same task – understand a piece of legacy code and propose a restructuring. One got a usable, concrete plan. The other got generic textbook text. The difference was not the model, not even the prompt in the narrow sense. One had given the model the relevant files, the test cases and the constraints. The other had typed a question into an empty window.\n\nIn my own sessions, the result often varies more with how the task is cut, the context and the verification than with switching between the top models under consideration. That is not a general measurement of the market, but an observation from this work. For me it follows: before I switch models, I first check whether task, context and acceptance criterion are clean enough.\n\n## If you bet on the best model, you bet on a commodity\n\nThat brings me to the thesis I consider the most important in this post: if you build your way of working, let alone your product, on “the best model,” you are betting on a commodity you do not own.\n\nThe models belong to a handful of vendors. I rent access through an API key or a subscription, just like my competitor, just like every other team. I cannot control when a version is deprecated, when behavior quietly shifts after an update, when the price drops or the next model upends the ranking. November demonstrated this: if you based your choice in October on a benchmark lead, you saw that lead change hands three times within two weeks.\n\nWhat I can own, on the other hand, is the layer around the model. That is not a platform and not a product, but simply everything I have in my own hands before and after the model computes:\n\n- how the tasks are cut, meaning the ability to break work down so that a piece of it becomes delegable\n- the context a session gets at the start, instead of the model having to guess my reality\n- the team’s knowledge in retrievable form, from conventions to the reasons behind old decisions\n- the process that governs when the AI works, when a person reviews and what may go into the main branch\n- the verification itself, meaning reliable ways to determine whether a result is correct before it has any effect\n\nThis layer is the opposite of a commodity. It is specific to my team, my codebase, my domain. Nobody can take it away from me with a release, and the competitor cannot simply rent it too. Above all: it survives model changes. An hour I invest in better task descriptions, in a well-maintained CLAUDE.md or AGENTS.md, in review criteria still pays off with the model after next. An hour of studying benchmarks is devalued with the next release.\n\nThere is a pleasant side effect that I know from architecture work: if you own the layer, your switching costs drop. When task cutting, context and verification are solid, the model behind them is as replaceable as a dependency behind a clear interface. Then I can even switch calmly when there is a real reason – because my actual capital does not hang on the model name.\n\n## Where the choice of model does matter\n\nHonesty is part of this, otherwise the thesis turns into dogma. There are situations in which the choice of model plays a real, measurable role. I run into three of them regularly.\n\nFirst, the special cases. If you work with exotic languages or niche frameworks, have strongly multimodal tasks or have to stay on-premises for data protection reasons, you quickly end up with smaller open models – and there the quality differences are real and the trade-offs are different. “Good enough” applies to the large frontier models for everyday tasks, not to every class of model for every task.\n\nSecond, cost and latency. As soon as models no longer run interactively but in volume – classification in a pipeline, autocompletion in the editor, processing thousands of documents – price per token and response time become hard criteria. Between models there are factors there, not percentage points, and measuring pays off.\n\nThird, long, agentic tasks. This is where the models still really differ noticeably at the end of 2025: how long they stay focused on a multi-step task, how reliably they operate tools, how they deal with their own mistakes. It is no coincidence that Claude Sonnet 4.5 in September and Opus 4.5 in November were promoted on exactly this capability. If you delegate entire work packages instead of individual questions, you may be picky about the choice of model.\n\nBut – and this matters more to me than the three exceptions themselves – all of this is the second question. It can only be answered seriously once the first one has been answered. Without a clear cut of the task and without reliable verification, I cannot compare models at all; I am then only comparing gut feelings on different days. Only when the layer is in place does the choice of model become what it should be: an optimization with measurements, roughly as exciting as choosing a database index. And as there, the rule is: reassess occasionally, pin versions deliberately, take behavior changes after updates seriously. “Good enough” means neither “all the same” nor “forever” – it just means: not the bottleneck.\n\n## The first question\n\nBack to the coffee break. Stick with the model you have, I told him, and put your team’s discussion energy into the questions before and after. How do you recognize that a result is correct? What would a session need to know about your system so it does not have to guess? Which of your tasks are even cut in a way that lets you hand them off? If you answer these three questions well, you get more out of any of the current models than your neighbor with the benchmark winner and an empty context window.\n\nHe was visibly unhappy – the answer is less spectacular than a model comparison, and it means work. But it has a consequence that has occupied me ever since and that carries the rest of this series: if the model is rarely the bottleneck, then something else makes the difference between the session that delivers and the one that burns time. For me, it comes down every time to the environment the model works in – how much it shows the model, what it allows it to do and what it checks its results against. That is exactly where the next post picks up.\n\n## Further reading\n\n- [Anthropic: Introducing Claude Opus 4.5](https://www.anthropic.com/news/claude-opus-4-5)\n- [Google: Gemini 3 – Google’s most capable model yet](https://blog.google/products/gemini/gemini-3/)\n- [Simon Willison: Claude Sonnet 4.5 is probably the best coding model in the world (at least for now)](https://simonwillison.net/2025/Sep/29/claude-sonnet-4-5/)\n- [Anthropic Engineering: Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents)"},{"locale":"en","translation_key":"von-der-session-zum-system-auftakt","slug":"from-tool-to-way-of-working","title":"From Tool to Way of Working","summary":"How a conversation in Berlin, after more than thirty years of software craftsmanship, got me working daily with Claude, ChatGPT and Claude Code – and why I still distrust my own enthusiasm for now.","tags":["Software","AI","Methodology"],"published_at":"2025-11-18T11:00:00+00:00","updated_at":"2026-07-14T20:54:48.643736+00:00","url":"https://www.mikebild.dev/en/blog/from-tool-to-way-of-working/","audio_url":null,"audio_duration_secs":null,"text":"*Opening of the series “From Session to System”.*\n\nSome time ago, I sat down with [Sebastian Korfmann](https://skorfmann.com/) in Berlin. I know Sebastian as a software engineer from the cloud and infrastructure world – someone who doesn’t judge tools by marketing slides, but by whether they take work off his hands in everyday life. He told me about his experiences with AI tools: what he builds with them, how his work has changed, where things get stuck. I listened with interest – and noticed that I had surprisingly little to contribute myself.\n\nI need to explain that. I have been working on software for more than thirty years, a large part of it on distributed systems – Node, TypeScript, GraphQL, cloud architectures – and for many years I gave training for software developers and architects. What appeals to me most about this work: building digital products, and doing it holistically. Really understanding the domain, making decisions about direction, shaping things – for a long time now, it hasn’t been just about programming and architecture for me. Over the years, my focus has shifted too: away from having every fine detail in my own hands, toward structure, consistency, processes, productivity, methods and concepts. Still, I had never worked with AI up to that point. Not a single session, no Copilot. Not out of rejection – fundamental skepticism toward new technology isn’t my style. It simply had never come up. The hype since the launch of ChatGPT at the end of 2022 was impossible to miss – headlines, conference keynotes, colleagues talking about it – but what I heard and read sounded to me like impressive demos, and my days were full. If anything, I was a little reserved – the way you are reserved about things you haven’t tried yourself yet.\n\nThere was something else, too, and I don’t like talking about it much, because it has nothing to do with technology and everything to do with me. I had grown tired. Not of the profession, but of a particular kind of undertaking: my own, larger projects, digital products I had carried around in my head for a long time. I know the complexity of such undertakings well enough to know that I can’t deliver many of these topics alone at the quality I expect of myself. The ideas were there, some of them worked out in detail, in notes and half-started repositories. What was missing was the energy for the sheer amount of implementation work – alongside a job and everything else. If you have ever tried to build a complete product on your own, you know the ratio: for every hour in which you really shape something – a decision about direction, a concept, a piece of the domain – there are twenty hours of grunt work. Boilerplate, configuration, forms, error handling, deployment, documentation, plus all the organizational stuff around it. At some point, I stopped opening new drawers, because the old ones were already full.\n\nThat was the state I was in when I met Sebastian. What grabbed me about the conversation was the way he told it: no superlatives, no “this changes everything” rhetoric, but the sober way you tell a colleague about a tool that has proven itself in everyday work. I knew that tone, and it made me curious. So I resolved to finally try it out myself. Not for ten minutes, but for a few days, on real tasks.\n\n## The first days\n\nI started with Claude and ChatGPT, in the browser, on tasks from my actual everyday work: reviewing an architecture concept, sketching an API migration, writing a data import I would otherwise have kept putting off. Shortly afterward, Claude Code and Codex joined in – the tools that don’t just answer, but work directly on the repository in the terminal: reading files, changing them, running tests. Anthropic had released Claude Sonnet 4.5 at the end of September, and OpenAI its Codex update at about the same time; without planning it, I got started at a pretty good moment.\n\nAnd then something happened that I hadn’t expected: within days, I was very taken with it. Not mildly interested – taken. Three things got me:\n\n- The speed. Tasks for which I would have planned half a day were, within an hour, in a state I could seriously review.\n- The productivity across the whole day. Not a single impressive moment, but the sum: in the evening, measurably more was done than before.\n- The quality. I had expected that least of all. The generated code wasn’t bug-free, but considerably better than I would have expected after everything I had heard and read about generated code – structured, with sensible error handling, often with tests.\n\nThe few days of trying turned into weeks of daily work. By now, I work with these tools every day and keep going deeper – Anthropic has just followed up with skills, a way to give Claude reusable working instructions, and I notice that I am starting to read such announcements the way I used to read Node release notes.\n\nA few weeks are not experience. I am aware of that, and that is exactly why I am writing this down. If you become a daily user this quickly, you should distrust your own enthusiasm for now – fresh enthusiasm is a poor witness. So I try to look closely and note down what I actually observe – with the only touchstone I have: more than thirty years of craft against which I can measure every result.\n\n## Observation one: generating gets cheap, checking becomes the bottleneck\n\nI noticed the first shift after just a few days, and it is more fundamental than it sounds. The expensive part of my work was always generating: writing code, wording documents, working out concepts. Checking – reviews, proofreading, acceptance – was the smaller item. That ratio is flipping right now. Generating is suddenly cheap; in one hour, more text and code come into being than I used to manage in a day. What hasn’t gotten cheaper: judging whether what was generated is right. My work is visibly shifting from writing to reading, from producing to assessing.\n\nIn a conversation with a colleague, I found a phrase for this that stuck: the tool is less an assistant, more a secretary. An assistant, as the product names promise, adds a line here and suggests a word there – the work stays mine. A secretary in the old sense takes on entire matters: I dictate the intent, they draw up the document, and I sign off. That sounds more convenient, but it is a different responsibility. With an assistant, I check suggestions in passing; with a secretary, I really have to read the finished piece, because my signature is underneath. If you sign without reading, you haven’t delegated, you have capitulated. I suspect that the real overhaul of my way of working lies in this shift – not in the tool itself.\n\n## Observation two: the drawers open again\n\nThe second observation is more personal, and it surprised me more than any benchmark. The tiredness I wrote about above isn’t gone – but it has lost its reason. The product ideas that were left lying around because implementing them was too big for one person are suddenly within reach again. Not because the AI builds the product. But because it takes over exactly the part that wore me down: the twenty hours of grunt work around the one hour that really requires thinking. The form scaffolding, the test coverage, the import adapter, the deployment script – all of this now comes into being so fast that, as the saying goes, I can strike while the iron is hot.\n\nMaybe that is also why the whole thing won me over so quickly: over the years, my focus had shifted to exactly where these tools take nothing away anyway – structure, consistency, concepts, the domain, the decisions about direction. The detailed work, on the other hand, and the recurring tasks, including the organizational ones, come more easily to me again now. Not all of them. But enough that it is fun again.\n\nOver the last few weeks, I have been building my own things again in the evenings, voluntarily and with a joy I hadn’t felt for a while. This is where I have to choose my words carefully, because it is so easily inflated into a gospel. So, soberly: for me, AI is above all a lever for the individual with experience right now. The emphasis is on both. The lever works because, after thirty years, I know what I want to build, how it has to be cut and how I can tell that a result is any good. Whether the same lever also works for someone who doesn’t have this judgment yet, I simply don’t know – I have a suspicion, but suspicion is not knowledge, and for this series I want to keep the two cleanly apart.\n\n## Observation three: the tone is always right\n\nI am only noting the third observation briefly, because I don’t understand it well enough yet to make more of it. I notice *how* these systems answer. In German working life, there is a tongue-in-cheek acronym for it: SABTA – “sicheres Auftreten bei totaler Ahnungslosigkeit”, confident demeanor despite total cluelessness. Psychology knows the pattern as the Dunning-Kruger effect: those who know the least often come across as the most confident. That is exactly how these systems strike me – the right answer and the wrong one come in the same calm, competent tone. In a code review, an unsure colleague gives themselves away through their wording – “I think”, “should actually”. Here, that signal doesn’t exist. Twice in the past few weeks, I almost adopted a claim that turned out, when checked, to be completely made up – an API signature that never existed, delivered with confidence. Both times, only my habit of looking things up saved me. This confident demeanor deserves fundamental distrust, and I want to understand where it comes from – structurally, not anecdotally. I am saving that for later in this series, once I have gathered enough observations.\n\n## What this series is meant to be\n\nI am starting a series here because I suspect the story is bigger than my desk. Right now, I am observing myself: one individual in the session, with direct control over every result. But I don’t work alone – I work in and with teams, and a team is something other than the sum of individual sessions. And above the teams are companies with their processes, their knowledge, their responsibility. I want to walk through this arc step by step in the coming installments: from me through us to the system. Not as theory, but along what I actually experience and try out – including the dead ends, of which there will predictably be a few.\n\nThe next question is already pressing. In the team, at lunch among colleagues, most recently in a conference hallway: after a few minutes, the conversation lands in the same place. Which model is the best? Claude or GPT, which version, which benchmark. I have had this discussion myself and developed an unease I am only gradually able to place: after these first weeks of daily work, I notice that the choice of model has changed my results less than pretty much everything else about my way of working. Everyone is talking about the best model – but is that even the right question? I will pursue it in the next installment.\n\n## Further reading\n\n- [Introducing Claude Sonnet 4.5](https://www.anthropic.com/news/claude-sonnet-4-5) – Anthropic’s announcement of the model I started with (September 2025)\n- [Claude Sonnet 4.5 is probably the “best coding model in the world”](https://simonwillison.net/2025/Sep/29/claude-sonnet-4-5/) – Simon Willison’s sober first assessment\n- [Introducing upgrades to Codex](https://openai.com/index/introducing-upgrades-to-codex/) – OpenAI’s Codex update with GPT-5-Codex (September 2025)\n- [Equipping agents for the real world with Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills) – Anthropic’s engineering post on skills (October 2025)"},{"locale":"en","translation_key":"react-ueberblick-von-jsx-zur-architektur","slug":"react-overview-from-jsx-to-component-architecture","title":"React Overview: From JSX to Component Architecture","summary":"A complete walk through React the way I teach it today – from declarative rendering through the question of who owns a piece of state to the architecture of a growing application. The details of individual stops will follow later as separate posts.","tags":["Software","Frontend","React"],"published_at":"2024-12-30T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/react-overview-from-jsx-to-component-architecture/","audio_url":null,"audio_duration_secs":null,"text":"# React Overview: From JSX to Component Architecture\n\nReact takes rendering off your hands, not architecture. The library computes a UI from a state and writes the differences to the DOM – but where this state lives, how long it lives and who may change it is something it never decides. Right there, at this inconspicuous boundary, the problems arise that you can no longer clean up later with any hook or library.\n\nThat’s why this post goes through React in one go – from the first piece of JSX to the point where individual components turn into a system. It is deliberately an overview. For most of the stops I only touch on briefly here, separate posts that dig deeper will follow. Today the goal is to have the big picture in your head before you get lost in a detail.\n\nI rely on two repositories that I’m currently merging: `introduction-react` for the fundamentals and `advanced-react` for the advanced patterns. Neither is a slide deck in text form; both are runnable code that we practice on together. The version I describe here is React 19 – the stable release from late 2024, with everything that has become everyday practice since.\n\n## The mental model: the UI is a function of state\n\nBefore a single line of JSX makes sense, one idea has to sink in. React flips the way you think about a UI. Instead of describing step by step how the DOM should change – insert an element here, change an attribute there, remove a node over there –, you only describe what the UI should look like for a given state. React takes care of getting there.\n\nYou can put this into a single sentence that carries everything else: the UI is a function of state. When the state changes, React calls the function again, compares the result with the previous one and writes only the actual differences to the real DOM. This reconciliation runs on an internal, lightweight representation of the tree, often called the Virtual DOM. The name matters less than the consequence: you describe the destination, not the route. I show how this reconciliation works step by step in detail in the post [How React Renders and Updates the Tree](https://www.mikebild.dev/en/blog/how-react-renders-and-updates-the-tree/).\n\n```mermaid\nflowchart LR\n  State[\"State\"] --> Render[\"Component renders\"]\n  Render --> View[\"Described UI\"]\n  View --> DOM[\"React reconciles and writes to the DOM\"]\n  User[\"User interaction\"] --> Event[\"Event / setState\"]\n  Event --> State\n```\n\nThe second load-bearing idea is unidirectional data flow. Data flows from top to bottom, from the parent component to the child, via props. Events flow in the other direction, upward as callbacks. There is no mysterious two-way binding in which an input field and a variable magically stay in sync. At first this feels more cumbersome than in older frameworks, but it is the reason React applications can still be explained after two years: for every spot in the UI, you can say where its data comes from and who may change it.\n\n## JSX and components: the smallest unit is a function\n\nJSX looks like HTML inside JavaScript, but it’s just a convenient notation for function calls. A `<button>` becomes a call that describes an object; it doesn’t create a DOM element. That’s why you can compute, map lists and render conditionally right in the middle of JSX – it’s all just JavaScript, after all:\n\n```jsx\nfunction InvoiceList({ invoices }) {\n  if (invoices.length === 0) return <p>No invoices.</p>;\n\n  return (\n    <ul>\n      {invoices.map((i) => (\n        <li key={i.id}>\n          {i.number} - {i.paid ? \"paid\" : \"open\"}\n        </li>\n      ))}\n    </ul>\n  );\n}\n```\n\nThree details in this small example are actually architecture topics. The `key` attribute is not a cosmetic detail but the information React uses when re-rendering to recognize which list item corresponds to which. Conditional rendering with `?` or with an early `return` is where loading, error and empty states become visible – exactly the states that tend to get swept under the rug in demo mode and then are missing in production. And `props` is a read-only interface: a component gets its data from outside and must not change it. This turns components into building blocks whose behavior you can understand from the outside. I cover the exact rules of JSX – what an expression is, what disappears during rendering, how keys really work – in detail in the post [JSX Precisely: The Rules Behind the Markup](https://www.mikebild.dev/en/blog/jsx-precisely-the-rules-behind-the-markup/).\n\nThe standard today is the functional component. It is a function that takes props and returns JSX, and with hooks it can now do everything you used to need classes for. Class components with a `render` method and lifecycle methods like `componentDidMount` still exist, and you run into them in older code. If you come across them in a grown project, there’s no need to panic – they are a historical layer, nothing more. But new code is written with functions. This is not a matter of fashion but a real simplification: an Effect that should do something on mount and on unmount used to be scattered across two separate lifecycle methods. Today it lives in one place.\n\nComposition replaces inheritance. Instead of extending a base component, you nest components inside each other and pass content through via `children`:\n\n```jsx\nfunction Card({ title, children }) {\n  return (\n    <section className=\"card\">\n      <h2>{title}</h2>\n      {children}\n    </section>\n  );\n}\n```\n\nA `Card` like this knows nothing about its content and is usable everywhere precisely because of that. Once you internalize this reflex – compose rather than inherit –, you write decoupled UIs almost automatically.\n\n## State is not a place\n\nNow comes the question from the beginning, and it is the most important one in this whole post. State is not a place in the code but a decision about ownership, lifetime and synchronization. Before you write `useState`, you should know who this state actually belongs to.\n\nThe local case is the simplest. A counter, an expanded menu, the text in an input field – state like this belongs in the component that displays it:\n\n```jsx\nimport { useState } from \"react\";\n\nfunction Counter({ start = 0 }) {\n  const [count, setCount] = useState(start);\n  return <button onClick={() => setCount((n) => n + 1)}>{count}</button>;\n}\n```\n\nThe rule React demands at this point is: keep components pure. The same inputs should produce the same output. The state isn’t mutated directly but replaced via the setter function, and React decides when to re-render. If you take this seriously, you get components you can play through in your head without a running browser.\n\nIt gets interesting as soon as a piece of state no longer fits into a single component. Then you have to answer honestly where it belongs, and the answer is rarely “in a global store”. I distinguish four places, and choosing between them is the real architecture work in the frontend:\n\n```mermaid\nflowchart TB\n  Frage[\"Who owns this state?\"]\n  Frage --> Lokal[\"Component<br/>(useState) – UI detail\"]\n  Frage --> URL[\"URL<br/>filter, page, selected object\"]\n  Frage --> Server[\"Server cache<br/>loaded data that belongs to the backend\"]\n  Frage --> Global[\"Global store<br/>app-wide, shared decisions\"]\n```\n\nMuch of what teams reflexively put into a global store actually belongs in the URL – which filter is active, which page is shown, which object is selected. In the URL, this state is shareable, can be saved as a bookmark and survives a reload. And a large part of what looks like application state isn’t state at all: it is data that belongs to the server and that you have merely cached. This distinction between real client state and cached server data is the most consequential one in the entire frontend, and I dedicate a separate post to it: [Client state vs. server cache](https://www.mikebild.dev/en/blog/client-state-vs-server-cache/).\n\n## Effects are the edge, not the center\n\n`useEffect` is the hook that has caused the most misunderstandings in the teams I’ve worked with. It synchronizes a component with something outside of React – a network call, a subscription, the title of the browser tab, a timer. The key sentence is: an Effect is the edge of the system, not its center. Anything you can compute from state doesn’t belong in an Effect but directly in rendering.\n\n```jsx\nimport { useState, useEffect } from \"react\";\n\nfunction useInvoice(id) {\n  const [data, setData] = useState(null);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    let active = true;\n    fetch(`/api/invoices/${id}`)\n      .then((r) => r.json())\n      .then((d) => active && setData(d))\n      .catch((e) => active && setError(e.message));\n    return () => {\n      active = false;\n    };\n  }, [id]);\n\n  return { data, error };\n}\n```\n\nTwo things about this example are the real lesson. The dependency array `[id]` determines when the Effect runs again – if you forget a value there, the component keeps working with stale data. And the returned cleanup function, which sets `active` to `false`, prevents a late-arriving response from overwriting the state of a component that has already unmounted or of a request that has since been superseded. This race between two requests is exactly the bug that never shows up in tests with fast responses and only strikes in production on a slow network.\n\nI deliberately pulled the logic here into its own custom hook `useInvoice`. That already brings us to today’s way of reusing logic – more on that in a moment. All that matters at this point is the mindset: limit Effects, don’t pile them up. A frontend in which data loading, derivation, synchronization and user events all end up in a single lump of Effects is fragile, because nobody can say anymore why which Effect runs when.\n\nThe most common mistake I see in code reviews is exactly the opposite reflex: mirroring a value that can be computed from other state into a second state via an Effect. If you write the full name from first and last name into its own variable via an Effect, you have built yourself two sources of truth that drift apart as soon as a render gets in between. The computed value doesn’t belong in an Effect, nor in a second `useState`, but simply in rendering, where it is created fresh on every pass. What can be derived is derived, not stored – this one rule saves you more bugs than any library. An Effect is only justified when something outside of React is really involved.\n\nBy the way, for loading server data you rarely have to write this mechanism by hand in real projects. In practice, a library specialized for this handles caching, refetching and consistency. React 19 goes one step further with the `use()` hook and Suspense and lets you await a Promise directly during rendering, so loading and error states move further out to an enclosing `<Suspense>` component. I cover this big topic of its own in the post [Suspense and the use Hook](https://www.mikebild.dev/en/blog/suspense-and-the-use-hook/).\n\n## From HOCs and render props to custom Hooks\n\nThe advanced React patterns, which form their own block in the `advanced-react` material, are almost all answers to the same question: how do I share logic between components without copying it? The answer has shifted over the years, and this shift is instructive in itself.\n\nThere used to be two established patterns for this. A higher-order component is a function that takes a component and returns an enhanced one – a wrapper that adds behavior. Render props solve the same problem by having a component expose its logic through a function as its child. Both work, but both come at the same price: they nest the component tree and turn a flat idea into a deep structure.\n\n[Custom Hooks](https://www.mikebild.dev/en/blog/from-hocs-and-render-props-to-custom-hooks/) solve exactly this problem without nesting the tree. A custom hook is simply a function whose name starts with `use` and that uses other hooks. The `useInvoice` from above is already one. The logic lives in a normal function, is called by several components and doesn’t show up in the tree at all:\n\n```jsx\nfunction InvoiceView({ id }) {\n  const { data, error } = useInvoice(id);\n  if (error) return <ErrorMessage text={error} />;\n  if (!data) return <LoadingIndicator />;\n  return <InvoiceDetails invoice={data} />;\n}\n```\n\nYou find the same movement with context. Passing data down through many levels without threading it as a prop through every intermediate component is the job of context: a provider at the top of the tree, a `useContext` further down. The important caveat: context is meant for distributing, not as a replacement for well-thought-out state ownership. If you put every changing value into a context, you only move the coupling problem one level up. I cover this too – context as a distribution channel versus context as hidden global state – in the post [Using Context well](https://www.mikebild.dev/en/blog/using-react-context-well/).\n\n## When shared state really is global: Redux and the alternatives\n\nSometimes state really is app-wide and is read and changed by many places far apart from each other. There are established tools for this case, and Redux is the best known. Its core is surprisingly small: the entire state lives in one store, it is changed only by dispatching an action – a plain object with a `type` –, and a reducer is a pure function that computes the new state from the old state and the action.\n\n```js\nfunction invoicesReducer(state = [], action) {\n  switch (action.type) {\n    case \"invoice/paid\":\n      return state.map((i) =>\n        i.id === action.id ? { ...i, paid: true } : i\n      );\n    default:\n      return state;\n  }\n}\n```\n\nThe appeal of this pattern is that every state change becomes a named, loggable event. You can trace the sequence of actions, record it and replay it in a test. The price is a certain amount of structure. In projects I have come across three ways to organize this structure, and the choice determines whether a UI system grows along the domain or along technical lines: the Rails style with separate folders for actions, reducers and containers; the domain style, which instead bundles per feature; and the Ducks pattern, which puts the actions and reducer for one thing into a single file. The domain split is almost always the better one, because it draws file boundaries along the domain and not along technical roles.\n\nToday hardly anyone writes Redux out by hand like this anymore. The official Redux Toolkit takes most of the repetition off your hands, and for many applications a lighter library or simply context with a reducer is enough. Reactive approaches like MobX pursue the same goal with a different model, in which derived values update automatically. Which of these tools fits depends less on fashion than on an honest answer to the ownership question from earlier – I dedicate a separate comparison to it: [State Management in React: Redux Toolkit, Lightweight Stores, MobX](https://www.mikebild.dev/en/blog/state-management-in-react/).\n\nIn architecture discussions, I like to do the cross-check: for how much of the supposedly global state do you really need the store? Most of the time the list shrinks dramatically as soon as you use the URL for selection and filters and treat loaded server data as what it is – cache, not state. What often remains is just a small core of real, app-wide decisions: the signed-in person, the chosen language or theme setting, maybe a shopping cart. For this core a store pays off; for the rest it is dead weight. So a global store isn’t the default answer but the exception you have to be able to justify.\n\n## Router, server and the edges of the application\n\nTwo edges are still missing. The first is navigation. In a single-page application, you don’t switch pages; you map URLs to components. The router keeps the address bar and the displayed component in sync, so the back and forward buttons, bookmarks and shared links keep working:\n\n```jsx\nimport { BrowserRouter, Routes, Route } from \"react-router-dom\";\n\nfunction App() {\n  return (\n    <BrowserRouter>\n      <Routes>\n        <Route path=\"/\" element={<Start />} />\n        <Route path=\"/invoices/:id\" element={<InvoiceView />} />\n        <Route path=\"*\" element={<NotFound />} />\n      </Routes>\n    </BrowserRouter>\n  );\n}\n```\n\nThis also makes the router the natural place for the state that belongs in the URL. The `:id` parameter, which you read in the component via `useParams`, is exactly the selected object I talked about above – no reason to also keep it in a store. For new projects, React Router now recommends the data router variant with `createBrowserRouter`, in which routes also get loading and writing functions; that is the more modern way, and I dedicate the post [React Router data router](https://www.mikebild.dev/en/blog/react-router-data-router-the-url-as-state/) to it.\n\nThe second edge is rendering on the server. For startup time, search engines and weak devices, it often makes sense to generate the first version of the page on the server and only bring it to life in the browser. Frameworks like Next.js take care of these mechanics for you. React 19 expanded the topic fundamentally once more with Server Components: components can run on the server, load data there and send only their result to the browser, while Server Actions form the counterpart for write operations. This noticeably shifts the old boundary between client and server, and it is such a big topic that I dedicate the post [React Server Components and Server Actions](https://www.mikebild.dev/en/blog/react-server-components-and-server-actions/) to it; here it only serves as a signpost.\n\n## Operations: tests, toolchain, types\n\nAn overview that stops at rendering would be incomplete, because all the boundaries I have described – state ownership, Effect discipline, data flow – can break unnoticed if nobody pins down an expectation about them. In the frontend, tests are not a chore but the place where these expectations stay visible.\n\nToday I test components with Vitest and the React Testing Library, and its guiding idea fits the architecture of this post exactly: you check what users see and do, not how the component is built inside. A test tied to the visible result survives a refactoring; a test glued to implementation details breaks with every rename.\n\n```jsx\nimport { describe, it, expect } from \"vitest\";\nimport { render, screen } from \"@testing-library/react\";\nimport userEvent from \"@testing-library/user-event\";\nimport { Counter } from \"./Counter\";\n\ndescribe(\"Counter\", () => {\n  it(\"counts up on click\", async () => {\n    render(<Counter start={0} />);\n    const button = screen.getByRole(\"button\", { name: \"0\" });\n    await userEvent.click(button);\n    expect(screen.getByRole(\"button\", { name: \"1\" })).toBeInTheDocument();\n  });\n});\n```\n\nBehind this is the same test pyramid as everywhere: many fast component tests at the base, fewer integration tests in the middle, a handful of end-to-end tests with a tool like Playwright at the top. If you turn this distribution upside down, you pay for it later with a sluggish build pipeline.\n\nThe toolchain is an architecture decision too, not a matter of taste. Whether a project starts with Vite, Next.js, Parcel or a handwritten webpack configuration determines how fast the feedback is during development, how easy server rendering becomes and how much you maintain yourself. And on top of all this sits [TypeScript](https://www.mikebild.dev/en/blog/typescript-in-react/), which turns props and state into checkable contracts. A mistyped prop then doesn’t become a runtime error for the user but a red squiggle in the editor. Finally, the React Compiler, which the React team develops as a separate project alongside the library, takes over part of the manual optimization: it analyzes components at build time and automatically remembers what hasn’t changed between two render passes, so many calls to `useMemo`, `useCallback` and `memo` become unnecessary.\n\n## The repository is already architecture\n\nOne last look at the structure of the repositories themselves. `introduction-react` and `advanced-react` aren’t one big lump but many small, self-contained examples – a basic app, a Redux app, a router app, one with server rendering, plus the advanced folders for asynchronous patterns, functional composition and structure. Each example stands on its own and can be started individually.\n\nThe fact that I’m currently merging the two repositories is therefore a small architecture exercise in itself. The question is the same as for any growing system: what may be shared, and what has to stay separate so that a change in one place doesn’t unexpectedly break something in another? A cleanly split monorepo of fundamentals and advanced examples solves exactly the same task as an application made up of many components and modules. In both places, the boundaries you draw are the real work.\n\n```mermaid\nflowchart TB\n  Repo[\"React monorepo\"]\n  Repo --> Grund[\"Basics<br/>JSX, components, hooks, router\"]\n  Repo --> Fort[\"Advanced<br/>async, functional, structure\"]\n  Repo --> Geteilt[\"Shared building blocks<br/>UI components, test helpers\"]\n  Grund --> Geteilt\n  Fort --> Geteilt\n```\n\n## What should stick in the end\n\nAt best, what remains from a walk-through like this is not the sentence “I know the hooks now” but a reflex: for every piece of state, first ask who owns it and how long it should live. That is exactly the core. React gives you a very good tool for describing UIs, but it doesn’t make the architecture decisions for you. Who owns a piece of state, where an Effect has its edge, which state lives in the URL, in the server cache or in the store – that remains the work a human has to do.\n\nThat’s why this post is an overview and not a handbook. I only briefly touched on many stops: the difference between client state and server cache, context as a distribution channel, the choice between Redux and its lighter alternatives, Suspense and Server Components, testing without theater. There is more to say about each of these stops than an overview can carry, and that is exactly the plan: the details will follow as separate posts, each with a concrete example and at least one failure case. Once you have the big picture in your head, you’ll know where you currently stand.\n\n## Further reading\n\n- Repository introduction-react (fundamentals): https://github.com/mikebild/introduction-react\n- Repository advanced-react (advanced patterns): https://github.com/mikebild/advanced-react\n- Slide overview for this overview: https://slides.mikebild.dev/introduction-react.en.html\n- React, official documentation (Thinking in React): https://react.dev/learn/thinking-in-react\n- React 19, announcement of the stable release: https://react.dev/blog/2024/12/05/react-19\n- React, managing and sharing state: https://react.dev/learn/managing-state"},{"locale":"en","translation_key":"formulare-in-react-19-mit-actions","slug":"forms-in-react-19-with-actions","title":"Forms in React 19: Actions, useActionState and useOptimistic","summary":"React 19 makes the form the actual interface: a function as the form action, plus three hooks for the result, the pending state and instant UI feedback. This post shows how they work together – and where optimistic rendering breaks down without a clean error path.","tags":["Software","Frontend","React"],"published_at":"2024-12-23T10:00:00+00:00","updated_at":"2026-07-13T08:57:08.736063+00:00","url":"https://www.mikebild.dev/en/blog/forms-in-react-19-with-actions/","audio_url":null,"audio_duration_secs":null,"text":"An optimistically inserted entry that disappears again on an error and leaves no message behind tells the user something false: they submitted, they saw it briefly, then there was nothing. This is the one place where the form APIs of React 19 create work instead of taking it off your hands – and that is why it comes first, right here at the start.\n\nEverything else about them is relief. Up to React 18, a form that saves a name consisted of `onSubmit`, `event.preventDefault()`, a `useState` for the loading state, a second one for the error message and a `try/catch` somewhere – a surprising amount of manual work for a surprisingly everyday task. React 19, stable since December 5, 2024, instead hands a function directly to the `<form>` element and puts three hooks next to it: `useActionState`, `useFormStatus` and `useOptimistic`. They take care of exactly the things you used to wire up by hand. I will go through what each of these building blocks takes over, how they work together and where the error path from the first paragraph belongs.\n\n## From onSubmit to action\n\nThe starting point is a small but far-reaching change to the `<form>` element. In React 19, the `action` attribute accepts a function – no longer just a URL string as in classic HTML. On submit, this function receives a `FormData` object and is called by React. React calls `preventDefault` itself, wraps the call in a transition and – a detail that is easily overlooked – automatically resets an uncontrolled form after a successful action.\n\nHere is the comparison. Before:\n\n```jsx\nfunction NameForm() {\n  const [isSaving, setIsSaving] = useState(false);\n  const [error, setError] = useState(null);\n\n  async function handleSubmit(event) {\n    event.preventDefault();\n    setIsSaving(true);\n    setError(null);\n    const formData = new FormData(event.currentTarget);\n    const result = await save(formData.get(\"name\"));\n    setIsSaving(false);\n    if (result.error) setError(result.error);\n  }\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <input name=\"name\" />\n      <button disabled={isSaving}>{isSaving ? \"Saving…\" : \"Save\"}</button>\n      {error && <p>{error}</p>}\n    </form>\n  );\n}\n```\n\nAnd after, with a client action:\n\n```jsx\nfunction NameForm() {\n  async function updateName(formData) {\n    await save(formData.get(\"name\"));\n  }\n\n  return (\n    <form action={updateName}>\n      <input name=\"name\" />\n      <button>Save</button>\n    </form>\n  );\n}\n```\n\nThe second variant is not just shorter, it shifts control. React now knows that a handover is happening here, keeps the pending state consistent and takes care of the native submit behavior. In its documentation, React simply calls a function that triggers transitions this way an “Action”. What the second variant still lacks is everything that actually made up the first code block: the loading state and the error handling. That is exactly what the three hooks bring back – but without the manual work.\n\n## Who takes care of what\n\nAt first glance, the three hooks sound similar, but they have very different jobs. So before the code, the responsibilities:\n\n- `useActionState` bundles the complete lifecycle of an action in one place: it wraps your action function, holds the returned result as state, provides an `isPending` flag and hands you back a wrapped `formAction` that you attach to the form.\n- `useFormStatus` reads the pending state of the nearest enclosing `<form>` – meant for child components like a submit button that don’t need to know anything about the action itself, but want to know whether a submission is in progress.\n- `useOptimistic` immediately shows an expected intermediate state while the action is still running, and afterwards automatically converges back to the real state – to the server value on success, to the old value on error.\n\nYou can use the three individually or together. In a real form, they usually interlock, and how they work together is exactly where it gets interesting.\n\n## useActionState: result and pending in one place\n\nYou import `useActionState` from `react` – not from `react-dom`, which is a common first source of errors. The signature:\n\n```jsx\nconst [state, formAction, isPending] = useActionState(action, initialState, permalink);\n```\n\nThe decisive point, and a surprising one for many, lies in the signature of the action function you pass in. It does **not** just receive the `FormData`; its first argument is the previous state, and only the second is the form data:\n\n```jsx\nimport { useActionState } from \"react\";\n\nasync function updateName(previousState, formData) {\n  const name = formData.get(\"name\");\n  const error = await save(name);\n  if (error) {\n    return { error };\n  }\n  return { ok: true };\n}\n\nfunction NameForm() {\n  const [state, formAction, isPending] = useActionState(updateName, {});\n\n  return (\n    <form action={formAction}>\n      <input name=\"name\" disabled={isPending} />\n      <SubmitButton />\n      {state.error && <p role=\"alert\">{state.error}</p>}\n      {state.ok && <p>Saved.</p>}\n    </form>\n  );\n}\n```\n\nWhat happens here is the entire first code block from above – just without the manual work. The return value of the action becomes the new `state`, React manages the `isPending` flag, and `formAction` is the wrapped function that gets attached to the `action` attribute. The error message is no longer a separate `useState`; it simply falls out of the returned state.\n\nWhen I see in a code review that the state is suddenly `undefined` or the previous state gets lost, the cause is almost always the same: the action was written as `(formData) => …` instead of `(previousState, formData) => …`. The first parameter is simply not the FormData. If you come from the old `onSubmit` world, this reflex is in your fingers, and it regularly costs a few minutes of searching.\n\nA historical note so that older tutorials don’t confuse you: in the canary versions, this hook was called `useFormState` and lived in `react-dom`. With React 19, it was moved to `react` and renamed to `useActionState`; the third element `isPending` was added at the same time. `useFormState` has been deprecated since – if you still see it somewhere, the code is from an older state.\n\n## useFormStatus: reading pending in the child\n\nNow to the submit button that I already used above as `<SubmitButton />`. You might ask why it is extracted – after all, I could have passed `isPending` from `useActionState` directly to a button in the form. Both are possible, but `useFormStatus` solves a specific problem: a reusable component that knows the pending state without you having to pass it down.\n\n```jsx\nimport { useFormStatus } from \"react-dom\";\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus();\n  return (\n    <button disabled={pending}>\n      {pending ? \"Saving…\" : \"Save\"}\n    </button>\n  );\n}\n```\n\nThe hook comes from `react-dom`, takes no parameters and, in addition to `pending`, returns `data`, `method` and `action` of the enclosing form. The one rule you need to know, and the one responsible for most of the error reports at this point: `useFormStatus` reads the status of the **nearest parent `<form>`** and therefore has to sit in a child component, not in the same component that renders the `<form>`.\n\nIf the hook accidentally sits in the form component itself, `pending` is simply always `false` – from that perspective, there is no enclosing form whose status could be read. The button has to be a child. A separate `SubmitButton` component is therefore not a matter of taste: without this nesting, the hook sees nothing at all.\n\n## useOptimistic: showing the expected state immediately\n\nThe third hook is the most impressive one – and the most dangerous if you only half understand it. `useOptimistic` immediately shows the state you expect after a successful action, without waiting for the server response. The classic example is a message list in which your own message appears immediately:\n\n```jsx\nimport { useOptimistic, useActionState } from \"react\";\n\nfunction Thread({ messages, sendMessage }) {\n  const [optimisticMessages, addOptimistic] = useOptimistic(\n    messages,\n    (currentMessages, newText) => [\n      ...currentMessages,\n      { text: newText, sending: true },\n    ]\n  );\n\n  const [state, formAction] = useActionState(\n    async (previousState, formData) => {\n      const text = formData.get(\"message\");\n      addOptimistic(text);\n      const error = await sendMessage(text);\n      if (error) {\n        return { error };\n      }\n      return { ok: true };\n    },\n    {}\n  );\n\n  return (\n    <div>\n      <ul>\n        {optimisticMessages.map((message, index) => (\n          <li key={index}>\n            {message.text}\n            {message.sending && <span> (sending…)</span>}\n          </li>\n        ))}\n      </ul>\n      <form action={formAction}>\n        <input name=\"message\" />\n        <SubmitButton />\n        {state.error && <p role=\"alert\">{state.error}</p>}\n      </form>\n    </div>\n  );\n}\n```\n\n`useOptimistic` receives the real state and a pure reducer function that computes the next intermediate state from the current state and the optimistic value. The call to `addOptimistic` has to happen inside an action or transition – here, inside the async action that `useActionState` manages. If you call it outside, you get a warning and no optimistic rendering.\n\nThe truly elegant part is the automatic convergence: the optimistic value only applies while the action is running. As soon as it has finished, the displayed state falls back to the real `messages` state. On success, that is the updated server value; on error, the old value – so the optimistically inserted message disappears again on its own. You don’t have to reset anything manually.\n\n## The pitfall: optimistic without an error path\n\nThe automatic convergence tempts you to consider the error case done. It isn’t – this is where the bugs come from that nobody sees in testing and everybody reports to support.\n\nImagine `sendMessage` fails. The optimistic value is rolled back automatically – the message disappears from the list. From the user’s point of view, that means: they submitted something, it appeared briefly, and then it was gone. Without any further feedback. No user interprets that as “error while sending”; most think they misclicked and simply try again – in the worst case, this creates a duplicate as soon as the server did respond after all.\n\nThe flawed reasoning is to mistake `useOptimistic` for error handling. The hook takes care of the *visible intermediate state*, not of *communicating the result*. You have to keep these two jobs apart:\n\n- `useOptimistic` makes sure the optimistic value is rolled back automatically on an error – that is the rollback of the UI state, and you get it for free.\n- The visible error message is a separate responsibility. It has to come from the `state` of `useActionState`: the action catches the error, returns it as `{ error }`, and the UI derives a message from it.\n\nWith concurrent changes, this UI rollback is not enough. Duplicate submissions, stale server states and conflicts still need idempotency keys, version checks or a domain conflict rule on the server.\n\nThat is exactly what happens in the code above: in the error case, the action returns `{ error }`, and `{state.error && <p role=\"alert\">…</p>}` makes it visible. The optimistic value disappears automatically, but the user sees *why*. If, on the other hand, you swallow the error in the `catch` or never return it in the first place, you have a UI that, on errors, silently gives the false impression that nothing happened. Optimistic rendering without a real error path is worse than no optimistic rendering at all.\n\n## How it fits together\n\nIf you arrange the four participants – the form, the action, the pending state and the optimistic value – in time, the pattern becomes clear:\n\n```mermaid\nflowchart LR\n  A[\"form action(fn)<br/>submit triggered\"] --> B[\"isPending = true<br/>button disabled<br/>via useFormStatus\"]\n  B --> C[\"addOptimistic()<br/>expected state<br/>visible immediately\"]\n  C --> D[\"await save()\"]\n  D -->|Success| E[\"real state<br/>state.ok<br/>form reset\"]\n  D -->|Error| F[\"optimistic value reverted<br/>state.error visible\"]\n```\n\nThe upper path is the normal case, the lower one is the one you have to actively design. React takes almost the entire path from A to D off your hands; the conscious design decision lies in the branch at D – and in making sure the error branch doesn’t lead nowhere.\n\nThe second diagram sorts out the responsibilities once more, because the risk of confusing the three is real:\n\n```mermaid\nflowchart TB\n  subgraph Form[\"React 19 form\"]\n    UAS[\"useActionState<br/>call + result + pending\"]\n    UFS[\"useFormStatus<br/>reads pending of the parent form<br/>in the child\"]\n    UO[\"useOptimistic<br/>instant intermediate state<br/>with auto-convergence\"]\n  end\n  UAS -->|passes isPending<br/>and state| UI[\"Error and success display\"]\n  UFS -->|pending| Button[\"SubmitButton\"]\n  UO -->|optimisticState| Liste[\"Live list\"]\n```\n\n## A word on Server Functions\n\nSo far, I have talked about client actions – functions that run in the browser. But the same mechanism also carries across the network boundary. With the `\"use server\"` directive at the top of a file or a function, you mark Server Functions that can be called from the client but run on the server:\n\n```js\n\"use server\";\n\nexport async function updateName(previousState, formData) {\n  const name = formData.get(\"name\");\n  await db.users.update({ name });\n  return { ok: true };\n}\n```\n\nYou can pass this function to `useActionState` or directly to `<form action={…}>` exactly like a client action – the signature is the same. It is important not to confuse `\"use server\"` with `\"use client\"`; the two directives mark opposite places of execution. And Server Functions require a framework or bundler that supports React Server Components; in a pure client app, they don’t exist.\n\nA nice side effect in this context is progressive enhancement. If you pass a `permalink` – a URL – to `useActionState` as the third argument, the form also works when JavaScript hasn’t hydrated yet or isn’t available at all: the browser navigates to this URL the classic way, the server processes the FormData, and as soon as React has hydrated, the client-side action takes over seamlessly. This is only relevant in an RSC context, but it shows that the Actions model was thought through all the way into server communication and is not just a prettier way of writing `onSubmit`. If you want to dig deeper into this interplay, my post on [React Server Components and Server Actions](https://www.mikebild.dev/en/blog/react-server-components-and-server-actions/) gives you the bigger picture.\n\n## What sticks\n\nAll in all, it comes down to a change of perspective. In React 19, you give the form a function; cleaning up after it with event handlers goes away. The three hooks are not three new things to memorize, but the three responsibilities you used to tie together yourself, cleanly separated: `useActionState` for the call, the result and pending, `useFormStatus` for the view of pending from the child, `useOptimistic` for instant feedback with automatic rollback.\n\nThe two stumbling blocks that, in my experience, cost the most time: the action of `useActionState` receives the previous state as its first argument, not the FormData. And optimistic rendering is only done when the error case has a visible message – the hook takes the rollback off your hands, but not the communication. With these two points in mind, forms in React 19 become shorter *and* more robust than anything you built by hand before.\n\n## Further reading\n\n- [React 19 release blog post (Actions overview)](https://react.dev/blog/2024/12/05/react-19)\n- [`useActionState` – react.dev](https://react.dev/reference/react/useActionState)\n- [`useFormStatus` – react.dev](https://react.dev/reference/react-dom/hooks/useFormStatus)\n- [`useOptimistic` – react.dev](https://react.dev/reference/react/useOptimistic)\n- [`<form action>` – react.dev](https://react.dev/reference/react-dom/components/form)\n- [`\"use server\"` / Server Functions – react.dev](https://react.dev/reference/rsc/use-server)\n- [`useTransition` (background on Actions/transitions) – react.dev](https://react.dev/reference/react/useTransition)"},{"locale":"en","translation_key":"react-server-components-und-server-actions","slug":"react-server-components-and-server-actions","title":"React Server Components and Server Actions: The New Boundary","summary":"Server Components run outside the client bundle and send their result to the browser instead of their code. Server Functions move writes to the server – both are implemented by a suitable framework or bundler.","tags":["Software","Frontend","React"],"published_at":"2024-12-19T10:00:00+00:00","updated_at":"2026-07-13T08:04:22.356388+00:00","url":"https://www.mikebild.dev/en/blog/react-server-components-and-server-actions/","audio_url":null,"audio_duration_secs":null,"text":"# React Server Components and Server Actions: The New Boundary\n\n```text\nError: You're importing a component that needs `useState`.\nThis React Hook only works in a Client Component.\nTo fix, mark the file (or its parent) with the \"use client\" directive.\n```\n\nFor many people, this message is their first contact with React Server Components, and the usual reflex is: put `\"use client\"` in the first line, error gone, move on. The build is green again, and the real question has been skipped. The message isn’t a configuration error, though. It asks which side of a boundary this piece of UI belongs on – and the answer reaches far beyond the file where the directive ends up.\n\nWhen you move an architectural boundary, you always move more than code: you also move where testing happens, what has to be deployed and which team owns which part of the UI. That is the trade-off this is really about. Faster delivery and a smaller bundle are the visible gain. The real effect lies underneath: shorter paths from data access to display, less friction at the seam between the two worlds – paid for with a boundary that you now have to draw and defend deliberately.\n\n**Editorial note (July 2026):** React 19 stabilized Server Components as a component model. The interfaces that frameworks and bundlers use to implement them, however, still don’t follow the usual semver stability within React 19.x. React alone therefore doesn’t yet provide a complete production architecture for them; the examples in this post use the Next.js App Router. Server Components can also run at build time or per request. Only the dynamic variant needs a runtime server.\n\nThis is where many people get stuck at first: you look for a new hook and instead run into a boundary that has moved – with consequences for testing, operations and team structure. From now on, the framework no longer decides for you which part of the UI stays on the server and which goes to the browser. That is what this post is about.\n\n## What a Server Component really is\n\nA Server Component runs in an environment outside the client bundle: at build time or on a server per request. There it can render with direct access to the database, file system or internal services and then send only its result to the browser. Not its code. That is the key sentence. For a component that merely displays something, no component code of its own ends up in the client bundle. The browser gets a description of what it should display, not the component that produced this description.\n\nThat is a different use of the word “render” than you are used to. This is why it’s worth going back to an earlier post: in [How React renders the tree](https://www.mikebild.dev/en/blog/how-react-renders-and-updates-the-tree/) I showed that rendering in React is only a calculation anyway – a function that turns inputs into a description of the tree, which React then compares with the last state. But if rendering is only a calculation, the question arises immediately: where does this calculation run? This is exactly where Server Components come in. They permanently move part of this calculation to the server instead of doing it in the browser as before.\n\n## The difference from SSR that almost everyone mixes up\n\nOne point needs setting straight here, because it reliably causes confusion: Server Components are not the same as server-side rendering, and the difference is not cosmetic.\n\nClassic SSR takes perfectly normal client components and renders them once on the server to HTML so that the browser sees something right away. After that, though, the server still sends the component code along, and hydration runs in the browser: React attaches itself to the delivered HTML, runs the same component again and makes it interactive. So the code goes along – SSR is an early first impression, not a way to save JavaScript. In the end, the component exists twice: once as HTML from the server, once as runnable code in the browser.\n\nA Server Component, by contrast, never exists in the client bundle. There is nothing to hydrate, because there is no second execution in the browser. The server has done the calculation, the result is there, and that’s the end of the story for this part of the tree. SSR answers the question “when does the user see something for the first time”. Server Components answer the other question: “does this code ever need to go to the browser at all”. For pure display, the answer is now no.\n\n```mermaid\nflowchart TB\n  subgraph Server\n    SC[\"Server Component<br/>reads data directly\"]\n  end\n  subgraph Browser\n    UI[\"finished result<br/>is displayed\"]\n    Island[\"Client island<br/>(hooks, events)\"]\n  end\n  DB[(\"Database / service\")]\n  SC -->|await| DB\n  SC -->|only the result,<br/>no code| UI\n  SC -.->|embeds| Island\n```\n\n## The boundary is called `\"use client\"`\n\nIf Server Components are the normal case, you need a marker for the exception – for the place where interactivity begins. This marker is the `\"use client\"` directive at the top of a file. Everything above this boundary runs on the server: loading data, displaying it, building structure, no state. From the directive on, you are in browser land with everything that comes with it – `useState`, `useEffect`, event handlers, access to `window`.\n\nWhat matters is the direction in which these two worlds fit together. A Server Component may contain Client Components as children – you sprinkle islands of interactivity into an otherwise static, server-rendered page. The other way around is restricted: a Client Component can’t simply import a Server Component, because the server code would then have to end up in the browser after all. It can only embed a Server Component as a passed-in `children` slot – the server renders the child, the client component receives the finished result and wraps its interactive shell around it. This one rule explains most of the error messages people stumble over at the start.\n\n```mermaid\nflowchart TB\n  Page[\"Server Component (page)<br/>loads data, displays it\"]\n  Page --> List[\"Server Component<br/>invoice list\"]\n  Page --> Button[\"Client island<br/>&quot;use client&quot;: button with onClick\"]\n  Button -->|allowed as children| Slot[\"Server content<br/>as slot\"]\n```\n\n## Server Components in practice\n\nBecause a Server Component only runs on the server, it may do something that never worked in the browser: it may be `async` and use `await` directly in its body. Loading data then happens without `useEffect`, without a loading flag, without the whole apparatus – you write it down as if it were a normal function that just happens to be able to access a database.\n\n```jsx\n// invoices-page.jsx — a Server Component, no \"use client\" here\nimport { db } from \"@/lib/db\";\nimport { PayButton } from \"./pay-button\";\n\nexport default async function InvoicesPage() {\n  const invoices = await db.invoice.findMany({ where: { open: true } });\n\n  return (\n    <section>\n      <h1>Open invoices: {invoices.length}</h1>\n      <ul>\n        {invoices.map((invoice) => (\n          <li key={invoice.id}>\n            {invoice.title} — {invoice.amount} €\n            <PayButton invoiceId={invoice.id} />\n          </li>\n        ))}\n      </ul>\n    </section>\n  );\n}\n```\n\nTwo things deliberately sit side by side here. The `await db.invoice.findMany(...)` accesses the database directly – this code never leaves the server, there is no API route in between and no loading state in the browser. And `PayButton` is an embedded client island: everything that needs a click moves into its own file with `\"use client\"`.\n\n```jsx\n// pay-button.jsx\n\"use client\";\n\nimport { useState } from \"react\";\n\nexport function PayButton({ invoiceId }) {\n  const [busy, setBusy] = useState(false);\n  return (\n    <button disabled={busy} onClick={() => setBusy(true)}>\n      {busy ? \"Paying…\" : \"Pay\"}\n    </button>\n  );\n}\n```\n\nWhat doesn’t work in a Server Component is just as instructive: no `useState`, no `useEffect`. In this environment there is no local client state that you keep across clicks. A Server Component can render again on a later request or a new server execution; but it doesn’t handle direct browser interaction. Everything that should react immediately in the browser to a click belongs in a client island beyond the boundary.\n\n## Server Actions: moving writes back to the server\n\nServer Components solve reading and displaying. For writing, there are Server Functions, often called Server Actions, marked with the `\"use server\"` directive. These are functions that run on the server but are called from the client through the framework’s integration – most directly as the `action` of a `<form>`. In the application, you don’t build your own API route or your own request format for this call. However, transport, serialization and the security boundary are not handled by React as a runtime alone, but by the framework you use.\n\n```jsx\n// invoice-actions.js\n\"use server\";\n\nimport { db } from \"@/lib/db\";\nimport { revalidatePath } from \"next/cache\";\n\nexport async function payInvoice(formData) {\n  const id = formData.get(\"invoiceId\");\n  await db.invoice.update({ where: { id }, data: { open: false } });\n  revalidatePath(\"/invoices\");\n}\n```\n\nIt is called directly from the form. So that the user gets feedback while the action is running, there are two hooks made exactly for this: `useActionState` bundles the call with its result and a pending flag, and `useFormStatus` reads the pending state of the surrounding form in a child element.\n\n```jsx\n// pay-form.jsx\n\"use client\";\n\nimport { useActionState } from \"react\";\nimport { useFormStatus } from \"react-dom\";\nimport { payInvoice } from \"./invoice-actions\";\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus();\n  return (\n    <button type=\"submit\" disabled={pending}>\n      {pending ? \"Paying…\" : \"Pay invoice\"}\n    </button>\n  );\n}\n\nexport function PayForm({ invoiceId }) {\n  const [state, formAction] = useActionState(payInvoice, null);\n  return (\n    <form action={formAction}>\n      <input type=\"hidden\" name=\"invoiceId\" value={invoiceId} />\n      <SubmitButton />\n    </form>\n  );\n}\n```\n\nThe appeal lies in how little is written here. No `fetch`, no manual `POST`, no hand-built endpoint, no serialization. You call a function that happens to run on the server, and the pending state for the UI comes along for free.\n\n```mermaid\nflowchart LR\n  Form[\"Form in the browser<br/>action = payInvoice\"]\n  Form -->|Submit| Action[\"Server Action<br/>&quot;use server&quot;\"]\n  Action -->|writes| DB[(\"Database\")]\n  Action -->|revalidatePath| Fresh[\"Server re-renders<br/>the affected view\"]\n  Fresh -->|new result| Form\n```\n\n## What this means for the series\n\nThis new boundary shifts another one I have already written about. In [Client State vs. Server Cache](https://www.mikebild.dev/en/blog/client-state-vs-server-cache/) the core point was: most of what looks like state is really borrowed server cache that you only keep temporarily in the browser. Server Components shift this boundary once more. A large part of the data loading for display, which used to require a cache library in the browser, now moves to the server – there the Server Component reads directly and sends only the result. The need to track the same data in the client shrinks accordingly.\n\nThat doesn’t mean server state libraries become unnecessary. As soon as things get interactive – data that changes after a click without reloading the whole page – the cache in the browser still makes sense. But the split shifts: less display in the client, more on the server. Staggered delivery is handled by [Suspense](https://www.mikebild.dev/en/blog/suspense-and-the-use-hook/), which streams the server-rendered parts to the browser piece by piece.\n\n## What the shifted boundary does to testing, operations and teams\n\nSo far this sounds like a clean technical reshuffle. It gets interesting, though, where this boundary meets the way a team works, tests and ships. Because an architectural boundary is never just a line of code. It decides where complexity arises – and complexity always comes with a bill.\n\nLet’s start with testability, because that is where it shows most clearly what the shift costs and what it saves. A pure display component that used to load data in the browser was surprisingly laborious to test: mock `fetch`, play through the loading state, reproduce the error path, wait for the re-render after the data arrives. As a Server Component, this whole apparatus disappears. The component is an `async` function that receives data and returns a description – testable like a function, without a browser environment, without timing. The price sits on the other side of the boundary: the direct `await db.invoice.findMany(...)` in the component body weaves data access and presentation together, and the component now wants to see a database for a test. So testing moves rather than disappears: you tend to check Server Components with integration tests against a real or in-memory data source, and the interactive islands still as isolated client tests. If you draw this split deliberately, you win; if you ignore it, you build hard-to-test hybrids.\n\nIn deployment, the character of the application shifts as soon as Server Components run per request or Server Functions write. Client-only React could end up as a bundle of static files behind a CDN; pure Server Components executed at build time can also be delivered statically. The dynamic variant, however, needs a running process with access to the database and internal services. That brings proximity – data access sits right next to the component, without a separate API layer in between – and operational responsibility: server capacity, runtime errors beyond the browser and a boundary between public and internal code that becomes a security boundary. The gain is a shorter chain from click to persistence. The cost is an operational surface that wasn’t there before.\n\nAnd then there is team structure, the point that is easiest to overlook and most expensive to pay for. In the classic split there was a hard seam: frontend builds the UI, backend delivers the API, and in between sits a contract of endpoints and formats. This seam was friction, but also a clear boundary of responsibility. Server Components and Server Actions dissolve it – data access moves into the component, writing into a function next to it, and the contract of API routes disappears. For a team that works across the full depth, this is a noticeable reduction in friction: shorter paths, less coordination about endpoints, less code that only carries data back and forth. For two separate teams with a clean frontend-backend split, it is the opposite: the boundary where they handed over responsibility is gone, and the new one runs right through the middle of the UI. Whether Server Components are a gain or a source of conflict therefore depends less on the technology than on the organization.\n\nThis leads to the decision criteria I apply in projects. Server Components pay off when the team works across the full depth and the frontend-backend seam has so far been more burden than protection, when a running server is part of operations anyway, and when the UI is data-heavy and not very interactive. They cost more than they bring when two teams deliver along a deliberately drawn API boundary, when operations are supposed to stay purely static, or when the application consists almost entirely of interactive islands. So the question is not “is the technology good” but “does the shifted boundary fit how we build, test and ship”.\n\n## An honest assessment: new and with friction\n\nI don’t want to sugarcoat this. Server Components are new, and they come with friction. You have to really understand the boundary between server and client, or you produce exactly the errors I described above – an import across the boundary, a hook on the wrong side, a data access that suddenly is supposed to end up in the browser. The ecosystem is still in flux: the widespread implementation today is the Next.js App Router, other frameworks are catching up, and some libraries first have to learn where they belong in this world.\n\nAnd not every application needs this. A highly interactive dashboard that runs almost entirely in the browser anyway gains little if you force it through the server-client boundary. Where Server Components clearly pay off, on the other hand: for data-heavy, largely static UIs where a lot is displayed and little is clicked; when the client bundle noticeably weighs you down and you want to get rid of display code that has no business being in the browser; and where server-delivered HTML matters for search engines and the first impression. That is an honest trade-off, not an obligation.\n\n## The real decision\n\nIf one thought from this post should stick, it is this one: Server Components are not a faster way to render. They are a decision about location. For every part of the UI, you now ask first: does this stay on the server – because it only reads and displays – or does it belong in the browser because a human interacts with it? The `\"use client\"` and `\"use server\"` directives are nothing more than the visible markers of this one decision.\n\nIf you draw the boundary deliberately, you reap the effect that lies beneath the technology: shorter paths from data access to display and therefore faster cycles, less friction at the dissolved frontend-backend seam, and testability that splits cleanly into server-side integration tests and client islands. If you blur the boundary, you get the opposite – hard-to-test hybrids, unclear responsibilities, operational load without a return. The difference doesn’t lie in the framework. It lies in whether the shifted boundary fits how a team builds, tests and ships – and whether you keep it clear enough afterwards to defend it. This question is what matters – long before you look up the first hook.\n\n## Further reading\n\n- Repository introduction-react (chapters server-components, server-actions; App Router examples): https://github.com/mikebild/introduction-react\n- React, “Server Components”: https://react.dev/reference/rsc/server-components\n- React, “Server Functions”: https://react.dev/reference/rsc/server-functions\n- Next.js, App Router: https://nextjs.org/docs/app"},{"locale":"en","translation_key":"react-router-data-router","slug":"react-router-data-router-the-url-as-state","title":"React Router Data Router: The URL as the Place for State","summary":"The data router in React Router makes the URL the point of coordination – a route loads its data via loader before rendering and writes via action, so loading logic disappears from the component body.","tags":["Software","Frontend","React"],"published_at":"2024-12-16T10:00:00+00:00","updated_at":"2026-07-13T13:23:13.585129+00:00","url":"https://www.mikebild.dev/en/blog/react-router-data-router-the-url-as-state/","audio_url":null,"audio_duration_secs":null,"text":"# React Router Data Router: The URL as the Place for State\n\nIn the data router of React Router, a route is no longer a mapping from path to component. It is a complete description of everything that belongs to an address: which part of the UI appears, where its data comes from, what happens on a write, what you see when something fails. These descriptions are objects, and because they exist before the first render, the router can read from them what to do for a URL – without running a single component.\n\nHow far this goes becomes clear when you compare it with the pattern the classic approach suggests: a route renders a component, the component has a `useEffect`, the effect loads the data, and next to it sit three `useState` calls for loading state, error and result. For one page, that works. For twenty nested pages, you get loading waterfalls: the outer component renders, its effect loads, only then does the inner one render, and its effect loads – one after the other, even though both were known from the start. In the React overview, I still showed routing with `BrowserRouter` and `Routes` and deliberately left the modern approach aside; it is the subject of this post. The data router reverses the order.\n\n**Editorial note (July 2026):** React Router 8 distinguishes three modes: Declarative, Data and Framework. This post covers Data Mode with `createBrowserRouter`. Framework Mode builds on it and adds, among other things, typed route modules, code splitting and optional SPA, SSR and static rendering strategies.\n\n## The core idea: the route loads before it renders\n\nThe key difference fits into one sentence. With the old approach, the component renders first and then loads its data. With the data router, the route loads its data first and then renders the component – with the data already in hand. For this, every route gets a function, the `loader`. It runs during navigation, before anything appears on the screen. Only when it’s done does React render the component, which picks up the data fully loaded instead of fetching it itself.\n\nThis removes the loading logic from the component body. No more `useEffect` that loads on first render, no handful of `useState` calls for a state that, strictly speaking, should never exist – because by the time the component renders, the data is long there. The writing counterpart is called `action`. It receives form submissions, writes to the server, and afterward React Router reloads the affected `loader`s on its own so that the view is correct again.\n\n## `createBrowserRouter` and the route objects\n\nYou no longer describe the application as nested JSX elements but as objects. `createBrowserRouter` takes an array of route definitions, and each definition carries its building blocks in one place: the path, the component, the `loader`, the `action`, the error element.\n\n```jsx\nimport { createBrowserRouter } from \"react-router\";\nimport { RouterProvider } from \"react-router/dom\";\n\nconst router = createBrowserRouter([\n  {\n    path: \"/invoices\",\n    element: <InvoiceList />,\n    loader: invoiceListLoader,\n    errorElement: <RouteError />,\n    children: [\n      {\n        path: \":invoiceId\",\n        element: <InvoiceDetail />,\n        loader: invoiceDetailLoader,\n        action: invoiceDetailAction,\n      },\n    ],\n  },\n]);\n\nfunction App() {\n  return <RouterProvider router={router} />;\n}\n```\n\nInstead of hunting for `path` and `element` scattered across half the application, everything that makes up a route sits together: what it shows, where its data comes from, how it responds to writes, what happens on an error. This bundling is not a cosmetic advantage. It is the prerequisite for React Router knowing the data before rendering – because the router can read from the object tree which `loader`s are responsible for a URL without rendering the components first.\n\n## The `loader`: fetch data before rendering\n\nA `loader` is an ordinary function. Among other things, it receives the parameters from the path, fetches the data and returns it. In the component, you pick it up with `useLoaderData()`.\n\n```jsx\nimport { useLoaderData } from \"react-router\";\n\nasync function invoiceDetailLoader({ params }) {\n  const response = await fetch(`/api/invoices/${params.invoiceId}`);\n  if (!response.ok) {\n    throw new Response(\"Not found\", { status: 404 });\n  }\n  return response.json();\n}\n\nfunction InvoiceDetail() {\n  const invoice = useLoaderData();\n  return <h1>Invoice {invoice.number}</h1>;\n}\n```\n\nNote what isn’t here. No `useState` for the invoice, no `useEffect` for loading, no check for `null` while loading is still in progress. When `InvoiceDetail` renders, the `loader` has finished. Whether `invoice` exists in domain terms is something the loader itself has to guarantee – for example by throwing a 404 response on an empty result. The router’s waiting doesn’t replace this validation.\n\nThe real gain shows with nested routes. If someone opens `/invoices/42`, two routes are involved: the list and the detail. With the `useEffect` approach, this would run sequentially – first the list renders and loads, then the detail renders and loads. React Router knows both `loader`s in advance and starts them **in parallel**. That eliminates the waterfall: all affected `loader`s start at the same time, and the page is ready as soon as the slowest one is through.\n\n```mermaid\nflowchart TB\n  Nav[\"Navigation to /invoices/42\"]\n  Nav --> Match[\"Router determines affected routes\"]\n  Match --> L1[\"loader list\"]\n  Match --> L2[\"loader detail\"]\n  L1 --> Ready[\"all loaders done\"]\n  L2 --> Ready\n  Ready --> Render[\"Components render<br/>with useLoaderData\"]\n```\n\nHere the connection to the server cache is worth making. In the post on [client state and server cache](https://www.mikebild.dev/en/blog/client-state-vs-server-cache/), I showed that server data is not state you own but a copy you manage – with a key, an age and invalidation, which is what a library like TanStack Query is good for. The `loader` sits one level above that. It says *when* to load, namely during navigation, tied to the route instead of the component. Whether there’s a bare `fetch` or a cache behind it is unaffected. The two complement each other cleanly: the `loader` calls the `queryClient`, and the library decides whether it holds a fresh copy or really reloads. The router determines the timing, the cache the validity – they don’t exclude each other, they mesh.\n\n## The `action`: writing via `<Form>`\n\nFor writes, React Router provides its own component. `<Form method=\"post\">` looks like an ordinary HTML form but is intercepted by the router: instead of reloading the page, it calls the `action` of the matching route and passes it the form data.\n\n```jsx\nimport { Form, redirect } from \"react-router\";\n\nasync function invoiceDetailAction({ request, params }) {\n  const formData = await request.formData();\n  await fetch(`/api/invoices/${params.invoiceId}/pay`, {\n    method: \"POST\",\n    body: formData,\n  });\n  return redirect(`/invoices/${params.invoiceId}`);\n}\n\nfunction InvoiceDetail() {\n  const invoice = useLoaderData();\n  return (\n    <Form method=\"post\">\n      <button type=\"submit\">Mark as paid</button>\n    </Form>\n  );\n}\n```\n\nThe decisive part happens after the `action`: by default, React Router revalidates the loaders of the active routes. The invoice has been paid, the `action` is through, and the view can show the fresh state because the affected loaders ran again. You can restrict this behavior with `shouldRevalidate`; external caches still have to be invalidated appropriately. The flow resembles the browser principle of “submit the form, fetch the page again,” just without rebuilding the whole document.\n\n```mermaid\nflowchart LR\n  F[\"Form method=post\"] --> A[\"action writes<br/>to the server\"]\n  A --> R[\"loaders are<br/>revalidated\"]\n  R --> U[\"View shows<br/>fresh state\"]\n```\n\nIf you compare this with the `useEffect` dashboard from the server cache post, you’ll recognize the same illness and a different medicine. There, the number at the top and the list next to it drifted apart because nobody made sure both reloaded after paying. Here, they reload together after the `action`, because revalidation affects all `loader`s of the active route levels and not a single component.\n\n## Nested routes and `<Outlet />`\n\nThe objects from the first example had `children`, and that’s more than a matter of organization. Nested routes mirror the UI hierarchy: an outer layout route renders the frame – navigation, header, sidebar – and where the inner route should appear, it places an `<Outlet />`.\n\n```jsx\nimport { Outlet, NavLink } from \"react-router\";\n\nfunction InvoiceList() {\n  const invoices = useLoaderData();\n  return (\n    <div className=\"layout\">\n      <nav>\n        {invoices.map((invoice) => (\n          <NavLink key={invoice.id} to={`/invoices/${invoice.id}`}>\n            {invoice.number}\n          </NavLink>\n        ))}\n      </nav>\n      <main>\n        <Outlet />\n      </main>\n    </div>\n  );\n}\n```\n\nIf you navigate in Data Mode from `/invoices/42` to `/invoices/43`, the outer route, whose own parameters haven’t changed, stays in place by default; its loader doesn’t run again in this example, and only the inner route switches its data and its content in the `<Outlet />`. Changed search parameters or a custom `shouldRevalidate` rule can trigger a broader revalidation. The URL then reads like a path through the tree of the UI: every segment stands for a level, every level for a route, every route for a piece of UI with its own data. A layout route without any `path`, by the way, can serve purely as the shared frame while its children carry the actual addresses.\n\n## The URL as state: search parameters\n\nSo far it was about the path. The second part of the URL is at least as useful: the search parameters after the `?`. In the React overview, I argued that selection and filters belong in the URL – and `useSearchParams` is the tool for that. It feels like `useState` but writes its value into the address bar.\n\n```jsx\nimport { useSearchParams } from \"react-router\";\n\nfunction InvoiceFilter() {\n  const [searchParams, setSearchParams] = useSearchParams();\n  const status = searchParams.get(\"status\") ?? \"all\";\n\n  return (\n    <select\n      value={status}\n      onChange={(event) =>\n        setSearchParams({ status: event.target.value })\n      }\n    >\n      <option value=\"all\">All</option>\n      <option value=\"open\">Open</option>\n      <option value=\"paid\">Paid</option>\n    </select>\n  );\n}\n```\n\nThe selected filter is now in the URL – `/invoices?status=open` – and that fundamentally changes its character. This state can be shared: you send the link, and the recipient sees the same filtered list. It can be saved as a bookmark. It survives a reload because it doesn’t live in component memory but in the address. And it can be connected to the `loader`: since the `loader` has access to the `request` URL, it can read the `status` parameter and fetch the correctly filtered list from the server right away. The filter is in the URL, the `loader` reads it, the server delivers – a piece of UI state becomes a navigable place.\n\n## Errors and slow partial data\n\nBecause the `loader` runs before rendering, failure needs a place of its own. If a `loader` or an `action` throws – such as the `throw new Response(..., { status: 404 })` from above – React Router looks for the nearest route with an `errorElement` and renders it instead of the component. Inside the error element, you get at what was thrown with `useRouteError()`.\n\n```jsx\nimport { useRouteError } from \"react-router\";\n\nfunction RouteError() {\n  const error = useRouteError();\n  return <p role=\"alert\">Something went wrong: {error.status}</p>;\n}\n```\n\nThis replaces many scattered `if (error)` branches with one place at the route level. The route error boundary handles not only errors from `loader` and `action` but also render errors in its branch of routes. The application should still model expected domain errors deliberately instead of treating every negative state as an exception.\n\nOne side topic, only touched on here: sometimes the page shouldn’t wait for the slowest data source. React Router 8 removed the former `defer` helper. Today, a loader returns non-critical data as a not-yet-resolved promise; in the component, `<Await>` waits for it inside a `<Suspense>` boundary. Critical data is still `await`ed in the loader. That way, a sluggish part doesn’t block the whole view, without needing a special `defer` response.\n\n## A word on the three modes\n\nWhat I’ve shown here is called Data Mode in the current documentation: `createBrowserRouter` in an existing application. Declarative Mode with `BrowserRouter` offers classic routing without the data APIs. Framework Mode builds on Data Mode, organizes routes as modules and adds build and server functions. That’s a separate, bigger topic, and I deliberately leave it aside here. The concepts that matter – `loader`, `action`, revalidation, the URL as the place for state – stay the same in Data and Framework Mode.\n\n## Where the data belongs\n\nThe common thread of this post is a single shift. In the classic approach, loading and writing hang off the component: it renders, its effect fetches, its handlers write, and with nesting the loads line up into a waterfall. The data router anchors both at the route. The `loader` fetches the data before rendering, and neighboring levels in parallel; the `action` writes and then lets the `loader`s revalidate on their own. What remains in the component is displaying – not fetching.\n\nThis finally turns the URL into what the overview only claimed it was. It is no longer the address field that shows where you are. It is the place where navigable state really lives: the path determines which routes and therefore which data get loaded, the search parameters carry filters and selection, and together they can be shared, saved and survive every reload. Once you build this way, you’re happy to move the loading logic out of the component body.\n\n## Further reading\n\n- Repository introduction-react (routing chapter, recipes folder on data fetching): https://github.com/mikebild/introduction-react\n- React Router, official documentation: https://reactrouter.com/\n- React Router, “Picking a Mode”: https://reactrouter.com/start/modes\n- React Router, “Data Loading”: https://reactrouter.com/start/data/data-loading\n- React Router, “Actions”: https://reactrouter.com/start/data/actions"},{"locale":"en","translation_key":"react-transitions-mit-usetransition","slug":"react-transitions-with-usetransition","title":"React Transitions: Non-Urgent Updates with useTransition","summary":"useTransition marks updates as non-urgent and keeps React responsive during expensive or suspending renders. Plus useDeferredValue as the tool for downstream renders.","tags":["Software","Frontend","React"],"published_at":"2024-12-13T10:00:00+00:00","updated_at":"2026-07-13T13:31:04.873406+00:00","url":"https://www.mikebild.dev/en/blog/react-transitions-with-usetransition/","audio_url":null,"audio_duration_secs":null,"text":"A React UI needs two priorities: one for what has to happen immediately and one for what can wait. React’s scheduler knows different priorities, but an ordinary state update is initially treated as a direct update. Only with a transition does the application explicitly mark the subsequent rendering work as non-blocking.\n\nThis becomes clearest at a point that already came up in the [post on Suspense and the use Hook](https://www.mikebild.dev/en/blog/suspense-and-the-use-hook/): the hard jump back to the fallback. The area is still showing real content, the state changes, the data is gone – and the spinner appears. That is exactly how a colleague’s question came up in a project: “The content is inside a Suspense boundary. When the state changes, the fallback kicks in. What are we supposed to do about that?” You tell React that this one update isn’t urgent. That is what `useTransition` is for.\n\n## Urgent or non-urgent – the only distinction that counts\n\nThe dividing line runs between two kinds of updates. On one side are the urgent ones: I type a letter, and the character has to appear in the input field immediately. I check a checkbox, and it has to be checked immediately. Anything that should feel like a direct physical reaction is urgent. If React delays it by even 100 milliseconds, the app feels broken.\n\nOn the other side are the non-urgent updates: I switch tabs, I change the filter of a large list, I change the search query. The result of this action may take a moment. Nobody expects 10,000 newly filtered rows to appear in zero milliseconds. But what everyone does expect: that the UI doesn’t freeze in the meantime and doesn’t flicker pointlessly.\n\nReact can’t infer from the name of a state value which domain reaction may wait. With the concurrent features, which have been stably available since React 18 and the switch to `createRoot`, we get the tools to communicate this intent. `useTransition` is the most important of them.\n\n## The signature is deliberately simple\n\n```jsx\nimport { useTransition } from 'react';\n\nfunction TabContainer() {\n  const [isPending, startTransition] = useTransition();\n  const [tab, setTab] = useState('overview');\n\n  function selectTab(nextTab) {\n    startTransition(() => {\n      setTab(nextTab);\n    });\n  }\n\n  return (\n    <>\n      <TabButton active={tab === 'overview'} onClick={() => selectTab('overview')}>\n        Overview\n      </TabButton>\n      <TabButton active={tab === 'reports'} onClick={() => selectTab('reports')}>\n        Reports\n      </TabButton>\n      <section style={{ opacity: isPending ? 0.6 : 1 }}>\n        <TabPanel tab={tab} />\n      </section>\n    </>\n  );\n}\n```\n\nThe hook takes no parameters and returns a two-tuple: `isPending`, a Boolean, and `startTransition`, a function. Like any hook, you may only call it in a component or a custom hook.\n\nThe crucial part is in `selectTab`. The `setTab` call moves into the `startTransition` callback. With that, the component tells React: “This update is a transition.” If the new panel suspends inside a Suspense boundary that is already visible, React can leave the previous content in place instead of immediately replacing it with the fallback. Newly added Suspense boundaries, on the other hand, may still show their fallback. As long as the transition is running, `isPending` is `true`. In my example, that is exactly what the subtle graying out via `opacity` hangs on.\n\nThis is the concrete fulfillment of the Suspense promise: an update inside `startTransition` prevents content that is already visible from jumping back to the fallback.\n\n## What really happens in the background\n\n“React takes care of it” isn’t enough of an explanation, so here is the flow explicitly as a diagram. The important part is the branch at the end: a transition is interruptible.\n\n```mermaid\nflowchart TD\n    A[User clicks tab] --> B[setTab runs in<br/>startTransition]\n    B --> C[React renders new tab<br/>in the background]\n    C --> D[Old UI stays visible<br/>isPending = true]\n    D --> E{New data /<br/>render done?}\n    E -->|yes| F[Switch to the new UI<br/>isPending = false]\n    E -->|urgent update<br/>comes in| G[Background render is<br/>discarded and restarted]\n    G --> C\n```\n\nThe left path is the normal case: React renders in the background, keeps the old UI, shows `isPending`, and switches at the end. The right path is the reason the app stays responsive during expensive updates at all. If a more urgent update comes in during the background render – a keystroke, for example – React discards the half-finished work and starts over. You don’t have to wait until the expensive render is done before you can type again. This interruptibility is the real trick behind the word “concurrent.”\n\n## startTransition without a component\n\nNot every state change originates in a component. In routers and stores, the triggering logic often sits outside the component tree. For this case, there is the standalone import:\n\n```jsx\nimport { startTransition } from 'react';\n\nfunction navigate(url) {\n  startTransition(() => {\n    setCurrentUrl(url);\n  });\n}\n```\n\nThis variant works everywhere but has a price: it doesn’t provide `isPending`. If you want to show the loading state, you need the hook. If you only want to mark an update as non-urgent and get the pending state from somewhere else, the standalone import serves you well. I use it deliberately in router callbacks, where the navigation indicator lives somewhere else anyway.\n\nBy the way, since React 19, stable since December 2024, `startTransition` also accepts async functions; the new Actions and `<form action>` build on this internally. That is a topic of its own – all that matters here is that the transition mechanism itself is the foundation underneath.\n\n## The classic mistake: freezing the input field\n\nIn code reviews, the same obvious mistake shows up at this point again and again. If a transition defuses expensive renders, why not simply wrap every update – including the search field’s?\n\n```jsx\n// Do NOT do this\nfunction onChange(e) {\n  startTransition(() => {\n    setText(e.target.value);\n  });\n}\n```\n\nThe result is a sluggish, mushy input field. The reason: text in the input is an urgent update. It feels directly physical; every letter has to appear immediately. If you put it in a transition, React may delay and interrupt it – and it does. So controlled inputs stay urgent, and the text state is set as usual. What is expensive isn’t the typing but what follows from the text – the filtered list. And there is a separate tool for that.\n\n## useDeferredValue: when part of the display may lag behind\n\n`useTransition` marks state updates at the place that triggers them. `useDeferredValue` takes a different approach: the current value stays urgent and visible, while an expensive consumer may temporarily keep working with the previous version. That is useful for props, but just as much for local input state whose derived list should catch up more slowly.\n\n```jsx\nimport { useDeferredValue, useState } from 'react';\n\nfunction SearchPage() {\n  const [query, setQuery] = useState('');\n  const deferredQuery = useDeferredValue(query);\n  const isStale = query !== deferredQuery;\n\n  return (\n    <>\n      <input value={query} onChange={(e) => setQuery(e.target.value)} />\n      <div style={{ opacity: isStale ? 0.5 : 1 }}>\n        <SlowList query={deferredQuery} />\n      </div>\n    </>\n  );\n}\n```\n\nHere, the input field stays urgent: `setQuery` runs without any transition, and every letter appears immediately. But the expensive `SlowList` doesn’t get `query`; it gets `deferredQuery`. React first keeps rendering with the old value – the list stays put for a moment – and then re-renders with the new value in the background. The comparison `query !== deferredQuery` tells me whether the list is currently stale, and I gray it out subtly in the meantime.\n\nSince React 19, the signature takes an optional second argument: `useDeferredValue(value, initialValue)`. Without `initialValue`, nothing is deferred on the very first render; if you provide it, the first pass renders with this initial value and pushes the real value into the background. For everyday use, the single-argument form is almost always enough.\n\nOne point that leads to misunderstandings again and again: `useDeferredValue` is not a debounce and not a throttle. There is no fixed delay, and it doesn’t prevent network requests. It is pure render prioritization. If you trigger a fetch on every keystroke, you have the same storm of fetches with `useDeferredValue` as before – only the rendering of the results is spread out. Debouncing the request remains a separate task.\n\n## The second classic: the lost context after await\n\nAs soon as async functions come into play, almost everyone falls into the same trap:\n\n```jsx\n// The transition context is lost after the await\nstartTransition(async () => {\n  const data = await fetchPage(url);\n  setPage(data); // no longer part of the transition\n});\n```\n\nThe `setPage` after the `await` no longer runs inside the transition. React tracks the transition context synchronously; after an `await`, the original call returned long ago. The fix is unspectacular: wrap the update after the `await` again.\n\n```jsx\nstartTransition(async () => {\n  const data = await fetchPage(url);\n  startTransition(() => {\n    setPage(data);\n  });\n});\n```\n\nA related stumbling block: a `set` call that happens from inside a `setTimeout` isn’t marked as a transition either, even if the `setTimeout` is inside `startTransition`. The callback only runs later, outside the synchronous window. `startTransition` expects a synchronous update; anything pushed into a later tick falls out of the transition context.\n\n## Which tool when – the decision tree\n\nWhether `useTransition` or `useDeferredValue` applies depends on what may be delayed: the state transition itself or just a downstream part of the display.\n\n```mermaid\nflowchart TD\n    A[Expensive update must not<br/>block interaction] --> B{May the transition<br/>itself wait?}\n    B -->|yes| C[useTransition /<br/>startTransition]\n    B -->|no, only the consumer| D[useDeferredValue]\n    C --> E[Update is marked<br/>isPending available]\n    D --> F[Current value applies immediately<br/>consumer catches up]\n    E --> G[Both: old UI stays in place<br/>instead of fallback]\n    F --> G\n```\n\nSo the dividing line isn’t “which one is more modern” but simply the question of control. To condense it, here are the two tools side by side:\n\n- `useTransition` / `startTransition`: I control an update whose visible result may wait. I want to avoid the hard jump back to the fallback, and with the hook I also need `isPending`. Typical: a tab switch or a non-urgent navigation.\n- `useDeferredValue`: the current value must apply immediately, but an expensive consumer may still see the previous version for a moment. There is no pending flag, but there is the comparison `value !== deferredValue` to gray out stale displays. Typical: the large derived list under a fast input field.\n\nWhat both have in common is that less urgent rendering work may take a back seat to a direct interaction. With a Suspense boundary that is already visible, the existing content can stay in place as a result. The difference lies in whether the triggering update or a value for downstream consumers is delayed; only `useTransition` provides `isPending`.\n\n## What I recommend in practice\n\nA few guardrails that have proven themselves in projects:\n\n- State that drives a controlled text field stays urgent and must not go into a transition. For other direct inputs, I check which part has to react immediately and which follow-up work can wait.\n- Navigation and tab switches can belong in `startTransition` if their target suspends or renders expensively. Routers may already handle this coordination themselves.\n- For expensive derived renders under a fast input, `useDeferredValue` is the tool, because the current input value should stay visible immediately and only the list catches up.\n- `isPending` and `value !== deferredValue` indicate that something is currently stale. I use them for subtle graying out instead of a full-page spinner. After all, the whole point is that the content doesn’t disappear.\n- The loss of context after `await` and in `setTimeout` is treacherous. If an update stubbornly behaves as urgent even though it is inside a transition, that is almost always the cause.\n\nIf you want to place the concurrent features in a broader context, you will find the bigger picture in my React overview from JSX to architecture. The key point for today stays narrow: React can’t know which domain reaction has to be visible immediately and which rendering work can wait. `useTransition` and `useDeferredValue` express this intent in different places. With expensive renders, this can keep the UI responsive; with Suspense content that is already visible, it lets you avoid an unnecessary jump back to the fallback.\n\n## Further reading\n\n- Repository: the examples for the tab switch with `useTransition`, the `useDeferredValue` search field, and the standalone `startTransition` are available as a runnable repo.\n- [react.dev – useTransition](https://react.dev/reference/react/useTransition)\n- [react.dev – startTransition](https://react.dev/reference/react/startTransition)\n- [react.dev – useDeferredValue](https://react.dev/reference/react/useDeferredValue)\n- [react.dev – Suspense](https://react.dev/reference/react/Suspense)\n- [React 19 release (Actions and transition context)](https://react.dev/blog/2024/12/05/react-19)"},{"locale":"en","translation_key":"react-testing-ohne-theater","slug":"react-testing-without-theater","title":"React Testing Without Theater","summary":"Tests tied to visible user behavior are less coupled to DOM structure, component boundaries and internal state. As a result, they survive certain refactorings without changes.","tags":["Software","Testing"],"published_at":"2024-12-12T10:00:00+00:00","updated_at":"2026-07-13T08:56:25.034215+00:00","url":"https://www.mikebild.dev/en/blog/react-testing-without-theater/","audio_url":null,"audio_duration_secs":null,"text":"# React Testing Without Theater\n\nA green test doesn’t prove that the application works. At first, it only proves that the code still looks the way it did on the day the test was written. React suites like to blur exactly this difference: every component is surrounded by mocks, every assertion knows the hook, the state, the name of the internal function. Such tests turn red in droves at the first refactoring, even though the application still works unchanged from a domain point of view – expensive to maintain and saying nothing about the product. That is the theater in the title: lots of stage, little substance.\n\nThe occasion for this post is mundane: a small Vite React app from the `introduction-react` repo, a single test, one visible line in the UI. What’s interesting is not the line but the boundary it draws – between what a user experiences and how I built it internally. This boundary is the real architectural decision in testing. If you draw it cleanly, you get tests that survive rebuilds. If you miss it, you get a suite that has to be maintained every sprint and still doesn’t catch a regression.\n\n## The thesis: behavior beats implementation\n\nA test has exactly two jobs. It should catch real misbehavior before it reaches the user. And it shouldn’t stop me from restructuring the code. These two goals are in tension, and the resolution is: test what the user observes, not how the component achieves it internally.\n\nThe difference becomes visible in two variants of the same test. First, the brittle variant that couples to the internals:\n\n```tsx\n// Brittle: couples the test to internal state and structure\ntest(\"increments the count state\", () => {\n  const { result } = renderHook(() => useCounter());\n\n  act(() => result.current.increment());\n\n  expect(result.current.count).toBe(1);\n});\n```\n\nThis test knows the hook, its return value and that “increment” is called that. As soon as I replace `useCounter` with a reducer, a store or a completely different mechanism, it breaks – even though the counter in the browser keeps doing what it should. The test measures my implementation, not the product.\n\nNow the same assertion via observable behavior:\n\n```tsx\n// Robust: asserts what the user actually sees\ntest(\"shows the new count after a click\", async () => {\n  const user = userEvent.setup();\n  render(<Counter />);\n\n  await user.click(screen.getByRole(\"button\", { name: /increment/i }));\n\n  expect(screen.getByRole(\"status\")).toHaveTextContent(\"Count: 1\");\n});\n```\n\nThis test knows nothing about hooks, state or structure. It knows that there is a button you click, and that a number appears afterwards. That is exactly the contract with the user. I can swap out all the internals, and as long as this contract holds, the test stays green. This is the point at which a test turns from a brake on restructuring into a safety net.\n\n## Where the boundary physically runs\n\nThis boundary is not an attitude; it is built into the query design of Testing Library. The order of the queries is a statement about trade-offs: `getByRole` and `getByLabelText` first, `getByText` after that, `getByTestId` as a last resort. That isn’t a matter of style. A role query checks accessibility along the way – if the test finds the element by its role, a screen reader finds it too. A `data-testid` only checks that I stuck a label on myself.\n\n```tsx\n// Prefer accessible queries – they double as an a11y assertion\nscreen.getByRole(\"searchbox\");\nscreen.getByRole(\"button\", { name: /search/i });\n\n// testid is an escape hatch, not the default\nscreen.getByTestId(\"product-list\");\n```\n\nThe practical consequence: I write components so that they can be addressed through roles and labels – semantic elements, `aria-label` where needed, real `<button>` instead of clicked `<div>`. The test forces me into accessible markup, because inaccessible markup is simply hard to test. That’s the kind of coupling I want: testability and product quality pull in the same direction.\n\nSo the `testid` isn’t forbidden; it just needs a justification. It is legitimate when a container has no meaningful role – a layout wrapper, a chart canvas, a list without a semantic counterpart. Then a deliberately set `data-testid` is more honest than a forced role that doesn’t even exist in the product. The difference is the order: I reach for the `testid` because the accessible query doesn’t fit, not because it was too cumbersome for me. This order is the entire methodical substance of the query priorities – it makes the exception visible instead of letting it become the rule.\n\n## The failure path is half the work\n\nThe happy path looks clean in demo mode. You earn your money with the rest: empty response, timeout, 500 errors, a double click, a slow connection. In React applications, this rest almost always sits at the network boundary, and that’s exactly where I put the mock – not on the hook, not on the `fetch` call, but at the HTTP layer. With Mock Service Worker, the component runs through its real data logic; only the response is controlled.\n\n```tsx\n// The happy path: results the API returned actually render\ntest(\"renders products returned by the API\", async () => {\n  const user = userEvent.setup();\n  render(<ProductSearch />);\n\n  await user.type(screen.getByRole(\"searchbox\"), \"react\");\n  await user.click(screen.getByRole(\"button\", { name: /search/i }));\n\n  expect(await screen.findByRole(\"listitem\"))\n    .toHaveTextContent(\"React Handbook\");\n});\n```\n\nAnd the flip side, which makes the difference in production:\n\n```tsx\n// The failure path: does the UI degrade gracefully?\ntest(\"shows an error message when the request fails\", async () => {\n  server.use(\n    http.get(\"/api/products\", () => HttpResponse.error()),\n  );\n\n  const user = userEvent.setup();\n  render(<ProductSearch />);\n\n  await user.click(screen.getByRole(\"button\", { name: /search/i }));\n\n  expect(await screen.findByRole(\"alert\"))\n    .toHaveTextContent(/something went wrong/i);\n});\n```\n\nThe second test is more important than the first. It describes what happens when the backend goes away – whether the app shows an error message or falls into an empty, confusing state. That I set the mock per test via `server.use` is intentional: the default is the happy path, and the disruption is an explicit, readable deviation. If you don’t test the failure path, you haven’t tested half the product. The user experiences both.\n\nAsync discipline is part of the failure path too. `findBy*` waits for an element to appear, `waitFor` for a condition to hold – but only for observable states, not for guessed `setTimeout` values. If you build in fixed wait times instead, you trade flakiness for slowness and end up keeping both.\n\n## Specification by Example: tests that speak the domain language\n\nThe most stable test names a domain intent, not a technical sequence. A test name like “calls dispatch with INCREMENT” describes mechanics and ages with every rename. “shows the new count after a click” describes a promise to the user and only ages when the promise changes. That is the core of Specification by Example: the example is domain documentation, expectation and automatable check at the same time – three things that otherwise drift apart.\n\nIn practice, this means I write the `describe` and `test` blocks so that a product owner could read and confirm them without knowing the code:\n\n```tsx\ndescribe(\"Product search\", () => {\n  test(\"shows results matching the query\", async () => { /* ... */ });\n  test(\"shows an empty state when nothing matches\", async () => { /* ... */ });\n  test(\"shows an error when the service is unavailable\", async () => { /* ... */ });\n});\n```\n\nThis suite is a specification. It says what the feature can do and what it does when something goes wrong. A reviewer sees immediately whether a case is missing – the empty state, the error case – and can object on domain grounds without reading the implementation. This is exactly where the methodical lever lies: misunderstandings become visible in the test, not only in production. That moves the expensive clarification from the end of the chain to the beginning.\n\n## The architecture of the suite: layers instead of mass\n\nNot every test costs the same or delivers the same. A sustainable React suite is layered. Pure logic – formatting, validation, reducers – I check with fast unit tests without a DOM. The behavior of the components I check with component tests with a mocked network boundary; that’s the layer in which I invest the most trust and the most time. And I keep a small number of real integration runs that play through the actual interplay of the parts once instead of simulating it.\n\n```mermaid\nflowchart TD\n  A[User intent<br/>Specification by Example] --> B[Component tests<br/>role and label queries]\n  B --> C[Network boundary<br/>mocked with MSW]\n  C --> D[Few integration runs<br/>real wiring]\n  D --> E[Refactor<br/>tests stay green]\n  E --> A\n```\n\nThe distribution is a deliberate investment decision, not dogma. Many slow end-to-end tests give you a warm feeling and a cold pipeline: they are slow, flaky and expensive to maintain, and when they turn red, nobody knows right away why. A few targeted integration runs plus a dense, fast component layer catch more real bugs per minute invested. The test run belongs in the developer’s fast feedback loop, not only in the nightly CI – hence Vitest and jsdom instead of a real browser, wherever the statement allows it.\n\n## Why it pays off\n\nTesting is not an end in itself and not a way to soothe your conscience; it is an investment with a measurable return. The yield is speed of change. A suite that couples to behavior allows refactoring without fear: I turn `useCounter` into a store, the tests stay green, and I know the contract holds. A suite that couples to implementation turns every refactoring into a second project – first restructure the code, then update dozens of tests. The second kind leads teams to postpone restructuring. That’s how technical debt arises not despite the tests but because of them.\n\nThe concrete advantage lies in lower coupling. If a test accesses the UI through role, label and visible result, I can split components, move internal state or rearrange the markup as long as the observable behavior stays the same. Whether reviews get shorter or the regression rate drops, on the other hand, depends on the suite, the run time and the failure paths actually checked.\n\n## Typical mistakes\n\nThe first mistake is confusing the tool with the solution. Testing Library doesn’t produce good tests; it only makes bad ones harder. You can still stick to `testid`s with it, inspect state through detours and cut the network boundary at the wrong point. The tool expresses a boundary; it doesn’t draw it.\n\nThe second mistake is confusing coverage with safety. Ninety percent line coverage says nothing about whether the failure path is checked. A suite that covers every happy path and no failure case has high numbers and low value. I’d rather count failure cases than lines.\n\nThe third mistake is mocking everything. If you mock the hook, mock the store and mock the child component, in the end you are only testing the mocks. The deeper the mock sits, the less real behavior runs through the test. The network boundary is almost always the right cut – behind it begins someone else’s code, in front of it lies my product.\n\n## How I check a test\n\nBefore a test is allowed into the suite, I ask it three questions. Would it turn red if the feature broke from a domain point of view? If not, it checks nothing. Does it stay green if I restructure the implementation without changing the behavior? If not, it’s a brake on restructuring. And does its name describe a user intent that a domain expert could confirm? If not, it ages with the next rename.\n\nA test that passes all three questions is cheap to maintain and expensive only once – when it’s written. A test that fails one of them gets paid for again every sprint. Over the lifetime of a project, this difference decides whether the suite creates trust or a maintenance burden.\n\n## Further reading\n\n- Workshop repo introduction-react: https://github.com/MikeBild/introduction-react\n\nThe repo shows the small Vite React app and the test examples in the context of a complete learning curve from building block to architecture. The docs of Testing Library and Vitest help you cross-check query priorities and async behavior – but the real point remains the decision of where, in the concrete example, the boundary between behavior and implementation runs.\n\n## Conclusion\n\nReact testing becomes valuable when tests answer a question the user cares about: does the application do what it should, even when something goes wrong? A test that simulates a click and checks a visible result stays stable through internal restructuring as long as the domain case stays the same. That is the solid advantage; speed or error rate have to prove themselves in the project."},{"locale":"en","translation_key":"react-suspense-und-use","slug":"suspense-and-the-use-hook","title":"Suspense and the use Hook: Rendering as If the Data Were Already There","summary":"Instead of managing a loading state in every component, Suspense lets you describe in a single place in the tree what appears while waiting – and the use hook lets the component below render as if the data had long arrived.","tags":["Software","Frontend","React"],"published_at":"2024-12-10T10:00:00+00:00","updated_at":"2026-07-13T08:03:33.68271+00:00","url":"https://www.mikebild.dev/en/blog/suspense-and-the-use-hook/","audio_url":null,"audio_duration_secs":null,"text":"# Suspense and the use Hook: Rendering as If the Data Were Already There\n\nIf you program waiting separately into every component, you pay for it in the UI: three data-loading components side by side mean three spinners that flash up independently and disappear again at three different times. The page twitches while it builds up, and each of these components drags the same three cases around with it – loading, error, data. Somewhere in each one there’s `if (isLoading) return <Spinner />` and below it `if (error) return <ErrorMessage />`.\n\nMoving to TanStack Query or SWR doesn’t change that either. In the [article on client state and server cache](https://www.mikebild.dev/en/blog/client-state-vs-server-cache/), I showed how server data moves out of the patchwork of `useState` and `useEffect` and into a cache library – the loading state doesn’t move along with it; it stays in every component that needs data. React 19 starts somewhere else, namely with the question of where in the tree the waiting happens at all. Suspense turns it around: waiting no longer belongs in each individual component but in one place above them. And the component below may act as if the data were already there.\n\n**Editorial note (July 2026):** Suspense doesn’t react to arbitrary data loading in an effect or event handler. For data, the flow described here works with Suspense-enabled frameworks and libraries or when reading a stable, cached promise with `use`. A freely usable, stable React API for building your own Suspense data sources is still not documented.\n\n## The loading state leaves the component\n\nLet’s first look at what it looks like without Suspense. A component that displays a list of invoices carries the three states itself:\n\n```jsx\nfunction InvoiceList() {\n  const { data, isLoading, error } = useInvoices();\n\n  if (isLoading) return <Spinner />;\n  if (error) return <ErrorMessage error={error} />;\n\n  return (\n    <ul>\n      {data.map((invoice) => (\n        <li key={invoice.id}>{invoice.title}</li>\n      ))}\n    </ul>\n  );\n}\n```\n\nThat’s not terrible, but it repeats itself. Every data-loading component looks like this, each has its own `Spinner`, its own error handling. And when three such components sit side by side, three spinners flash up independently and disappear at different times – a restless picture.\n\nSuspense offers a different idea. You wrap part of the tree once with `<Suspense>` and say: everything in here that is still waiting for data should show this fallback until then.\n\n```jsx\n<Suspense fallback={<Spinner />}>\n  <InvoiceList />\n</Suspense>\n```\n\nThe `InvoiceList` itself no longer knows about a loading state. It requests the data, and if it isn’t there yet, React pauses the component and shows the fallback of the nearest enclosing `<Suspense>` component instead. The word for this is *suspending*: the component pauses in the middle of rendering until what was promised arrives. The fallback is no longer the component’s business but that of the `<Suspense>` above it.\n\n## The `use` hook reads a promise\n\nFor a component to be able to suspend at all, it needs a way to “read” a promise that is still pending. That’s exactly what the `use` hook does, which is stable as of React 19. You pass it a promise, and it returns the resolved value – or interrupts rendering if the value isn’t there yet.\n\n```jsx\nimport { use } from \"react\";\n\nfunction InvoiceList({ invoicesPromise }) {\n  const invoices = use(invoicesPromise);\n\n  return (\n    <ul>\n      {invoices.map((invoice) => (\n        <li key={invoice.id}>{invoice.title}</li>\n      ))}\n    </ul>\n  );\n}\n```\n\nYou read this line almost like synchronous code: `const invoices = use(invoicesPromise)`, and after that `invoices` is simply available. The component sees nothing of the time in between, while the promise is still pending. If the promise isn’t fulfilled yet, `use` suspends the component, React pauses and shows the fallback of the enclosing `<Suspense>` component. As soon as the promise is fulfilled, React renders the component again, this time with the value in hand.\n\nBy the way, besides promises, `use` also accepts a context and replaces `useContext` in that role. But the interesting case for this article is the promise, because that’s where the interplay with Suspense hinges.\n\n## Why `use` may be called conditionally\n\nIt’s worth taking a quick look at a peculiarity that at first glance looks like breaking the rules. For all other hooks, an iron rule applies: they have to be at the top level of the component, always in the same order, never inside a condition or loop. The reason is that React maps the hooks per render by their call order – if the order gets mixed up, React confuses the states.\n\n`use` is explicitly exempt from this rule. You may call it inside an `if` condition, in a loop, after an early `return`:\n\n```jsx\nfunction Message({ show, messagePromise }) {\n  if (show) {\n    const message = use(messagePromise);\n    return <p>{message}</p>;\n  }\n  return null;\n}\n```\n\nThat’s more than a convenience. `use` doesn’t store any state itself that would have to be mapped to a component through a fixed call order – it only reads a value from an object you hand it. That’s why it can sit where it belongs in terms of content, instead of being forced to the top of the component. You read a promise exactly when you actually need its value.\n\n## The error boundary handles errors\n\nThat leaves the third state from above: the error. If the promise isn’t fulfilled but rejected, `use` throws that error during rendering. And a thrown error ends up at the nearest *error boundary* – the same mechanism React has always used to catch render errors.\n\n```jsx\n<ErrorBoundary fallback={<ErrorMessage />}>\n  <Suspense fallback={<Spinner />}>\n    <InvoiceList invoicesPromise={invoicesPromise} />\n  </Suspense>\n</ErrorBoundary>\n```\n\nWith that, the math works out. The three states that each component used to manage itself – loading, error, data – have become two safety nets in the tree plus the pure success case in the component. The `<Suspense>` takes care of waiting, the `<ErrorBoundary>` of failing, and the component itself only renders the case it’s actually there for: the available data. The `if (isLoading)` and the `if (error)` are gone without replacement.\n\n```mermaid\nflowchart TB\n  R[\"Component renders,<br/>calls use(promise)\"] --> Q{\"Promise state?\"}\n  Q -->|pending| S[\"suspends →<br/>Suspense shows fallback\"]\n  S -.->|promise fulfilled| R\n  Q -->|fulfilled| OK[\"Content appears<br/>with the data\"]\n  Q -->|rejected| ERR[\"Error is thrown →<br/>ErrorBoundary catches it\"]\n```\n\nAt this point, an error boundary is still a class component, or you reach for a small package like `react-error-boundary` – there’s no built-in function variant in React 19 yet. But that doesn’t change the picture: conceptually, it’s the second safety net next to Suspense.\n\n## Staying honest: `use` isn’t a cache library\n\nNow comes the part that’s easy to skim over, because the examples above look so tidy. Where does the `invoicesPromise` actually come from? In the code snippets I passed it in as a prop and thereby postponed the question. But it’s the decisive one.\n\nYou might get the idea of simply creating the promise in the component:\n\n```jsx\nfunction InvoiceList() {\n  // Trap: creates a new promise on EVERY render\n  const invoices = use(fetch(\"/api/invoices\").then((r) => r.json()));\n  // ...\n}\n```\n\nThat looks compact and is still wrong. Every render pass calls `fetch` again and creates a fresh promise. React sees a pending promise, suspends, re-renders after it resolves – and in doing so immediately creates the next new promise. You build yourself an infinite loop of loading. `use` caches nothing, it deduplicates nothing, it only *reads* what you give it.\n\nFor this to work, the promise has to come from outside rendering: from someone who creates it once, stores it under a key and returns the same promise on the next request. That’s exactly the bookkeeping – keys, age, deduplication, invalidation – that I described in the [article on the server cache](https://www.mikebild.dev/en/blog/client-state-vs-server-cache/). `use` and Suspense don’t solve it; they presuppose it.\n\nIn practice, therefore, the same tools you already use deliver the promises. TanStack Query and SWR both have a Suspense mode: instead of returning `isLoading` and `error`, they suspend and throw in the error case, so that Suspense and the error boundary take over the states. Or a framework like Next.js creates the promises on the server and passes them in. The rule from the cache article applies unchanged: server data needs a cache with keys and invalidation. Suspense only changes how waiting for it feels in the tree – not the fact that someone has to run the cache.\n\n## Where the effort pays off\n\nIf `use` doesn’t take the bookkeeping off your hands, why the whole rework? The gain lies elsewhere, namely in coordinating several data sources under a shared `<Suspense>`.\n\nImagine a profile page that loads user data, the latest posts and some statistics – three sources. Without Suspense, three spinners flash up independently and resolve at three different times; the page twitches as it builds up. If you put the three components under a shared `<Suspense>`, React waits until all three are ready and then shows the finished page in one piece. One fallback instead of three, one moment of appearing instead of three.\n\nJust as often you want the opposite: not to wait for the slowest source, but to show the fast part right away. Then you nest several `<Suspense>` components. The user profile sits under an outer `<Suspense>` and appears early; the slow statistics get their own inner `<Suspense>` with their own fallback and slide in as soon as they’re there.\n\n```jsx\n<Suspense fallback={<PageSkeleton />}>\n  <UserProfile userPromise={userPromise} />\n  <Suspense fallback={<StatsSkeleton />}>\n    <Statistics statsPromise={statsPromise} />\n  </Suspense>\n</Suspense>\n```\n\nThat’s how you describe a staggered appearance as structure in the tree, not as logic in the components. Where something appears and in what order, you can read from the nesting of the `<Suspense>` components – in one place, instead of scattered across a dozen `isLoading` checks. That’s the real gain: the loading UI lives where you think about layout, not once more in every component.\n\nA second, less visible benefit is connected to this: Suspense counteracts loading waterfalls. A waterfall occurs when a component first loads, then renders, and a child inside it only then starts its own loading – the requests line up one after another even though they don’t depend on each other at all. Classic `useEffect` loading produces exactly this pattern almost by itself, because each component only fetches once it renders, and children only render once their parents have finished loading. If you instead pass the promises in from outside and start them early, the requests run in parallel, while `use` collects them again under a shared `<Suspense>`. The structure of waiting and the structure of loading no longer necessarily coincide.\n\n## A reload that leaves the old UI standing\n\nOne more detail deserves a brief mention, because it quickly becomes important in practice. Suspense shows its fallback not only on the first load but also when the data under a `<Suspense>` changes – for example, when you switch from one invoice to the next and a new promise is created. Without precautions, the page then jumps back to the spinner, even though usable data was visible just a moment ago.\n\nThat’s exactly what `useTransition` and `startTransition` are for. If you mark the data change as a transition, React keeps the old UI standing and loads in the background instead of dropping straight into the fallback. Meanwhile, you can indicate that something is in progress – grayed out, with a subtle hint – without throwing away the content that’s already rendered. That deserves its own article; here it should just be clear that jumping hard back into the fallback isn’t mandatory.\n\n## What should stick\n\nSuspense and `use` don’t shift who fetches the data – that remains the job of a cache. They shift where waiting is described. Instead of programming three states into every component, you pull loading and errors together in two places in the tree – Suspense and the error boundary – and let the components below assume the success case. Each individual component gets smaller and more honest as a result: it acts as if the data were there, because a `<Suspense>` above it makes sure they are when the component’s turn comes.\n\nWhen designing a page, that leaves one question: at which places in the tree may waiting happen, and what should be visible there in the meantime? The answer is a few `<Suspense>` components in the right places – and components that no longer need to know anything about waiting.\n\n## Further reading\n\n- Repository introduction-react (chapters server-access, react-hooks; recipes folder on data fetching): https://github.com/mikebild/introduction-react\n- React, “Suspense”: https://react.dev/reference/react/Suspense\n- React, “use”: https://react.dev/reference/react/use\n- React, Suspense-enabled data fetching: https://react.dev/reference/react/Suspense#displaying-a-fallback-while-content-is-loading"},{"locale":"en","translation_key":"client-zustand-und-server-cache","slug":"client-state-vs-server-cache","title":"Client State vs. Server Cache: The Most Consequential Boundary in the Frontend","summary":"Server data is state, but not client-owned state. Why this distinction matters, when useEffect turns into a bad cache and what a server state library takes over.","tags":["Software","Frontend","React"],"published_at":"2024-12-06T10:00:00+00:00","updated_at":"2026-07-13T13:19:06.078134+00:00","url":"https://www.mikebild.dev/en/blog/client-state-vs-server-cache/","audio_url":null,"audio_duration_secs":null,"text":"# Client State vs. Server Cache: The Most Consequential Boundary in the Frontend\n\n```jsx\nconst [invoices, setInvoices] = useState([]);\n\nuseEffect(() => {\n  fetch(\"/api/invoices\")\n    .then((r) => r.json())\n    .then(setInvoices);\n}, []);\n```\n\n`invoices` is not client-owned state. It is a cached copy of data whose original lives in a database behind `/api/invoices`. And this cache lacks everything that makes a usable cache: a key under which a second component finds the same copy; an age after which it counts as outdated; a place where you declare it invalid after a change. As long as only one component loads and nobody changes anything, none of this shows.\n\nThe React overview distinguishes four places for state: the component, the URL, a global store and, almost in passing, the server cache. This last boundary deserves a post of its own, because in everyday work it causes the most bugs and because it is so easy to overlook.\n\nThis confusion is not a beginner’s mistake you grow out of. I see it in code reviews from people who have been writing React for years, and I made it myself for a long time. The difference sounds academic but has very practical consequences: it decides which tool you choose, how many bugs you’ll chase later and how small or large the part of the application you have to manage by hand becomes.\n\n## Two kinds of state that keep getting confused\n\nLet’s start with a simple question: where does the truth live? With real client state, it lives in the browser. The text in an input field, whether a menu is expanded or collapsed, which tab is currently active – all of this arises from a user interaction and exists only here. Nobody outside this browser knows or needs this value. When the component disappears, the value disappears with it, and that is perfectly fine.\n\nWith server data, it’s the other way around. The list of invoices, the user profile, the inventory – the truth about them lives in the backend, in a database, behind an API. What the browser has of it is only a copy. And copies have an unpleasant property: they go stale. The second the server sends the response, someone else may already have changed the record. The browser then holds a snapshot that looks like the truth but no longer is.\n\n```mermaid\nflowchart TB\n  Frage[\"Where does the truth live?\"]\n  Frage --> Client[\"in the browser<br/>= client state\"]\n  Frage --> Server[\"in the backend<br/>= server data\"]\n  Client --> C1[\"inputs, selection,<br/>expanded menus\"]\n  Server --> S1[\"The browser only holds<br/>a copy – it goes stale\"]\n```\n\nOnce you ask this question, a lot falls into place differently. The counter, the form, the filter selection – client state. The loaded list, the search result, the account balance – server data, i.e. a cache. And different rules apply to a cache than to state you own yourself.\n\n## Why `useEffect` alone doesn’t replace a server cache\n\nThe usual first reflex looks like this: you take `useState` for the data, `useEffect` for loading, and you’re done. Here is the pattern from the beginning again, this time with an error path and a cleanup function so that it is correct at all:\n\n```jsx\nfunction useInvoices() {\n  const [data, setData] = useState(null);\n  const [error, setError] = useState(null);\n\n  useEffect(() => {\n    let active = true;\n    fetch(\"/api/invoices\")\n      .then((r) => r.json())\n      .then((d) => active && setData(d))\n      .catch((e) => active && setError(e.message));\n    return () => {\n      active = false;\n    };\n  }, []);\n\n  return { data, error };\n}\n```\n\nThat works – for exactly one component that loads exactly once. As soon as the application grows, almost everything server data really needs is missing here. Two components showing the same list load it twice, because neither knows about the other. If you navigate away and come back, loading starts from scratch, even though the data from a moment ago would still be good enough. There is no way to renew the copy specifically after a change. And the race between an old and a new request, which the cleanup function above defuses, is only the most obvious of a whole family of problems.\n\nAn example I experienced in a similar form in a real project: a dashboard, at the top a number “open invoices: 12”, next to it a list of the same invoices. Both building blocks load their data in their own effect. Already at startup, two requests fire where one would have been enough. It gets more annoying when someone pays an invoice: the list reloads and shows eleven, the number at the top doesn’t reload and keeps showing twelve. Two copies of the same truth that drift apart – and nobody made a mistake; the code is just honestly thought through to its end. Exactly such contradictions arise inevitably when each component holds its own little cache without a shared place that knows which data is currently valid.\n\nThe real point is a different one. An effect synchronizes a component with something outside React – that is its job, and it is the right tool for that. But managing a cache is not a side concern of a single component. It is an application-wide problem: who holds which data, how old may it be, when is it renewed, who shares it? Solving this problem in every `useEffect` individually and by hand is roughly like writing your own little database in every function. It works, but it doesn’t scale, and every copy has its own bugs.\n\n## What a server state library takes over\n\nAt this point, a tool built for exactly this case pays off. TanStack Query (formerly React Query) and SWR are the two widespread representatives. They share the same basic idea, which you can read from SWR’s name: *stale-while-revalidate*. Show the existing, possibly stale copy immediately, and renew it in the background. The user sees data right away, and the fresh data shortly afterwards.\n\nThe core is a central cache that stores data under a key. You only describe what you want and where it comes from:\n\n```jsx\nimport { useQuery } from \"@tanstack/react-query\";\n\nfunction useInvoices() {\n  return useQuery({\n    queryKey: [\"invoices\"],\n    queryFn: () => fetch(\"/api/invoices\").then((r) => r.json()),\n    staleTime: 30_000,\n  });\n}\n```\n\nThat hardly looks shorter than the `useEffect`, but there is a whole machinery behind it. If two components query `[\"invoices\"]` at the same time, only one request is sent – that is deduplication. If a component comes back whose data is younger than the `staleTime`, nothing is reloaded at all. If it is older, the library shows the old copy immediately and reloads in the background. The `queryKey` is more than a name: it is the identity of the data in the cache and the pivot for everything else.\n\nThe difference becomes clearest when writing. After a mutation, the cache has to learn that its copy is now wrong:\n\n```jsx\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\n\nfunction usePayInvoice() {\n  const queryClient = useQueryClient();\n  return useMutation({\n    mutationFn: (id) => fetch(`/api/invoices/${id}/pay`, { method: \"POST\" }),\n    onSuccess: () => {\n      queryClient.invalidateQueries({ queryKey: [\"invoices\"] });\n    },\n  });\n}\n```\n\nThe call `invalidateQueries` marks all queries under `[\"invoices\"]` as stale and reloads the active ones among them. So you no longer say “set this state” but “this server data is now unreliable, fetch it fresh”. That is exactly the right mindset for a cache: you don’t own the data, you only hold it provisionally, and after a change you declare the copy invalid. If the counter and the list use the same key family, this one invalidation updates them together. That removes a common cause of diverging displays; it doesn’t replace a guarantee, because keys, error handling and server responses still have to fit together.\n\nIf you like, you can go one step further and update the UI before the server has even responded. Via the `onMutate` callback, you write the expected new state directly into the cache, so the invoice appears as paid immediately; if the server then comes back with an error, the library rolls the cache back to the old state. This optimistic updating makes UIs noticeably faster, and it is only possible at all because the data lives in a central, named place and isn’t scattered across a dozen individual `useState` values.\n\n```mermaid\nflowchart LR\n  A[\"Component asks for<br/>queryKey\"] --> B{\"Copy in the cache<br/>and still fresh?\"}\n  B -->|yes| C[\"show immediately,<br/>load nothing\"]\n  B -->|stale| D[\"show old copy +<br/>reload in the background\"]\n  D --> E[\"fresh data<br/>replaces the copy\"]\n```\n\nOn top of that comes a whole series of small things you would otherwise have to build by hand: reloading when the window regains focus, retrying on network errors, `pending` and `error` states as a clean result instead of three separate `useState` calls, and tools that make the cache visible in the browser. None of this is magic – it is exactly the bookkeeping a cache needs and that is always missing in a `useEffect`.\n\n## SWR or TanStack Query?\n\nBoth libraries solve the same problem but set different priorities. SWR is deliberately lean, has a narrow API and is quickly understood. You tell it how long data counts as fresh and call `mutate(key)` to renew it. For read-heavy UIs with simple writes, that is often exactly right, especially in the Next.js world.\n\nTanStack Query is more extensive and gives more control: `staleTime` and `gcTime` cleanly separate how long data stays fresh and when it drops out of memory; `invalidateQueries` can declare entire families of queries stale at once via a prefix, which is worth a lot with nested data; and `useMutation` is a complete state machine with callbacks for optimistic updates. The price is a bit more weight and a few more knobs. For small, manageable cases, SWR is enough; as soon as server state complexity threatens to grow, TanStack Query pays off.\n\nThe more important point, though, runs across this choice: as soon as you treat server data as what it is – a cache with a key, an age and invalidation – all the `useState`-and-`useEffect` tinkering disappears, no matter which of the two you choose.\n\n## What is still real client state then\n\nNow comes the actual punchline, and it regularly surprises experienced colleagues too. If you pull server data out of state management, shockingly little remains. The cross-check is quickly done: list everything that has so far been considered “global state”, then strike it off item by item. The loaded lists? Cache. The detail data? Cache. The search result? Cache. Which filter is active, which page you are on, which record is selected? That belongs in the URL – shareable, bookmarkable, survives a reload.\n\nWhat remains as client-owned state in the end is, in many applications, a small core: the text in a form while you’re still typing, UI details such as expanded sections and a few app-wide decisions – theme or shopping cart, say. For that, `useState`, Context or a lightweight store is often enough. Server data is state too, but it has a different source, lifetime and invalidation logic. That is exactly why it doesn’t simply belong in the same global store.\n\nThat is why I consider this boundary the most consequential in the entire frontend. It doesn’t just decide on a tool. It clears away half of state management before you even build it.\n\n## React 19: `use()` and Suspense\n\nA look ahead, because something is shifting here right now. With `use()` and Suspense, React 19 brings another way to bring server data into rendering: you hand a component a stable promise, `use()` suspends until it is fulfilled, and an enclosing `<Suspense>` component shows a fallback until then. The promise should come from a framework or a cache and not be created anew on every render. This moves loading and error states to the edges instead of handling them individually in every component.\n\nThis doesn’t replace a cache library – someone still has to create, cache and invalidate the promises, and that is exactly what TanStack Query and SWR now do with Suspense support. But it changes how waiting feels in the tree. I devote the post Suspense and the use Hook to this big topic of its own; here it is only a signpost, so it’s clear where React is heading.\n\n## What should stick\n\nIf one sentence from this post should stick, it’s this one: for every value that looks like state, first ask where its truth lives. If it lives in the browser, it is real client state, and `useState` is right. If it lives in the backend, it is a cache, and then it needs cache rules – key, age, invalidation – and a tool that takes over this bookkeeping instead of copying it into every `useEffect`.\n\nMaking this distinction first and choosing the tool only afterwards prevents duplicate caches and contradictory copies. Server data is borrowed state: the client manages its presentation but owns neither its truth nor its lifecycle alone.\n\n## Further reading\n\n- Repository introduction-react (chapters server-access, react-hooks; recipes folder on data fetching): https://github.com/mikebild/introduction-react\n- React, “You Might Not Need an Effect”: https://react.dev/learn/you-might-not-need-an-effect\n- React, Synchronizing with Effects: https://react.dev/learn/synchronizing-with-effects\n- TanStack Query, Query Invalidation: https://tanstack.com/query/latest/docs/framework/react/guides/query-invalidation\n- SWR, official documentation: https://swr.vercel.app/"},{"locale":"en","translation_key":"scheduler-und-virtuelle-zeit-testen","slug":"testing-schedulers-and-virtual-time","title":"Testing Schedulers and Virtual Time","summary":"Injectable time makes time-dependent rules testable quickly and deterministically. Data, isolation and external systems remain unaffected by it.","tags":["Software","Reactive"],"published_at":"2024-11-12T10:00:00+00:00","updated_at":"2026-07-13T08:53:24.655184+00:00","url":"https://www.mikebild.dev/en/blog/testing-schedulers-and-virtual-time/","audio_url":null,"audio_duration_secs":null,"text":"# Testing Schedulers and Virtual Time\n\nThe most expensive spot in an asynchronous codebase is rarely the algorithm. It is time. Debounce, retry, timeout, polling, “wait 250 ms and then fire the last value” – such rules are simple from a domain point of view but brutal in tests. If you check them with real time, you build suites that run slowly, occasionally turn red and no longer prove anything to anyone. The way out lies in a spot that hardly stands out in the code: the scheduler from which an operator gets its clock. If it sits in the signature as an argument instead of as a framework default in the background, you can fast-forward the clock in the test instead of waiting for it.\n\nThe order in which this reveals itself is not the order of the documentation: MVVM, asynchronous programming, scheduler, streams, observable pattern, message bus, testing. First the problem with time arises, then Rx comes along as a model for it, and at the very end stands the scheduler as the boundary at which the whole thing becomes testable in the first place. This last step carries the most weight – it turns an elegant but hard-to-grasp technique into something you can test in seconds and defend in the team.\n\n## The real problem isn’t async but waiting\n\nReactive programming – whether RxJS in the frontend or ReactiveUI in the desktop client – models asynchronous data as observables with operators. The strength doesn’t lie in the number of operators. It lies in making time, cancellation, errors and transformation explicit. `debounce`, `switchMap`, `mergeMap` and `combineLatest` each make a different statement about the system: is an old request canceled? May results arrive in parallel? Does only the last value count? Operators are answers to these questions, not a vocabulary list.\n\nAs soon as time comes into play, though, testability tips over. A test for “debounce by 250 ms” has three bad options: wait for real (slow, and the run time adds up with every such rule), set generous sleeps (nondeterministic, because they tick differently on slow CI) or not test the logic at all (the rule drifts unnoticed). All three cost something – and exactly where it hurts most: in the team’s daily feedback cycle. A suite that runs for ten minutes and turns red for no reason every few runs is no longer trusted. And a suite nobody trusts, nobody follows.\n\n## The idea: time is a dependency\n\nThe architectural lever is unspectacular and precisely for that reason sustainable: time isn’t taken from the runtime but passed in. A scheduler is the abstraction through which operators get time – “when is the next event scheduled, and relative to which clock”. In production, that’s a real clock. In the test, it’s a virtual clock that I fast-forward by hand.\n\n```ts\nconst result$ = input$.pipe(\n  debounceTime(250, scheduler),\n  distinctUntilChanged(),\n  switchMap((query) => search(query))\n);\n```\n\nThe only difference from the naive variant is the second argument of `debounceTime`. It looks like a detail, but it shifts control over time from an implicit framework default to an explicit, swappable dependency. That is the same principle as dependency injection for a database or an HTTP client – only applied to the one resource that otherwise can’t be mocked.\n\nIn the test, there is then no waiting. Time is moved.\n\n```ts\nscheduler.advanceBy(249);\nexpect(search).not.toHaveBeenCalled();\nscheduler.advanceBy(1);\nexpect(search).toHaveBeenCalledWith(\"abc\");\n```\n\nThe test makes a statement that couldn’t even be expressed before: “At 249 ms nothing happens; at exactly 250 ms the call fires.” It runs in microseconds, independent of the machine, and it documents the domain rule exactly. The gain is not primarily speed. It is precision: a timing decision that used to be only talked about becomes provable.\n\n```mermaid\nflowchart LR\n  Input[User input] --> Debounce\n  Debounce --> Distinct\n  Distinct --> SwitchMap\n  SwitchMap --> Result\n  SwitchMap -. cancel old request .-> Cancelled\n```\n\n## Why this is an architecture question, not a testing technique\n\nIt would be convenient to file virtual time away as a trick of the test layer. That falls short. The decision to make time injectable forces the production code to disclose its temporal dependencies. Where a `setTimeout` used to sit quietly inside a class, there is now a scheduler in the signature. Time turns from a hidden side effect into a visible contract.\n\nFor the debounce, the domain rule is: the backend shouldn’t receive every keystroke, but the UI should react promptly. The scheduler turns the chosen 250 milliseconds into a swappable input. If the value is too tight, I change it together with a boundary test instead of through manual clicking in a slow environment.\n\nThe trade-off is real and deserves to be named. A scheduler in the signature is more ceremony than a direct timer. You have to pass it through, and teams introducing Rx for the first time feel this as overhead at first. By the second or third time-dependent rule at the latest, the effort pays for itself. Before that it’s discipline; after that it runs by itself. If you carry the scheduler along from the start, you pay a small constant price; if you have to retrofit it, you pay it as an expensive refactoring across the whole call chain.\n\n## A second example: retry with backoff\n\nDebounce is the friendly case, because the time is small and single-digit. The case that remains practically untestable without virtual time is retry with exponential backoff. The domain intent: a transient network error shouldn’t go through immediately but should be retried after 1 s, then 2 s, then 4 s – and fail for good after three attempts.\n\n```ts\nconst result$ = request$.pipe(\n  retryWhen((errors) =>\n    errors.pipe(\n      scan((count) => count + 1, 0),\n      delayWhen((count) => timer(2 ** count * 1000, scheduler)),\n      take(3)\n    )\n  )\n);\n```\n\nWith real time, testing this rule is an imposition: a single run waits seven seconds, and nobody likes checking the boundary “after the third attempt the error goes through” in a suite that runs a hundred times a day. With injected time, it becomes a precise, instant test:\n\n```ts\nscheduler.advanceBy(1000);\nexpect(request).toHaveBeenCalledTimes(2);\nscheduler.advanceBy(2000);\nexpect(request).toHaveBeenCalledTimes(3);\nscheduler.advanceBy(4000);\nexpect(onError).toHaveBeenCalled();\n```\n\nThis is the moment when the decision shows its value. A rule that decides about resilience in production – too aggressive a retry overloads an already weak backend, too timid a retry leaves users out in the rain – becomes a matter of three lines that I can adjust and prove. Without virtual time, exactly this rule is the one that stays untested in practice and becomes a mystery during an incident.\n\n## The second boundary: ownership instead of global streams\n\nMaking time testable only solves one half. The other is the subscription boundary. In UI and messaging systems, what matters most is who owns a stream and when it ends. A stream that is subscribed to everywhere and ended nowhere is just global state under another name – with the same symptoms: memory leaks, duplicate side effects, behavior under load that is hard to explain.\n\nGood streams therefore have three properties that I actively look for in review: a clear owner, a defined lifetime and named side effects. That is not a stylistic virtue but the precondition for tests to remain meaningful at all. A test with virtual time is worthless if the subscription in the real system lives longer than intended and fires twice in production. Control over time and control over lifetime are two sides of the same discipline.\n\n## Commands instead of button handlers\n\nReactiveUI carries the same idea – making state and lifetime explicit – into interaction. ReactiveCommands model a UI action as an executable operation with state: can execute, is running, delivers a result, delivers an error. The button thus no longer carries any business logic; it only displays the state of a command.\n\n```mermaid\nflowchart LR\n  Button --> Command\n  Command --> CanExecute\n  Command --> IsExecuting\n  Command --> Result\n  Command --> Error\n  Result --> ViewModel\n  Error --> ErrorPolicy\n```\n\nThe user doesn’t click “a function”. They start an operation with a lifetime – and that, again via the scheduler, can be tested deterministically: is `CanExecute` false during execution? Is the error path routed into the ErrorPolicy instead of into a swallowed exception handler? These are exactly the questions that never come up in demo mode and become expensive in production. ReactiveCommands, Dynamic Data, `Bind`/`OneWayBind` and a central ExceptionHandler point in the same direction: reactive programming doesn’t mean learning operator lists but modeling UI lifetime and error paths.\n\n## The methodical consequence for reviews\n\nIf time is a dependency, what I look at in review changes. I no longer ask “is there a test” but “which timing decision does this test prove”. Does the debounce fire at exactly the threshold? Does `switchMap` demonstrably cancel the old request? Does the retry run with the expected backoff, checked via a fast-forwarded clock instead of real waiting?\n\nAnd I check the error path, not just the happy one. Many systems look clean in the demo. It gets interesting with repetition, partial failures, network problems and human correction. A common fallacy remains confusing the tool with the solution: Rx is not a domain model, a scheduler is not a test, and a green happy path is not proof. The tools can express good boundaries, but they don’t create them by themselves.\n\n## What the effort brings\n\nThe benefit can be checked on two things: time-dependent cases run with virtual time in milliseconds instead of real waiting intervals, and boundary values like “nothing at 249, fire at 250” are described exactly. That eliminates time-based flakiness. A red run can still come from data, shared isolation or external systems; the scheduler doesn’t solve these causes. What’s relevant, therefore, is the run time of exactly these tests and their share of unstable CI runs.\n\n## Conclusion\n\nReactive code doesn’t get better by starting with operator lists. It gets easier to understand when its temporal semantics become explicit. Turning time from a hidden default into an injected dependency costs some ceremony, but it allows fast tests for debounce, timeout and backoff. The scheduler promises no more than that."},{"locale":"en","translation_key":"graphql-ueberblick-vom-schema-zur-foederierten-api","slug":"graphql-overview-from-schema-to-federated-api","title":"GraphQL Overview: From Schema to Federated API","summary":"A walk through GraphQL – from the typed schema through queries and resolvers to real time, operations and federated architecture, assessed as of October 2024.","tags":["Software","API","GraphQL"],"published_at":"2024-10-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/graphql-overview-from-schema-to-federated-api/","audio_url":null,"audio_duration_secs":null,"text":"# GraphQL Overview: From Schema to Federated API\n\nA typed schema and at least one `Query` entry point are enough to ask very different questions of a GraphQL API. These operations often run over an HTTP endpoint; the GraphQL specification itself, however, doesn’t prescribe the transport. The crucial question behind it is who determines the shape of the response. With a classic REST interface, the server defines the representation of a route. GraphQL lets the client select the fields it needs from it. Control stays with the backend, because every allowed selection is fixed in the schema beforehand.\n\nThis post walks the path from schema to distributed architecture once all the way through, so that you know the stations before you get lost in one of them. For individual stations – how exactly execution works internally – I write separate, deeper posts, such as [GraphQL Concepts: Schema, Resolvers, Execution](https://www.mikebild.dev/en/blog/graphql-concepts-schema-resolvers-execution/). Here it’s about the whole picture, with the tooling as of October 2024: Apollo Server 4 serves as the Node.js example, and the federation section refers to Apollo Federation 2. GraphQL over HTTP was a stage 2 draft specification back then and still is in July 2026; it describes the HTTP semantics for queries and mutations, not the transport of subscriptions.\n\nGraphQL connects several responsibilities without turning them into a single building block.\n\n:::relationship{title=\"From need to resolved response\" role=\"primary\" preferredPattern=\"architecture-map\"}\n- Client operation · describes the shape of the response it needs\n- Schema · limits types, fields and allowed operations\n- Execution · validates and plans the requested selection\n- Resolver · resolves exactly one field within its context\n- Data source · owns data and domain rules behind the resolver\n- Gateway · can coordinate several subgraphs under one contract\n:::\n\nThe schema remains the contract and the point of orientation. It replaces neither the domain logic nor the data ownership of the connected systems.\n\n## GraphQL is a specification, not a framework\n\nThe most common misconception at the start: GraphQL is a library you install. It isn’t. GraphQL is a specification – it describes a query language and how a server has to evaluate such a query. There are reference implementations such as `graphql-js`, and servers like Apollo Server or GraphQL Yoga build on them, but the heart of it is a contract, not a runtime.\n\nAlmost everything else follows from this one fact. Because the contract is typed, the client can know before the first call which fields exist and what type they have. And because the server evaluates the selection instead of just delivering a fixed representation, a shared HTTP endpoint can answer many different questions. A single endpoint is the common way to deploy it, not a requirement of the transport-agnostic specification.\n\n```mermaid\nflowchart LR\n  Client[\"Client<br/>formulates the question\"] -->|one query| Endpoint[\"one GraphQL endpoint\"]\n  Endpoint --> Engine[\"Execution<br/>against the schema\"]\n  Engine --> DB[(\"Database\")]\n  Engine --> REST[\"REST API\"]\n  Engine --> Service[\"other service\"]\n  Engine -->|exactly the requested fields| Client\n```\n\nWhat matters here: anything can sit behind that one endpoint. GraphQL is not a database and doesn’t replace one – it is a layer that brings different sources together under a shared, typed model.\n\n## The schema first\n\nEverything starts with the schema. It is written in the Schema Definition Language, SDL for short, and describes the types and their relationships. A small example from the world of a blog:\n\n```graphql\ntype Author {\n  id: ID!\n  name: String!\n  posts: [Post!]!\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  author: Author!\n}\n\ntype Query {\n  author(id: ID!): Author\n  posts: [Post!]!\n}\n```\n\nThree things are worth a close look. First, the modifiers: the exclamation mark means “must not be null”, the square brackets mean “list”. So `[Post!]!` is a non-nullable list of non-nullable posts – a very precise statement a client can rely on. Second, the relationships: `Author` refers to `Post` and vice versa. The schema doesn’t describe a flat catalog but a graph of nodes and edges – hence the name.\n\nThird, and this is the core: `Query` is a special type. Optionally, `Mutation` for writing and `Subscription` for ongoing results are added. These operation types are the entry points into the graph. Anything that isn’t listed there as a field can’t be selected by any client. This makes the schema a real contract: it states bindingly which operations and response shapes are allowed.\n\nTwo tools make this contract much easier to handle in daily work. Fields can be marked as deprecated with `@deprecated(reason: \"…\")` without removing them right away – clients get the hint but don’t break. And for mutations there are dedicated input types, so that inputs aren’t confused with output types. Both are small signs that GraphQL is meant for long-lived APIs, not for the throwaway endpoint.\n\n## The query side: the client asks precisely\n\nA query looks similar to the data part of the response it produces. You describe the desired selection, and the successful response follows this shape:\n\n```graphql\nquery AuthorWithPosts($id: ID!) {\n  author(id: $id) {\n    name\n    posts {\n      title\n    }\n  }\n}\n```\n\nHere the client asks for an author’s name and the titles of their posts – and gets only that. No superfluous field, no second round trip for the posts. The `$id` is a variable; queries are not parameterized by string fiddling but through typed variables that the server checks.\n\nTwo more building blocks show up quickly. Fragments bundle recurring sets of fields so that you don’t repeat them in every query. And introspection lets you query the schema itself – the server describes itself, which is why tools like GraphiQL can offer autocompletion and documentation without additional configuration. So the contract is not only binding, it is also readable.\n\n## Execution: resolver by resolver\n\nHow does a query become a response? The server walks through the query from top to bottom and calls a function for each field, the resolver. Each resolver receives four arguments in a fixed order: the parent object (`source`), the field’s arguments (`args`), a request-scoped context (`context`) and information about the execution state (`info`).\n\n```js\nconst resolvers = {\n  Query: {\n    author: (source, { id }, context) => context.db.loadAuthor(id),\n  },\n  Author: {\n    posts: (author, args, context) => context.db.loadPostsForAuthor(author.id),\n  },\n};\n```\n\nYou can see the principle: the resolver for `author` returns an author, and its return value becomes the `source` for the field resolvers below it – the resolver for `posts` gets the author as its first argument and uses it to load the posts. This way, execution moves through the graph as a chain. A resolver can work synchronously, with a promise or `async`, and can talk to any data source – a database, a REST API, another service.\n\nThis is exactly where the best-known trap lurks, the N+1 problem. If someone queries ten authors with their posts, the `posts` resolver runs ten times and makes ten individual database queries – plus the one for the authors. The solution is batching: you collect the ten requests within one execution tick and answer them with a single query. The usual library for this is DataLoader.\n\n```mermaid\nflowchart TB\n  subgraph Ohne[\"Without DataLoader (N+1)\"]\n    Q1[\"10 authors\"] --> R1[\"10× posts resolver\"]\n    R1 --> DB1[(\"10 individual queries\")]\n  end\n  subgraph Mit[\"With DataLoader\"]\n    Q2[\"10 authors\"] --> R2[\"10× posts resolver\"]\n    R2 --> L[\"DataLoader collects IDs\"]\n    L --> DB2[(\"1 batched query\")]\n  end\n```\n\nHow execution runs through the tree in detail, in which order sibling fields are evaluated and why mutations are treated differently from queries – that’s a topic of its own, to which I dedicate a separate, deeper section in the [concepts post](https://www.mikebild.dev/en/blog/graphql-concepts-schema-resolvers-execution/). For this overview, it’s enough to know: a query is a path through the graph, and every node on the path is served by a resolver.\n\n## Writing and real time\n\nReading is only half the story. Mutations are the writing part and look like queries, but they carry an intent:\n\n```graphql\nmutation CreatePost($input: PostInput!) {\n  createPost(input: $input) {\n    id\n    title\n  }\n}\n```\n\nThe difference is more than cosmetic: at the top level, the server executes mutations one after another, not in parallel, so that two writes don’t get in each other’s way. And because a mutation returns a result – here the created post – the client can update its state directly from the response without reloading.\n\nFor ongoing updates there are subscriptions. The client subscribes to an event, and the server sends new data as soon as it arises. Classically this ran over WebSockets; by now, transport over server-sent events is common too, especially when a simple, one-way connection is enough – I have written more about this [elsewhere](https://www.mikebild.dev/en/blog/graphql-subscriptions-over-sse/). The GraphQL over HTTP draft spells out the HTTP semantics for queries and mutations so that servers and clients from different vendors work together more reliably. Subscriptions are explicitly outside its scope.\n\n## Operations: errors, pagination, auth, caching\n\nBetween the first working schema and an API that holds up in production lie a few topics you shouldn’t skip.\n\nGraphQL handles errors in its own way: a response can contain data and an `errors` field at the same time. A failed subfield doesn’t break the whole response – the rest still arrives. That is powerful, but it demands discipline so that clients can tell expected errors from real failures.\n\nPagination is rarely solved with simple `offset`/`limit` arguments, but mostly with [cursor-based connections](https://www.mikebild.dev/en/blog/graphql-pagination-cursors-and-connections/) – the connections pattern with edges and page info, which comes from the Relay world and has established itself as a convention. It is a bit more cumbersome to read, but stable when the list changes under your fingers.\n\n[Authentication and authorization](https://www.mikebild.dev/en/blog/graphql-auth-identity-in-the-context/) are not the same thing. The identity is often determined when the `context` is built and passed on from there to execution. The actual access rules can live in resolvers, directives, the domain layer or the data access layer. What matters is that every relevant access point enforces the same policy instead of merely trusting that a field stays hidden in the schema.\n\nFinally, caching is different from many REST APIs, where URL and HTTP method form an obvious cache key. GraphQL over HTTP can use HTTP caching as well, but different operations often share the same address and often sit in the request body. Clients like [Apollo Client](https://www.mikebild.dev/en/blog/apollo-client-normalized-cache-and-optimistic-updates/) therefore add a normalized object cache: objects with a stable identity can be updated together across several queries.\n\n## Architecture: a layer that aggregates\n\nThis brings us to GraphQL’s real strength at scale. Because any source can sit behind the endpoint, GraphQL is excellent as an aggregation layer – a backend for frontend that pulls several services, databases and third-party APIs together under one model, tailored to what the UI really needs.\n\n```mermaid\nflowchart TB\n  App[\"Web & mobile client\"] --> GW[\"GraphQL gateway<br/>(federated schema)\"]\n  GW --> S1[\"Subgraph: users\"]\n  GW --> S2[\"Subgraph: orders\"]\n  GW --> S3[\"Subgraph: catalog\"]\n  S1 --> DB1[(\"Users DB\")]\n  S2 --> DB2[(\"Orders DB\")]\n  S3 --> REST[\"Catalog REST\"]\n```\n\nIf the schema becomes too big for a single team, [federation](https://www.mikebild.dev/en/blog/graphql-federation-and-subgraphs/) comes into play. Instead of a monolith, each team runs its own subgraph, and a gateway assembles them into a single, coherent schema for the client. The client notices nothing of this – it still sees one graph. Federation is today the usual way when GraphQL has to scale organizationally; you still find the older schema stitching approach in existing systems.\n\nWhen it comes to choosing a server, the field has sorted itself out. Apollo Server 4 is the safe default choice for an ordinary Node.js stack – the largest ecosystem, good federation support, broad use in practice. GraphQL Yoga is the leaner alternative, especially when you deploy to edge runtimes where Apollo Server would be too heavyweight. Both rely on `graphql-js` version 16 as their shared foundation.\n\n## The repository as a common thread\n\nIf you want to get hands-on with all of this, you’ll find the stations as individual chapters in `introduction-graphql` – from `intro`, `architecture` and `principles` through `schema`, `types` and `resolver` to `mutations`, `subscriptions`, `paging`, `auth` and `caching`. On top of that there are runnable examples: an Apollo monorepo, a server in C# as evidence that GraphQL is language-independent, and a folder with recipes for recurring tasks – DataLoader, pagination, auth, optimistic UI, server-side rendering. The chapters are deliberately cut so that each can be read on its own, and that’s exactly how this post is meant too.\n\n## What should stick\n\nIf one sentence from this overview should stick, it is this one: GraphQL is first a question of API design and only then a question of tooling. The schema is the contract, the resolvers are the implementation, and everything on top – federation, caching, the concrete server – is the execution of this one idea that the client asks its question and the backend keeps an explicit model.\n\nThe tools will keep changing; Apollo Server 4 won’t be the last generation, and the next one is sure to come. What remains is the typed schema and execution along the graph. There are separate posts on individual stations – how execution works internally and how to [design a schema that grows](https://www.mikebild.dev/en/blog/a-graphql-schema-that-grows/).\n\n## Further reading\n\n- Repository introduction-graphql (chapters, Apollo example, recipes): https://github.com/mikebild/introduction-graphql\n- Slide overview for this post: https://slides.mikebild.dev/introduction-graphql.en.html\n- GraphQL, official introduction: https://graphql.org/learn/\n- GraphQL specification: https://spec.graphql.org/\n- GraphQL over HTTP: https://graphql.github.io/graphql-over-http/\n- Apollo Server, documentation: https://www.apollographql.com/docs/apollo-server\n- DataLoader (batching against N+1): https://github.com/graphql/dataloader"},{"locale":"en","translation_key":"nodejs-http2-und-server-sent-events","slug":"http2-and-server-sent-events-in-nodejs","title":"HTTP/2 and Server-Sent Events in Node.js","summary":"How HTTP/2 multiplexes many streams over one connection and why Server-Sent Events are often a simpler answer to live data than WebSocket – with a working SSE endpoint in Node and the usual pitfalls.","tags":["Software","Node.js","Backend"],"published_at":"2024-10-22T10:00:00+00:00","updated_at":"2026-07-13T08:02:43.199724+00:00","url":"https://www.mikebild.dev/en/blog/http2-and-server-sent-events-in-nodejs/","audio_url":null,"audio_duration_secs":null,"text":"WebSocket is not a protocol for live data. It is a bidirectional channel that happens to handle live data too – and if you open it, you pay for the return channel whether you use it or not: hand-written reconnect logic, upgrade support at every hop, custom timeouts for long-lived connections, and in a cluster usually sticky sessions and a pub/sub layer on top. For a stock ticker, a build progress bar or a notification bar, exactly one direction of that channel is ever in use.\n\nThat makes the choice of transport a design decision with direct consequences for operations and testing, not a matter of taste. It depends on three axes: the direction of the data, the operating environment and testability. If you reach for a transport by reflex, you pay later in more code, more infrastructure and more home-grown error handling – not with the first endpoint, but with every feature that hangs off the channel afterwards. Before we get to Server-Sent Events, it is worth a quick look at the layer underneath, because HTTP has changed more in recent years than most of us notice in daily work.\n\n## What HTTP/2 changes at the foundation\n\nFor years our mental model of HTTP was as simple as it gets: one request, one connection, one response. HTTP/1.1 stretched that a bit with keep-alive and pipelining, but at its core a TCP connection could still only serve one request at a time in any useful way. For years the browser worked around this with brute force: it opened up to six parallel connections per origin. Six. If you have ever built a page with a hundred small assets, you know what that bottleneck feels like.\n\nHTTP/2 turns this model around. Instead of many connections there is a single one, and many independent streams run in parallel over that one connection – this is called multiplexing. Each stream carries exactly one request/response, and all of them share the same TCP tunnel. This removes head-of-line blocking at the application level, and the artificial limit of six per origin is no longer an issue. Most implementations allow 100 concurrently open streams (`SETTINGS_MAX_CONCURRENT_STREAMS`) – the HTTP/2 specification recommends this as a minimum – and the value is configurable.\n\n```mermaid\ngraph LR\n  subgraph HTTP1[\"HTTP/1.1 – six connections\"]\n    C1[Client] -->|Connection 1| S1[Server]\n    C1 -->|Connection 2| S1\n    C1 -->|Connection 3| S1\n    C1 -->|... up to 6| S1\n  end\n  subgraph HTTP2[\"HTTP/2 – one connection, many streams\"]\n    C2[Client] -->|Stream 1<br/>Stream 3<br/>Stream 5| S2[Server]\n  end\n```\n\nTwo more things matter in practice. First, HTTP/2 compresses headers with HPACK. If you have ever captured traffic and seen how often the same cookie and user agent headers travel over the wire, you can guess how much redundancy is in there. HPACK keeps a static and a dynamic table for this and refers to recurring headers only by index instead of spelling them out again.\n\nSecond, there is server push – and by now I am explicitly cautious about it. The idea was charming: the server sends along resources it knows the client will need shortly, before the client even asks. In practice it was hard to use correctly, it often wasted bandwidth, and Chrome removed HTTP/2 server push by default with version 106 in 2022. The feature is still there in Node’s `http2` module, but today I would not advise anyone to build an architecture on it. If you want preloading, you are better served by `preload` hints and `103 Early Hints`.\n\nAn important point for the browser context: browsers speak HTTP/2 practically only over TLS with ALPN negotiation to `h2`. The Node module does support unencrypted h2c, but for anything a browser is supposed to touch, you need certificates.\n\n## The http2 module in Node\n\nNode ships HTTP/2 as its own core module, `node:http2`, stable since the early Node 10 days. When this post was published, 18, 20 and 22 were the relevant release lines; in July 2026, 22 and 24 are LTS and 26 is Current. The module is available without a flag. There are two ways to work with it. The first is the native core API built around streams:\n\n```js\nimport { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst server = createSecureServer({\n  key: readFileSync('localhost-key.pem'),\n  cert: readFileSync('localhost-cert.pem'),\n});\n\nserver.on('stream', (stream, headers) => {\n  const path = headers[':path'];\n  stream.respond({\n    ':status': 200,\n    'content-type': 'text/plain; charset=utf-8',\n  });\n  stream.end(`you requested ${path}`);\n});\n\nserver.listen(8443);\n```\n\nWhat stands out are the pseudo headers with a leading colon and in lower case: `:status`, `:method`, `:path`, `:scheme`, `:authority`. They are the HTTP/2 replacement for the old status line and the classic request metadata. The `stream` event is the heart of it – for every incoming stream you get your own duplex object.\n\nThe second way is the compatibility API. It mimics `req`/`res` the way you know them from the old `http` module, so existing HTTP/1 code keeps running almost unchanged:\n\n```js\nimport { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst server = createSecureServer(\n  {\n    key: readFileSync('localhost-key.pem'),\n    cert: readFileSync('localhost-cert.pem'),\n  },\n  (req, res) => {\n    res.writeHead(200, { 'content-type': 'text/plain' });\n    res.end('ok');\n  },\n);\n\nserver.listen(8443);\n```\n\nOn the client side you connect with `http2.connect(authority)` and send requests via `client.request({ ':path': '/' })`. If you want to dig deeper into Node internals and how they interact with the event loop, my [Node.js training](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/) gives you the right foundation.\n\n## Server-Sent Events: the one-way stream\n\nNow to the actual core. In a great many live applications, data flows almost entirely in one direction: the server has something new, and the client should learn about it. A stock ticker, a build progress bar, a notification bar, a live log. For all of these you need no bidirectional channel, no protocol upgrade and no custom reconnect logic. You need Server-Sent Events.\n\nSSE is not a special module and not a new protocol. It is ordinary HTTP with a particular content type: `text/event-stream`. The server keeps the response open and keeps writing new events into it in a simple line format. The browser has a native client for it in `EventSource`, and – this is the real charm – that client reconnects on its own when the connection drops.\n\nThe wire format is deliberately plain. A message consists of fields, each on its own line, and ends with a blank line:\n\n```\ndata: hello world\n\nevent: tick\ndata: {\"count\":42}\nid: 42\n\n: this is a keep-alive comment\n\n```\n\nThe most important fields are `data:` for the payload, `event:` for a named event type, `id:` for a sequential identifier and `retry:` for the reconnect delay in milliseconds. Lines that start with a colon are comments and work well as a keep-alive ping. What matters is the double line break, the `\\n\\n`, at the end of every message – if you forget it, the event is simply never delivered.\n\n```mermaid\nsequenceDiagram\n  participant B as Browser (EventSource)\n  participant S as Node Server\n  B->>S: GET /events\n  S-->>B: 200 text/event-stream\n  loop every 1s\n    S-->>B: data: { ... }<br/>(response kept open)\n  end\n  Note over B,S: Connection drops\n  B->>S: GET /events<br/>Last-Event-ID: 42\n  S-->>B: 200 text/event-stream<br/>(resumes from id 42)\n```\n\n## An SSE endpoint in Node\n\nThe code is pleasantly short. What matters are the response headers, flushing immediately and – most people miss this the first time – cleaning up when the client closes the connection.\n\n```js\nimport { createServer } from 'node:http';\n\nconst server = createServer((req, res) => {\n  if (req.url !== '/events') {\n    res.writeHead(404).end();\n    return;\n  }\n\n  res.writeHead(200, {\n    'Content-Type': 'text/event-stream',\n    'Cache-Control': 'no-cache',\n    'Connection': 'keep-alive',\n    'X-Accel-Buffering': 'no',\n  });\n  res.flushHeaders();\n\n  let count = 0;\n  const timer = setInterval(() => {\n    count += 1;\n    const payload = { count, time: Date.now() };\n    res.write(`id: ${count}\\n`);\n    res.write(`event: tick\\n`);\n    res.write(`data: ${JSON.stringify(payload)}\\n\\n`);\n  }, 1000);\n\n  req.on('close', () => {\n    clearInterval(timer);\n  });\n});\n\nserver.listen(3000);\n```\n\nThe `req.on('close', ...)` handler is not optional. Without it, the `setInterval` keeps happily running even when the browser closed the page long ago. The handler then writes into a dead connection, the timer stays around, and with many clients you have a real memory leak. In projects, this is the bug I run into most reliably – the endpoint works fine on the happy path, and only under load does anyone notice that nothing gets cleaned up.\n\nOn the browser side, the client is almost unremarkable:\n\n```js\nconst es = new EventSource('/events');\n\nes.onmessage = (event) => {\n  // fires for messages without an explicit event: field\n  console.log('default message', event.data);\n};\n\nes.addEventListener('tick', (event) => {\n  const payload = JSON.parse(event.data);\n  render(payload);\n});\n\nes.onerror = (err) => {\n  // EventSource reconnects on its own; log and let it recover\n  console.warn('connection lost, reconnecting…', err);\n};\n\n// later, when you no longer need it\n// es.close();\n```\n\nThe point that matters most to me here: you do not have to build the reconnect yourself. `EventSource` remembers the last `id:` it saw and sends it along in the `Last-Event-ID` header when it reconnects. If your server reads this header, it can pick up seamlessly from the last message. The `retry:` field controls how long the browser waits before trying again.\n\n## The pitfall that is guaranteed to catch you\n\nThere is one classic, and I have seen it live often enough to spell it out here: reverse proxy buffering. In development, everything runs against the bare Node process and works flawlessly. As soon as nginx sits in front of it, the events suddenly no longer arrive one by one every second, but bundled and delayed – or seemingly not at all. The reason: nginx buffers response bodies by default, and to the buffer a `text/event-stream` is at first just a body that is not finished yet.\n\nThe fix is the response header `X-Accel-Buffering: no`, which nginx recognizes and then turns off buffering for that one response. Alternatively, you set `proxy_buffering off;` in the nginx configuration. That is why this header is already in the example above – not because every environment needs it, but because it saves you exactly the debugging afternoon that would otherwise inevitably come.\n\nTwo more stumbling blocks belong here. First, the format mentioned earlier: you have to either split line breaks inside the payload across several `data:` lines or avoid them – a raw `\\n` in the middle of the JSON tears the message apart. Second, a limitation of `EventSource` itself: the native client can only do GET and cannot set custom headers. Authentication therefore typically runs through cookies or a token in the query string, not through an `Authorization` header.\n\n## When SSE and when WebSocket\n\nThe deciding factor is the direction of the data. Here is the comparison that pins it down:\n\n- Direction: SSE is one-way, server to client. WebSocket is fully bidirectional.\n- Protocol: SSE is ordinary HTTP with a special content type. WebSocket needs a protocol upgrade of the connection.\n- Reconnect: Built into SSE, including `Last-Event-ID`. With WebSocket you build it yourself.\n- Payload: SSE carries UTF-8 text only. WebSocket handles text and binary data.\n- Infrastructure: SSE runs through normal proxies, auth and compression. WebSocket needs upgrade support everywhere.\n- Typical use: SSE for notifications, live feeds and progress indicators. WebSocket for chat, games and collaborative editors.\n\nIf the client mostly just listens, SSE is enough. Only when you need a real low-latency return channel – the user types, clicks, moves a game piece – is WebSocket the right investment. For everything else, SSE means less code, less infrastructure fiddling and less home-grown error handling.\n\n## Choosing a transport as a design decision\n\nThe comparison above answers the question of data direction. In practice, though, direction alone rarely decides; what the choice costs in operations and testing does. Three axes carry the decision, and you can walk through them in this order.\n\nFirst, data direction, because it is the hardest constraint. If traffic flows mainly from server to client, the return channel of WebSocket is dead weight that still needs looking after. If it flows both ways with low latency, SSE is the wrong tool, and any attempt to rebuild the return channel with a second HTTP request quickly gets more unpleasant than a clean WebSocket. This axis is not a matter of taste; it determines which capability you need at all.\n\nThen the operating environment, because it decides the running costs. SSE is ordinary HTTP. It runs through the same reverse proxies, load balancers, auth layers and compression stages as any other request, and your existing monitoring sees it without special treatment. WebSocket requires upgrade support at every hop, custom timeouts for long-lived connections and often sticky sessions so that a client stays with its backend. All of that is manageable, but it is extra operational surface someone has to maintain. If you scale horizontally, you notice the difference first: an SSE connection is a stream that any node can end and the client can reestablish, while a WebSocket cluster usually needs its own pub/sub layer so that an event also reaches the node the recipient is connected to.\n\nFinally, testability, because it sets your development cycles. I test an SSE endpoint with tools that are already there. A `curl -N http://localhost:3000/events` shows the raw stream in the terminal, and in a browser test the native `EventSource` is enough to check events and reconnects. A WebSocket channel usually needs its own client library in the test setup and more choreography to cover the handshake, the bidirectional flow and the home-grown reconnect. That does not show up with the first line, but with every feature afterwards that hangs off the channel.\n\nEconomically, the math is unspectacular and that is exactly why it matters. The cheaper transport is the one that touches fewer outside systems and can be tested with built-in tools. For a live feed, a progress bar or a notification bar, that almost always means SSE: shorter cycles, because less infrastructure is involved, and less friction in operations, because nothing new has to be monitored. The limit is just as clear. As soon as real interaction with a return channel comes into play, WebSocket earns back its higher operating costs with a capability SSE simply does not have. Making the choice deliberately costs a few minutes of thought once. Making it by reflex costs considerably more over the lifetime of the system.\n\n## SSE and HTTP/2 together\n\nAnd this brings us full circle. SSE does not need HTTP/2 – it runs perfectly happily over HTTP/1.1. But it benefits from it. Over HTTP/1.1, every open SSE connection counts against the browser’s limit of six per origin. If you work with several tabs or several parallel streams, you hit that quickly. Over HTTP/2, on the other hand, open SSE connections are streams within one connection. How many of them may be open at the same time is negotiated by the peer via `SETTINGS_MAX_CONCURRENT_STREAMS`; RFC 9113 recommends at least 100 but does not guarantee that value. The rigid HTTP/1.1 limit usually becomes much less relevant as a result.\n\nBecause SSE is a long-lived stream that delivers data in small pieces, it is also worth looking at how Node handles streams internally and what happens when a client reads more slowly than the server writes. If you serve many clients, you should understand backpressure – my post on [Node.js streams and backpressure](https://www.mikebild.dev/en/blog/nodejs-streams-understanding-backpressure/) fits right in.\n\nHTTP/2 has relaxed the transport layer so much that many old optimization tricks have become unnecessary, and Server-Sent Events bring exactly as much complexity as a one-way stream needs – not a bit more. The boundary stays sharp: as soon as data really flows in both directions, WebSocket is the right investment. It just flows both ways less often than the first reflex suggests. If you walk through the three axes once before you commit, in the best case you save yourself an entire pub/sub layer.\n\n## Further reading\n\n- [Node.js training](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/) and [Node.js streams and backpressure](https://www.mikebild.dev/en/blog/nodejs-streams-understanding-backpressure/) – the matching foundations from my blog.\n- [Node.js HTTP/2 module](https://nodejs.org/api/http2.html) – core API, compatibility API, `createSecureServer`, `pushStream`.\n- [MDN: Using server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) – SSE in practice.\n- [MDN: EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) – the EventSource interface in detail.\n- [WHATWG: Server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html) – the specification of the `text/event-stream` format.\n- [RFC 9113 (HTTP/2)](https://www.rfc-editor.org/rfc/rfc9113) and [RFC 7541 (HPACK)](https://www.rfc-editor.org/rfc/rfc7541) – the underlying standards."},{"locale":"en","translation_key":"markdown-reports-statt-dashboard","slug":"markdown-reports-instead-of-dashboards","title":"Markdown Reports Instead of Dashboard Mandates","summary":"Why a diffable Markdown report often does more for traceability, review and operations than a dashboard – and how I set that up architecturally.","tags":["Software","Content","Publishing"],"published_at":"2024-10-12T10:00:00+00:00","updated_at":"2026-07-20T13:27:22.94021+00:00","url":"https://www.mikebild.dev/en/blog/markdown-reports-instead-of-dashboards/","audio_url":null,"audio_duration_secs":null,"text":"# Markdown Reports Instead of Dashboard Mandates\n\nIf you build an evaluation only as a dashboard, half a year later you can no longer prove what it showed at the time of approval. The view still exists, the numbers are current – just no longer the same. The usual stopgap is a screenshot, and it does exactly what a screenshot does: it cannot be verified, searched or compared.\n\nA Markdown report costs almost nothing at the same point. It freezes a state, it consists of text and is therefore diffable, and it outlives the system that produced it. This post is not a hymn to text files. It describes an architectural decision – the report as a versioned artifact instead of a live view – and what this decision concretely changes for review cycles, operations and quality.\n\nThe format question becomes clearer as soon as the reader’s purpose comes before the UI.\n\n::::comparison{title=\"Watching live or proving a state\" role=\"primary\" preferredPattern=\"split-comparison\"}\n:::side{label=\"Dashboard\"}\n- Question · What is happening right now?\n- State · recomputed on every request\n- Strength · fast reaction to ongoing changes\n- Limit · the earlier state is not documented without an additional archive\n:::\n:::side{label=\"Published report\"}\n- Question · What was true for the closed period?\n- State · immutable, versioned artifact\n- Strength · verifiable, diffable and readable in the long term\n- Limit · no interactive real-time analysis\n:::\n::::\n\nSo the two forms do not compete for the same job. They only get mixed up when historical evidence is treated like a live view.\n\n## The real question: transient state or artifact\n\nA dashboard answers the question “What does it look like right now?” That is valuable when I monitor a running process and have to react within seconds – latencies, error rates, load. For operations, a dashboard is often unbeatable.\n\nThe fallacy begins when the same pattern is applied to evaluations whose real value lies in traceability: an inventory, a reconciliation, a publishing run, a data migration report. Here the interesting question is not “What does it look like now?” but “What did it look like at time X, why, and what has changed since then?” A dashboard structurally cannot answer that, because it has no fixed state. It re-renders on every request. Last week’s state is gone as soon as the underlying data shifts.\n\nA Markdown report draws the line differently. It freezes a state, is textual and therefore diffable, and can be stored, versioned and passed on as a file. Three properties matter in practice:\n\nTraceability means that the report carries its own context – input state, rules, result, exceptions. If you open it in six months, you do not have to reconstruct the system that produced it.\n\nDiffability means that two runs can be compared without anyone laying two screenshots side by side. A `git diff` shows in seconds which item is new, which match flipped, which line disappeared. Review thus turns from an act of interpretation into a mechanical process.\n\nArchivability means that the report survives without the infrastructure that produced it. No running service, no database connection, no auth token. A text file in a repository will still be readable in ten years.\n\n## The report as an architectural artifact\n\nThis becomes clearest with a tool I built for an inventory and account reconciliation. The task: match inventory items against invoices and bookings, assign receipts to the right transactions, make gaps visible. The obvious solution would have been a dashboard with a few green and red tiles. Instead, I made the report the central artifact – and aligned the entire architecture with it.\n\nWhat carries the design is a three-stage structure that applies regardless of the file format: link the account ledger to PDFs via invoice numbers, match inventory items against invoice line items, and handle non-PDF vendors separately through booking text rules. These stages are the actual domain logic. The output format is the consequence, not the decision.\n\nWithin the matching stage, I strictly separate hard matches and the fuzzy fallback. First, defined tokens have to appear in the product title; only when the hard path finds nothing does fuzzy matching kick in. Whether the automation stays explainable depends on this order. Every line in the report can say why it was assigned the way it was – `exact` or `fuzzy` – and a person can check exactly the second category in a targeted way.\n\n```ts\ntype MatchKind = \"exact\" | \"fuzzy\" | \"orphan\";\n\ntype ReconciliationRow = {\n  inventoryItem: string;\n  invoiceNumber: string | null;\n  purchaseDate: string | null;\n  matchKind: MatchKind;\n  confidence: number; // 0..1, only meaningful for fuzzy\n  note: string;\n};\n```\n\nI deliberately treat the OCR layer not as truth but as a sensor. Apple Vision provides the basis, Tesseract specifically corrects amounts in the debit/credit region, and a JSON cache makes later runs reproducible. That is the architectural point: a sensor has a measurement error, and as soon as that is in the model, dealing with uncertainty becomes an explicit part of the system instead of a hidden assumption. The cache is not there for speed; it guarantees determinism – the same receipt produces the same report.\n\nThe result is a report that makes inventory items, invoice numbers, purchase date, match type, orphaned account entries and unused invoice lines visible:\n\n```md\n## Reconciliation 2024-10-12\n\n| item              | invoice | date       | match  | note                  |\n|-------------------|---------|------------|--------|-----------------------|\n| ThinkPad X1       | R-1042  | 2024-03-11 | exact  | token \"X1\" matched    |\n| USB-C Hub         | R-1043  | 2024-03-11 | fuzzy  | 0.82, title reworded  |\n| Monitor Stand     | —       | —          | orphan | no invoice position   |\n\nOrphans: 1 · Fuzzy: 1 · Unused invoice lines: 3\n```\n\nThat is exactly what turns a script into a verifiable data system. The orphaned entries – the really interesting part – are not in a log that nobody reads, but in the same artifact as the successful matches. An accountant can sign off on this report, file it and hold it up against the new one next year. A dashboard would have shown the same information and forgotten it on the next reload.\n\nThe concrete case that convinced me of this design was unspectacular and instructive for exactly that reason. A vendor had listed the same item twice on an invoice, once as a bundled item and once individually. The hard match hit both times, and in a tile view this would have passed as “all green.” In the diffable report it stood out, because the same invoice number suddenly appeared in two lines with different purchase dates – an anomaly you see when reading and overlook when rendering. The mistake was in the data, not in the code; the report turned it into a visible line instead of a silent double booking. For me, that is the core: an artifact you read uncovers a different class of errors than a view you only skim.\n\n## Publishing as the same movement\n\nThe same principle holds in a completely different context: publishing. Here Markdown is the input, but the way from text to published page is not a magic CMS click. I break it down into separate, nameable states: Markdown as input, revision as an unchangeable state, preview as a trust step, release as an activated pointer, rollback as a controlled return.\n\n```mermaid\nflowchart LR\n  Markdown[Markdown input] --> Revision[Immutable revision]\n  Revision --> Preview[Preview build]\n  Preview --> Release[Release pointer]\n  Release --> Live[Live site]\n  Release -.rollback.-> Revision\n```\n\nThe decisive trade-off lies in separating build and activation. A revision is built and checked before it becomes visible. Activation is then just a pointer switch – and so is rollback. That takes the thrill out of the release: if you see exactly what will be published and know that a mistake is one pointer switch away from being undone, you need less courage and produce fewer midnight hotfixes. Immutable releases pay off exactly here: the cost of a mistake shifts from “reconstruction under pressure” to “one command.”\n\nHaving Markdown as the input keeps the whole chain portable. Content stays separate from presentation and operations. From the same text I can later generate a presentation or export it to another target system without rewriting it. For personal sites and technical portfolios, this setup is almost always more valuable than a big CMS – what matters are preview, atomic publishing, stable URLs and a clear export path, not the feature set of an editor.\n\n## The decision before the format\n\nIn the reconciliation, gaps should stay visible and correctable; in publishing, a draft should be publishable and retractable in a controlled way. The boundaries follow from that: OCR is a sensor, matching stays domain logic, revision and release are separate states. Only then do I decide on the format. For a verifiable state, a versioned artifact fits; for ongoing observation, a dashboard.\n\n## What this measurably changes\n\nThe effect of this decision is not just aesthetic; it is measurable in daily work.\n\nReview cycles get shorter because the diff replaces interpretation. Instead of comparing two states visually, a reviewer sees the three changed lines. What used to be a half-hour review becomes a glance at a pull request.\n\nFriction drops because approvals hang on a concrete artifact instead of a transient view. A signed-off report is a document with a timestamp. A dashboard view someone nodded at is a memory.\n\nQuality rises because the failure path is part of the output. Orphaned entries, fuzzy matches and unused line items are in the same artifact as the successes. You do not have to look for them; you see them while reading. And in publishing, rollback-as-pointer shifts the mean time to repair from minutes under pressure to a single command.\n\nThese effects are the real business outcome: review faster, argue less, find mistakes earlier. “We have a nice dashboard” is not on this list.\n\n## Where I stick with the dashboard\n\nI do not want to make the decision dogmatic. For real monitoring – live metrics, alerts, time series with per-second resolution – a dashboard is the right tool, and a Markdown report would be absurd. The dividing line follows from the nature of the question, not from a matter of faith of report versus dashboard: continuous observation of a running system versus a verifiable state of a completed evaluation. Many teams reach for the dashboard because it is the default, even though their question clearly belongs to the second category. That reflexive default is exactly what I want to break open.\n\n## The failure path as the touchstone\n\nAn idea only holds up when its failure path is described too. For the reconciliation, I ask: what happens on repetition? Is the run idempotent? The JSON cache takes care of that – the same receipt twice, the same result twice. For publishing: can I extend the schema without breaking existing pages? Can I explain a faulty release and roll it back? If the answer were no, a part of the architecture would still be missing, no matter how clean the happy path looks.\n\nThe most common mistake here is confusing the tool with the solution. Markdown is not an architecture, a CMS is not a publishing process, and OCR is not proof of truth. These tools can express good boundaries, but they do not create them by themselves. You draw the boundary beforehand, in the model – and the report only makes it visible.\n\n## Closing\n\nThe reflex “let’s build a dashboard” is so well practiced that the alternative hardly gets consciously considered anymore. Yet in a surprising number of cases, a Markdown report is the stronger choice: diffable, archivable, self-explanatory, and therefore a real artifact instead of a transient window. The real gain is not in the format. It is in the boundary it draws – between what is happening right now and what has to stay traceable. If you set this boundary deliberately, you review faster, publish more calmly and find mistakes where they are still cheap.\n\n## Further reading\n\n- [CommonMark specification 0.31.2](https://spec.commonmark.org/0.31.2/)\n- [Git: `git diff`](https://git-scm.com/docs/git-diff/2.45.0)"},{"locale":"en","translation_key":"graphql-federation-und-subgraphs","slug":"graphql-federation-and-subgraphs","title":"GraphQL Federation: One Schema from Many Subgraphs","summary":"When one team can no longer carry a monolithic schema on its own, Federation splits the graph into subgraphs that a router composes into a supergraph. Using a users and orders example, this article shows how @key and __resolveReference hold entities together across subgraph boundaries.","tags":["Software","GraphQL","API"],"published_at":"2024-09-24T10:00:00+00:00","updated_at":"2026-07-13T08:52:54.757214+00:00","url":"https://www.mikebild.dev/en/blog/graphql-federation-and-subgraphs/","audio_url":null,"audio_duration_secs":null,"text":"```bash\n$ rover supergraph compose --config ./supergraph.yaml\n\nerror[E029]: Encountered 1 build error while trying to build a supergraph.\n\nCaused by:\n    INVALID_GRAPHQL: [orders] Unknown directive \"@key\".\n```\n\nThis message doesn’t come from a running server. It comes from a build step that a single GraphQL service doesn’t even know about: composition. The orders service uses `@key` without having imported the directive first – and this one missing entry is enough to keep several schemas from becoming a shared graph.\n\n`@key` is the directive Apollo Federation uses to make a type referenceable across service boundaries. Everything else hinges on it: who owns which type, who contributes which fields, who assembles the parts into a response – and the question of how to cut apart a schema that three teams work on without the clients noticing. Drawn too early, though, this split costs more than it brings in; I’ll come back to that at the end.\n\n## The problem: a schema that nobody owns anymore\n\nAt the beginning, a GraphQL schema is wonderful. One team, one repository, one `type Query`, everything in one place. After all, the appeal of GraphQL is that clients fetch exactly the fields they need from a single endpoint. I have already covered related questions in earlier posts – for example how to deliver lists cleanly with [GraphQL pagination](https://www.mikebild.dev/en/blog/graphql-pagination-cursors-and-connections/) or how permissions are passed through with [GraphQL auth in the context](https://www.mikebild.dev/en/blog/graphql-auth-identity-in-the-context/).\n\nThe problem starts with growth. As soon as several teams work on one schema, the file becomes a bottleneck. The users team wants to attach a field to `type Order`, but to do so it has to reach into the orders team’s code. Deployments become coupled. A `type` suddenly belongs to many, and in practice “belongs to many” means: to nobody. What shows up as a merge conflict in everyday work is a conflict of ownership.\n\nFederation turns the question around. Instead of “How do teams share a schema?”, it asks: “How does each team run its own schema – and the client still sees only one graph?”\n\n## The basic idea: subgraphs, supergraph, one endpoint\n\nIn Apollo Federation 2 – the generation that has been relevant since 2022 and the one I mean throughout this article – each team runs a **subgraph**. A subgraph is a perfectly normal GraphQL service with its own schema, its own database and its own deployment. The individual subgraph schemas are composed into a **supergraph schema**. At runtime, a router (or a gateway) sits in front of them, receives the incoming query, creates a plan and distributes the sub-queries to the responsible subgraphs.\n\nThe key point: the client notices none of this. It talks to one endpoint, sees one schema, sends one query. The split is purely an operational and team topology – invisible to the consumer.\n\n```mermaid\nflowchart TB\n  Client[\"Client<br/>one query, one endpoint\"]\n  Router[\"Router / Gateway<br/>executes the query plan\"]\n  Users[\"Users subgraph<br/>Team A\"]\n  Orders[\"Orders subgraph<br/>Team B\"]\n  UDB[(\"Users DB\")]\n  ODB[(\"Orders DB\")]\n\n  Client --> Router\n  Router --> Users\n  Router --> Orders\n  Users --> UDB\n  Orders --> ODB\n```\n\nIf you run the runtime, you have two established options in 2024: the **`@apollo/gateway`** in Node or the **Apollo Router**, written in Rust. Both are valid. The router is the faster option and the usual recommendation for new setups, but the gateway is by no means deprecated – if you already run a Node gateway, you don’t have to move.\n\n## Roles in the system\n\nBefore writing code, it helps to keep the three building blocks clearly apart:\n\n- The **subgraph** contributes exactly its own fields. It knows its database, its schema, its deployment – and nothing else. This is where team autonomy lives.\n- The **`@key`** directive marks a type as an entity, meaning it’s referenceable across subgraphs. Without `@key`, another subgraph can neither extend the type nor point to it by reference.\n- The **router** plans the query. It breaks an incoming request into sub-queries, fetches each subgraph’s contribution and assembles the response again. Cross-subgraph joins are its job, not the teams’.\n\nThis separation is the whole trick: teams think locally, the router thinks globally.\n\n## Fed 2 is explicit: the @link opt-in\n\nA subgraph in Federation 2 states explicitly which Federation directives it wants to use. It does this through `@link` on the schema. That’s a deliberate break with Federation 1, where `extend type ... @key` implicitly came with certain behavior. In Fed 2, you import what you need:\n\n```graphql\nextend schema\n  @link(\n    url: \"https://specs.apollo.dev/federation/v2.0\"\n    import: [\"@key\", \"@shareable\", \"@external\"]\n  )\n```\n\nIf you forget the `@link` or use a directive that wasn’t imported, you don’t get a runtime error but a composition error – and you get it early, when composing or publishing. That regularly surprises people moving from Fed 1, but it’s the better moment for an error.\n\n## The users subgraph\n\nLet’s start with the easy part. The users subgraph owns the `User` entity. It defines it, marks it with `@key` and provides a reference resolver that resolves a `User` representation.\n\n```graphql\nextend schema\n  @link(url: \"https://specs.apollo.dev/federation/v2.0\", import: [\"@key\"])\n\ntype User @key(fields: \"id\") {\n  id: ID!\n  name: String!\n  email: String!\n}\n\ntype Query {\n  user(id: ID!): User\n}\n```\n\nThe code for it uses `buildSubgraphSchema` from the `@apollo/subgraph` package. That’s the building block that turns `typeDefs` and `resolvers` into a federated `GraphQLSchema` that knows the Federation directives and the fields required by the spec, such as `_entities`.\n\n```ts\nimport { ApolloServer } from '@apollo/server';\nimport { startStandaloneServer } from '@apollo/server/standalone';\nimport { buildSubgraphSchema } from '@apollo/subgraph';\nimport gql from 'graphql-tag';\n\nconst typeDefs = gql`\n  extend schema\n    @link(url: \"https://specs.apollo.dev/federation/v2.0\", import: [\"@key\"])\n\n  type User @key(fields: \"id\") {\n    id: ID!\n    name: String!\n    email: String!\n  }\n\n  type Query {\n    user(id: ID!): User\n  }\n`;\n\nconst resolvers = {\n  Query: {\n    user: (_parent, { id }) => fetchUserById(id),\n  },\n  User: {\n    // The router hands us a representation: { __typename: \"User\", id }\n    __resolveReference: (reference) => fetchUserById(reference.id),\n  },\n};\n\nconst server = new ApolloServer({\n  schema: buildSubgraphSchema({ typeDefs, resolvers }),\n});\n\nconst { url } = await startStandaloneServer(server, { listen: { port: 4001 } });\nconsole.log(`Users subgraph ready at ${url}`);\n```\n\nThe heart of it is `__resolveReference`. This function receives a **representation** – an object with `__typename` and the `@key` fields – and returns the complete entity (or `null` if it doesn’t exist). The important thing to understand: a normal field resolver isn’t enough here, because the router starts the resolution process with only the key fields. Without a reference resolver, it can’t fill the gap.\n\n## The orders subgraph with a cross-reference\n\nNow it gets interesting. The orders subgraph owns `Order`. An order belongs to a user – but the orders subgraph only knows the user’s ID. It still wants to offer an `order.user` field. To do that, it includes `User` as a stub: with `@key`, but only with the key field, without resolving the other fields itself.\n\n```graphql\nextend schema\n  @link(url: \"https://specs.apollo.dev/federation/v2.0\", import: [\"@key\"])\n\ntype Order @key(fields: \"id\") {\n  id: ID!\n  total: Int!\n  user: User\n}\n\n# User lives in the users subgraph; here it is only referenced.\ntype User @key(fields: \"id\") {\n  id: ID!\n}\n\ntype Query {\n  order(id: ID!): Order\n}\n```\n\nThe resolver for `Order.user` does something that seems almost too simple at first: it only returns a reference – `__typename` plus the key field. The actual resolution of `name` or `email` happens later in the users subgraph.\n\n```ts\nconst resolvers = {\n  Query: {\n    order: (_parent, { id }) => fetchOrderById(id),\n  },\n  Order: {\n    __resolveReference: (reference) => fetchOrderById(reference.id),\n    // Return just a reference; the users subgraph fills in the rest.\n    user: (order) => ({ __typename: 'User', id: order.userId }),\n  },\n};\n```\n\nThis way, each responsibility stays where it belongs. The orders team knows which user an order belongs to (the `userId` lives in its database), but it doesn’t need to know the user data itself. The router takes care of the rest.\n\n## What the router does behind the scenes\n\nLet’s take a client query that spans both:\n\n```graphql\nquery {\n  order(id: \"42\") {\n    total\n    user {\n      name\n    }\n  }\n}\n```\n\nThe client sees a query. The router sees a plan. It first fetches `total` and the `user.id` from the orders subgraph, then sends an `_entities` request with the representation `{ __typename: \"User\", id }` to the users subgraph, whose `__resolveReference` uses it to get the `name`, and finally merges everything into one response.\n\n```mermaid\nsequenceDiagram\n  participant C as Client\n  participant R as Router\n  participant O as Orders subgraph\n  participant U as Users subgraph\n\n  C->>R: order(id: 42) { total, user { name } }\n  R->>O: order { total, user { id } }\n  O-->>R: { total: 90, user: { id: 7 } }\n  R->>U: _entities([{ __typename: User, id: 7 }])\n  U-->>R: { name: \"Ada\" }\n  R-->>C: { total: 90, user: { name: \"Ada\" } }\n```\n\nOnce this flow sinks in, it clicks: `@key` says how an entity can be recognized, `__resolveReference` says how to make it complete from that recognition, and the router orchestrates in between.\n\n## Composing and starting\n\nThe subgraph schemas have to be merged into a supergraph. That’s a build or publishing step, not a task the router performs during a request. Locally, you compose with `rover supergraph compose` and a configuration that points to the subgraphs:\n\n```bash\n# supergraph.yaml lists each subgraph and its endpoint\nrover supergraph compose --config ./supergraph.yaml > supergraph.graphql\n\n# Start the Apollo Router with the composed supergraph\n./router --supergraph supergraph.graphql\n```\n\nIn larger setups, managed federation through Apollo Studio / GraphOS takes over this step: each subgraph publishes its schema, composition happens centrally, and the router pulls the current supergraph version. The important point stays the same – composition is the moment errors show up, not runtime.\n\n## Shared fields: the difference from Federation 1\n\nA detail that regularly trips up people moving from Fed 1: in Federation 2, non-key fields are **not** shareable by default. If the same field of a type is resolved in several subgraphs, it has to be marked explicitly with `@shareable` – otherwise composition fails. This mainly affects value types that appear identically in several subgraphs.\n\n```graphql\ntype Money @shareable {\n  amount: Int!\n  currency: String!\n}\n```\n\n`@external` is related: a field that this subgraph only references and that belongs to another one is marked as `@external` – often together with `@requires` or `@provides`, when a subgraph needs a foreign field for its logic. Fed 2 is stricter than Fed 1 here, and that’s intentional: ambiguities become errors instead of hiding quietly at runtime.\n\n## Three pitfalls\n\nFederation solves an organizational problem, but it brings technical quirks with it. Three of them carry particular weight.\n\nN+1 lurks in the reference resolver. The router resolves entities one at a time or in batches, and if `__resolveReference` naively makes one database round trip per call, you end up with many small queries. A DataLoader per subgraph request bundles them – the same pattern you use against N+1 outside of Federation, too.\n\nThe key field also has to land reliably in the payload. A field with arguments, or a union or interface return type, doesn’t work as a `@key`; a nullable field is allowed but not recommended. Different key fields for the same entity across different subgraphs are permitted but error-prone – when in doubt, use the same key everywhere.\n\nAnd the third point hits everyone who comes from a world where such things only blow up in production: a forgotten `@shareable`, a type mismatch, a missing `@link` import – all of these are rejected as early as composing or publishing, not at runtime. The right moment, but an unfamiliar one.\n\n## Federation 2 or schema stitching?\n\nIf you have worked with GraphQL for a while, you’ll still know **schema stitching** – the older way of merging several schemas, today for example with `@graphql-tools/stitch`. With stitching, you combine remote schemas manually and write the delegation and merge logic yourself. That works, but the coupling lives in the gateway code, not in a spec. Federation instead declares the relationships in the schema (`@key`, `@shareable`) and leaves execution to the router. Stitching isn’t dead – for some special cases with third-party schemas you can’t change, it’s still useful. But for a new, team-driven architecture in 2024, I reach for Federation 2.\n\n## When I DON’T federate\n\nThe most important point comes last, because it triggers the most pushback in architecture discussions: Federation is overhead. Router, composition, reference resolvers, an extra network hop for each cross-subgraph join – all of that has to be operated and understood. If a single team runs a schema that fits well into one service, Federation solves a problem this team doesn’t have. You take on a distributed system to model an organizational boundary that doesn’t even exist yet.\n\nFederation follows the team structure, not the technology. Only when several teams get in each other’s way on one schema, when deployments become coupled, when a `type` no longer belongs to anyone – that’s when the split pays off. Before that, a good monolith with clear modules is almost always the better choice. And if you already work cleanly with [Apollo Client caching](https://www.mikebild.dev/en/blog/apollo-client-normalized-cache-and-optimistic-updates/) on the client side, you’ll notice: Federation changes nothing on the client – there, it remains exactly the one graph it always was.\n\n## Further reading\n\n- Introduction to Apollo Federation: https://www.apollographql.com/docs/federation/\n- Entities (`@key`, `__resolveReference`): https://www.apollographql.com/docs/federation/entities\n- Implementing a Subgraph with Apollo Server: https://www.apollographql.com/docs/federation/subgraphs/\n- API `@apollo/subgraph` (`buildSubgraphSchema`): https://www.apollographql.com/docs/apollo-server/using-federation/api/apollo-subgraph\n- Moving to Federation 2 (including `@shareable`): https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/reference/moving-to-federation-2\n- Subgraph spec (`_entities`, `_Entity`, `@link`): https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/reference/subgraph-spec"},{"locale":"en","translation_key":"fuzzy-matching-mit-grenzen","slug":"fuzzy-matching-with-explicit-limits","title":"Fuzzy Matching with Explicit Limits","summary":"A fuzzy match is a claim with a confidence, not a fact – it only becomes useful through versioned thresholds, three decision zones, and a diffable report of the gray zone.","tags":["Software","Data","Tools"],"published_at":"2024-09-12T10:00:00+00:00","updated_at":"2026-07-14T17:24:17.741369+00:00","url":"https://www.mikebild.dev/en/blog/fuzzy-matching-with-explicit-limits/","audio_url":null,"audio_duration_secs":null,"text":"# Fuzzy Matching with Explicit Limits\n\n```sql\nSELECT similarity('Schmidt Bau GmbH', 'Schmitt Bau GmbH');\n-- 0.72\n\nSELECT similarity('Bäckerei Hoffmann GmbH & Co. KG',\n                  'BAECKEREI HOFFMANN DANKE RG 4711');\n-- 0.34\n```\n\nThe first value looks like a match and isn’t one: two different companies, one letter apart, both of them exist. The second value looks like noise and is the right customer – just the way it arrives in a bank transfer’s payment reference: in capitals, without umlauts, with an invoice number and a sign-off in the same field. Once you have seen these two numbers side by side, you never trust a similarity function blindly again. That is exactly the right state of mind for working with fuzzy matching.\n\n## The starting point: payment references against open items\n\nThe context is the same private data project as the month before: reconciling invoice and payment data. On one side are open items with clean debtor names from master data maintenance. On the other side are bank transactions whose payment reference is a free-text field. People and accounting systems write whatever they want there: sometimes the invoice number, sometimes the company name in one of five spellings, sometimes both, sometimes neither.\n\nAs long as an invoice number is in the text, the reconciliation is trivial – a regular expression, an exact key, done. It gets interesting with the remaining payments, where only a company name is left as an anchor. “Müller & Söhne GmbH” arrives as “MUELLER SOEHNE,” “Mueller u. Soehne Bau,” or “M&S GmbH.” Exact matching finds nothing here, and that is exactly what fuzzy matching is for. The question isn’t whether to use it but how to prevent “similar” from silently turning into “equal.”\n\nOne sentence helped me here, which I wrote on the report early on: a match is a claim with a confidence, not a fact. Everything else in this post is the technical consequence of that sentence.\n\n## Normalization first\n\nBefore any distance function runs, the most boring step pays off the most: normalization. A large part of the apparent fuzziness isn’t fuzziness at all – it consists of systematic differences that you can clear away deterministically. Legal forms such as GmbH, AG, or KG carry almost no distinguishing power but inflate every similarity calculation. In payment transactions, umlauts traditionally appear as ae/oe/ue. Upper and lower case, double spaces, punctuation: all noise.\n\n```python\nimport re\n\nLEGAL_FORMS = re.compile(\n    r\"\\b(gmbh|ag|kg|ug|ohg|gbr|mbh|co)\\b\\.?\",\n    re.IGNORECASE,\n)\n\nUMLAUT_MAP = str.maketrans(\n    {\"ä\": \"ae\", \"ö\": \"oe\", \"ü\": \"ue\", \"ß\": \"ss\"}\n)\n\ndef normalize_name(raw: str) -> str:\n    text = raw.strip().lower().translate(UMLAUT_MAP)\n    text = LEGAL_FORMS.sub(\" \", text)\n    text = re.sub(r\"[^a-z0-9 ]+\", \" \", text)\n    return re.sub(r\"\\s+\", \" \", text).strip()\n```\n\nAfter this step, “Müller & Söhne GmbH” and “MUELLER SOEHNE” are both `mueller soehne` – an exact match, without any fuzzy method at all. In my data set, normalization alone turned roughly half of the previously “fuzzy” cases into exact matches. That is why I don’t see normalization as a preliminary stage of fuzzy matching but as a stage in its own right, with its own measure of success. Every case that becomes exact here doesn’t have to be defended with a confidence later.\n\nIt is important that `normalize_name` runs identically on both sides – on the debtor names just as on the payment references. As soon as two slightly different normalizations are in play, you end up chasing ghosts.\n\n## Distances, trigrams, phonetics\n\nFor the rest, the classic methods remain, and they have different strengths. Levenshtein counts edit operations and is good for typos. Jaro-Winkler weights matches at the start of a word more heavily – a good fit for company names, where the beginning is usually stable and suffixes vary at the end. Trigram similarity breaks strings into groups of three characters and compares the sets; it is insensitive to word order and available directly in SQL in Postgres through the pg_trgm extension.\n\nThere is also a method that is mentioned too rarely in German-speaking countries: Kölner Phonetik (Cologne phonetics). It is the German counterpart to Soundex and maps words to a sound code designed for German pronunciation. “Meyer,” “Maier,” and “Mayr” end up with the same code – for distance functions, these are three different strings; to the ear, it is the same name. As the sole criterion, phonetics is too coarse; as an additional signal next to a distance, it is valuable.\n\nIn Python, rapidfuzz bundles the distance methods in a fast library. I combine two measures into one score, because no single method covers all types of errors:\n\n```python\nfrom rapidfuzz import fuzz, distance\n\ndef score_pair(payment_name: str, debtor_name: str) -> float:\n    jaro_winkler = distance.JaroWinkler.similarity(\n        payment_name, debtor_name\n    )\n    token_sort = fuzz.token_sort_ratio(\n        payment_name, debtor_name\n    ) / 100\n    return 0.6 * jaro_winkler + 0.4 * token_sort\n```\n\n`token_sort_ratio` sorts the words before comparing them and thus catches swapped word order (“bau schmidt” versus “schmidt bau”). The weights 0.6 and 0.4 aren’t a law of nature – they are a parameter that I calibrated on a hand-labeled slice of the data. That, too, is part of the method’s honesty: the score is a constructed quantity, not the truth.\n\n## Blocking against the quadratic trap\n\nIf you compare every payment reference against every open item, you pay O(n²). With a few hundred records, that doesn’t matter; with tens of thousands of payments against thousands of debtors, it does. The standard answer is blocking: a cheap, coarse preselection that shrinks the set of candidates before the expensive comparisons run.\n\nThis is where pg_trgm plays its second strength. Trigram similarity is not only a function but also an indexable operator. With a GIN index on the normalized name, Postgres returns the most similar candidates without touching the whole table:\n\n```sql\nCREATE EXTENSION IF NOT EXISTS pg_trgm;\n\nCREATE INDEX idx_open_invoice_debtor_trgm\n    ON open_invoice\n    USING gin (debtor_name_normalized gin_trgm_ops);\n\nSET pg_trgm.similarity_threshold = 0.45;\n\nSELECT i.invoice_no,\n       i.debtor_name_normalized,\n       similarity(i.debtor_name_normalized, :payment_name)\n           AS trigram_score\nFROM open_invoice AS i\nWHERE i.debtor_name_normalized % :payment_name\nORDER BY trigram_score DESC\nLIMIT 10;\n```\n\nThe `%` operator checks against the configured threshold and uses the index while doing so. The 0.45 is deliberately set low: at this stage, a missed candidate is worse than twenty superfluous ones, because whatever blocking discards, the detailed scoring never sees again. The actual decision is made later – with `score_pair` over the ten candidates, not in SQL.\n\nThis two-way split has proven itself: Postgres does the preselection coarsely and quickly, Python does the scoring precisely and traceably. Each stage has its own threshold with its own justification.\n\n## Three zones instead of one threshold\n\nNow to the actual point. Most fuzzy matching examples you find end with a single threshold: a score above X is a match, below it is no match. That is the point where a useful tool turns into a dangerous one, because a single threshold claims a precision of separation that the data doesn’t support. There is always a range in which the method simply doesn’t know whether two names belong together – and this not-knowing belongs in the architecture, not under the rug.\n\nThat is why my reconciliation has three zones instead of one threshold:\n\n- Above the acceptance threshold, the assignment is made automatically, and it carries the score as metadata.\n- Between the thresholds, the pair ends up on a review list – a human decides.\n- Below the rejection threshold, nothing happens; the payment stays open.\n\n```python\nTHRESHOLDS = {\n    \"version\": \"2024-09-03\",\n    \"accept\": 0.93,\n    \"reject\": 0.72,\n}\n\ndef classify(score: float) -> str:\n    if score >= THRESHOLDS[\"accept\"]:\n        return \"accept\"\n    if score < THRESHOLDS[\"reject\"]:\n        return \"reject\"\n    return \"review\"\n```\n\nThe thresholds are versioned in the repository, not scattered as a constant somewhere in the code. Every change to them is a commit with a justification. That sounds bureaucratic, but it helped me after just two weeks: when I raised the acceptance threshold from 0.90 to 0.93 because the Schmidt/Schmitt pair from the introduction had slipped through, I could see exactly in the history which assignments had been made under which version of the rules.\n\n```mermaid\nflowchart LR\n    P[Verwendungszweck] --> N[normalize_name]\n    D[Debitorenname] --> N\n    N --> B[Blocking<br/>pg_trgm, Schwelle 0.45]\n    B --> S[Feinbewertung<br/>score_pair]\n    S --> Z{Score}\n    Z -->|ab 0.93| A[automatisch<br/>zuordnen]\n    Z -->|0.72 bis 0.93| R[Durchsicht<br/>durch Menschen]\n    Z -->|unter 0.72| X[offen lassen]\n    R --> AL[Alias-Regel<br/>versioniert]\n    AL --> N\n```\n\nThe feedback loop at the bottom right of the diagram is not a detail. Every manual decision from the review is recorded as an alias rule – “M&S” is “Müller & Söhne” – and flows back into normalization as data. On the next run, the same case is an exact match. As a result, the gray zone shrinks over time, and it does so through documented decisions rather than bolder thresholds.\n\n## The gray zone report\n\nFor me, the review list isn’t a dashboard but a Markdown file that every run generates deterministically: same input, same thresholds, same report. Sorted by score, with both names in their original and normalized form, the trigram value from blocking, and the combined score next to them.\n\nThe reason for Markdown is diffability. You can compare two runs with `diff`, and the difference tells a story: which cases disappeared from the gray zone thanks to new alias rules? Which new doubtful cases came in with the last bank statement? Did the threshold change make the zone bigger or smaller? A dashboard shows the latest state; a diffable report shows the movement. For a reconciliation system whose core question is “what changed and why,” that carries more weight than any UI.\n\nSide Effect: the report is also the audit artifact. If I want to know in three months why a payment was assigned the way it was, the score, the version of the rules, and, where applicable, the manual decision are in the history.\n\n## Asymmetric costs\n\nThat leaves the question of where the thresholds should be – and you don’t answer it with statistics alone but with the costs of the two types of error. Here, they are clearly asymmetric. An unassigned payment is a known problem: it shows up in the list of open cases, someone looks at it, assigns it, done. A wrongly assigned payment is an unknown problem: one customer’s open item counts as paid, and the other may get a dunning notice for a paid invoice. The error only gets noticed when someone complains – and then troubleshooting is expensive, because nobody knows anymore which run with which version of the rules produced the assignment.\n\nThat is why the acceptance threshold is deliberately high and the gray zone is wider than the pure hit rate would suggest. I would rather accept twenty manual reviews per month than one silent wrong assignment per quarter. That isn’t a technical decision but a business one – but it only becomes possible because the architecture makes the adjusting screw explicit. A single, hard-coded threshold doesn’t even offer this trade-off.\n\n## What I take away from this\n\nFuzzy matching has a bad reputation among people who were once bitten by a wrong assignment, and too good a reputation among people who have only seen the demo. Both miss the point. The methods – Levenshtein, Jaro-Winkler, trigrams, Kölner Phonetik – have been understood for decades and reliably do what they promise: they measure similarity. What they can’t do is establish identity. The error almost never lies in the method but in the system boundary that silently turns a similarity value into a fact.\n\nThe whole thing becomes useful at exactly the moment the limits become explicit: normalization as a stage of its own, so that what is deterministic stays deterministic. Blocking with a deliberately low threshold, so that the expensive scoring stays affordable. Three zones with versioned thresholds, so that the method’s not-knowing has a defined place. A diffable report, so that the gray zone visibly shrinks instead of growing unnoticed. And thresholds that are guided by the asymmetric costs of errors rather than by the hit rate.\n\nNone of this is new, and that is exactly what I like about it. It is the same attitude that already paid off when modeling the invoice data the month before: don’t abstract uncertainty away; give it a name, a value, and a place in the data model. A match is a claim with a confidence. Systems that take this seriously can be trusted with automation.\n\n## Further reading\n\n- RapidFuzz on GitHub: https://github.com/rapidfuzz/RapidFuzz\n- Postgres 16, pg_trgm extension: https://www.postgresql.org/docs/16/pgtrgm.html\n- Kölner Phonetik (Wikipedia): https://de.wikipedia.org/wiki/K%C3%B6lner_Phonetik"},{"locale":"en","translation_key":"event-sourcing-auf-aws-dynamodb-streams","slug":"event-sourcing-on-aws-dynamodb-streams-and-lambda","title":"Event Sourcing on AWS: DynamoDB Streams and Lambda","summary":"Event Sourcing implemented serverless: DynamoDB as an append-only event store, DynamoDB Streams as the change feed and Lambda as an idempotent projector into CQRS read models.","tags":["Software","AWS","Cloud"],"published_at":"2024-09-10T10:00:00+00:00","updated_at":"2026-07-13T07:29:27.668417+00:00","url":"https://www.mikebild.dev/en/blog/event-sourcing-on-aws-dynamodb-streams-and-lambda/","audio_url":null,"audio_duration_secs":null,"text":"An event store is not a table whose rows you update. You only append: every state change is a new, immutable item, and the state of an aggregate only emerges when you fold its events in version order. In my [conceptual look at Event Sourcing](https://www.mikebild.dev/en/blog/event-sourcing-the-event-store-as-a-logbook/), I described this as a logbook – the sequence of events carries the truth, and the state is merely its result.\n\nOn the whiteboard, that is quickly explained. It only becomes viable with the answers to the next questions: Where does the store run? Who guarantees the order? What happens when a consumer sees the same event twice? On AWS, you can assemble this from managed services, and the sharp edges then lie in concurrency when appending, in the order of the change feed and in duplicate delivery to the projection. That is exactly what this article is about – including the code I write for it.\n\n## The three building blocks\n\nBefore I get into the code, the mental model. If you separate the roles cleanly, you make far fewer mistakes later:\n\n- The event store is a DynamoDB table, append-only: one item per event, immutable. This is the source of truth, the only truth in the system.\n- The streams form the change feed of this table. Every new row creates a stream record. No second store, just a window onto the changes.\n- The projection is a Lambda that reads the stream records and writes denormalized read models from them. This is exactly the [projection idea behind read models](https://www.mikebild.dev/en/blog/read-models-from-events-projections/), just cast in AWS services.\n\nImportant for debugging later: the stream is not an archive. Records are trimmed after 24 hours. If you need the complete history, you read it from the table, not from the stream. The stream only carries the flow of deltas from the write side to the read side.\n\nPut together, the path of a command looks like this:\n\n```mermaid\ngraph LR\n  A[Command] --> B[CommandHandler]\n  B -->|Conditional write| C[(DynamoDB<br/>event store)]\n  C --> D[DynamoDB Streams]\n  D --> E[Lambda<br/>projector]\n  E --> F[(Read model table)]\n  F --> G[Query]\n```\n\nThe write side is on the left, the read side on the right. The stream connects both sides asynchronously. DynamoDB Streams holds each change record once; processing by Lambda, on the other hand, is at-least-once. That is exactly why the projection has to tolerate repetitions.\n\n## The event store as a table\n\nThe data model is deliberately simple. The partition key is the `aggregateId`, the sort key is the `version` – zero-padded so that numeric sorting works as a string. An aggregate is thus one partition, and its events sit there in ascending version order. This maps directly to the principles of [single-table design](https://www.mikebild.dev/en/blog/dynamodb-data-modeling-single-table-design/): the access path is in the key.\n\nI enable streams when creating the table via the `StreamSpecification`. The `StreamViewType` has exactly four valid values – `KEYS_ONLY`, `NEW_IMAGE`, `OLD_IMAGE` and `NEW_AND_OLD_IMAGES`. For Event Sourcing, I need the new image, because the event lives in the freshly written row:\n\n```yaml\nResources:\n  EventStore:\n    Type: AWS::DynamoDB::Table\n    Properties:\n      TableName: event-store\n      BillingMode: PAY_PER_REQUEST\n      AttributeDefinitions:\n        - AttributeName: pk\n          AttributeType: S\n        - AttributeName: sk\n          AttributeType: S\n      KeySchema:\n        - AttributeName: pk\n          KeyType: HASH\n        - AttributeName: sk\n          KeyType: RANGE\n      StreamSpecification:\n        StreamViewType: NEW_IMAGE\n```\n\nA detail that once cost me hours: the `StreamViewType` cannot be changed after creation. If you want to switch it, you have to disable the stream and create it again – with a new stream ARN and therefore a new event source mapping. Getting this right on the first attempt saves you an unpleasant migration step later.\n\n## Appending events with optimistic concurrency\n\nThe interesting part of writing is not the writing itself, but the question: What if two commands want to advance the same aggregate to version N+1 at the same time? Exactly one may win. I solve this with optimistic concurrency through a conditional write.\n\nThe idea: I write the event for `version = expectedVersion + 1` and tie it to the condition that no item exists under this key yet. If it already exists, someone else has taken the version, and DynamoDB throws a `ConditionalCheckFailedException`. The caller then rereads the current version and retries the command.\n\n```ts\nimport { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\nimport {\n  DynamoDBDocumentClient,\n  PutCommand,\n} from \"@aws-sdk/lib-dynamodb\";\nimport { ConditionalCheckFailedException } from \"@aws-sdk/client-dynamodb\";\n\nconst client = DynamoDBDocumentClient.from(new DynamoDBClient({}));\n\nexport class ConcurrencyError extends Error {}\n\ninterface DomainEvent {\n  type: string;\n  payload: Record<string, unknown>;\n}\n\nexport async function appendEvent(\n  aggregateId: string,\n  expectedVersion: number,\n  event: DomainEvent,\n): Promise<void> {\n  const nextVersion = expectedVersion + 1;\n\n  try {\n    await client.send(\n      new PutCommand({\n        TableName: \"event-store\",\n        Item: {\n          pk: aggregateId,\n          sk: String(nextVersion).padStart(12, \"0\"),\n          version: nextVersion,\n          type: event.type,\n          payload: event.payload,\n          createdAt: new Date().toISOString(),\n        },\n        ConditionExpression: \"attribute_not_exists(pk)\",\n      }),\n    );\n  } catch (err) {\n    if (err instanceof ConditionalCheckFailedException) {\n      throw new ConcurrencyError(\n        `version ${nextVersion} already exists for ${aggregateId}`,\n      );\n    }\n    throw err;\n  }\n}\n```\n\n`attribute_not_exists(pk)` checks whether the complete item key is free – DynamoDB evaluates the condition against exactly the item whose key is in the `PutCommand`. This makes the combination of `aggregateId` and `version` the uniqueness anchor. No additional lock, no separate sequence table, no transaction across several systems.\n\nWhen I have to write several events atomically – for example, for a command that triggers two domain events – I use `TransactWriteItems` instead of individual puts. This bundles up to 100 items in one atomic transaction, and I can put the same condition on each event. For the rule “one event = one item”, the simple conditional write is enough.\n\n## The projection as a stream handler\n\nNow for the read side. As soon as an event is written, it appears in the stream, and the event source mapping pulls it into a Lambda. Its job: fold the events into a read model.\n\nThe handler receives a `DynamoDBStreamEvent` with a batch of records. Each record carries an `eventName` – for our append-only store, that is always `INSERT`. I read the new image from `dynamodb.NewImage` and unmarshall it into a plain object.\n\n```ts\nimport type { DynamoDBStreamEvent, DynamoDBBatchResponse } from \"aws-lambda\";\nimport { unmarshall } from \"@aws-sdk/util-dynamodb\";\nimport {\n  DynamoDBDocumentClient,\n  GetCommand,\n  UpdateCommand,\n} from \"@aws-sdk/lib-dynamodb\";\nimport { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\n\nconst client = DynamoDBDocumentClient.from(new DynamoDBClient({}));\n\nclass ProjectionGapError extends Error {}\n\nexport async function handler(\n  event: DynamoDBStreamEvent,\n): Promise<DynamoDBBatchResponse> {\n  const batchItemFailures: { itemIdentifier: string }[] = [];\n\n  for (const record of event.Records) {\n    if (record.eventName !== \"INSERT\") continue;\n    if (!record.dynamodb?.NewImage) continue;\n\n    try {\n      const item = unmarshall(record.dynamodb.NewImage as never);\n      await project(item);\n    } catch (err) {\n      batchItemFailures.push({\n        itemIdentifier: record.dynamodb!.SequenceNumber!,\n      });\n    }\n  }\n\n  return { batchItemFailures };\n}\n```\n\nTwo things matter here. First, I return `batchItemFailures` at the end. If `ReportBatchItemFailures` is enabled on the event source mapping, Lambda uses the smallest reported `SequenceNumber` as a checkpoint and retries from there. This reduces repetitions, but doesn’t rule them out for subsequent records that already succeeded. Without partial feedback, the entire batch counts as failed.\n\nSecond, the actual projection. This is where the most expensive mistake of the whole setup lurks, so it gets its own section.\n\n## Idempotency is not optional\n\nThe event source mapping delivers at-least-once. The stream itself contains each record exactly once – but processing by Lambda can deliver the same batch several times on retries, with `BisectBatchOnFunctionError` or on a timeout. Secondary sources often mix up these two statements: the stream is exactly-once and ordered per item; Lambda processing is at-least-once. For the code I write, the second statement is what counts.\n\nIn concrete terms: my projection has to cope with the same event twice without corrupting the read model. With a count, duplicate processing would otherwise be a double count. The guard against it is a conditional write on a gapless, increasing version in the read model. I only write the new projection if its version directly follows the last stored one:\n\n```ts\nasync function project(item: Record<string, unknown>): Promise<void> {\n  const aggregateId = item.pk as string;\n  const version = item.version as number;\n\n  const current = await client.send(\n    new GetCommand({\n      TableName: \"read-model-orders\",\n      Key: { pk: aggregateId },\n      ConsistentRead: true,\n    }),\n  );\n\n  const lastProcessedVersion =\n    (current.Item?.lastProcessedVersion as number | undefined) ?? 0;\n\n  // A repeated delivery has no effect.\n  if (version <= lastProcessedVersion) return;\n\n  // A later event must wait until the missing versions were applied.\n  if (version !== lastProcessedVersion + 1) {\n    throw new ProjectionGapError(\n      `expected version ${lastProcessedVersion + 1}, received ${version}`,\n    );\n  }\n\n  await client.send(\n    new UpdateCommand({\n      TableName: \"read-model-orders\",\n      Key: { pk: aggregateId },\n      UpdateExpression: [\n        \"SET lastProcessedVersion = :v\",\n        \"#status = :status\",\n        \"updatedAt = :now\",\n      ].join(\", \"),\n      ConditionExpression:\n        \"attribute_not_exists(pk) OR lastProcessedVersion = :previous\",\n      ExpressionAttributeNames: {\n        \"#status\": \"status\",\n      },\n      ExpressionAttributeValues: {\n        \":v\": version,\n        \":previous\": lastProcessedVersion,\n        \":status\": deriveStatus(current.Item?.status, item),\n        \":now\": new Date().toISOString(),\n      },\n    }),\n  );\n}\n```\n\nIf an event arrives twice, the function stops before the update. If, on the other hand, version 5 arrives while the read model is only at version 3, the gap is reported as an error. Lambda redelivers this record; version 4 can be processed first. The condition in the `UpdateCommand` additionally protects against two projectors working at the same time. If it fails after the read, the record is retried as well – it must not simply vanish as a successful duplicate case.\n\nAn edge case that is easy to miss: a `PutItem` or `UpdateItem` that doesn’t actually change the data creates no stream record. If you tie your projection expectations to “every write produces an event”, you will otherwise wonder about missing records. In the append-only event store, this doesn’t happen, because every event is a new item – but as soon as you start remodeling the store, you should keep it in mind.\n\n## The projection has to check ordering itself\n\nThe second pitfall concerns order. AWS guarantees for DynamoDB Streams: for each individual item, the stream records appear in the same order as the actual changes to that item. In this data model, however, each event version is its own item – same partition key, different sort key. So the per-item guarantee does not imply a guaranteed order across the events of an aggregate.\n\nIn normal operation, consecutive writes often arrive in the expected order. The projector still must not rely on that, especially not with retries, partial batch failures or an increased `ParallelizationFactor`. That is why the code above checks for a gapless version. A gap is retried or deliberately filled from the event store, instead of pulling a later event ahead and then discarding the missing one as outdated.\n\nThere is no global ordering across aggregates either. The records are spread across shards, and shards are processed in parallel. If you need a globally chronological view – say, a feed of all orders sorted by time – you have to model an order suited for that. A timestamp can serve for display, but on its own it is not a conflict-free global sequence.\n\n## Rebuild and snapshots\n\nA read model can be derived. That is one of the nicest advantages of the approach: if I change the projection logic or a read model is corrupt, I throw it away and rebuild it. The rebuild is a replay – I read all events of an aggregate in ascending order and fold them:\n\n```ts\nimport {\n  DynamoDBDocumentClient,\n  QueryCommand,\n} from \"@aws-sdk/lib-dynamodb\";\n\nexport async function rebuildProjection(\n  aggregateId: string,\n  fromVersion = 0,\n): Promise<ReadModelState> {\n  const result = await client.send(\n    new QueryCommand({\n      TableName: \"event-store\",\n      KeyConditionExpression: \"pk = :id AND sk > :from\",\n      ExpressionAttributeValues: {\n        \":id\": aggregateId,\n        \":from\": String(fromVersion).padStart(12, \"0\"),\n      },\n    }),\n  );\n\n  const events = result.Items ?? [];\n  return events.reduce(applyEvent, initialState());\n}\n```\n\nFor aggregates with a very large number of events, this gets expensive – every replay reads the whole stream. Against that, the AWS Prescriptive Guidance recommends snapshots: the materialized state of an aggregate at version N, stored periodically. The rebuild then loads the snapshot and folds only the delta events since that version. The `fromVersion` parameter above is exactly the seam for this – I start the query at `snapshot.version` instead of at zero. The complete rebuild without a snapshot remains the emergency brake for the case where the fold logic itself has changed.\n\n## Hot partitions and the blocked shard\n\nThe third pitfall is the price of clear partitioning. The `aggregateId` as the partition key means: a very active aggregate concentrates all writes and all stream traffic on one partition and one shard. That leads to throttling and latency – a classic hot partition.\n\nOn top of that comes a reader limit: at most two processes may read from a shard at the same time. A batch that the Lambda cannot process also blocks the shard’s progress until it either succeeds or expires. This is exactly what the settings on the event source mapping are for:\n\n- `BisectBatchOnFunctionError` splits a failed batch recursively to isolate the one poisonous record.\n- `MaximumRetryAttempts` and `MaximumRecordAgeInSeconds` limit how long a record may block.\n- An on-failure `DestinationConfig` pushes batches that have failed for good to SQS or SNS instead of holding them in the stream.\n\nTogether with `ReportBatchItemFailures` from the handler, this gives you error handling that doesn’t let a single broken event halt the entire projection. If you set this up from the start, you spare yourself the incident where a read model table stands still for hours because a single record could not be parsed.\n\n## Conclusion\n\nEvent Sourcing on AWS needs surprisingly little: a DynamoDB table with `aggregateId` as the partition key and `version` as the sort key, a conditional write for optimistic concurrency, DynamoDB Streams as the change feed and a Lambda that folds idempotent read models from it. That is Event Sourcing plus CQRS, assembled serverless from managed services.\n\nThe concepts hold up just as well as on the whiteboard – but the operational details decide whether the system survives the night. I take three things into every project: projections have to be idempotent, because processing is at-least-once. The order of the separate event items has to be checked via their version. And the error handling on the event source mapping decides whether the stream clears itself again or gets stuck.\n\nOnce you have set up this stack, you quickly notice how well it can be extended – for example, toward a GraphQL read side with [AppSync and DynamoDB](https://www.mikebild.dev/en/blog/graphql-apis-with-appsync-and-dynamodb/) that sits directly on the projected read models. The event store remains the truth, the projections remain derivable, and the API only reads views that are already fully shaped.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html\n- [DynamoDB Streams – retention, StreamViewType, ordering, shards](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)\n- [DynamoDB Streams and Lambda triggers](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.html)\n- [Using AWS Lambda with DynamoDB – ESM, Batch, ParallelizationFactor, Error Handling](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html)\n- [Condition Expressions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html)\n- [Optimistic locking with versioning](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html)\n- [AWS Prescriptive Guidance – Event Sourcing Pattern](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/event-sourcing.html)\n- [AWS Database Blog – Build a CQRS event store with Amazon DynamoDB](https://aws.amazon.com/blogs/database/build-a-cqrs-event-store-with-amazon-dynamodb/)"},{"locale":"en","translation_key":"rxjs-testen-mit-marble-diagrammen","slug":"testing-rxjs-with-marble-diagrams","title":"Testing RxJS with Marble Diagrams","summary":"Marble diagrams make the timing of asynchronous streams visible. With TestScheduler.run and virtual time, you test RxJS operators deterministically: no real waiting, no flakiness.","tags":["Software","Reactive"],"published_at":"2024-08-13T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/testing-rxjs-with-marble-diagrams/","audio_url":null,"audio_duration_secs":null,"text":"A test for `debounceTime(2000)` against the real clock takes two seconds. Twenty such tests take forty seconds – and despite all that waiting, they fail sporadically as soon as the machine is under load. This is the math reactive test suites fail on: `setTimeout`, `done` callbacks, a framework that waits for each test case. The suite gets slow, it gets flaky, and at some point nobody dares to take it seriously anymore.\n\nThe `TestScheduler` computes instead. Inside `run()`, a virtual clock runs in which one frame equals exactly one millisecond, and the complete timing of a stream is written as a short string: `'-a-b-c|'`. Two seconds of waiting become microseconds of compute time. How this marble syntax works, how you test real operators with `TestScheduler.run` and where the typical pitfalls are – that’s what this article is about, based on RxJS 7 throughout.\n\n## Why time is the real problem\n\nAn observable is a value over time – or more precisely: a sequence of emissions spread across a timeline, finished by a `complete` or aborted by an error. With synchronous values, testing is trivial: subscribe, collect the values in an array, compare. But the interesting part of RxJS is precisely the time-based part. When does a `debounceTime` fire? Does a `throttleTime` swallow the right values? Does the `complete` come before or after the last emission?\n\nAs soon as you test this with real time, you have three problems at once. The test really takes as long as the timing dictates. It’s nondeterministic, because the real clock simply doesn’t tick with millisecond precision. And it forces you into asynchronous test code with `done` callbacks, where one forgotten call makes the test hang silently until the timeout kicks in.\n\nMarble testing turns this logic around. Instead of real time, a virtual clock runs that the `TestScheduler` controls. Time isn’t waited for, it’s computed. And the flow isn’t described in imperative code but as a diagram.\n\n## The marble syntax\n\nA marble diagram is a string in which every character has a meaning on the timeline. Time runs from left to right, and every symbol stands either for time passing or for an event in the stream. This is the entire reference:\n\n- `-` – one time frame, meaning one tick of the virtual clock. Inside `run()`, one frame equals exactly 1 ms.\n- `a`–`z` (or any other character) – a `next` emission. The concrete value is mapped through a `values` object, such as `{ a: 1, b: 2 }`.\n- `|` – the `complete` signal; the stream ends normally.\n- `#` – an `error`; the stream ends with an error.\n- `()` – synchronous grouping: several notifications in the same frame, for example `(ab|)`.\n- `^` – the subscription point for `hot`, the so-called zero frame. Frames before it count as negative.\n- `!` – the unsubscription point, relevant in subscription diagrams.\n- `<n>ms` / `<n>s` / `<n>m` – shorthand for many frames, such as `10ms` instead of ten hyphens.\n\nA detail that is easy to overlook: spaces don’t create a frame. They only serve visual alignment and are ignored. So you can write the input and the expected output one below the other and align them neatly with spaces without changing the timing – only `-` and the actual symbols count.\n\nThe string `'-a-b-c|'` therefore reads like this: one frame of silence, then value `a`, one frame, value `b`, one frame, value `c`, immediately followed by `complete`. Six frames in total, three values, a clean completion. This readability is exactly the point – you see the timing without having to reconstruct it from imperative code.\n\n## cold and hot\n\nBefore we write tests, you need the distinction between `cold` and `hot`, because it determines when time starts to run.\n\nA `cold` observable only starts when someone subscribes. The timeline begins at the moment of subscription. That’s the typical behavior for HTTP requests or other data sources that start anew for each subscriber. A `hot` observable, on the other hand, is already running, independent of subscriptions – like a DOM event or a Subject that is already firing while you aren’t even listening yet. Here, the `^` marks the moment the tested subscription joins; everything before it has already happened and lies in the negative frame range.\n\nIf you want to read up on the four Subject types and their multicast behavior again, I covered them in detail in [The Four Subject Types in RxJS](https://www.mikebild.dev/en/blog/the-four-subject-types-in-rxjs/) – `hot` marbles model exactly this “already running” behavior.\n\n## The first test: map with virtual time\n\nLet’s start with the simplest meaningful case: a `map` operator. We want to show that every incoming value is multiplied by ten and that timing and completion are passed through unchanged.\n\nFirst, setting up the `TestScheduler`. The constructor receives an assertion function that wraps the deep equality of your test framework – here using Jest as an example, but Jasmine or Vitest work the same way:\n\n```ts\nimport { TestScheduler } from 'rxjs/testing';\nimport { map, debounceTime } from 'rxjs/operators';\n\nlet testScheduler: TestScheduler;\n\nbeforeEach(() => {\n  testScheduler = new TestScheduler((actual, expected) => {\n    expect(actual).toEqual(expected);\n  });\n});\n```\n\nThe actual test then runs entirely inside `testScheduler.run`. The callback receives a `helpers` object from which we pull `cold` and `expectObservable`:\n\n```ts\ntest('map multiplies each value by ten', () => {\n  testScheduler.run(({ cold, expectObservable }) => {\n    const source$ = cold('-a-b-c|', { a: 1, b: 2, c: 3 });\n\n    const result$ = source$.pipe(map((x) => x * 10));\n\n    expectObservable(result$).toBe('-a-b-c|', { a: 10, b: 20, c: 30 });\n  });\n});\n```\n\nThe pattern you see here repeats in every marble test: actual stream against expected diagram. The input is a `cold` observable with a diagram and a `values` object. The operator pipeline hangs off it. And `expectObservable(...).toBe(...)` describes what should come out. The output timing is identical to the input timing, because `map` doesn’t change anything about time – only the value mapping in the second object is different.\n\nWhy does this work without real waiting? Because `run()` automatically runs through the virtual time when it returns – internally through a `flush` that you usually don’t have to call yourself. The whole flow has been processed synchronously as soon as the callback ends.\n\n## The real payoff: debounceTime\n\nWith `map`, you don’t really notice the advantage yet. It becomes obvious the moment a time-based operator comes into play. `debounceTime(n)` only passes a value on when `n` frames of silence follow it – if a new value arrives before that, the old one is discarded. That’s exactly the kind of behavior that becomes torture with real time and a finger exercise with virtual time.\n\nThe key point: inside the `run()` callback, every time-based operator is automatically redirected to the `TestScheduler`. You don’t have to pass the scheduler to `debounceTime` manually. `delay`, `debounceTime`, `throttleTime`, `interval`, `timer` – they all use the virtual clock as soon as they run inside `run()`.\n\n```ts\ntest('debounceTime keeps only the last value after a quiet window', () => {\n  testScheduler.run(({ hot, expectObservable }) => {\n    // frame:      0    5    10\n    const source$ = hot('-a--b--c---|');\n\n    const result$ = source$.pipe(debounceTime(3));\n\n    // a is displaced by b, b by c; only c survives the 3-frame quiet window\n    expectObservable(result$).toBe('----------c|');\n  });\n});\n```\n\nLet’s work through it, because this is exactly where most mistakes happen. `a` arrives at frame 1, so its debounce window would expire at frame 4. But that’s exactly when `b` arrives and displaces `a` before its emission is triggered. For `b`, the window starts over and would end at frame 7 – that’s where `c` arrives, same game, `b` drops out too. After `c` at frame 7, there is finally enough quiet: the window expires at frame 10, and the `complete` follows at frame 11. So only `c` remains, shifted back by three frames. The expected diagram models exactly this shift.\n\nThis arithmetic isn’t a side show; it’s the core. If your expected marble is off by even one frame, the deep equality check fails. That’s annoying at first and quickly becomes a strength: the test forces you to really understand the timing instead of guessing it.\n\n## What happens in a frame\n\nThe following diagram shows the flow for the `map` case as three parallel timelines – input at the top, operator in the middle, output at the bottom. This is the fastest way to see that `map` transforms the values but leaves the timing untouched.\n\n```mermaid\nflowchart TB\n  subgraph IN[\"input$ – cold('-a-b-c|')\"]\n    direction LR\n    i0[\"-\"] --> i1[\"a=1\"] --> i2[\"-\"] --> i3[\"b=2\"] --> i4[\"-\"] --> i5[\"c=3\"] --> i6[\"|\"]\n  end\n  subgraph OP[\"operator\"]\n    direction LR\n    op[\"map(x =&gt; x * 10)<br/>same frames,<br/>new values\"]\n  end\n  subgraph OUT[\"output$ – '-a-b-c|'\"]\n    direction LR\n    o0[\"-\"] --> o1[\"a=10\"] --> o2[\"-\"] --> o3[\"b=20\"] --> o4[\"-\"] --> o5[\"c=30\"] --> o6[\"|\"]\n  end\n  IN --> OP --> OUT\n```\n\nEach box is a frame. The values travel from top to bottom through the operator, and the timing is preserved frame by frame. With a time-based operator like `debounceTime`, the bottom timeline would shift relative to the top one and drop values – exactly what we just worked through.\n\n## Checking subscription timing\n\nSometimes it isn’t enough to know which values come out – you want to know when and for how long a subscription existed at all. For this, `cold` and `hot` provide a `.subscriptions` property that you can check against a diagram of its own. `expectSubscriptions` uses `^` for the subscribe moment and `!` for the unsubscribe moment:\n\n```ts\ntest('records subscription and unsubscription frames', () => {\n  testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => {\n    const source$ = cold('-a-b-c|');\n    const subscription = '^-----!';\n\n    expectObservable(source$).toBe('-a-b-c|');\n    expectSubscriptions(source$.subscriptions).toBe(subscription);\n  });\n});\n```\n\nThis is especially valuable when you test operators like `switchMap` or `takeUntil`, where the real effect is that an inner subscription is canceled at the right moment. The value stream then often looks unspectacular – the truth lies in the subscription diagram.\n\n## The three pitfalls\n\nThe same three sources of errors keep coming up in code reviews. They are behind most “Why is my test red?” moments.\n\nFirst: real time instead of virtual time. The automatic redirection of time-based operators applies exclusively inside the `run()` callback. If you build your observable outside of it or fall back on the old style, where you pass the scheduler manually, the real clock suddenly runs again. The test becomes slow and flaky, and the whole gain is gone. Everything that has timing belongs in the `run()` callback.\n\nSecond: frame counting. `debounceTime(20)` inside `run()` means 20 frames, that is, 20 ms. Your expected diagram has to model this delay exactly – whether with 20 hyphens or with `20ms`. An off-by-one in frame counting is by far the most common reason for a failing marble test. Take the time to really work out the timing instead of estimating it.\n\nThird: whitespace is deceptive. Spaces don’t create a frame; they only align things visually. When you align input and expected output, make sure both are frame-synchronous – and that values firing synchronously in the same frame are grouped with `()`. An `(ab|)` is something completely different from `ab|`, even though it looks almost the same.\n\n## The old style for contrast\n\nFor context, a word about history, because you will come across older code online. In the past, you used the `TestScheduler` without `run()`, passed the scheduler explicitly to the operators and called `testScheduler.flush()` manually at the end. In this legacy style, one frame also equaled 10 ms instead of 1 ms. In principle, that still works, but it’s more error-prone and more cumbersome.\n\nThe recommended way is clearly `testScheduler.run(helpers => …)` with the clear rule: one frame equals 1 ms, automatic redirection of all time-based operators, automatic flush at the end. So if you see `testScheduler.flush()` or a manually passed scheduler argument somewhere, that’s a sign of old code – not a pattern you should follow.\n\n## Conclusion\n\nMarble testing solves the one problem that makes reactive programming hard to test: time. Instead of waiting for it, you make it visible and computable. A short string describes the complete timing of a stream, the `TestScheduler` verifies it in virtual time, and your suite stays fast and deterministic – no `done` callbacks, no timeouts, no sporadic failures.\n\nGetting started takes some practice, especially with counting frames. But once that sinks in, you won’t want to go back. A `debounceTime` test that used to run for two seconds and was occasionally red now runs in microseconds and is reliable. And on top of that, the expected diagram documents the behavior so clearly that it replaces half the docs. Start small – a `map`, a `debounceTime` – and work through every timing deliberately. If you then use reactive streams on the server side too, you’ll find the right follow-up in [RxJS in Node.js](https://www.mikebild.dev/en/blog/rxjs-in-nodejs-event-streams/).\n\n## Further reading\n\n- [Testing RxJS Code with Marble Diagrams](https://rxjs.dev/guide/testing/marble-testing) – the official guide to marble syntax and `TestScheduler.run`.\n- [TestScheduler API](https://rxjs.dev/api/testing/TestScheduler) – the complete API reference with all helper signatures."},{"locale":"en","translation_key":"rechnungsdaten-als-domaene","slug":"invoice-data-as-a-domain","title":"Invoice Data as a Domain","summary":"Why an invoice import isn’t a CSV job but a domain with its own terms, invariants and time rules – and how explicit types and a rejection report turn silent data errors into explainable data.","tags":["Software","Data","Tools"],"published_at":"2024-08-12T10:00:00+00:00","updated_at":"2026-07-14T17:22:26.666484+00:00","url":"https://www.mikebild.dev/en/blog/invoice-data-as-a-domain/","audio_url":null,"audio_duration_secs":null,"text":"# Invoice Data as a Domain\n\nFrom a domain perspective, invoice data isn’t columns of numbers. An invoice is a document of record: it has an issuer, a recipient, a document number, line items and tax rates – and a legal meaning that the German VAT Act describes quite precisely. A document has relatives: the credit note, which gives an amount back, and the cancellation, which voids a document and must reference the original. And a document carries rules that appear in no export file: the sum of the line items must match the document total, net plus tax must equal gross, and a payment term counts from the invoice date – not from the date of supply, and certainly not from the day the money actually moves.\n\nIf you read an invoice only as a row with an amount, you read it wrong. But that’s exactly what happens when you treat the task of “merging invoice data” as what it looks like at first glance: an import job.\n\n## A private data project as the trigger\n\nThe occasion was unspectacular. Over several years, invoice and receipt data had piled up for me in three forms: PDFs from suppliers, CSV exports from an accounting tool and an account export from the bank. I wanted to merge them into a local database so I could finally answer questions none of the individual systems answers: which amounts were invoiced but never paid? How are expenses distributed across tax rates? Which credit notes belong to which originals? Everything anonymized and purely private – this is about the structure of the problem, not about concrete business figures.\n\nThe first version was an evening’s work: convert PDFs to text, read CSVs with Papa Parse, rename columns, into SQLite. The import ran through without a single error message. And that was exactly the problem.\n\nBecause the data was silently broken. One supplier exports gross amounts, the other net – both call the column `amount`. One export writes German decimal commas, the next uses periods. In one file the date column held the date of supply, in the other the invoice date. Two cancellations showed up as perfectly normal invoices with a negative amount, with no link to the original. None of this is a parser error. Every single row was syntactically flawless. What was wrong was the meaning – and no CSV parser checks meaning.\n\nAt this point I realized I had filed the task in the wrong drawer. This wasn’t data transport. This was domain modeling, just for data that already exists.\n\n## Taking the terms seriously\n\nThe first step out of silent breakage wasn’t code but a list of terms. Which domain things actually appear in these files? In the end, surprisingly few terms ended up on the piece of paper, but each with a sharp meaning:\n\n- Document – the document as a whole, with a unique document number and a document type\n- Line item – a row on the document, with quantity, unit price and its own tax rate\n- Tax rate – in my data 0, 7 or 19 percent, nothing else\n- Credit note – a separate document with the sign reversed\n- Cancellation – voids a document and references its document number\n- Payment term – a date derived from the invoice date plus a period\n\nThis list looks trivial. But it immediately forced decisions that had previously been hidden invisibly in the column mapping. Is a negative amount a credit note or a cancellation? From a domain perspective, a huge difference: the credit note is a new transaction, the cancellation invalidates an old one. In my raw data, both were the same row with a minus sign. Without the list of terms, I would never have recognized this as a problem – after all, the number is right.\n\nThe relationships between the document types fit into a small drawing:\n\n```mermaid\nflowchart LR\n  I[\"Invoice<br/>INV-2023-0117\"] --> P1[\"Line item 1<br/>19 %\"]\n  I --> P2[\"Line item 2<br/>7 %\"]\n  C[\"Cancellation<br/>CAN-2023-0119\"] -- \"references\" --> I\n  G[\"Credit note<br/>CRN-2023-0121\"] -- \"refers to\" --> I\n```\n\nIn this picture, a cancellation without a reference simply can’t be drawn. That’s exactly how it should be: what can’t be drawn shouldn’t be storable either.\n\n## Invariants: what must always hold\n\nTerms alone aren’t enough. The real substance of a domain lies in its invariants – the statements that must hold for every valid record, no matter where it comes from. For invoice data, there are three main ones:\n\nFirst: totals must add up. The line item totals per tax rate, the tax on top, the whole thing added up – that must equal the gross amount of the document, to the cent. Rounding happens per tax rate group, not per line item, otherwise it drifts.\n\nSecond: a cancellation references an original. A cancellation without a reference isn’t a cancellation but a data error with a minus sign.\n\nThird – the classic: gross and net must never be confusable. A field that sometimes contains one and sometimes the other is worse than no field at all. With a 19 percent difference, the error doesn’t even show up right away in total analyses; it spreads like an even fog over all the numbers.\n\nWith TypeScript and Zod, all of this can be made explicit. I always store amounts as integer cent values – floating point and money don’t get along:\n\n```typescript\nimport { z } from \"zod\";\n\nconst TaxRate = z.union([z.literal(0), z.literal(7), z.literal(19)]);\n\nconst InvoiceLine = z.object({\n  description: z.string().min(1),\n  quantity: z.number().positive(),\n  unitPriceNetCents: z.number().int(), // money as integer cents, never floats\n  taxRate: TaxRate,\n});\n\nconst Invoice = z.object({\n  invoiceNumber: z.string().regex(/^(INV|CRN|CAN)-\\d{4}-\\d{4}$/),\n  kind: z.enum([\"invoice\", \"credit_note\", \"cancellation\"]),\n  referencesInvoice: z.string().optional(),\n  issueDate: z.string().date(),   // invoice date\n  serviceDate: z.string().date(), // date of supply\n  dueDate: z.string().date(),     // payment target\n  lines: z.array(InvoiceLine).min(1),\n  totalGrossCents: z.number().int(),\n});\n```\n\nThat’s just the structure. The invariants come on top as a refinement, so that a violation takes the same path as a structural error:\n\n```typescript\nconst ValidInvoice = Invoice.superRefine((inv, ctx) => {\n  // sum per tax rate group, round per group, then add up\n  const grossByRate = new Map<number, number>();\n  for (const line of inv.lines) {\n    const net = line.quantity * line.unitPriceNetCents;\n    const gross = Math.round(net * (1 + line.taxRate / 100));\n    grossByRate.set(line.taxRate, (grossByRate.get(line.taxRate) ?? 0) + gross);\n  }\n  const computedGross = [...grossByRate.values()].reduce((a, b) => a + b, 0);\n\n  if (computedGross !== inv.totalGrossCents) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message: `gross mismatch: lines say ${computedGross}, document says ${inv.totalGrossCents}`,\n    });\n  }\n  if (inv.kind === \"cancellation\" && !inv.referencesInvoice) {\n    ctx.addIssue({\n      code: z.ZodIssueCode.custom,\n      message: \"cancellation must reference an original invoice\",\n    });\n  }\n});\n```\n\nThe difference from the first version of the project is fundamental. Before, the import accepted whatever could be parsed. Now it accepts what is correct from a domain perspective. That’s the same shift you know from Domain-Driven Design, just at the most inconspicuous level there is: reading files.\n\n## Three dates, three meanings\n\nThe time rules deserve their own section, because they’re where analyses go wrong most quietly. A document carries up to three dates, and none of them is “the date”:\n\nThe date of supply says when something was delivered or performed. The invoice date says when the document was issued. The payment date – which isn’t on the document at all but comes from the account export – says when money moved. Weeks can pass between supply and invoice, and again between invoice and payment. An analysis of “expenses per month” delivers three different truths depending on the chosen date, and each of the three is the right one for some question: the date of supply belongs to the question “When was the cost incurred?”, the invoice date to VAT, the payment date to liquidity.\n\nIn my raw data, each source had exactly one date column, and no two sources meant the same thing by it. Since the three dates became separate, mandatory fields, every analysis has to say which one it means – the question can no longer be skipped by accident. The payment term is then just derived information: invoice date plus period gives `dueDate`, and a comparison with the payment date shows what was overdue.\n\n## The boundary: reject instead of waving through\n\nThat leaves the question of what happens to rows that fail the check. The usual answer is a log line, and the usual consequence is that nobody reads it. For an import that runs once a month, that’s equivalent to silent data loss – except that this time the bad data stays out instead of in, which is better, but still invisible.\n\nThe answer that works for me: rejected rows are a result of the run, on equal footing with the accepted ones. The import produces two artifacts – the database and a rejection report as a Markdown file, with source, row number and the domain reason:\n\n```typescript\ntype RejectedRow = {\n  source: string;   // e.g. \"supplier-a-2023.csv\"\n  rowNumber: number;\n  reason: string;   // human-readable, domain language\n};\n\nconst rejectedRows: RejectedRow[] = [];\n\nfor (const [rowNumber, candidate] of candidates.entries()) {\n  const result = ValidInvoice.safeParse(candidate);\n  if (!result.success) {\n    rejectedRows.push({\n      source: candidate.source,\n      rowNumber,\n      reason: result.error.issues.map((i) => i.message).join(\"; \"),\n    });\n    continue;\n  }\n  accepted.push(result.data);\n}\n// afterwards: write rejected-rows report next to the database, fail if quota exceeded\n```\n\nThe report is deliberately a file and not a log stream. Files can be diffed, archived, compared with the previous month next month. If the import runs twice over the same inputs, it must produce exactly the same report – I explained in more detail why I put so much weight on this property in [Deterministic CLIs](https://www.mikebild.dev/en/blog/deterministic-clis/). And for values that come from PDFs, heightened distrust applies anyway: what text recognition delivers is a measurement with uncertainty, not a fact – more on that in [OCR with a Cache and Distrust](https://www.mikebild.dev/en/blog/ocr-with-a-cache-and-distrust/).\n\nThe complete flow then looks like this:\n\n```mermaid\nflowchart LR\n  A[\"PDF documents\"] --> N[\"Normalize<br/>commas, encoding, columns\"]\n  B[\"CSV exports<br/>accounting\"] --> N\n  K[\"Account export<br/>bank\"] --> N\n  N --> V{\"Domain validation<br/>types + invariants\"}\n  V -- \"valid\" --> DB[(\"SQLite<br/>documents + line items\")]\n  V -- \"rejected\" --> R[\"Rejection report<br/>Markdown, diffable\"]\n```\n\nWhat matters in this picture is the one diamond. There is exactly one place where raw data becomes domain data. Behind this boundary, any code may trust the fields: `totalGrossCents` is gross, in cents, and the totals add up. Before the boundary, everything is suspect. This asymmetry is what makes the rest of the project so pleasant – the analyses no longer contain a single defensive line, no “in case the field is empty after all,” no second recalculation.\n\n## Analyzing once the data is clean\n\nFor the analyses, I put DuckDB directly on top of the database. Once the domain is right, the interesting questions become surprisingly short SQL statements. Open items, for example – documents whose payment term has passed without a payment date existing:\n\n```sql\nSELECT i.invoice_number,\n       i.due_date,\n       i.total_gross_cents / 100.0 AS gross_eur\nFROM invoices i\nLEFT JOIN payments p ON p.invoice_number = i.invoice_number\nWHERE i.kind = 'invoice'\n  AND p.paid_date IS NULL\n  AND i.due_date < current_date\nORDER BY i.due_date;\n```\n\nThis query owes its correctness entirely to the boundary before it. With the raw data of the first version, the same query would have delivered plausible and wrong numbers – cancellations counted as open items, gross and net mixed, the date of supply interpreted as the due date. None of it would have stood out, because the result looks like money and amounts of money always seem somehow credible.\n\nA side effect I hadn’t expected: the rejection report became the best tool for understanding the sources themselves. If rejections from one file pile up with the same reason, that isn’t noise but an insight about the exporter – for example, that a tool sets the sign differently for credit notes than for invoices. Patterns like that used to appear in no log; now they’re collected in a file I actually read.\n\n## And e-invoicing?\n\nYou could object that the problem will solve itself: with the Growth Opportunities Act, Germany decided in March 2024 that electronic invoicing in German B2B business becomes mandatory step by step from 2025 – structured formats according to EN 16931 instead of PDF prose. That’s good news, because exactly the fields this was about are formally defined there: document type, tax rates per line item, date of supply and invoice date.\n\nBut a structured format only shifts the work; it doesn’t eliminate it. Whether an XML field or a CSV column claims to be a gross amount – the receiving side still has to check that the totals add up and that the cancellation finds its original. And the historical data of past years stays what it is anyway: PDFs and exports with quirks. So the domain boundary doesn’t become superfluous; it just gets better input material in the future.\n\n## What I take away from it\n\nThe reflex to treat invoice data as a transport problem is understandable – the files are small, the formats known, the tools ready. But the difficulty isn’t in the transport. It lies in the fact that this data has a domain language, invariants no parser knows, and three time axes that can’t be squeezed into one date column. If you ignore that, you get an import that runs green and still produces wrong numbers. If you model it, you get something rarer than correct data: explainable data. Every number in the database has an origin, every missing row a documented reason.\n\nAll in all, this small private project said more about software architecture than many a service split: you don’t recognize a domain by its size, but by the fact that it has its own terms, its own rules and its own time. Invoice data has all three.\n\n## Further reading\n\n- [Zod on GitHub](https://github.com/colinhacks/zod) – schema validation for TypeScript\n- [Zod documentation](https://zod.dev) – reference for refinements and error handling\n- [DuckDB documentation](https://duckdb.org/docs/) – local analyses directly on files and databases\n- [§ 14 UStG](https://www.gesetze-im-internet.de/ustg_1980/__14.html) – mandatory information on an invoice under German VAT law\n- [Papa Parse](https://www.papaparse.com/) – CSV parsing in the browser and in Node.js"},{"locale":"en","translation_key":"nodejs-testing-mit-mocha","slug":"testing-nodejs-the-test-pyramid-with-mocha","title":"Testing Node.js: The Test Pyramid with Mocha","summary":"How to distribute a Node.js test suite sensibly across different test levels and how Mocha, node:assert, sinon and supertest work together along the way.","tags":["Software","Node.js","Backend"],"published_at":"2024-07-16T10:00:00+00:00","updated_at":"2026-07-13T08:02:04.028363+00:00","url":"https://www.mikebild.dev/en/blog/testing-nodejs-the-test-pyramid-with-mocha/","audio_url":null,"audio_duration_secs":null,"text":"A test doesn’t prove that code works. It records which behavior someone once expected from that code – and raises the alarm when that expectation breaks. A test suite is therefore less a proof than a memory, and the person who breaks the expectation is surprisingly often you yourself, half a year later. In the backend, where a wrong calculation slips silently through an API and only gets noticed in accounting, this memory is worth its weight in gold.\n\nSo the key question is never “Do we test?” but “How do we distribute our testing effort?” There’s a picture for exactly that which has held up for years: the test pyramid. It’s a heuristic, not a ratio that looks the same for every system. In this article I look at how it works, why suites tip over time, and which tools fit in everyday Node.js work – Mocha as the runner, `node:assert` for assertions, sinon for isolating external dependencies and supertest for HTTP endpoints. Node.js now ships its own stable test runner with `node:test`; Mocha remains the deliberately chosen option here, not the only up-to-date one.\n\n## The pyramid: broad base, narrow top\n\nThe idea is simple. Not all tests are equally expensive, and not all of them give you an answer equally fast. A unit test runs in milliseconds, isolates a single function and, when it fails, tells me fairly precisely where the problem is. An end-to-end test boots the whole application, clicks through several systems and takes seconds to minutes – and when it turns red, all I know at first is that something broke somewhere along the long way.\n\nThis often leads to a distribution with many fast tests at the base, targeted integration tests in the middle and a few end-to-end scenarios at the top. How wide the layers turn out depends on the risks and the system boundaries.\n\n```mermaid\ngraph TD\n    E2E[\"E2E<br/>few, slow, brittle\"]\n    INT[\"Integration<br/>fewer, medium speed\"]\n    UNIT[\"Unit<br/>many, fast, isolated\"]\n    E2E --> INT\n    INT --> UNIT\n    style UNIT fill:#2d6a4f,color:#fff\n    style INT fill:#40916c,color:#fff\n    style E2E fill:#74c69d,color:#000\n```\n\nThe base is broad because unit tests are cheap – quick to write, quick to run, stable. The top is narrow because E2E tests are expensive to maintain. They break with every environment change, they become flaky as soon as timing comes into play, and they cost time in every CI run. You need a few of them – they’re the only ones that show the parts also work together. But they’re the salt, not the soup.\n\n## Which tool for what\n\nBefore I get to code, a quick overview, because in Node.js the work is spread across a small ecosystem rather than a single framework:\n\n- Mocha is the runner. It provides the structure (`describe`/`it`), runs the tests, manages hooks and reports results. Mocha itself deliberately ships no assertions.\n- `node:assert` provides exactly those assertions – built in, without an extra dependency. If you want a more expressive BDD syntax, you can use Chai instead (in the CommonJS world of 2024, the v4 line).\n- sinon provides test doubles: spies observe calls, stubs replace behavior. I use them to isolate external dependencies such as the database, HTTP or time.\n- supertest tests HTTP endpoints at the app level without needing a real network port or a browser.\n\nThis separation irritates people coming from other languages at first. But it’s a strength: you combine interchangeable building blocks instead of tying yourself to a monolithic framework.\n\n## Unit tests: the foundation\n\nLet’s start at the bottom. A unit test takes a function, gives it inputs and checks the output. Nothing else – no database, no network, no file system.\n\nMocha structures this with `describe` (a block that groups related tests) and `it` (a single test case). For the assertion I use `node:assert` in strict mode. The `node:` prefix makes clear that it’s a built-in, and `/strict` ensures that no silent type coercion happens.\n\n```js\nconst assert = require('node:assert/strict');\nconst { sum } = require('../src/math');\n\ndescribe('sum()', () => {\n  it('adds two positive numbers', () => {\n    assert.strictEqual(sum(2, 3), 5);\n  });\n\n  it('handles negative operands', () => {\n    assert.strictEqual(sum(-4, 1), -3);\n  });\n});\n```\n\nTwo details deserve a second look. First, the argument order: `assert.strictEqual(actual, expected)` – always the actual value first, then the expected one. If you swap them, a failure gives you a diff output that reads exactly the wrong way around. Second, `strictEqual` instead of `equal`: strict mode compares with `Object.is`/`===` and doesn’t silently convert anything. `1` is not `'1'`. That sounds pedantic, but it prevents exactly the class of bugs you actually want to catch with tests.\n\nFor objects and arrays I use `deepStrictEqual`, which compares deeply and with exact types:\n\n```js\nconst assert = require('node:assert/strict');\n\nit('builds the expected payload', () => {\n  const result = buildUser({ id: 1, name: 'Ada' });\n  assert.deepStrictEqual(result, {\n    id: 1,\n    name: 'Ada',\n    role: 'guest',\n  });\n});\n```\n\n## Test behavior, not implementation\n\nThis is where most discussions in code reviews start. A colleague once asked whether he shouldn’t check that his function calls `Array.map` internally. Better not: the test should care about the result – the transformed list – not the way there.\n\nThe difference is practical, not academic. A test that targets observable behavior survives a refactoring: as long as the function returns the same output for the same input, it stays green, whether there’s `map`, `reduce` or a `for` loop inside. A test that nails down implementation details, on the other hand, breaks with every rework – even though nothing is broken from a domain perspective. Tests like that train a team to shy away from refactoring. And a team that no longer dares to restructure accumulates technical debt faster than any test could ever catch it.\n\n## Isolating external dependencies with sinon\n\nAs soon as a function leaves pure computation and talks to a database, an HTTP client or the clock, things get interesting. I don’t want to hit these dependencies for real in a unit test – they’re slow, unreliable and hard to bring into a defined state. Instead, I replace them with test doubles.\n\nsinon mainly distinguishes between a spy and a stub. A spy lets the real function run and only observes how often and with what it was called. A stub replaces the behavior completely – I tell it what to return or throw.\n\nTake a service that loads a user through a repository. I want to test that it behaves correctly on a DB error without ever touching a real database:\n\n```js\nconst assert = require('node:assert/strict');\nconst sinon = require('sinon');\nconst userRepo = require('../src/user-repo');\nconst service = require('../src/user-service');\n\ndescribe('userService.getUser()', () => {\n  afterEach(() => {\n    sinon.restore();\n  });\n\n  it('propagates a repository failure', async () => {\n    const stub = sinon\n      .stub(userRepo, 'findById')\n      .rejects(new Error('db down'));\n\n    await assert.rejects(() => service.getUser(1), /db down/);\n    assert.ok(stub.calledOnceWith(1));\n  });\n\n  it('returns the user on success', async () => {\n    sinon.stub(userRepo, 'findById').resolves({ id: 1, name: 'Ada' });\n\n    const user = await service.getUser(1);\n    assert.strictEqual(user.name, 'Ada');\n  });\n});\n```\n\nThe most important piece here isn’t the stub itself but the `afterEach(() => sinon.restore())`. Since sinon v5, the default `sinon` object is itself a sandbox; `restore()` resets all replaced methods. If you forget it, the stubs live on beyond the test case. The next test then silently gets a manipulated `userRepo` slipped in – and depending on the execution order, it passes sometimes and sometimes doesn’t. That’s exactly what “flaky” means: a test whose result depends on order or parallelism, not on the code. If you prefer your own sandbox, use `const sandbox = sinon.createSandbox()` and call `sandbox.restore()` – the principle stays the same.\n\nBut be careful: test doubles are a sharp knife. If you mock everything away, in the end you’re only testing that the mocks react the way you configured them. Tests like that mirror your own expectation back at you and break at the first real refactoring. Replace the boundary to the external system – not your own logic along with it.\n\n## Integration tests: HTTP endpoints with supertest\n\nOne level up are integration tests. Here I no longer want to check a single function but the interplay – for example, that an Express route returns the right status code and body. That’s what supertest is for.\n\nsupertest takes an Express app or an `http.Server`, binds it to an ephemeral port and sends real HTTP requests against it. No browser, no manually started server, no fixed port number. The API is fluent and reads almost like a description:\n\n```js\nconst assert = require('node:assert/strict');\nconst request = require('supertest');\nconst app = require('../src/app');\n\ndescribe('GET /users', () => {\n  it('returns 200 and a JSON list', async () => {\n    const res = await request(app)\n      .get('/users')\n      .expect(200)\n      .expect('Content-Type', /json/);\n\n    assert.ok(Array.isArray(res.body));\n    assert.strictEqual(res.body.length, 2);\n  });\n\n  it('returns 404 for an unknown user', async () => {\n    await request(app).get('/users/999').expect(404);\n  });\n});\n```\n\nThe `await` at the front is crucial. supertest returns a promise; without `await` (or a `return` of the promise), the test ends before the assertions have run – and Mocha wrongly reports it as green. This kind of false positive is especially treacherous, because the suite stays reassuringly green for weeks even though it checks nothing.\n\nThat also makes it clear why I consistently handle async one way. Mocha allows two styles: either `async`/promise-returning or the classic `done` callback. You must not mix them. Either\n\n```js\nit('waits for the promise', async () => {\n  const value = await loadValue();\n  assert.strictEqual(value, 42);\n});\n```\n\nor, if you’re working with a callback-based API:\n\n```js\nit('waits for the callback', function (done) {\n  loadValue((err, value) => {\n    if (err) return done(err);\n    assert.strictEqual(value, 42);\n    done();\n  });\n});\n```\n\nBoth at once – a `done` parameter and `async` – Mocha rejects with a clear error (“Resolution method is overspecified”). A side note: Mocha’s default timeout per test is 2000 ms. If an asynchronous test never calls its `done` or a promise never resolves, it runs into this timeout and turns red – often the first hint of a forgotten `await` or `done`.\n\n## The most common mistake: the pyramid upside down\n\nNow to the most common pitfall. A team starts with the best intentions but mostly writes E2E tests, because they feel so nicely “real.” After a year, the distribution looks like this:\n\n```mermaid\ngraph TD\n    UNIT[\"Unit<br/>barely there\"]\n    INT[\"Integration<br/>a few\"]\n    E2E[\"E2E<br/>many, slow, flaky\"]\n    UNIT --> INT\n    INT --> E2E\n    style E2E fill:#9d0208,color:#fff\n    style INT fill:#dc2f02,color:#fff\n    style UNIT fill:#f48c06,color:#000\n```\n\nThis is called the “ice cream cone” – the inverted pyramid with the broad, expensive top up above. The symptoms are always the same: the suite runs for ten minutes instead of ten seconds. A single red test doesn’t tell you where the bug is, because it passes through a dozen components at once. And because E2E tests depend on timing and environment, they become flaky – at some point the team simply reruns the pipeline until it’s green. That’s the moment when tests stop being a memory and become a ritual nobody takes seriously anymore.\n\nThe way out is unspectacular: for every bug a slow E2E test catches, you write the actual regression test one level lower – as a unit or integration test that catches the same cause in milliseconds. The pyramid doesn’t straighten itself out through one big rework, but through the habit of pinning down bugs at the cheapest level where they’re reproducible.\n\nThis attitude fits a thought I already described in [errors as architecture](https://www.mikebild.dev/en/blog/errors-as-architecture-in-nodejs/): an error isn’t a nuisance you push away, but information about the system. A test is the preserved form of that information. And if you want to understand why asynchronous tests play such a big role in the backend in the first place, you’ll find the basics in the [Node.js training](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/) on the event loop and architecture.\n\n## A word about hooks\n\nFor tests to stay independent, each one needs a clean starting state. Mocha offers four hooks for this: `before` and `after` run once per `describe` block, `beforeEach` and `afterEach` before and after each individual test. The order is reliable: first all `before`, then per test `beforeEach` → test → `afterEach`, and finally `after`.\n\n```js\ndescribe('orderService', () => {\n  let db;\n\n  before(async () => {\n    db = await connectTestDb();\n  });\n\n  beforeEach(async () => {\n    await db.reset();\n  });\n\n  afterEach(() => {\n    sinon.restore();\n  });\n\n  after(async () => {\n    await db.close();\n  });\n\n  it('creates an order', async () => {\n    // ...\n  });\n});\n```\n\nExpensive one-time work like setting up the connection belongs in `before`/`after`, resetting state in `beforeEach`/`afterEach`. A `beforeEach` inside a nested `describe` only applies to its tests – that’s how you keep setup local and avoid a global hook needlessly slowing down half the suite.\n\n## Conclusion\n\nTesting in the backend isn’t busywork you tack on at the end. It’s how a team records its architectural expectations and safeguards them across refactorings. The test pyramid gives a direction, but no fixed count: fast tests carry the base, integration tests secure important boundaries, a few end-to-end scenarios check the interplay. In this example the toolbox is small and interchangeable – Mocha structures, `node:assert` checks, sinon isolates external dependencies, supertest tests HTTP endpoints.\n\nWhat has turned out to be the core for me over the years: test observable behavior, not the implementation, and pin down bugs at the cheapest level where they’re reproducible. Then the suite stays fast, meaningful and – most importantly – trustworthy. A test suite nobody believes in anymore is more expensive than none at all.\n\n## Further reading\n\n- Mocha – documentation and hooks: [mochajs.org](https://mochajs.org/) and [mochajs.org/features/hooks](https://mochajs.org/features/hooks/)\n- node:assert – strict mode: [nodejs.org/api/assert.html](https://nodejs.org/api/assert.html)\n- node:test – built-in test runner: [nodejs.org/api/test.html](https://nodejs.org/api/test.html)\n- sinon – test doubles and stubs: [sinonjs.org](https://sinonjs.org/) and [sinonjs.org/concepts/stubs](https://sinonjs.org/concepts/stubs/)\n- supertest: [npmjs.com/package/supertest](https://www.npmjs.com/package/supertest)\n- Chai (alternative to assert): [chaijs.com](https://www.chaijs.com/)\n- Companion repository with a testing chapter: [github.com/mikebild/introduction-nodejs](https://github.com/mikebild/introduction-nodejs)"},{"locale":"en","translation_key":"deterministische-clis","slug":"deterministic-clis","title":"Deterministic CLIs","summary":"Determinism is an architecture decision: same inputs, same report, reviewable via diff. It pays off wherever an artifact is checked repeatedly.","tags":["Software","Data","Tools"],"published_at":"2024-07-12T10:00:00+00:00","updated_at":"2026-07-20T13:27:22.94021+00:00","url":"https://www.mikebild.dev/en/blog/deterministic-clis/","audio_url":null,"audio_duration_secs":null,"text":"# Deterministic CLIs\n\nTwo runs, the same input files, two different reports. The difference consists of a timestamp in the header and a table whose rows are in a different order this time. Nothing has changed in substance, but the diff shows a hundred lines, and none of them means anything. So the reviewer reads the whole report again. The next time, they don’t read it at all.\n\nA deterministic CLI turns this situation around: whatever shows up in the diff has also changed in substance. Byte for byte. That sounds like an implementation detail, but in reality it is a decision about system boundaries.\n\nDeterminism is usually treated as a Side Effect that you pick up “on top.” In truth, it is the prerequisite for a result to become reviewable. And reviewability is the currency in which digital product development actually pays: what I can’t compare, I can’t approve, can’t refute, and can’t automate with a clear conscience.\n\n## Why determinism is an architecture lever\n\nThe reflex is to see determinism as a property of the output. I see it as a property of the system boundary. A CLI that works reproducibly forces me to make every source of nondeterminism explicit: timestamps, random numbers, unsorted maps, network responses, OCR results, model outputs. I have to freeze, sort, cache, or keep each of these sources out of the result.\n\nExactly this exercise is valuable, regardless of the tool. If you name the nondeterminism, you have already half documented the state and dependency boundaries of a system. The question “why isn’t this run reproducible?” is almost always the same as “which part of my system is hidden, untamed I-don’t-know?”\n\nThe business outcome is concrete. A deterministic report can be reviewed via `diff`. A reviewer sees in seconds what changed between two runs instead of reading an entire output again. That shortens the feedback cycle from “I’ll read the whole thing again” to “I’ll look at the three changed lines.” In teams that produce reports like these every day, that is the difference between friction and flow.\n\n## The cost model – determinism isn’t free\n\nDeterminism has a price. If you keep quiet about it, you are delivering an advertising message instead of a trade-off.\n\nYou pay in explicit state control. Time has to be injected instead of read. Randomness needs a seed. External sensors – OCR, HTTP, a model – need a cache so that a second run sees the same thing as the first. Sorting becomes mandatory, not optional, because otherwise the order of a hash map changes the report. That is extra work, and for small throwaway scripts, it often doesn’t pay off.\n\nWhat you get in return is reviewability, auditability, and testability in one. A deterministic report is automatically a golden master test: I check in an expected report and let CI diff against it. I don’t need a separate desert of assertions; the artifact itself is the test. The costs are incurred once; the effect repeats with every run. That is exactly why I use determinism where something runs often and is checked often – and leave it out where a script tips something over once and then disappears.\n\nThis trade-off is the real engineering achievement, not the implementation. I have seen teams that wanted to force every script to be deterministic and stumbled over seed injection in throwaway tools. And I have seen the opposite: a daily report that nobody read anymore because it looked different on every run and a review would have cost hours. The line doesn’t run between “always” and “never.” It runs along the question of whether the artifact is checked repeatedly. If it is, the price pays off by orders of magnitude. If it isn’t, determinism is gold-plating.\n\n## The boundary before the tool\n\nBefore choosing a tool, I clarify which data is authoritative, what has to be traceable later, and which parts should be changeable independently. That way, I can swap the PDF parser without touching the matching rules or the report format. Determinism helps with the last point but doesn’t replace a clear domain boundary: a reproducible report can also reliably repeat ambiguity.\n\n## A concrete example – matching receipts against bookings\n\nI show this with an inventory tool that I use again and again as a pattern. The task: link an account ledger to PDF receipts via invoice numbers, match inventory items against invoice line items, and make the gaps visible. It sounds like bookkeeping, but in truth it is an architecture exercise about uncertain data.\n\nThree design decisions carry the whole thing, and none of them is a tool.\n\nThe first is the three-stage structure: link the account ledger to receipts, match line items, and handle non-PDF vendors separately via rules on the booking text. These stages are more important than any file format. They are the domain boundary at which I can later change something independently.\n\nThe second is the clean separation of hard match and fuzzy fallback. First, defined tokens must appear in the product title; fuzzy matching only comes into play when the hard path finds nothing. That keeps the automation explainable. For every row, I can say why it was assigned – hard via a rule or soft via a similarity above a threshold. A fuzzy match that nobody can justify anymore isn’t a feature – it is the debugging session of the day after tomorrow.\n\nThe third is treating OCR as an uncertain sensor. Vision provides the base, Tesseract corrects amounts specifically in the debit/credit region, and a JSON cache makes later runs reproducible. The decisive sentence: the recognized text is a measurement, not the truth. Amounts, names, and numbers can be misread. That is why this layer gets a cache, thresholds, manual alias rules, and – this is the core – diffability.\n\nThe report itself is then an architecture artifact, not a by-product. Inventory items, invoice numbers, purchase date, match type, orphaned account entries, and unused invoice line items appear side by side. That is exactly what turns a script into a verifiable data system: you see not only what was matched but also what doesn’t fit – and that is usually the more interesting information.\n\n## How it is called\n\n```bash\ninventory-correlate \\\n  --account account.pdf \\\n  --inventory inventory.pdf \\\n  --out report.md\n\n# review is just a diff against the last known-good run\ndiff last-report.md report.md\n```\n\nThe example is deliberately small. It isn’t meant to simulate a complete application but to show the boundary. A good example doesn’t have the most features. It has the one decision you can argue about after five minutes. Here, it is in the second call: because the report is deterministic, the review is a `diff`. No dashboard, no state, no “read the whole thing again.”\n\n```mermaid\nflowchart LR\n  PDFs --> Parser\n  Parser --> Normalize\n  Normalize --> Match[\"Hard match<br/>then fuzzy fallback\"]\n  Match --> Report[\"Deterministic<br/>Markdown report\"]\n  Report --> Diff[\"Review via diff\"]\n```\n\n## Markdown as an audit artifact\n\nWhy Markdown and not a UI right away? Because a Markdown report is reviewable, diffable, and archivable without me having to build a dashboard. For data tools, diffability is a strong quality attribute. If a report exists as Markdown, a change can be seen in the review – line by line, with full history in Git. That is often more valuable than a UI that only shows the latest state and can’t answer the question “what changed?” at all.\n\nThe same principle carries far beyond bookkeeping. Publishing tools can work according to the same pattern: input in, deterministic artifact out, changes visible as a diff. Whether I am matching receipts or generating presentations – the architecture is identical, because the quality problem is identical: I want to see changes, not guess states.\n\n## How I check the benefit\n\nA diff limits the review to the lines that actually changed. Whether that saves time can be read from the review duration of a recurring report. An expected report can also serve as a golden master; an unexpected diff is then a concrete signal to check. For that, I invest in caches, seeds, and explicit sorting – not because determinism would be an end in itself for every script.\n\n## What I check before calling it production-ready\n\nAn idea only holds up once its failure path is described as well. What happens on repetition? What is idempotent? Where is the transaction boundary? Which logs or reports help with analysis later? These questions seem dry, but they are often the difference between a demo and operations.\n\nWith a deterministic CLI, there is one specific question on top: is the nondeterminism really captured, or is it just quiet by chance right now? A report that is stable today because the map happens to come out sorted tips over tomorrow on a different runtime. That is why I enforce sorting explicitly, version caches, and treat manual corrections as data, not as manual steps. Fuzzy matching needs explicit thresholds and a way to prefer hard rules – otherwise the result can no longer be explained. A tool may be uncertain, but it has to show its uncertainty.\n\nBefore using it in production, I check three things:\n\n- The same inputs produce a byte-for-byte identical result.\n- Time, randomness, order, and external responses are explicitly constrained.\n- Errors and uncertain assignments show up in the verifiable artifact.\n\n## Typical mistakes\n\nThe first mistake is confusing the tool with the solution. Docker isn’t an architecture. GraphQL isn’t a domain model. React isn’t a state concept. An LLM isn’t a process. These tools can express good boundaries, but they don’t create them automatically. Determinism is the same: it is a decision about system boundaries, not a flag you set.\n\nThe second mistake is overrating the happy path. Many systems look clean in demo mode. It gets interesting with repetition, partial failures, old data, network problems, wrong permissions, or human correction. That is exactly where it shows whether the model holds – and whether the report will produce the same diff tomorrow as it does today.\n\n## Closing\n\nI invest in determinism when a result is checked repeatedly. Then the diff shows the change, and caches, seeds, or explicit sorting have a concrete purpose. For a one-off throwaway script, the same effort would be gold-plating.\n\n## Further reading\n\n- [Git: `git diff`](https://git-scm.com/docs/git-diff/2.45.0)\n- [Reproducible Builds: Definition](https://reproducible-builds.org/docs/definition/)"},{"locale":"en","translation_key":"observability-mit-opentelemetry","slug":"observability-with-opentelemetry","title":"Observability with OpenTelemetry: Logs, Traces and Metrics","summary":"Instrument logs, traces and metrics consistently with OpenTelemetry, connect them through trace IDs and export them via OTLP to suitable backends.","tags":["Software","Platform"],"published_at":"2024-07-09T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/observability-with-opentelemetry/","audio_url":null,"audio_duration_secs":null,"text":"```json\n{\"ts\":\"2024-07-09T12:14:03.221Z\",\"level\":\"error\",\"msg\":\"stock reservation failed\",\"order_id\":\"4711\"}\n```\n\nThis line is structured, has a timestamp, a clean field for the order ID – and still answers none of the questions that matter after an outage. Which request triggered it? Which call ran before it, which one after? Is this an isolated case or the hundredth since noon? The line knows nothing about the operation it came from, and so searching the log volume remains exactly that: searching.\n\nWhat’s missing is the connection – between the single event, the path of the request through the services and the aggregated view over time. That’s what logs, traces and metrics are for, and they only become really useful once they reference each other. OpenTelemetry is the standard I use to collect them consistently in Node.\n\nThe three telemetry signals aren’t interchangeable representations of the same information. Each answers a different question.\n\n::::comparison{title=\"Three signals, three investigative questions\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Metrics\"}\n- Question · How does an aggregated value change over time?\n- Strength · trends, thresholds and alerting\n- Limit · doesn’t explain a single slow request\n:::\n:::side{label=\"Traces\"}\n- Question · Which path did a specific execution take?\n- Strength · latency and dependencies across service boundaries\n- Limit · doesn’t replace long-term aggregation\n:::\n:::side{label=\"Logs\"}\n- Question · Which discrete event was recorded with which context?\n- Strength · details, error messages and domain hints\n- Limit · hard to analyze without correlation and limits\n:::\n::::\n\nThe practical gain comes from switching between these perspectives: from the trend to the affected trace, and from there to the correlated events.\n\n## Three signals, three angles\n\nBefore I talk about tools, it’s worth getting the terms straight. Logs, traces and metrics aren’t three ways of doing the same thing – they answer different questions and have different costs.\n\n- Logs are discrete events with a timestamp: “Order 4711 rejected because stock is zero.” They deliver the detail, the specific case, the debug context. In exchange, they are expensive to retain and quickly get confusing at high cardinality.\n- Traces show the path of a single request through the system: which service calls which, how long each hop takes, where the latency comes from. A trace is a tree of spans, and it doesn’t end at the service boundary.\n- Metrics are aggregated number series over time: requests per second, error rate, latency distribution. They’re cheap to store and good for alerts and trends – but they never tell me *which* request was slow, only *that* there were some.\n\nThe mistake in thinking I see again and again is the assumption that one of these signals is enough. Metrics alone tell me that latency went up, but not why. Logs alone drown in volume. Traces alone show the path, but not the trend over a week. Only together do they form a picture – and the real gain comes where I can jump between them: from a latency spike in the metric to the specific trace, and from there into the correlated logs.\n\n## OpenTelemetry separates instrumentation and backend\n\nOpenTelemetry (OTel for short) is a vendor-neutral CNCF project, and that neutrality is exactly why I recommend it. Observability used to mean tying yourself to a backend: the vendor’s agent SDK was woven into the code, and switching meant rewriting the instrumentation. OTel separates the generation and transport of telemetry from the backend. I instrument my code against a standardized API and export the data via OTLP or a suitable exporter. That lowers switching costs considerably, but it doesn’t make backends interchangeable: query languages, aggregations, retention, supported signals and dashboards remain product-specific. A switch can therefore start with the collector configuration and still require adjustments to semantics and analysis.\n\nA word about maturity, because in mid-2024 it isn’t the same everywhere. Tracing is stable in JavaScript, and so are metrics. The logs signal in JS, on the other hand, is still experimental – `@opentelemetry/api-logs` and `sdk-logs` carry the alpha stamp and are meant as a bridge for existing loggers, not as a direct log API for application code. In practice, that means I keep writing my logs with the logger of my choice and make sure myself that the trace correlation is in there. More on that later.\n\n## Setting up the SDK – early enough\n\nInstrumentation starts with the Node SDK. The key point I flag most often in reviews: the SDK has to start *before* any other module is loaded. OTel works by monkey-patching the libraries – if `http` or `graphql` are already loaded before the SDK could patch them, I get a no-op tracer and wonder about empty traces. That’s why I load the instrumentation via `--require`, not as a regular import in `app.ts`.\n\n```ts\n// instrumentation.ts\nimport { NodeSDK } from '@opentelemetry/sdk-node';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';\nimport { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';\nimport { Resource } from '@opentelemetry/resources';\nimport { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';\n\nconst sdk = new NodeSDK({\n  resource: new Resource({\n    [SemanticResourceAttributes.SERVICE_NAME]: 'checkout-service',\n    [SemanticResourceAttributes.SERVICE_VERSION]: '1.4.0',\n  }),\n  traceExporter: new OTLPTraceExporter({\n    url: 'http://collector:4318/v1/traces',\n  }),\n  metricReader: new PeriodicExportingMetricReader({\n    exporter: new OTLPMetricExporter({\n      url: 'http://collector:4318/v1/metrics',\n    }),\n  }),\n  instrumentations: [\n    getNodeAutoInstrumentations({\n      // File-system spans are noisy; turn them off.\n      '@opentelemetry/instrumentation-fs': { enabled: false },\n    }),\n  ],\n});\n\nsdk.start();\n\nprocess.on('SIGTERM', () => {\n  sdk.shutdown().finally(() => process.exit(0));\n});\n```\n\nThe whole thing is started so that the instrumentation is guaranteed to run first:\n\n```bash\nnode --require ./instrumentation.js ./app.js\n```\n\n`getNodeAutoInstrumentations()` covers a surprising amount without me touching a single line of business code: HTTP and HTTPS, Express or Fastify, GraphQL, gRPC, common database clients. To start with, I get a complete request tree through the standard layers practically for free. If you’re wondering in general how to keep an eye on a running Node process, [Debugging and Observing Node.js](https://www.mikebild.dev/en/blog/debugging-and-profiling-nodejs-locally/) covers the basics this builds on.\n\n## Manual spans for business logic\n\nAuto-instrumentation knows HTTP and GraphQL, but it doesn’t know my domain. Whether a checkout fails the credit check or runs out of stock is something no generic instrumentation plugin sees. That’s exactly what I use manual spans for – where the interesting domain decisions are made.\n\n```ts\nimport { trace, SpanStatusCode } from '@opentelemetry/api';\n\nconst tracer = trace.getTracer('checkout', '1.4.0');\n\nexport async function processCheckout(order: Order): Promise<Receipt> {\n  return tracer.startActiveSpan('checkout.process', async (span) => {\n    span.setAttribute('order.id', order.id);\n    span.setAttribute('order.item_count', order.items.length);\n\n    try {\n      await reserveStock(order);\n      const receipt = await charge(order);\n      span.setAttribute('payment.provider', receipt.provider);\n      return receipt;\n    } catch (err) {\n      span.recordException(err as Error);\n      span.setStatus({ code: SpanStatusCode.ERROR });\n      throw err;\n    } finally {\n      span.end();\n    }\n  });\n}\n```\n\nThree things matter here. `startActiveSpan` makes the span the active context, so everything that happens inside the callback – including the auto-instrumentation spans for `reserveStock` and `charge` – is correctly attached as children. `recordException` plus `setStatus` marks the span as failed, which makes it findable in the backend. And `span.end()` in `finally` makes sure the span is closed even in the error case – a forgotten `end()` is a leak that shows up in the backend as a hanging span.\n\nI’m careful with attributes. The order ID belongs there, and so does the item count. What doesn’t belong there is anything that blows up cardinality or is sensitive – full shopping carts, personal data, free text.\n\n## The trace doesn’t stop at the service boundary\n\nThe real value of a trace shows as soon as several services are involved. A request hits the gateway, which calls the checkout service, which talks to the database and, on the side, to a payment provider. For this to remain one connected trace instead of falling apart into four unconnected fragments, the trace context has to travel across the boundaries.\n\nBy default, OpenTelemetry uses the W3C Trace Context for this: a `traceparent` header that carries the trace ID, span ID and sampling decision. Auto-instrumentation injects and extracts it automatically on HTTP calls – the receiver attaches its spans to the parent from the header, and the tree keeps growing across process boundaries.\n\n```mermaid\ngraph TD\n    A[Client Request] -->|traceparent| B[API Gateway<br/>Span: http.request]\n    B -->|traceparent| C[Checkout Service<br/>Span: checkout.process]\n    C --> D[Span: db.query]\n    C -->|traceparent| E[Payment Provider<br/>Span: payment.charge]\n    B -.->|one trace_id| F[(One trace =<br/>tree of spans)]\n    C -.-> F\n    D -.-> F\n    E -.-> F\n```\n\nIt gets interesting where there’s no HTTP header. In a Lambda Function or with a message queue, there’s no automatic transport for the context. Then I have to pass it through the event payload myself – write it into the message with `propagation.inject` when sending, pull it out with `propagation.extract` when receiving, and set the context as active. With serverless, two more points come in: the cold start lengthens the init phase, and before the function is frozen I have to trigger a force flush, otherwise the last spans get lost because the export couldn’t send them out anymore.\n\n## Linking logs to traces – through the trace_id\n\nNow to the point where, in my view, observability stands or falls: correlation. A log without a trace reference is a line in the middle of nowhere. A log with `trace_id` and `span_id` is a springboard – from the error message straight into the complete request path that produced it.\n\nThe active span lives in the context, and in Node the context is carried by `AsyncLocalStorage` – which is also the default context manager OTel uses internally. So all I have to do is read the active SpanContext and attach its IDs to every structured log. I described in detail how `AsyncLocalStorage` carries this implicit context through asynchronous call chains in [Async Context with AsyncLocalStorage](https://www.mikebild.dev/en/blog/async-context-in-nodejs-with-asynclocalstorage/); here it’s the carrier that makes trace correlation possible in the first place.\n\n```ts\nimport { trace } from '@opentelemetry/api';\n\ntype Fields = Record<string, unknown>;\n\nexport function log(level: 'info' | 'warn' | 'error', msg: string, fields: Fields = {}): void {\n  const span = trace.getActiveSpan();\n  const ctx = span?.spanContext();\n\n  const entry = {\n    ts: new Date().toISOString(),\n    level,\n    msg,\n    ...(ctx && { trace_id: ctx.traceId, span_id: ctx.spanId }),\n    ...fields,\n  };\n\n  process.stdout.write(JSON.stringify(entry) + '\\n');\n}\n```\n\nA call like `log('error', 'stock reservation failed', { order_id: order.id })` in the middle of the business logic now produces a JSON line that carries the same `trace_id` as the span it was created in. Later, in the backend, I filter on that ID and have the log and trace side by side. In practice, I don’t wrap this myself but let an established logger like Pino handle it through a mixin – the principle stays the same: read the active SpanContext and attach it.\n\n## RED: Rate, Errors, Duration\n\nMetrics are the aggregated health of the system, and I don’t start with a hundred custom metrics, but with three. The RED method – Rate, Errors, Duration – covers the essentials for every service: how many requests come in, how many of them fail, how long they take.\n\n```ts\nimport { metrics } from '@opentelemetry/api';\n\nconst meter = metrics.getMeter('http-server');\n\nconst requestCounter = meter.createCounter('http.server.requests', {\n  description: 'Total number of HTTP requests',\n});\nconst errorCounter = meter.createCounter('http.server.errors', {\n  description: 'Total number of failed HTTP requests',\n});\nconst latencyHistogram = meter.createHistogram('http.server.duration', {\n  description: 'HTTP request duration in milliseconds',\n  unit: 'ms',\n});\n\nexport function recordRequest(route: string, statusCode: number, durationMs: number): void {\n  const attributes = { route, status_class: `${Math.floor(statusCode / 100)}xx` };\n  requestCounter.add(1, attributes);\n  if (statusCode >= 500) {\n    errorCounter.add(1, attributes);\n  }\n  latencyHistogram.record(durationMs, attributes);\n}\n```\n\nThese three calls live in a middleware and run for every request. The counter for the rate, the counter for the errors, the histogram for the duration – the latter because with latency I’m not interested in the average but in the distribution, the p95 and p99. An average of 80 milliseconds hides that every twentieth user waits two seconds.\n\nWhat matters with attributes is restraint. I label with `route` and a status class – values with a limited, manageable range. What I don’t do: use the full URL with an embedded order ID as a label, or the user ID. Every unique label combination creates its own time series, and unbounded values make cardinality explode until the metrics backend buckles. Cardinality belongs in traces, not in metrics.\n\n## The pitfalls that cost me time\n\nI see a few mistakes so regularly that I name them explicitly here. The most expensive one is the logging without correlation mentioned above – logs that are structured but carry no `trace_id`. They look tidy and still help little when it counts, because I can’t assign them to any request. The second is initializing the SDK too late, which makes the monkey-patching come to nothing.\n\nThe third concerns sampling. Capturing every trace in production rarely makes sense – volume and costs explode. So you sample. But naive head sampling that blindly keeps every hundredth trace is very likely to throw away exactly the error traces I want to see. That’s why I go with `ParentBased(TraceIdRatio)`: the sampling decision is made at the start, propagated through the `traceparent` header and stays consistent for the whole trace – no service decides on its own, so I don’t get half traces. The fourth pitfall is the cardinality trap with custom metrics already mentioned.\n\n## Conclusion\n\nObservability isn’t a question of the right dashboard but of being able to answer any question about a running system – including the ones I didn’t think to ask beforehand. The three signals provide the raw data for that: logs for the specific event, traces for the request path, metrics for the aggregated health. They only unfold their real power through correlation, when I can jump from the metric spike to the trace and from there to the log without switching tools.\n\nOpenTelemetry keeps instrumentation more vendor-neutral and lets you configure the export targets separately from it. Auto-instrumentation gets me close quickly, manual spans cover the domain, trace context propagation holds everything together across service boundaries, and linking logs to the `trace_id` via `AsyncLocalStorage` closes the loop. The start can be small: three RED metrics, auto-instrumentation, correlated logs. When you switch backends, you still need to check its query model, dashboards and quirks. By the next incident at the latest, the groundwork pays off – then the system is visible before anyone starts fixing it.\n\n## Further reading\n\n- [OpenTelemetry JS – Getting Started (Node.js)](https://opentelemetry.io/docs/languages/js/getting-started/nodejs/)\n- [OpenTelemetry JS – Instrumentation](https://opentelemetry.io/docs/languages/js/instrumentation/)\n- [OpenTelemetry – Traces](https://opentelemetry.io/docs/concepts/signals/traces/), [Metrics](https://opentelemetry.io/docs/concepts/signals/metrics/) and [Logs](https://opentelemetry.io/docs/concepts/signals/logs/)\n- [OpenTelemetry – Context Propagation](https://opentelemetry.io/docs/concepts/context-propagation/)\n- [OpenTelemetry – signal maturity (status)](https://opentelemetry.io/docs/specs/status/)\n- [W3C Trace Context](https://www.w3.org/TR/trace-context/)\n- [The RED Method – Grafana Blog](https://grafana.com/blog/2018/08/02/the-red-method-how-to-instrument-your-services/)"},{"locale":"en","translation_key":"graphql-client-apollo-link-und-fragments","slug":"graphql-client-apollo-link-and-fragments","title":"The GraphQL Client: Apollo Link and Fragments","summary":"Apollo Link runs every GraphQL operation through a chain of middleware: authLink sets headers, errorLink handles errors in one place, split routes subscriptions. Plus fragments as reusable field sets and why interfaces need possibleTypes.","tags":["Software","GraphQL","API"],"published_at":"2024-06-25T10:00:00+00:00","updated_at":"2026-07-13T10:04:59.062506+00:00","url":"https://www.mikebild.dev/en/blog/graphql-client-apollo-link-and-fragments/","audio_url":null,"audio_duration_secs":null,"text":"The post on [Apollo Client caching](https://www.mikebild.dev/en/blog/apollo-client-normalized-cache-and-optimistic-updates/) was about what happens to a response once it reaches the client: how the normalized cache breaks the data apart, stores it and finds it again. This time I turn the view around. Before a response can land in the cache, the request has to go out to the server, and along the way there are decisions that have nothing to do with the individual query: sending a token, handling a 401 in one place, routing subscriptions to a different transport. These are cross-cutting concerns, and the real question is not which API you call for them but where they belong. Spread across every single `useQuery` call, or bundled in one place.\n\nThat is exactly the decision this post is about, and I consider the bundled variant the more sustainable one. Apollo Client answers it with a chain of middleware. The trade-off is manageable: you accept one indirection that you have to understand once, and you get an architecture in which auth, error handling and routing each live in one named place instead of being scattered across dozens. If the auth strategy changes, you change one link, not forty components. That is how you measure the value of a transport layer, not by the number of its options.\n\nRequirements like these arrive in stages. First there is an `ApolloClient`, and everything works. Then someone says: “We need to send an auth token.” Shortly after: “And when the server returns a 401, all affected operations should be handled centrally.” And finally: “Oh, and we need subscriptions too.” By this point at the latest, it becomes clear that the one network link from the setup was only the tip. Underneath sits a composable system built for exactly these cases: Apollo Link.\n\nThe second part of this post is about fragments. At first glance they look like a mere convenience for writing, but they are the building block that lets you compose queries cleanly and keep components maintainable. I use Apollo Client 3.10; the import paths and signatures refer to this version. In Apollo Client 4, React hooks such as `useFragment` come from `@apollo/client/react`; the cache model shown here stays the same.\n\n## Apollo Link is a chain\n\nThe basic idea is quickly told. Every operation, whether query, mutation or subscription, passes through a chain of links before it reaches the server, and the response travels back through the same chain in reverse. A link is a piece of middleware: it may look at the operation, change it and pass it on to the next link. The last link in the chain is special. It is **terminating**, which means it does not pass anything on but actually sends the request. In the vast majority of cases, that is the `HttpLink`.\n\nIf you have ever seen Express middleware or a Redux middleware chain, you will recognize the pattern right away. Each link receives the operation and a `forward` function it uses to hand over to the next link. And as with any middleware chain, the order determines the behavior.\n\nYou assemble the chain with `ApolloLink.from`, which links an array of links in exactly the order in which they appear. For two links, `linkA.concat(linkB)` is enough. Let’s look at a typical chain.\n\n```typescript\nimport { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';\nimport { setContext } from '@apollo/client/link/context';\nimport { onError } from '@apollo/client/link/error';\n\nconst httpLink = new HttpLink({ uri: '/graphql' });\n\nconst authLink = setContext((_, { headers }) => {\n  const token = getToken();\n  return {\n    headers: {\n      ...headers,\n      authorization: token ? `Bearer ${token}` : '',\n    },\n  };\n});\n\nconst errorLink = onError(({ graphQLErrors, networkError, operation }) => {\n  if (graphQLErrors) {\n    for (const err of graphQLErrors) {\n      console.error(`[GraphQL error] ${operation.operationName}: ${err.message}`);\n    }\n  }\n  if (networkError) {\n    console.error(`[Network error] ${networkError.message}`);\n  }\n});\n\nconst link = ApolloLink.from([errorLink, authLink, httpLink]);\n\nconst client = new ApolloClient({\n  link,\n  cache: new InMemoryCache(),\n});\n```\n\nThree links, a clear division of labor. The `errorLink` sits on the outside because it should see both the outgoing operation and the incoming response. Errors that occur deep in the chain pass through it on the way back. The `authLink` sits just before the network link because it sets the token as late as possible, when it is most current. And the `httpLink` sits at the very end because it is terminating.\n\n## Why the order matters\n\nThis is exactly where the pitfall lies that I run into most often in code reviews. The terminating link has to be the last element. If the `authLink` accidentally sits behind the `httpLink`, it is never reached, because the request has long been sent by the time this link would get its turn. The result: the token is missing, the server responds with 401, and debugging starts in completely the wrong place, at the auth server instead of the link order.\n\nThe `authLink` deserves a second look because its name can be misleading. `setContext` does not change the HTTP headers directly. It returns an object that is merged into the operation’s context, usually under the key `headers`. Only the `HttpLink` reads this context and translates it into real HTTP headers. So the `authLink` only prepares; the sending happens elsewhere. Once you have internalized that, you also understand why the order is so important: the preparer has to come before the sender.\n\nA detail you need often in practice: the function in `setContext` may be asynchronous. If it returns a promise, Apollo Link waits before the operation continues. That lets you load or refresh a token on demand without burdening the calling component with it. Just keep in mind that every operation waits for this resolution: a slow token endpoint then slows down all requests. As a rule, you therefore keep the token in a store that `setContext` can read synchronously and trigger the refresh separately.\n\nThe `errorLink` distinguishes two classes of errors that you should not confuse. `graphQLErrors` is an array of errors the server returned deliberately, such as a failed validation or a record that was not found. The transport worked; the response simply contains errors in the `errors` field. `networkError`, on the other hand, means that the transport itself failed: no connection, a 500, a timeout. This separation is why `onError` is the right place for central handling. You do not have to check in every single `useQuery` call whether the token has expired; you do it once, in one place.\n\nWhen I draw the same chain as a diagram, the path of an operation looks like this.\n\n```mermaid\nflowchart LR\n  Op[Operation] --> E[errorLink onError]\n  E --> A[authLink setContext]\n  A --> H[httpLink terminating]\n  H --> S[(GraphQL Server)]\n  S -. response .-> H\n  H -. response .-> A\n  A -. response .-> E\n  E -. response .-> Op\n```\n\nThe solid arrows show the request going out, the dashed ones the response on the way back. The fact that the `errorLink` takes part in both directions makes clear why it sits on the very outside.\n\n## The common links at a glance\n\nBeyond the three mentioned, there are a few links you need regularly. Here are the most important ones with their respective jobs:\n\n- `errorLink` (`onError`): central handling of GraphQL and network errors, such as logging or logging out when a token has expired.\n- `authLink` (`setContext`): prepares headers and token and merges them into the operation context.\n- `retryLink` (`RetryLink`): retries operations on network errors, with configurable backoff and jitter.\n- `splitLink` (`split`): routes operations to different branches based on a predicate, classically subscriptions versus queries.\n- `httpLink` (`HttpLink`): the terminating link that sends the request over HTTP.\n\nThe `RetryLink` belongs in the chain before the terminating link so that it can trigger the retry before the request finally goes out. A sensible complete chain would therefore be `from([errorLink, retryLink, authLink, httpLink])`. One important point: set the retry condition explicitly. If you unconditionally return a `forward(operation)` in `onError` to retry an operation, this can turn into an infinite loop when the error is permanent. The `RetryLink` with its `retryIf` condition is the more robust way because it limits the number of attempts.\n\n```typescript\nimport { RetryLink } from '@apollo/client/link/retry';\n\nconst retryLink = new RetryLink({\n  delay: { initial: 300, max: 3000, jitter: true },\n  attempts: {\n    max: 3,\n    retryIf: (error) => Boolean(error),\n  },\n});\n```\n\n## Branching off subscriptions with split\n\nAs soon as subscriptions come into play, a second transport may become necessary. In this example, queries and mutations run over HTTP, subscriptions over a persistent WebSocket connection. Other stacks transport subscriptions over HTTP and server-sent events. In the WebSocket setup shown here, `split` takes on the job of directing the operation to the right branch. The function receives a predicate and two links: if the predicate is true, the operation goes into the first branch, otherwise into the second.\n\nTo decide whether an operation is a subscription, `getMainDefinition` helps. It extracts the main definition from the query document so that you can check `kind` and `operation`.\n\n```typescript\nimport { split } from '@apollo/client';\nimport { getMainDefinition } from '@apollo/client/utilities';\nimport { GraphQLWsLink } from '@apollo/client/link/subscriptions';\nimport { createClient } from 'graphql-ws';\n\nconst wsLink = new GraphQLWsLink(\n  createClient({ url: 'wss://example.com/graphql' }),\n);\n\nconst splitLink = split(\n  ({ query }) => {\n    const definition = getMainDefinition(query);\n    return (\n      definition.kind === 'OperationDefinition' &&\n      definition.operation === 'subscription'\n    );\n  },\n  wsLink,\n  ApolloLink.from([errorLink, authLink, httpLink]),\n);\n```\n\nThe WebSocket transport here is called `GraphQLWsLink` and builds on the `graphql-ws` library. For a WebSocket branch, that is the right choice. The older combination of `WebSocketLink` and `subscriptions-transport-ws` still shows up in many projects, but it is considered deprecated. Whether WebSocket is the right transport at all depends on the server and the subscription protocol in use; SSE is one possible alternative.\n\nOne point that is easy to overlook: the WebSocket branch bypasses `errorLink` and `authLink` because it hangs off its own branch in `split`. A subscription therefore does not authenticate via the HTTP header but via the `connectionParams` of the `graphql-ws` client, which are set when the connection is established. If you only pass the token in the `authLink`, you will otherwise wonder why the query is authorized but the subscription is not.\n\n## From Apollo detail to principle\n\nTake a step back, and it is no longer about Apollo. The link chain is a special case of a pattern that reaches far beyond GraphQL: cross-cutting concerns move out of the domain code into a chain of middleware that every operation passes through. Auth, logging, error handling, retries, routing. These are concerns that are needed everywhere and belong nowhere in the domain. Express does it with its middleware, Redux with its middleware chain, an API gateway with its filter chain, and Apollo Client with its links. Once you have recognized the pattern, you see it everywhere.\n\nThe appeal lies in drawing a clear line. Domain code requests data and displays it. It should know nothing about how a token comes about or what happens on a 401. The chain takes this off its hands, and it does so in a single, named place. The gain is not the technique but the locality of change. A new concern arrives as an additional link without touching a single `useQuery` call. That is the difference between an adjustment you finish in an afternoon and one that runs through forty files and carries a risk in each of them.\n\nThis does not come for free. The price is indirection. The path of an operation no longer reads linearly in the component code but is spread across a chain whose order you have to know to understand the behavior. A misplaced link is harder to find than a wrongly set header right at the call site. For a handful of operations without shared concerns, the chain would therefore be effort without return.\n\nThe assignment comes down to a few criteria. If a concern affects many or all operations, it belongs in the chain. If it affects exactly one, it belongs at the call site. If it changes independently of the domain code and for different reasons, that is a strong signal for the chain. And the more such concerns are on the table at the same time, the more clearly the separation pays off, because it prevents auth, errors and transport from getting mixed up in the same piece of code. In exactly this situation, when several concerns come together, the chain is not overhead but what keeps the codebase clear.\n\n## Fragments: queries from building blocks\n\nOn to the second half. A fragment is a named, reusable set of fields of a specific type. Instead of listing the same fields again in every query that loads a `User`, you define them once and insert them with a spread.\n\n```typescript\nimport { gql } from '@apollo/client';\n\nconst USER_FIELDS = gql`\n  fragment UserFields on User {\n    id\n    name\n    email\n  }\n`;\n\nconst GET_USER = gql`\n  query GetUser($id: ID!) {\n    user(id: $id) {\n      ...UserFields\n    }\n  }\n  ${USER_FIELDS}\n`;\n```\n\nTwo things matter. The spread `...UserFields` refers to the fragment, and the fragment document has to be passed to the query via `${USER_FIELDS}`, otherwise the parser does not know the name. This is a common beginner’s mistake: the spread is there, but the interpolation is missing, and the error message is not particularly telling.\n\nThe real gain only shows in a larger project, and it is called colocation. The idea: a fragment sits right next to the component that displays exactly these fields. A `UserCard` component defines its own `UserFields` fragment and exports it. The parent query that fills several components collects the fragments of its children and puts them together. If the fields the `UserCard` needs change, only its fragment changes, and the query at the top picks up the change automatically. The data requirement lives where the data is needed, not in a distant, central query file that nobody wants to maintain anymore.\n\nSince Apollo Client 3.8 there is also the hook `useFragment` for this. It lets a component read exactly the fields of a fragment from the cache without issuing a query itself. The component only re-renders when the fields of its fragment change, a finer cut than re-rendering on every change to the parent query.\n\n```tsx\nimport { useFragment } from '@apollo/client';\n\nfunction UserCard({ id }: { id: string }) {\n  const { data } = useFragment({\n    fragment: USER_FIELDS,\n    fragmentName: 'UserFields',\n    from: { __typename: 'User', id },\n  });\n\n  return <div>{data.name} · {data.email}</div>;\n}\n```\n\n## Fragment matching and possibleTypes\n\nOne last point that is often overlooked and then causes errors that are hard to track down. As soon as a fragment sits on an interface or a union instead of a concrete type, the cache has to know which concrete types belong to this abstract type. Take an interface `SearchResult` that is implemented by `User` and `Post`. A query wants to load different fields depending on the concrete type.\n\n```graphql\nquery Search($term: String!) {\n  search(term: $term) {\n    __typename\n    ... on User {\n      name\n    }\n    ... on Post {\n      title\n    }\n  }\n}\n```\n\nFor Apollo to match these inline fragments, `... on User` and `... on Post`, correctly, the `InMemoryCache` needs a `possibleTypes` entry. It tells the cache which concrete types stand behind each interface or union.\n\n```typescript\nconst cache = new InMemoryCache({\n  possibleTypes: {\n    SearchResult: ['User', 'Post'],\n  },\n});\n```\n\nWithout this entry, the cache cannot perform the matching reliably. Fields are then missing from the results, or Apollo falls back on a heuristic and prints a warning. The tricky part is that it seems to work anyway in simple cases and only breaks with more complex queries. That is why you are best off not maintaining `possibleTypes` by hand at all but generating it from the schema, via introspection or with GraphQL Codegen. That way the entry stays up to date automatically when a new type implements the interface.\n\n## Conclusion\n\nThe transport layer of Apollo Client is not a monolithic network component but a chain of small, clearly defined pieces. The return only shows in the effect. Because every concern sits in exactly one place, later adjustments are local instead of scattered. That shortens cycles, reduces friction with every change to auth or error handling and keeps the boundary between domain code and infrastructure clean. The price is the indirection of the chain, and most of the frustrating debugging sessions I have experienced with it come down to a swapped order. That is a fair deal as long as you set the order deliberately and put the terminating `HttpLink` at the end.\n\nFragments are the counterpart on the query side and follow the same principle. They keep field sets reusable and enable colocation close to the components, so that the data requirement lives where the data is needed and not in one giant central query that nobody wants to maintain anymore. When a component changes its needs, its fragment changes instead of a distant file. As soon as abstract types come into play, `possibleTypes` is the easily forgotten prerequisite without which matching breaks. Link order and fragment boundaries thus remain two concrete places where I review changes; Apollo does not make these decisions for me.\n\nHow the token that the `authLink` sets comes about in the first place and how it is checked on the server is a topic of its own; the post on [GraphQL auth in the context](https://www.mikebild.dev/en/blog/graphql-auth-identity-in-the-context/) fits here. And when the loaded lists grow, it is worth looking at [GraphQL pagination and connections](https://www.mikebild.dev/en/blog/graphql-pagination-cursors-and-connections/), where fragments and `fetchMore` work together.\n\n## Further reading\n\n- [Apollo Link: Overview](https://www.apollographql.com/docs/react/api/link/introduction)\n- [ApolloLink API (from, concat, split)](https://www.apollographql.com/docs/react/api/link/apollo-link)\n- [Error handling with onError](https://www.apollographql.com/docs/react/data/error-handling)\n- [Fragments (colocation, possibleTypes, useFragment)](https://www.apollographql.com/docs/react/data/fragments)\n- [Subscriptions (split and getMainDefinition)](https://www.apollographql.com/docs/react/data/subscriptions)"},{"locale":"en","translation_key":"ocr-mit-cache-und-misstrauen","slug":"ocr-with-a-cache-and-distrust","title":"OCR with a Cache and Distrust","summary":"Why an OCR pipeline for receipt data only feels reliable once you secure every recognized value with a hash cache, a confidence gate and plausibility rules instead of believing it.","tags":["Software","Data","Tools"],"published_at":"2024-06-12T10:00:00+00:00","updated_at":"2026-07-13T13:22:38.960627+00:00","url":"https://www.mikebild.dev/en/blog/ocr-with-a-cache-and-distrust/","audio_url":null,"audio_duration_secs":null,"text":"# OCR with a Cache and Distrust\n\nIn its TSV output format, Tesseract returns a confidence value for recognized words, usually between zero and one hundred; structural lines can carry `-1`. This internal score is a useful signal, but not a calibrated probability that the word is correct. `image_to_string` doesn’t return it. If you only take the string, you throw away an important piece of information about the recognition.\n\nI noticed this in a small inventory project in which ledger entries from an account statement were supposed to be matched with the corresponding invoice items. Sounds like an afternoon of work: read in PDFs, pull out amounts, dates and receipt numbers, match them against the ledger entries, done. The catch wasn’t in the matching. It was in the fact that some of the invoices existed only as scanned images and I had to extract the fields via OCR. OCR is not a function that returns text. OCR is a measuring instrument: it gets it right with a certain probability and is an expensive source of errors in the remaining cases.\n\nThis view shaped the architecture of the little tool more than any matching rule. As soon as you understand OCR as an unreliable sensor, three duties follow almost by themselves: you store the measurement, because it is expensive and can change with preprocessing, configuration or engine version. You keep the confidence score, because otherwise a misreading looks exactly like a correct hit. And you check the result against domain rules, because an amount that looks plausible is far from being the right amount.\n\n## The error that convinced me\n\nAll this caution sounds exaggerated at first. A single record convinced me. A scanned invoice showed a gross amount of 138.00 euros. The OCR read 133.00 euros, because the 8 was set narrow in the font used and the scan had swallowed the upper loop. An 8 that turns into a 3 is not far off visually; for a model that reconstructs glyphs from pixels, it is an obvious slip.\n\nThe insidious part wasn’t the misreading. Misreadings happen. The insidious part was what happened next. The account statement actually contained an entry of 133.00 euros from a different transaction. The fuzzy matching, which weights receipt number, date and amount, found a seemingly clean partner for the misread invoice and assigned it to the wrong entry. The actual 138-euro item was left behind as an orphaned account entry. Two errors that made each other look plausible. No stack trace, no exception, no red log. Just a report that looked tidy and was wrong.\n\nThat is exactly where the danger lies: an OCR error without confidence and without validation does more damage than a crash. A crash forces you to look. A silent misreading travels through the entire pipeline and disguises itself as a correct result. With monetary amounts, this is not an academic concern.\n\n## Why OCR is a sensor and not a function\n\nIt’s worth briefly separating what you are dealing with. Plain text extraction from a digitally generated PDF reads an existing text layer. OCR, by contrast, works on pixels, and the result depends on resolution, contrast, font, page orientation, preprocessing, configuration and engine version. A local Tesseract run with identical bytes and an identical environment is usually reproducible; if one of these factors changes, the result can change too.\n\nThat’s why I treat both paths separately. First I try to read the embedded text layer. Only if it is missing or empty does the pipeline fall back to OCR. This fallback is the point where uncertainty enters the system, and exactly this point has to be marked, measured and contained.\n\nIt helps that serious OCR engines report their own uncertainty. With Tesseract, the word confidence comes via the TSV output format, together with the bounding box and position on the page. Cloud services return comparable values, often as a float between 0 and 1 per field. This value is the most important piece of information in the whole recognition, and yet it usually ends up nowhere, because `image_to_string` returns only a string. If you use `image_to_data` with `tsv` instead, you get the confidence per word and can build a decision on it.\n\nIn my receipt dataset, word values below about 95 were often critical and values above 99 were much more reliable. These are not universally valid limits. The threshold has to be calibrated on labeled examples for engine, document type and field, and it also depends on the damage an error causes. For a free-text field, the bar can be lower than for an amount that gets posted to the ledger.\n\n## Cache by content hash, not by file name\n\nBefore I talk about thresholds, first the unspectacular measure that brings the most calm into the pipeline: a cache that computes a document’s OCR exactly once.\n\nOCR is slow and, with cloud services, expensive per page. An inventory run that you repeat twenty times during development would recognize the same pages twenty times. That costs time and money. A cache also pins the result observed once, so that a change of engine, configuration or external service doesn’t silently alter historical evaluations.\n\nThe crucial point is the cache key. The file name won’t do. Files get renamed, moved, re-exported, and two scans with identical content can have different names. Conversely, the same name can hide changed content. The only stable key is the content itself, that is, a cryptographic hash of the bytes, usually SHA-256. Same content, same hash, same cache entry, regardless of what the file happens to be called.\n\nBut the key needs more than just the file hash. If I change the OCR configuration, such as the page segmentation mode or the engine version, old results are no longer comparable. That’s why a version identifier of the pipeline also goes into the key. This way, a changed configuration invalidates the cache automatically, without me having to clean up by hand.\n\n```python\nimport hashlib\nimport json\nfrom dataclasses import dataclass, asdict\nfrom pathlib import Path\n\nimport pytesseract\nfrom PIL import Image\n\n# Changes to this configuration must invalidate the cache,\n# otherwise results from different setups get compared.\nOCR_VERSION = \"tesseract-5.3.4+psm6+v3\"\nCONF_MIN = 95.0          # word values below this count as uncertain\nCACHE_DIR = Path(\".ocr-cache\")\n\n\n@dataclass\nclass Word:\n    text: str\n    conf: float          # 0..100, straight from the TSV output format\n\n\ndef file_key(path: Path) -> str:\n    \"\"\"Content hash plus pipeline version. The file name deliberately plays no role.\"\"\"\n    digest = hashlib.sha256(path.read_bytes()).hexdigest()\n    return hashlib.sha256(f\"{digest}:{OCR_VERSION}\".encode()).hexdigest()\n\n\ndef run_ocr(path: Path) -> list[Word]:\n    \"\"\"Expensive; cache the observed result together with its pipeline version.\"\"\"\n    data = pytesseract.image_to_data(\n        Image.open(path),\n        config=\"--psm 6\",\n        output_type=pytesseract.Output.DICT,\n    )\n    words: list[Word] = []\n    for text, conf in zip(data[\"text\"], data[\"conf\"]):\n        text = text.strip()\n        if not text:\n            continue\n        words.append(Word(text=text, conf=float(conf)))\n    return words\n\n\ndef ocr_cached(path: Path) -> list[Word]:\n    \"\"\"Idempotent access: same content always yields the same cache entry.\"\"\"\n    CACHE_DIR.mkdir(exist_ok=True)\n    cache_file = CACHE_DIR / f\"{file_key(path)}.json\"\n    if cache_file.exists():\n        raw = json.loads(cache_file.read_text())\n        return [Word(**w) for w in raw]\n    words = run_ocr(path)\n    cache_file.write_text(json.dumps([asdict(w) for w in words], ensure_ascii=False))\n    return words\n```\n\nThe cache deliberately sits on disk here as one JSON file per document. For a local tool that is perfectly sufficient and has a pleasant side effect: the cache files are readable and can be diffed locally. With invoices and other documents containing personal data, though, such OCR output doesn’t belong unencrypted in the Git repository. Traceability needs protected storage with appropriate retention and access control.\n\n## The confidence gate\n\nWith the cache and word confidence in hand, the silent error from above becomes a loud one. The trick is not to ignore the confidence but to make it the decision: fields above the threshold count as trustworthy and may flow on automatically, fields below it are flagged and end up in manual review.\n\n```python\nimport re\n\nAMOUNT_RE = re.compile(r\"^\\d{1,3}(?:[.\\s]\\d{3})*,\\d{2}$\")  # e.g. 1.234,56\n\n\n@dataclass\nclass Field:\n    raw: str\n    conf: float\n    needs_review: bool\n    reason: str = \"\"\n\n\ndef extract_amount(words: list[Word]) -> Field:\n    \"\"\"Finds the gross amount and decides how to proceed based on the confidence.\"\"\"\n    candidates = [w for w in words if AMOUNT_RE.match(w.text)]\n    if not candidates:\n        return Field(raw=\"\", conf=0.0, needs_review=True, reason=\"no amount detected\")\n\n    # The last plausible amount on the receipt is usually the total.\n    best = candidates[-1]\n\n    if best.conf < CONF_MIN:\n        return Field(\n            raw=best.text,\n            conf=best.conf,\n            needs_review=True,\n            reason=f\"Confidence {best.conf:.0f} below threshold {CONF_MIN:.0f}\",\n        )\n    return Field(raw=best.text, conf=best.conf, needs_review=False)\n```\n\nIf the misread 133.00 had had a low confidence, it would have been caught here. But that doesn’t finish the gate. OCR engines are sometimes confidently wrong. A cleanly printed 3 that should actually be an 8 can come back with confidence 98. The model is sure the glyph is a 3, because it looks like a 3. The information that it should really be an 8 isn’t in the pixels but in the domain context. Confidence alone is therefore not enough. It is necessary, but it only catches the cases in which the model itself hesitates.\n\n## Validation against the world, not against itself\n\nThe second line of defense doesn’t check how sure the recognition was, but whether the result fits reality. Such rules cost little and catch exactly the confident errors where the confidence gate fails.\n\nWith receipt data, there are a number of obvious checks. A gross amount must equal the sum of net amount and tax; if it differs, at least one of the three values is wrong. An invoice date must come before the posting date and must not lie in the future. A receipt number often has a fixed format or even a check digit; if it doesn’t match, the recognition was wrong. And an amount that is supposed to be matched against a ledger entry must lie within a narrow tolerance, not within five euros.\n\nIn the concrete error case, a single one of these rules would have been enough. If the receipt shows net and tax separately, then 138.00 as gross at 19 percent gives a net value of 115.97, while 133.00 leads to 111.76. If the OCR reads net and gross independently and the sum doesn’t add up, the wrong 3 stands out immediately, no matter how sure the engine was. The redundancy on the receipt is the control measure that the pixels can’t provide.\n\n```python\nfrom decimal import Decimal\n\n\ndef parse_eur(s: str) -> Decimal:\n    return Decimal(s.replace(\".\", \"\").replace(\",\", \".\"))\n\n\ndef cross_check_total(netto: Field, steuer: Field, brutto: Field) -> Field:\n    \"\"\"A high confidence is unconvincing when the sum does not add up.\"\"\"\n    if any(f.needs_review or not f.raw for f in (netto, steuer, brutto)):\n        return brutto  # missing parts are already handled by the review anyway\n\n    expected = parse_eur(netto.raw) + parse_eur(steuer.raw)\n    actual = parse_eur(brutto.raw)\n    if abs(expected - actual) > Decimal(\"0.02\"):  # tolerance only for rounding\n        return Field(\n            raw=brutto.raw,\n            conf=brutto.conf,\n            needs_review=True,\n            reason=f\"Sum {expected} differs from read gross {actual}\",\n        )\n    return brutto\n```\n\nWhat matters is the order in your head: confidence and validation are not either-or. A field with high confidence that violates a domain rule still belongs in review. And a field with low confidence that satisfies all rules is still suspicious enough to show it to a human. Both gates have to be open for a value to pass through without supervision.\n\n## The decision flow at a glance\n\n```mermaid\nflowchart TD\n  A[Document] --> B{Text layer present?}\n  B -->|yes| C[Read text directly<br/>deterministic]\n  B -->|no| D{In the hash cache?}\n  D -->|yes| E[Load cache entry]\n  D -->|no| F[Run OCR<br/>expensive, uncertain]\n  F --> G[Cache result under content hash]\n  G --> E\n  C --> H[Extract fields]\n  E --> H\n  H --> I{Confidence above threshold?}\n  I -->|no| R[Flag: manual review]\n  I -->|yes| J{Domain rules met?}\n  J -->|no| R\n  J -->|yes| K[Automatically into matching]\n  R --> L[Store correction as data]\n  L --> K\n```\n\nTwo gates stand between a recognized value and its automatic use. If you take them seriously, you accept that some of the receipts pass through a human’s hands. That is not a defeat. Mature systems process most documents without intervention and, depending on the receipts, route a smaller share into review. That this share exists is the admission that OCR remains a sensor and not an oracle.\n\n## Corrections are data, not one-off actions\n\nWhat happens to the fields that end up in review? A human looks at the receipt and the flagged value and corrects the 133 back to 138. If this correction only flows into the current run and then disappears, you haven’t solved the problem, only steered around it once. On the next run with the same file, the OCR reads 133 again, and someone corrects it again.\n\nThat’s why I treat corrections as first-class data. A correction is bound to the content hash of the document and overrides the OCR result for exactly this field. It sits, protected, next to the cache, versioned and traceable. On the next run, the correction applies before the uncertain measurement even comes into play. This turns manual review from a recurring burden into a one-time investment per document. Along the way, you get a sensitive dataset from which you can later read where the recognition is systematically weak – with the same protection and deletion obligations as for the source documents.\n\nThis separation has another advantage for traceability. In the report, you can say for every value where it came from: from the deterministic text layer, from OCR above the threshold, or from a human correction. Three origins, three levels of trust, and all three are visible. A value that comes from a correction carries its history with it instead of disguising itself as an anonymous string.\n\n## What I would build this way right away next time\n\nLooking back, only a few decisions made the difference, and none of them was laborious. The content hash as the cache key took half an hour and made every further development run cheap and reproducible. The confidence gate was a handful of lines once I switched from `image_to_string` to `image_to_data` and stopped throwing the confidence away. In the end, the domain rules were the most valuable layer, because they catch exactly the class of errors in which the model is sure and wrong at the same time.\n\nThe common denominator is an attitude, not a framework. Where a model returns a confidence or uncertainty value, the system should keep it without hastily reading it as a probability. Where such a value is missing or poorly calibrated, domain rules, spot checks and human review have to make the uncertainty visible. With monetary amounts, I prefer a flagged line in the report to a clean number I can’t trust.\n\n## Further reading\n\n- Tesseract, TSV output format with word confidence: [Tesseract OCR](https://tesseractocr.org/) and [explanation of the TSV format](https://tomrochette.com/tesseract-tsv-format/)\n- Confidence thresholds in practice: [discussion on how Tesseract computes confidence](https://groups.google.com/g/tesseract-ocr/c/SN8L0IA_0D4)\n- Validation and human review in receipt OCR: [Invoice OCR Error Handling](https://invoicedataextraction.com/blog/invoice-ocr-error-handling)"},{"locale":"en","translation_key":"rxjs-die-vier-subject-typen","slug":"the-four-subject-types-in-rxjs","title":"The Four Subject Types in RxJS","summary":"Subject, BehaviorSubject, ReplaySubject and AsyncSubject differ in what late subscribers see and in how completion or an error ends their stored behavior.","tags":["Software","Reactive"],"published_at":"2024-05-21T10:00:00+00:00","updated_at":"2026-07-13T08:51:45.630871+00:00","url":"https://www.mikebild.dev/en/blog/the-four-subject-types-in-rxjs/","audio_url":null,"audio_duration_secs":null,"text":"A Subject isn’t an Observable with a `next()` method bolted on. It’s a different model: hot instead of cold, multicast instead of unicast, with a lifecycle that keeps running whether anyone is listening or not. If you only use it as a convenient shortcut to finally push values into a stream yourself, you get timing behavior you never asked for.\n\nSo before you choose between the four types, there is another question: Is a stream worth it here at all, or would a simpler model do the job just as well? If you skip that question, you build reactivity where a variable or a promise would have been enough. If you ask it and answer yes, you have exactly one decision left to make – and made correctly, it saves you a whole class of timing bugs that are hard to reproduce and expensive to debug.\n\nA Subject is the building block you use to call into the reactive world from imperative code. A normal observable isn’t built for that – it describes a source you subscribe to, and it only starts its work then, lazily, anew for each subscription. This is exactly where the Subject enters the stage. And as soon as this bridge is in place, the next question follows: Why are there four variants of it? The short answer: they differ in memory. The long answer is this article.\n\nIf you want to refresh the basics of the push model, you’ll find them in [RxJS: Push and Pull](https://www.mikebild.dev/en/blog/rxjs-telling-push-and-pull-apart/). Here I assume that you’re familiar with Observable and Subscription, and I focus on the decision behind them and on the Subjects themselves. This covers RxJS 7.\n\n## Is reactivity worth it here at all?\n\nBefore I choose between the four types, I ask a question first: Does this place need a stream at all? Reactivity isn’t an end in itself. It’s a model with costs. A Subject comes with a lifecycle you have to take care of – subscriptions you unsubscribe again, buffers that hold memory, timing you have to keep in your head. These costs pay off, but not everywhere.\n\nFor a single value that is computed once and then read, a variable is enough. For a single asynchronous operation with exactly one result, a promise is the simpler and more familiar tool. For a finished list that is fully available, an array with the usual methods will do. Setting up a stream in all these cases makes the code more expensive without giving anything back – you take on the subscription lifecycle and get nothing in return that the simpler model wouldn’t have delivered too.\n\nReactivity pays off the moment three things come together: values arrive spread out over time, not all at once; there is more than one party interested in the same values; and you want to combine, filter, cancel or merge these values instead of just receiving them once. A click stream, a WebSocket, a state shared by several components – these are the cases where a tangle of variables and callbacks quickly gets confusing and a stream takes out the friction.\n\nThe upfront question costs nothing and keeps the amount of reactive code small. Where reactivity carries weight, it plays to its strengths, and the rest stays simple. Only when the answer is yes does the second question become relevant, the one this article is about: what memory the stream should have for late subscribers.\n\n## A Subject is both at once\n\nThe key sentence about Subjects is already in the class definition: `Subject<T>` extends `Observable<T>` and at the same time implements the Observer interface. That means a Subject is Observable and Observer in a single instance. You can subscribe to it like any Observable – and you can feed values into it through `next`, `error` and `complete` like into an Observer.\n\n```ts\nimport { Subject } from 'rxjs';\n\nconst subject = new Subject<number>();\n\n// als Observable: abonnieren\nsubject.subscribe((value) => console.log('received', value));\n\n// als Observer: Werte hineingeben\nsubject.next(1);\nsubject.next(2);\nsubject.complete();\n```\n\nThis dual role has an important consequence. A plain observable is cold and unicast: every subscriber gets its own execution, and the code inside the observable runs again for each subscription. A Subject, on the other hand, is multicast. It keeps a list of its subscribers, and when `next` is called, the same value goes to all of them at the same time. There is one source and many receivers.\n\n```mermaid\nflowchart LR\n  P[\"Source<br/>next / error / complete\"] --> S((\"Subject\"))\n  S --> A[\"Subscriber A\"]\n  S --> B[\"Subscriber B\"]\n  S --> C[\"Subscriber C\"]\n```\n\nThe second central trait follows from this: Subjects are hot. Values flow regardless of whether anyone is listening. If I call `subject.next(1)` before any subscriber exists, that value is simply gone with a plain `Subject`. It was emitted, but nobody was there to receive it. Exactly this point – what happens to values that flowed before a subscription – is what separates the four types.\n\n## The four types and their memory\n\nBefore we go into the details, here’s the overview. All four inherit from `Subject`, and all four are hot and multicast. The difference lies in what a subscriber sees when it arrives late:\n\n- A `Subject` has no memory. If you subscribe after a `next`, you missed the value. Only what flows from the moment of subscribing arrives.\n- A `BehaviorSubject` remembers the last value and needs an initial value. Every new subscriber immediately gets the current state – ideal for the “current state” case.\n- A `ReplaySubject` buffers the last n values and replays them to every new subscriber, even after `complete`.\n- An `AsyncSubject` emits only the very last value, and only once `complete` has been called.\n\nThe list only describes `next` and `complete`. An `error` ends each of these streams. After that, a `BehaviorSubject` no longer delivers a last value and an `AsyncSubject` no final result; a `ReplaySubject` still replays its buffer and then reports the error. These terminal signals are therefore just as much part of the choice as the behavior for late subscriptions.\n\nLet’s look at each type with a small timing example, because timing is exactly what matters.\n\n## Subject – the forgetful one\n\nLet’s start with the plain `Subject`. It has no memory. To make this visible, we subscribe at different times and watch who gets what.\n\n```ts\nimport { Subject } from 'rxjs';\n\nconst subject = new Subject<number>();\n\nsubject.next(1); // niemand hört zu -> verloren\n\nsubject.subscribe((v) => console.log('A', v));\nsubject.next(2);\n\nsubject.subscribe((v) => console.log('B', v));\nsubject.next(3);\n\n// Ausgabe:\n// A 2\n// A 3\n// B 3\n```\n\nThe value `1` vanished because no subscriber existed when it was emitted. Subscriber A joins before the `2` and therefore sees `2` and `3`. Subscriber B only arrives after the `2` and sees only `3`. That’s not a bug. That’s the definition. A `Subject` is a pure distributor for the moment.\n\nWhat is that good for? For real events where the past doesn’t matter. A click, a WebSocket frame, a command that gets triggered. If you aren’t listening when the event happens, you simply didn’t witness it – and that’s perfectly fine.\n\n## BehaviorSubject – the state holder\n\nNow the type I see and recommend most often in practice: the `BehaviorSubject`. It differs in two ways. First, its constructor needs an initial value – you can’t create a `BehaviorSubject` without a defined starting state. Second, it always remembers the last emitted value and delivers it synchronously to every new subscriber.\n\n```ts\nimport { BehaviorSubject } from 'rxjs';\n\nconst state$ = new BehaviorSubject<number>(0); // Initialwert Pflicht\n\nstate$.subscribe((v) => console.log('A', v)); // A bekommt sofort 0\nstate$.next(1);\n\nstate$.subscribe((v) => console.log('B', v)); // B bekommt sofort 1\nstate$.next(2);\n\n// Ausgabe:\n// A 0\n// A 1\n// B 1\n// A 2\n// B 2\n```\n\nSubscriber B joins late and still isn’t left empty-handed. On subscribing, it immediately receives the current value `1` and then the rest. That’s exactly what makes the `BehaviorSubject` the standard tool for state. A state always has a current value, and whoever asks for it wants that value – not the prospect of learning something at the next `next`.\n\nA practical bonus: the `BehaviorSubject` offers synchronous access to the current state through `getValue()` and the `value` property, without subscribing.\n\n```ts\nconst counter$ = new BehaviorSubject<number>(0);\ncounter$.next(42);\n\nconsole.log(counter$.getValue()); // 42\nconsole.log(counter$.value); // 42\n```\n\nIf you have ever worked with streams as a data source in [RxJS in React](https://www.mikebild.dev/en/blog/rxjs-in-react-observables-in-the-ui-data-flow/), you know the situation: a component mounts and subscribes, and of course it should be able to show something right away. A `BehaviorSubject` guarantees exactly that.\n\nA detail that is easy to overlook: after `complete()`, a `BehaviorSubject` no longer sends its last value to new subscribers. It then only delivers the complete signal. So the current value is only available as long as the stream is active.\n\n## ReplaySubject – memory with a buffer\n\nThe `BehaviorSubject` remembers exactly one value. Sometimes you need more history. That’s what the `ReplaySubject` is for. Its constructor takes a buffer size and replays these last n values to every new subscriber.\n\n```ts\nimport { ReplaySubject } from 'rxjs';\n\nconst replay$ = new ReplaySubject<number>(2); // die letzten 2 Werte puffern\n\nreplay$.next(1);\nreplay$.next(2);\nreplay$.next(3);\n\nreplay$.subscribe((v) => console.log('late', v));\nreplay$.next(4);\n\n// Ausgabe:\n// late 2\n// late 3\n// late 4\n```\n\nThe late subscriber gets `2` and `3` after the fact – the two last buffered values – and then `4` live. The value `1` drops out of the buffer, because the buffer only has two slots.\n\nTwo properties make the `ReplaySubject` special. First, besides the buffer size there is an optional time window parameter: `new ReplaySubject<number>(bufferSize, windowTime)`. With it, only values that flowed within the last x milliseconds are replayed. Second – and this is the big difference from the `BehaviorSubject` – the `ReplaySubject` still replays its buffer after `complete()`.\n\n```ts\nconst cache$ = new ReplaySubject<number>(3);\n\ncache$.next(10);\ncache$.next(20);\ncache$.next(30);\ncache$.complete();\n\n// nach complete abonnieren\ncache$.subscribe((v) => console.log('after complete', v));\n\n// Ausgabe:\n// after complete 10\n// after complete 20\n// after complete 30\n```\n\nThis works well as a small cache: a result is produced once and then delivered again to everyone who asks later. Be careful with a buffer size of `Infinity`, though – that’s the default. A `ReplaySubject` without a size remembers every value it has ever emitted and grows without limit. In long-lived streams, that’s a source of memory leaks. That’s why I set the buffer size deliberately.\n\n## AsyncSubject – only the final result\n\nThe fourth type is the most idiosyncratic. The `AsyncSubject` emits only a single value – the last one – and only when `complete()` is called. As long as no `complete` arrives, there’s nothing.\n\n```ts\nimport { AsyncSubject } from 'rxjs';\n\nconst async$ = new AsyncSubject<number>();\n\nasync$.subscribe((v) => console.log('result', v));\n\nasync$.next(1);\nasync$.next(2);\nasync$.next(3);\nasync$.complete(); // erst jetzt wird emittiert\n\n// Ausgabe:\n// result 3\n```\n\nThe `AsyncSubject` doesn’t care about the intermediate values `1` and `2`. It only remembers the latest one, and on `complete` it passes that one on to all subscribers – including those who only subscribe after the `complete`. The behavior is deliberately reminiscent of a promise: a computation that runs and delivers exactly one result at the end.\n\nThe most common pitfall here is the missing `complete`. Without this call, the `AsyncSubject` never emits. The mistake looks harmless and still costs half an hour: the values flowed, the console stays empty, and at first you look everywhere – except at the missing completion.\n\n## Which one when – the decision\n\nLet’s sum up the choice. The question you should always ask is: What should a subscriber see that arrives late?\n\n- It’s about an event, and the past is irrelevant? **Subject.**\n- It’s about a current state that must always be available? **BehaviorSubject.**\n- New subscribers should receive the last n values or a time window after the fact? **ReplaySubject.**\n- All that matters is a single final result after completion? **AsyncSubject.**\n\nIn practice, two of them dominate. `BehaviorSubject` for state, `Subject` for events. `ReplaySubject` and `AsyncSubject` are special tools for specific needs.\n\n## Two pitfalls from practice\n\nFinally, the two mistakes I run into most often. Both are easy to avoid once you have seen them.\n\nThe first is mixing up `Subject` and `BehaviorSubject` for state. You build a service that holds a current value but use a plain `Subject`. Then a component mounts, subscribes – and stays empty, because the last `next` already happened. The bug shows up as “sometimes the value is there, sometimes it isn’t,” depending on timing. For state, the rule is: always `BehaviorSubject`, so there is a defined current value.\n\nThe second pitfall is subtler and affects the architecture: exposing Subjects everywhere instead of plain Observables. If I expose a `Subject` as a public property, anyone outside can call `next()` or `complete()` on it. That breaks encapsulation – any place in the code can interfere with the stream or complete it. The clean solution is a private Subject and a public Observable through `asObservable()`:\n\n```ts\nimport { Subject, Observable } from 'rxjs';\n\ninterface Command {\n  type: string;\n}\n\nclass CommandBus {\n  private commandsSubject = new Subject<Command>();\n\n  // nach außen nur lesbar\n  readonly commands$: Observable<Command> = this.commandsSubject.asObservable();\n\n  dispatch(command: Command): void {\n    this.commandsSubject.next(command);\n  }\n}\n```\n\nFrom the outside, you can subscribe to `commands$`, but you can’t write into it. The `next` runs exclusively through the controlled `dispatch` method. That’s the same principle that also carries [RxJS in Node.js](https://www.mikebild.dev/en/blog/rxjs-in-nodejs-event-streams/): events flow in through a defined interface and back out through subscribable observables. A Subject as the engine inside, an Observable as the facade outside.\n\nDon’t get me wrong: Subjects aren’t an anti-pattern. They are the right tool whenever you have to write into a stream from imperative code. The Subject itself should just stay inside wherever possible.\n\n## Conclusion\n\nA Subject is Observable and Observer in one and multicasts the same values to all its subscribers. It’s hot – values flow whether anyone is listening or not. The four variants differ in only a single dimension: their memory for subscribers that arrive late. No memory for the `Subject`, the last value for the `BehaviorSubject`, the last n values for the `ReplaySubject`, the final result after completion for the `AsyncSubject`.\n\nIf you make this one question – what does a late subscriber see? – a habit, the choice becomes almost automatic. And if you ask the question before it – is a stream worth it here at all? – you keep the amount of reactive code limited to what actually benefits from it. The outcome is unspectacular and useful for exactly that reason: you settle on the right type faster, a whole class of timing bugs never comes into being, and the data flow stays under control where it originates – behind Observables on the outside, with a Subject as the engine inside. And where a variable, a promise or an array is enough, that’s what it stays. Reactivity is the tool for values over time and many receivers, not the default for every value.\n\n## Further reading\n\n- [RxJS Guide: Subject](https://rxjs.dev/guide/subject)\n- [RxJS API: BehaviorSubject](https://rxjs.dev/api/index/class/BehaviorSubject)\n- [RxJS API: ReplaySubject](https://rxjs.dev/api/index/class/ReplaySubject)\n- [RxJS API: AsyncSubject](https://rxjs.dev/api/index/class/AsyncSubject)\n- [RxJS: Push and Pull](https://www.mikebild.dev/en/blog/rxjs-telling-push-and-pull-apart/)\n- [RxJS in Node.js](https://www.mikebild.dev/en/blog/rxjs-in-nodejs-event-streams/)\n- [RxJS in React](https://www.mikebild.dev/en/blog/rxjs-in-react-observables-in-the-ui-data-flow/)"},{"locale":"en","translation_key":"graphql-client-caching-mit-apollo","slug":"apollo-client-normalized-cache-and-optimistic-updates","title":"Apollo Client: The Normalized Cache and Optimistic Updates","summary":"HTTP caching is possible with GraphQL too, but for client state it is often less direct. That is why Apollo normalizes objects and supports optimistic updates in the UI.","tags":["Software","GraphQL","API"],"published_at":"2024-05-14T10:00:00+00:00","updated_at":"2026-07-13T08:51:30.971485+00:00","url":"https://www.mikebild.dev/en/blog/apollo-client-normalized-cache-and-optimistic-updates/","audio_url":null,"audio_duration_secs":null,"text":"If you store whole GraphQL responses under a hashed query string, you haven’t built a cache but a collection of copies. When a user changes their name, these copies know nothing about each other: the list view keeps showing the old value, the detail view already shows the new one, and nobody notices until someone clicks back and forth. With GraphQL, the key under which a response is stored is the real problem – and the solution lies one level deeper than the response itself.\n\nThis post is exclusively about the cache in the browser, that is, the client. There is also server-side caching – request batching and deduplication with DataLoader, for example – but that is a completely different construction site with different goals. Here we are talking about the `InMemoryCache` of Apollo Client 3, about normalization, about optimistic updates, and about the one pitfall that can easily cost you half an hour of debugging.\n\n## Why the URL alone isn’t enough as a cache key\n\nWith a classic REST API, caching is conceptually simple. Every resource has its own URL, and a `GET /users/1` always returns the same slice. The browser, a CDN, or an HTTP cache layer can store the response under exactly that URL and return it on the next call. The key is the address.\n\nWith many GraphQL APIs, different queries share one endpoint, and they often run as `POST /graphql`. That doesn’t rule out classic HTTP caching: GET requests, the query body as part of the cache key, or persisted queries can make responses cacheable. For the state of an interactive application, though, a pure response cache stays unwieldy as soon as the same entity shows up in several queries and needs to be updated in a targeted way.\n\nThe case where this becomes visible: a list view loads all users, a detail view loads a single user. Both show the name of `User:1`. If this user changes their name, a response-based cache would have to invalidate both entries separately – and the cache would first have to know that the same object is inside both responses. That is exactly what a pure response cache can’t do.\n\n## Normalization: one object, once, with a stable identity\n\nApollo’s answer to this is normalization. Instead of storing whole responses, the `InMemoryCache` breaks every response down into its individual objects and stores each object exactly once – flat, under a stable cache ID. By default, Apollo forms this ID from two fields: the `__typename` and the object’s primary key. The result looks like `User:1` or `Product:42`.\n\nBy default, Apollo uses `id` as the key field, and if that doesn’t exist, `_id`. If both are missing and nothing else is configured, something important happens that I will come back to below: the object isn’t normalized but embedded inline in the parent object.\n\nThe effect of normalization is best shown with the case just mentioned. Two queries, one shared object:\n\n```mermaid\ngraph TD\n  QA[\"Query GET_USERS<br/>(Listenansicht)\"] --> N[\"User:1<br/>{ name, email }\"]\n  QB[\"Query GET_USER<br/>(Detailansicht)\"] --> N\n  N --> S[(\"Normalisierter<br/>InMemoryCache\")]\n```\n\nBoth queries point to the same node `User:1`. The user is stored exactly once. If their name changes, it changes for all views that point to this node. That is the core everything else revolves around.\n\nFor this to work, every query has to select the identity fields as well. Apollo adds `__typename` automatically, but we have to request `id` ourselves:\n\n```graphql\nquery GET_USERS {\n  users {\n    id\n    name\n    email\n  }\n}\n\nquery GET_USER($id: ID!) {\n  user(id: $id) {\n    id\n    name\n    email\n  }\n}\n```\n\nSetting up the cache itself is unspectacular. You instantiate an `InMemoryCache` and pass it to the `ApolloClient`:\n\n```ts\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"/graphql\" }),\n  cache: new InMemoryCache(),\n});\n```\n\nHere is how I sum up what normalization actually brings:\n\n- Every entity is stored exactly once in memory, no matter how many queries loaded it.\n- A field update in one place automatically propagates to every view that shows the same object – without manual invalidation.\n- The cache gets smaller and more consistent, because duplicate data collapses into one reference.\n- The UI can render data from the cache immediately and refetch in the background without different views drifting apart.\n\n## Field updates happen automatically, structural updates don’t\n\nThis is where, in practice, what Apollo does for us separates from what we have to handle ourselves. The difference matters because it clears up the most common confusion.\n\nIf I change the value of a field on an object that is already cached, Apollo handles it automatically. A mutation that returns `User:1` with a new name overwrites the field in the store, and every view updates. I don’t have to write anything for that – provided the mutation also returns `id` and `__typename`, so that Apollo knows which entry to hit.\n\n```ts\nconst UPDATE_USER = gql`\n  mutation UpdateUser($id: ID!, $name: String!) {\n    updateUser(id: $id, name: $name) {\n      id\n      name\n    }\n  }\n`;\n\n// Apollo matches the response onto User:1 and updates\n// every view that shows this user - no update function needed.\nconst [updateUser] = useMutation(UPDATE_USER);\n```\n\nIt looks different when the structure changes, that is, when an element is added to a list or removed from it. If I create a new user via a mutation, Apollo dutifully normalizes the new object into the store – but it doesn’t know which list this user belongs to. Membership in a particular `GET_USERS` query isn’t a property of the object, and that is why Apollo can’t guess it. The result: the new object exists in the cache but doesn’t show up in the list view until you reload.\n\nFor these cases, there is the `update` function on the mutation. It receives the cache and the response and explicitly extends the list:\n\n```ts\nconst ADD_USER = gql`\n  mutation AddUser($name: String!) {\n    addUser(name: $name) {\n      id\n      name\n    }\n  }\n`;\n\nconst [addUser] = useMutation(ADD_USER, {\n  update(cache, { data }) {\n    const newUser = data.addUser;\n    cache.modify({\n      fields: {\n        users(existingRefs = [], { toReference }) {\n          return [...existingRefs, toReference(newUser)];\n        },\n      },\n    });\n  },\n});\n```\n\nSo the dividing line runs exactly here: Apollo handles value changes, we handle list membership.\n\n## Optimistic updates: the UI reacts before the server responds\n\nThe second big topic is perceived speed. Every mutation goes over the network, and even 150 milliseconds feel sluggish for a toggle button. Optimistic updates solve this by writing the expected end state into the cache immediately – before the server has responded. The UI reacts without latency. When the real response arrives, it replaces the optimistic layer. If the mutation fails, Apollo automatically discards the optimistic layer and restores the previous state. That is the crucial point: you don’t have to write the rollback yourself.\n\nThe flow is easy to show as a sequence:\n\n```mermaid\nsequenceDiagram\n  participant UI\n  participant Cache\n  participant Server\n  UI->>Cache: optimistisches Ergebnis schreiben\n  Cache-->>UI: sofort neu rendern\n  UI->>Server: Mutation senden\n  alt Erfolg\n    Server-->>Cache: echtes Ergebnis schreiben\n  else Fehler\n    Server-->>Cache: optimistische Schicht verwerfen\n    Cache-->>UI: vorigen Zustand wiederherstellen\n  end\n```\n\nIn code, it looks like this. A todo can be checked off, and we write the `completed` state optimistically:\n\n```ts\nconst TOGGLE_TODO = gql`\n  mutation ToggleTodo($id: ID!, $completed: Boolean!) {\n    toggleTodo(id: $id, completed: $completed) {\n      id\n      completed\n    }\n  }\n`;\n\nconst [toggleTodo] = useMutation(TOGGLE_TODO, {\n  optimisticResponse: {\n    toggleTodo: {\n      __typename: \"Todo\",\n      id: todo.id,\n      completed: !todo.completed,\n    },\n  },\n});\n```\n\nTwo things are non-negotiable here. First, the `optimisticResponse` must have the same shape as the real server response – the same fields, the same nesting. Second, it must contain `__typename` and the key fields. Without `__typename` and `id`, Apollo can’t normalize the optimistic entry onto `Todo:...`, the merge hits the wrong target, and the rollback behaves unexpectedly. This is one of those bugs that happen silently: it looks almost right, but the UI flickers or jumps back.\n\nIf you like, you can also write `optimisticResponse` as a function that receives the variables – handy when the optimistic state is derived from the mutation arguments:\n\n```ts\noptimisticResponse: (vars) => ({\n  toggleTodo: {\n    __typename: \"Todo\",\n    id: vars.id,\n    completed: vars.completed,\n  },\n}),\n```\n\n## fetchPolicy: how much say the cache has\n\nOne detail that easily gets lost here is a query’s `fetchPolicy`. It controls the relationship between the cache and the network. The default is `cache-first`: Apollo looks in the cache first, and only if the data is missing does it go to the network. That is usually exactly right, and it is the reason why the second detail view of a user who has already been loaded gets by without a request.\n\nThe most important values you should know:\n\n- `cache-first` – default; cache first, network only when data is missing.\n- `cache-and-network` – renders from the cache immediately and fetches fresh data in parallel; good for lists that should be current but may show something right away.\n- `network-only` – ignores the cache when reading but writes the result to the cache.\n- `no-cache` – doesn’t read from or write to the cache at all; the data exists only within this query.\n- `cache-only` – cache only, never network; throws if nothing is there.\n\nI leave the default in place until there is a concrete reason to change it. `cache-and-network` is the most common deliberate choice, because it combines the best of both: immediately visible and still fresh.\n\n## The pitfall: objects without a stable identity\n\nNow to the problem I announced above – one that goes unnoticed for a long time because it never reports itself. Normalization only works if Apollo can form a stable identity. If `id` and `_id` are missing and no alternative key field is configured, Apollo doesn’t normalize the object. Instead, it silently embeds it in the parent object. No error, no warning in the console – the app runs, but the cache doesn’t do what you expect.\n\nThe symptoms show up later and seem unrelated: the same entity is in the cache several times, an update hits only one copy, and two views show different values for the same thing. This happens especially often with computed or aggregated fields, with wrapper types from pagination, or with objects whose id you simply forgot to select in the query. If you work with cursor-based paging, you know wrapper types like these from practice – I covered the topic in more detail in [GraphQL pagination](https://www.mikebild.dev/en/blog/graphql-pagination-cursors-and-connections/).\n\nThere are two clean solutions. The simplest: just request the identity field as well. Often the id is there; it just wasn’t in the selection. If the type really has no `id` key but another unique field – an article number, say – you tell Apollo via `typePolicies` and `keyFields`:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Product: {\n      keyFields: [\"upc\"],\n    },\n    Book: {\n      keyFields: [\"isbn\"],\n    },\n  },\n});\n```\n\n`keyFields` can be more than just a replacement field:\n\n- `keyFields: [\"upc\"]` – an alternative key field instead of `id`.\n- `keyFields: [\"name\", \"email\"]` – a composite key made up of several fields.\n- `keyFields: []` – a singleton with exactly one entry per type (such as a global `Settings` type).\n- `keyFields: false` – deliberately turn off normalization for this type when embedding is what you want.\n\nAs a side note: in Apollo Client 2, you used `dataIdFromObject` for this. In version 3, it still exists to ease migration, but it is the old way. For new code, `typePolicies` with `keyFields` are the right choice, because they can be configured precisely and locally per type instead of globally through a single function.\n\nA related case where identity decides things on the server is authorization: who may see which object at all doesn’t belong in the client cache but in the Resolver context. How I anchor that there is described in [GraphQL auth in the context](https://www.mikebild.dev/en/blog/graphql-auth-identity-in-the-context/).\n\n## What should stick\n\nGraphQL can cache HTTP responses; in the browser, Apollo solves a different problem. The client normalizes entities at the object level so that several queries share the same instance and targeted field updates stay consistent. Structural changes to lists remain our job via the `update` function. Optimistic updates react immediately and roll back on errors, as long as the `optimisticResponse` has the right shape, including `__typename`. The most common silent bug remains an object without a stable identity that doesn’t get normalized. Consistent IDs and deliberately set `keyFields` save a lot of debugging here.\n\n## Further reading\n\n- Cache configuration – cache IDs and keyFields: https://www.apollographql.com/docs/react/caching/cache-configuration\n- Cache normalization (concept): https://www.apollographql.com/docs/react/caching/overview\n- Optimistic mutation results: https://www.apollographql.com/docs/react/performance/optimistic-ui\n- Mutations and the update function: https://www.apollographql.com/docs/react/data/mutations\n- fetchPolicy and how it interacts with the cache: https://www.apollographql.com/docs/react/data/queries#setting-a-fetch-policy"},{"locale":"en","translation_key":"graphql-absichern-depth-complexity-rate-limiting","slug":"securing-graphql-depth-complexity-rate-limiting","title":"Securing GraphQL: Query Depth, Complexity and Rate Limiting","summary":"A single GraphQL endpoint accepts arbitrarily nested queries – convenient and at the same time a risk of abuse. I show how I build a layered defense against expensive queries with a depth limit, a complexity budget, pagination caps and rate limiting.","tags":["Software","GraphQL","API"],"published_at":"2024-04-16T10:00:00+00:00","updated_at":"2026-07-13T13:20:10.670504+00:00","url":"https://www.mikebild.dev/en/blog/securing-graphql-depth-complexity-rate-limiting/","audio_url":null,"audio_duration_secs":null,"text":"With a REST API, the cost profile of a route is usually more narrowly bounded: if you build `/users/1/posts`, you know the intended execution path, even if parameters and data volume still change the actual cost. GraphQL gives the caller more influence over the shape and depth of the query. For developer experience, that’s a win. For operations, it means the cost of a request can only be estimated from the incoming document and the resolver behavior.\n\nThe question on which everything hinges is: What happens when someone sends a query nested twenty levels deep with `first: 1000` on every level? If you have no answer to that, you are running an API that falls over at the first unfriendly client – and you’ll notice for the first time exactly then.\n\nThis post is not about authentication or authorization – I covered that in [GraphQL auth in the context](https://www.mikebild.dev/en/blog/graphql-auth-identity-in-the-context/). This is about something orthogonal: protection against expensive and malicious queries. A properly authenticated, authorized user can still bring the server to its knees. If all you have is auth, you are unprotected against this class of problems.\n\n## Why one endpoint becomes dangerous\n\nThe core problem is cyclic relationships in the schema. As soon as a `User` has its `posts` and a `Post` has its `author` – who in turn has their `posts` – the depth is formally unbounded:\n\n```graphql\nquery MaliciousDepth {\n  user(id: \"1\") {\n    posts {\n      author {\n        posts {\n          author {\n            posts {\n              author {\n                # ... and so on, as deep as the client wants\n                name\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n```\n\nEach additional level can multiply the number of resolver calls. Whether this also turns into a corresponding number of database accesses depends on batching, caching and the resolvers. Combined with unbounded lists, though, an extremely expensive query can still emerge – a denial of service with a single HTTP request. This is not a hypothetical textbook scenario. I have seen production APIs tip over exactly like this because a frontend bug accidentally generated a recursive query.\n\nThe good news: defense works well in layers here. No single measure is enough, but the combination makes the attack surface manageable. The flow I aim for looks like this:\n\n```mermaid\nflowchart TD\n  A[Client request] --> B{Rate limit<br/>at the edge}\n  B -->|budget exceeded| R1[429 Too Many Requests]\n  B -->|ok| C{Depth gate<br/>graphql-depth-limit}\n  C -->|too deep| R2[Validation error]\n  C -->|ok| D{Complexity gate<br/>cost budget}\n  D -->|over budget| R3[Validation error]\n  D -->|ok| E[Resolver execution<br/>with pagination caps]\n  E --> F[Response]\n```\n\nThe crucial property: the depth and complexity checks kick in during the validation phase, i.e. **before** a single resolver runs. Parsing and validation also cost resources, but with size and rate limits they remain much easier to bound than the actual resolver execution.\n\n## Layer 1: Limiting query depth\n\nThe simplest and most effective first step is a limit on nesting depth. In Apollo Server 4, you add a validation rule to the `validationRules` of the constructor. The widely used library for this is `graphql-depth-limit`:\n\n```ts\nimport { ApolloServer } from \"@apollo/server\";\nimport depthLimit from \"graphql-depth-limit\";\nimport { typeDefs } from \"./schema\";\nimport { resolvers } from \"./resolvers\";\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  validationRules: [\n    // Reject any operation nested deeper than 7 levels.\n    depthLimit(7),\n  ],\n});\n```\n\n`depthLimit(maxDepth)` returns a graphql-js validation rule that counts the deepest nesting during validation and rejects operations above the limit. Introspection fields such as `__schema` and `__type` are ignored by default so tools keep working.\n\nA word of warning that belongs here in 2024: `graphql-depth-limit` (v1.1.0) hasn’t been maintained since 2018 and counts only selection depth – not the depth of lists. For many projects that is enough as a first layer, as long as you are aware of the gap. If you want to be stricter, take a look at `@graphile/depth-limit`, which also accounts for list depth.\n\nThe conceptual limit matters: depth limiting knows nothing about field costs. A flat query that selects a thousand expensive fields on a single level goes through without complaint. Depth is just one dimension of abuse.\n\n## Layer 2: Complexity and cost analysis\n\nThat brings us to the second layer, which compensates for the weakness of the first. Instead of only counting depth, I assign costs per field and reject every query that exceeds an overall budget. The established tool for this is `graphql-query-complexity` by slicknode.\n\nThe core is `createComplexityRule`, which I configure with a `maximumComplexity` budget and a list of estimators. Estimators are the rules by which costs are calculated – they are consulted in order until one returns a value:\n\n```ts\nimport { ApolloServer } from \"@apollo/server\";\nimport depthLimit from \"graphql-depth-limit\";\nimport {\n  createComplexityRule,\n  simpleEstimator,\n  fieldExtensionsEstimator,\n} from \"graphql-query-complexity\";\n\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  validationRules: [\n    depthLimit(7),\n    createComplexityRule({\n      maximumComplexity: 1000,\n      estimators: [\n        // Prefer explicit costs declared on the schema fields...\n        fieldExtensionsEstimator(),\n        // ...and fall back to a flat cost of 1 per field.\n        simpleEstimator({ defaultComplexity: 1 }),\n      ],\n      onComplete: (complexity) => {\n        console.log(`Query complexity: ${complexity}`);\n      },\n    }),\n  ],\n});\n```\n\nThe actual modeling happens on the fields themselves. Through `fieldExtensionsEstimator`, I read costs from the schema extensions – and this is exactly where I model lists realistically. A field that returns a list doesn’t have a constant cost but one proportional to the requested `first` value:\n\n```ts\nimport { GraphQLObjectType, GraphQLList } from \"graphql\";\nimport type { ComplexityEstimatorArgs } from \"graphql-query-complexity\";\n\nconst UserType = new GraphQLObjectType({\n  name: \"User\",\n  fields: {\n    posts: {\n      type: new GraphQLList(PostType),\n      args: { first: { type: GraphQLInt } },\n      extensions: {\n        // Cost scales with the number of requested items.\n        complexity: ({ args, childComplexity }: ComplexityEstimatorArgs) => {\n          const requested = args.first ?? 20;\n          return childComplexity * requested;\n        },\n      },\n    },\n  },\n});\n```\n\nThis is where cost analysis plays to its strength. A deep query with small lists can be cheaper than a flat one with huge lists. The budget of 1000 is not a magic number – I derive it from real query patterns by first letting `onComplete` only log and observing where legitimate clients end up before I lock the gate for real.\n\nOne detail about the Apollo Server 4 integration that tends to cost time: for plain rejection, the validation rule above is enough. But if you want to process the complexity further in the request lifecycle – for example for cost accounting per API key – you use a custom plugin and compute the complexity in the `didResolveOperation` hook with `getComplexity()`. The ready-made AS3 plugin wrapper `createComplexityPlugin` no longer fits directly into AS4, which is why the manual plugin route is worth a brief mention:\n\n```ts\nimport type { ApolloServerPlugin } from \"@apollo/server\";\nimport { getComplexity, simpleEstimator } from \"graphql-query-complexity\";\nimport { separateOperations } from \"graphql\";\n\nconst complexityPlugin: ApolloServerPlugin = {\n  async requestDidStart() {\n    return {\n      async didResolveOperation({ request, document, schema }) {\n        const complexity = getComplexity({\n          schema,\n          operationName: request.operationName,\n          query: request.operationName\n            ? separateOperations(document)[request.operationName]\n            : document,\n          variables: request.variables,\n          estimators: [simpleEstimator({ defaultComplexity: 1 })],\n        });\n\n        if (complexity > 1000) {\n          throw new Error(\n            `Query is too expensive: ${complexity}. Maximum allowed: 1000.`,\n          );\n        }\n      },\n    };\n  },\n};\n```\n\n## Layer 3: Pagination caps\n\nThe cost rule can only evaluate lists correctly if I bound lists in the first place. A `first` argument without a server-side maximum is an open flank: a single call with `first: 100000` triggers tens of thousands of resolvers. That’s why I clamp every pagination parameter on the server, regardless of what the client asks for:\n\n```ts\nconst MAX_PAGE_SIZE = 100;\nconst DEFAULT_PAGE_SIZE = 20;\n\nconst resolvers = {\n  User: {\n    posts: (parent, args, context) => {\n      // Never trust the client-supplied page size.\n      const first = Math.min(args.first ?? DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);\n      return context.dataSources.posts.byAuthor(parent.id, { first });\n    },\n  },\n};\n```\n\nIf you build your schema cleanly following the connections pattern, you already have a natural place for this limit – I described what that looks like structurally in [GraphQL pagination and connections](https://www.mikebild.dev/en/blog/graphql-pagination-cursors-and-connections/). The cap belongs in the resolver or a shared helper function, not in the documentation as a polite request to the client.\n\n## Layer 4: Rate limiting\n\nDepth and complexity limit the cost of a single query. They say nothing about how many queries per second someone fires. Rate limiting is not a core Apollo feature, and in my experience the most reliable place for it is the transport layer – a reverse proxy or a middleware in front of the GraphQL handler:\n\n```ts\nimport express from \"express\";\nimport rateLimit from \"express-rate-limit\";\n\nconst app = express();\n\nconst limiter = rateLimit({\n  windowMs: 60_000, // one minute\n  max: 120, // limit each IP to 120 requests per window\n  standardHeaders: true,\n  legacyHeaders: false,\n});\n\napp.use(\"/graphql\", limiter);\n```\n\nFor fine-grained per-field limits, there are directive-based approaches such as `graphql-rate-limit` with a `@rateLimit` directive in the schema. That is powerful, but it also adds operational complexity. A coarse limit at the edge carries most of the load; fine-grained directives only pay off where a specific field demonstrably causes trouble.\n\n## Persisted queries and allowlisting – with caution\n\nAt this point, the suggestion regularly comes up: “Let’s turn on Automatic Persisted Queries (APQ), then the problem is solved.” That is a widespread misunderstanding I want to clear up.\n\nAPQ is a performance feature. Instead of the full query, the client sends only a SHA-256 hash; if the server doesn’t know the hash, it responds with `PERSISTED_QUERY_NOT_FOUND`, the client sends the query once, and the server caches it. That saves bandwidth. It is **not** an allowlist – APQ automatically registers any incoming operation, including the malicious one.\n\n```ts\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  // Performance optimization, NOT a security control.\n  persistedQueries: { ttl: 900 },\n});\n```\n\nReal safelisting is something else: a pre-registered list of allowed operations that the server checks against. Anything not on the list is rejected – no matter how deep or expensive. In the Apollo world, this runs through a Persisted Query List in GraphOS together with the Apollo Router, an enterprise feature where APQ is then deliberately disabled. For internal APIs with a known set of client operations, this is the strongest defense of all, because the set of possible queries is finite and checked. For a public API with arbitrary clients, however, it is not an option – there, depth and complexity carry the load.\n\n## Introspection in production\n\nThe last building block is often overrated. Disabling introspection in production (`introspection: false`) prevents an attacker from conveniently querying the schema. That is a sensible default for non-public APIs – but I deliberately don’t call it security; I call it taking away an attacker’s convenience. It is security by obscurity: anyone who knows or guesses the schema gets past any disabled introspection. Disabling introspection replaces not a single one of the real limits above. It’s a nice extra, not a foundation.\n\n```ts\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  introspection: process.env.NODE_ENV !== \"production\",\n});\n```\n\nThis also includes a server-side request timeout, so that a query that runs long despite all the gates doesn’t tie up resources indefinitely. That is the emergency brake behind all the other layers.\n\n## The layers at a glance\n\nFor a production GraphQL endpoint, I add the layers from the outside in:\n\n- Rate limiting at the edge limits how many requests get through at all per time window.\n- Persisted queries or an allowlist only allow known operations when the circle of clients is closed.\n- A depth limit caps the nesting depth before execution even starts.\n- The complexity budget assigns costs per field and rejects queries that are too expensive.\n- Pagination caps prevent unbounded lists and make cost analysis correct in the first place.\n- A resolver timeout is the emergency brake for everything that still slips through.\n\nNone of these layers is complete on its own. Depth without complexity misses wide queries. Complexity without pagination caps calculates with the wrong multipliers. Rate limiting without cost analysis lets individual expensive queries through. Only in combination do you get an endpoint whose worst case I know and can control.\n\n## Conclusion\n\nGraphQL’s flexibility shifts control from the server to the client – and with it the ability to overload the server. The most common mistake in practice is assuming that authentication is enough protection. It isn’t: an attack via expensive queries is orthogonal to the question of who the user is. A legitimate, logged-in client can produce the same DoS query through a simple bug as an attacker can on purpose.\n\nThe order that has proven itself: first make the cost profile visible (log complexity), then add the gates from coarse to fine – depth limit and pagination caps as quick wins, the complexity budget as the actual backbone, rate limiting as the frame, an allowlist where the circle of clients permits it. Introspection and timeouts round things off but don’t carry the load. With these layers in place, you can bound the load per request much better and observe in operation where estimated and real resolver costs diverge.\n\n## Further reading\n\n- [Apollo Server – Automatic Persisted Queries](https://www.apollographql.com/docs/apollo-server/performance/apq)\n- [Apollo GraphOS – Safelisting with persisted queries](https://www.apollographql.com/docs/graphos/platform/security/persisted-queries)\n- [graphql-query-complexity (slicknode)](https://github.com/slicknode/graphql-query-complexity)\n- [graphql-depth-limit (npm)](https://www.npmjs.com/package/graphql-depth-limit)\n- [@graphile/depth-limit](https://github.com/graphile/depth-limit)\n- [Apollo Server – configuration and introspection](https://www.apollographql.com/docs/apollo-server/api/apollo-server)"},{"locale":"en","translation_key":"typescript-in-node","slug":"typescript-in-nodejs","title":"TypeScript in Node.js: Setup, Types and Tests","summary":"Setting up TypeScript in a Node project: understand the tsconfig essentials, type async code and handlers, and get the tests running, step by step from project practice.","tags":["Software","Node.js","Backend"],"published_at":"2024-03-19T10:00:00+00:00","updated_at":"2026-07-13T07:29:12.674203+00:00","url":"https://www.mikebild.dev/en/blog/typescript-in-nodejs/","audio_url":null,"audio_duration_secs":null,"text":"TypeScript is not a Node runtime and not a language that Node executes. It is a check layer in front of it: it kicks in during compilation and is gone without a trace afterward. Everything else follows from this one property – right up to the question that is actually up for debate when you set up a project. That question is not which switch you put into `tsconfig.json`, but where an error should show up: at your desk, while the cursor is still on the line, or at the user’s end, while the request is already running. TypeScript moves this place of failure forward. The price is a build step and a handful of deliberate configuration decisions; the return is a feedback loop in which seconds, not minutes, lie between “I’m building garbage” and “I can see the garbage.”\n\n**Editorial note (July 2026):** The main text describes Node 20 and TypeScript 5.4 in March 2024. Current Node versions can run TypeScript with erasable syntax directly. Node strips the types but performs no type checking and ignores `tsconfig.json`; for TypeScript-specific runtime constructs or a full build, you still need an external tool. For modern Node projects, `node16` or `nodenext` are also the appropriate resolution modes. `node10` belongs to the historical CommonJS setup of this article.\n\nThe rest is craft, and that is exactly what follows here: a configuration in which every entry has a reason, typed functions and handlers, and finally a test setup that runs `.ts` files directly.\n\nI assume that Node 20 (the active LTS) is installed and that an `npm init` has already run. We will build everything else together. If you want to refresh the layer underneath, that is, the Event Loop, the module system and runtime behavior, you will find it in my [Node.js training](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/); here we stay one floor up, with types and tools.\n\n## What TypeScript actually does in Node\n\nThe decisive point right at the start: Node does not run TypeScript. Node only knows JavaScript. TypeScript is a layer that checks at compile time and then disappears. The types are deleted during compilation; this is called type erasure. At runtime not a single type exists anymore, no `interface`, no `: number`. What remains is ordinary JavaScript.\n\nThis results in a flow that is the norm in 2024: a `.ts` file goes through the compiler `tsc` and becomes a `.js` file. `node` runs this `.js` file. For daily development there is a shortcut: `ts-node` compiles and starts in one go, without a visible `.js` file being created. But what ships in the end is always compiled JavaScript.\n\n```mermaid\nflowchart LR\n  A[source.ts] -->|tsc| B[dist/source.js]\n  B -->|node| C[Laufzeit]\n  A -.->|ts-node<br/>Entwicklung| C\n```\n\nThe dashed branch is the dev convenience; the solid one is what runs in production. Keeping this separation in mind saves a lot of confusion, for example about why a type error stops the build but never shows up in the running program.\n\nOne more note: in 2024, Node has no built-in way to start `.ts` files directly. There is no way around `tsc` or `ts-node`; that is the standard. If you read a blog post about “just `node index.ts`,” you are reading about a future that does not exist yet.\n\n## Types as executable contracts\n\nThe change of perspective that has helped me most in projects: a type is not documentation but a contract that a machine enforces on every build. `function total(items: LineItem[]): number` records two promises, one to every caller and one to me as the author, and the compiler refuses the build as soon as one side breaks its part. The lever lies in the timing: what matters is when correctness is demanded. Without such contracts, the check slips to the back, until a wrong field name or a forgotten `undefined` only surfaces at the user’s end through an error report. Contracts that kick in earlier report the break while the cursor is still on the line, and they push the length of the feedback loop down to seconds.\n\nThis is not free: a compile step, the discipline to maintain types instead of suppressing them with `any`, and moments in which the compiler insists on something that would never have broken at runtime. The decision therefore falls along a clear edge. The longer a piece of code lives, the more hands touch it and the more expensive a production error is, the more clearly the contract wins. A throwaway script does not need it; a payment path or a public API earns back every one of those seconds.\n\n## The foundation: the right packages\n\nBefore we write a single line of configuration, we need three things as a `devDependency`:\n\n```bash\nnpm install --save-dev typescript @types/node ts-node\n```\n\n`typescript` provides the compiler. `ts-node` is the dev tool for starting directly. And `@types/node` is the package I see forgotten most often in project setups, with noticeable consequences. It contains the type declarations for the Node core APIs: `fs`, `http`, `events`, `process`, `Buffer` and all the rest. Without this package, the compiler simply does not know that `process` exists and reports `Cannot find name 'process'`. The version follows the Node major version, so for Node 20 the 20.x line.\n\nRule of thumb: every JavaScript library without its own types needs a matching `@types/*` package, announced by the message `Could not find a declaration file for module 'x'`.\n\n## tsconfig.json: every switch on purpose\n\nNow the heart of it. I give a reason for every entry instead of generating the file with a generator and then ignoring it. A baseline for a classic CommonJS Node project:\n\n```jsonc\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"CommonJS\",\n    \"moduleResolution\": \"Node10\",\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"outDir\": \"dist\",\n    \"rootDir\": \"src\",\n    \"skipLibCheck\": true,\n    \"resolveJsonModule\": true,\n    \"sourceMap\": true\n  },\n  \"include\": [\"src/**/*\"]\n}\n```\n\nThe most important switches and what they actually do:\n\n- `target` sets which JavaScript version the code is compiled to. The default is conservative (historically `ES3`), which produces needlessly old code on a modern Node. `ES2022` fits Node 20 and lets `async/await`, optional chaining and class fields pass through unchanged instead of rewriting them in a roundabout way.\n- `module` determines the module format of the output. `CommonJS` is the classic Node way with `require`. If you want real ESM, you set `NodeNext` here, but that has consequences.\n- `moduleResolution` controls how the compiler resolves import paths. The value has no fixed default but depends on `module`. `Node10` goes with `CommonJS` (formerly written simply as `\"node\"`). `module: NodeNext` goes with `moduleResolution: NodeNext`. These pairs have to match, or you get resolution errors.\n- `strict` is the switch that makes TypeScript valuable in the first place. It is `false` by default, and without it TypeScript is little more than JavaScript with colons. `strict: true` enables a whole family: `noImplicitAny`, `strictNullChecks`, `strictFunctionTypes` and more. More on that below.\n- `esModuleInterop` governs imports between CommonJS and ESM. It is also `false` by default and, as many overlook, is not enabled by `strict`. You have to set it yourself. Without it, `import express from 'express'` breaks.\n- `outDir` determines where the compiled `.js` files are written. Without it, they land next to the source files, which clutters the project. The convention is `dist`. Together with `rootDir: \"src\"`, you get a clean separation: sources live in `src`, the result in `dist`.\n\n`skipLibCheck` skips type checking of the declaration files in `node_modules` and can speed up the build. It is not risk-free in every project: contradictory or faulty declarations can go unnoticed as a result. `resolveJsonModule` allows `import config from './config.json'`. `sourceMap` generates source maps so that the debugger points to the `.ts` lines and not to the compiled JavaScript.\n\n## Why `strict` makes the difference\n\nThis becomes clearest in the failure case. Without `strict`, or more precisely without `noImplicitAny`, the following passes:\n\n```ts\nfunction total(items) {\n  return items.reduce((sum, item) => sum + item.price, 0);\n}\n```\n\nThe parameter `items` has the implicit type `any` here, and so does `item.price`. The compiler stays silent, and you have exactly zero type safety; a typo like `item.prise` only surfaces at runtime. This is the `any` sprawl: an untyped `any` spreads, because everything you read from it is `any` again.\n\nWith `strict: true`, the compiler demands an annotation:\n\n```ts\ninterface LineItem {\n  price: number;\n  quantity: number;\n}\n\nfunction total(items: LineItem[]): number {\n  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n}\n```\n\nNow `item.prise` is a compile-time error, and the return value is guaranteed to be a `number`. If a value really does come from outside whose shape you do not know, you reach for `unknown` instead of `any`, because `unknown` forces you to check the type before using it instead of silently undermining it.\n\n## Typing async correctly\n\nAsynchronous code is everywhere in Node, and TypeScript describes it precisely. An `async` function always returns a `Promise<T>`; even if the body contains a bare value, it gets wrapped in a promise. Conversely, `await` unwraps a `Promise<T>` back to `T`.\n\n```ts\ninterface User {\n  id: number;\n  name: string;\n  email: string;\n}\n\nasync function fetchUser(id: number): Promise<User> {\n  const response = await fetch(`https://api.example.com/users/${id}`);\n  if (!response.ok) {\n    throw new Error(`Request failed with status ${response.status}`);\n  }\n  return response.json() as Promise<User>;\n}\n```\n\nThe return type `Promise<User>` is the promise to all callers: if you write `await fetchUser(1)`, you get a `User`, nothing else. Drop the annotation, and an `any` would creep back in at a place like `response.json()`, which returns `Promise<any>` out of the box. An `await` can also throw an exception; under `strict`, the `catch` branch receives it as `unknown`, which again forces a deliberate type check.\n\n## Typing an HTTP handler and an EventEmitter\n\nTwo patterns come up constantly in Node: the HTTP handler and the event-based flow. Both can be typed cleanly as soon as `@types/node` is installed.\n\n```ts\nimport { createServer, IncomingMessage, ServerResponse } from \"node:http\";\n\nconst server = createServer((req: IncomingMessage, res: ServerResponse): void => {\n  if (req.method === \"GET\" && req.url === \"/health\") {\n    res.statusCode = 200;\n    res.setHeader(\"Content-Type\", \"application/json\");\n    res.end(JSON.stringify({ status: \"ok\" }));\n    return;\n  }\n  res.statusCode = 404;\n  res.end(\"Not Found\");\n});\n\nserver.listen(3000, () => {\n  console.log(\"Server listening on port 3000\");\n});\n```\n\n`IncomingMessage` and `ServerResponse` are the Node types for request and response. Thanks to them, the editor knows that `req.method` is a `string | undefined`, and it is exactly this `undefined` that makes the check `req.method === \"GET\"` necessary under `strict`, not just good style.\n\nThe `EventEmitter` is the second classic. It is dynamic by nature, but you can pin down the event names and their payload with your own interface:\n\n```ts\nimport { EventEmitter } from \"node:events\";\n\ninterface OrderEventMap {\n  created: [orderId: string];\n  cancelled: [orderId: string, reason: string];\n}\n\nclass OrderBus extends EventEmitter {\n  on<K extends keyof OrderEventMap>(\n    event: K,\n    listener: (...args: OrderEventMap[K]) => void\n  ): this {\n    return super.on(event, listener as (...args: unknown[]) => void);\n  }\n\n  emit<K extends keyof OrderEventMap>(event: K, ...args: OrderEventMap[K]): boolean {\n    return super.emit(event, ...args);\n  }\n}\n\nconst bus = new OrderBus();\nbus.on(\"created\", (orderId) => {\n  console.log(`Order ${orderId} was created`);\n});\nbus.emit(\"created\", \"order-42\");\n```\n\nThe gain: `bus.emit(\"created\")` without the `orderId` is now a compile error, and in the listener `orderId` is automatically a `string`. You have turned the loose event mechanism into a typed contract without changing the Node mechanics. If you want to apply such patterns in the frontend as well, you will find the React side of it in [TypeScript in React](https://www.mikebild.dev/en/blog/typescript-in-react/).\n\n## The interop stumbling block: CommonJS and ESM\n\nIn practice, this stumbling block causes the most red squiggles, which is why the warning belongs here. Many npm packages, such as Express, are CommonJS modules with a single `module.exports`. The intuitive import\n\n```ts\nimport express from \"express\";\n```\n\nonly works when `esModuleInterop: true` is set. Without this switch, TypeScript insists on the clunky form `import * as express from \"express\"`, which then often breaks somewhere else at runtime. Internally, the switch inserts the matching interop helpers and thereby allows the natural default import.\n\nThe second part of the stumbling block concerns real ESM. If you set `\"type\": \"module\"` in `package.json` and configure `module: \"NodeNext\"`, you have to write relative imports with a file extension:\n\n```ts\nimport { total } from \"./billing.js\";\n```\n\nThis is irritating every time: you write `.js` even though the source file is called `billing.ts`, because the import describes the state after compilation. If the extension is missing or `module` and `moduleResolution` do not match, Node responds with `ERR_MODULE_NOT_FOUND`. For getting started, I therefore recommend the CommonJS baseline; you take the ESM route deliberately when the project needs it.\n\n## Tests that understand TypeScript directly\n\nThat leaves the question of how to run `.ts` tests without compiling by hand after every change. With Mocha there are two workable ways.\n\nThe convenient way for development uses `ts-node` as a register hook. A `.mocharc.json` in the project root is enough:\n\n```json\n{\n  \"require\": \"ts-node/register\",\n  \"extensions\": [\"ts\"],\n  \"spec\": [\"test/**/*.spec.ts\"]\n}\n```\n\nWith that, Mocha understands `.ts` files directly, without a separate build step. A matching test, here with the built-in `node:assert`:\n\n```ts\nimport assert from \"node:assert\";\nimport { total } from \"../src/billing\";\n\ndescribe(\"total\", () => {\n  it(\"sums price times quantity\", () => {\n    const result = total([{ price: 10, quantity: 2 }]);\n    assert.strictEqual(result, 20);\n  });\n});\n```\n\nThe second way is the compiled one: first `tsc`, then run the generated `.js` tests.\n\n```bash\ntsc && mocha \"dist/**/*.spec.js\"\n```\n\nI recommend the `ts-node` route for the fast development loop and the compiled route for the chain before shipping; there you test exactly the JavaScript that also goes to production. The matching scripts in `package.json` make this tangible:\n\n```json\n{\n  \"scripts\": {\n    \"dev\": \"ts-node src/index.ts\",\n    \"build\": \"tsc\",\n    \"start\": \"node dist/index.js\",\n    \"test\": \"mocha\"\n  }\n}\n```\n\n`dev` starts directly from the source code, `build` creates the `dist` directory, `start` runs the compiled result, `test` reads the `.mocharc.json`. Four lines, the whole lifecycle.\n\n## The common thread\n\nThe order behind it is simple: TypeScript checks at compile time and disappears; in `tsconfig.json`, `strict` and `esModuleInterop` carry the most weight; `@types/node` gives the Node APIs types in the first place; and the tests run via the register hook or the compiled output.\n\nThe mistake I see most often is not the complicated generic type but the silent `any` that spreads without `strict` until nothing is left of type safety. If you adopt the baseline from this article, that is, `strict: true`, `esModuleInterop: true`, `@types/node` and a clean separation of `outDir` and `rootDir`, you move the place where errors show up: to your desk instead of to the user. This is not a formality; it is the actual effect – shorter feedback loops, less friction in review and higher quality in the code that actually ships. The limit is part of it, because the contract pays off where code lives long and passes through many hands, not in the throwaway script. If you know that limit, you get exactly what TypeScript in Node promises: making errors visible early instead of passing them through to runtime.\n\n## Further reading\n\n- TSConfig reference: https://www.typescriptlang.org/tsconfig/\n- TypeScript Handbook, choosing compiler options: https://www.typescriptlang.org/docs/handbook/modules/guides/choosing-compiler-options.html\n- Announcing TypeScript 5.4: https://devblogs.microsoft.com/typescript/announcing-typescript-5-4/\n- ts-node (npm): https://www.npmjs.com/package/ts-node\n- ts-node Mocha recipe: https://typestrong.org/ts-node/docs/recipes/mocha/\n- @types/node (npm): https://www.npmjs.com/package/@types/node\n- Mocha: https://mochajs.org/\n- [Node.js: Modules – TypeScript](https://nodejs.org/dist/latest/docs/api/typescript.html)\n- [TypeScript: `moduleResolution`](https://www.typescriptlang.org/tsconfig/moduleResolution.html)"},{"locale":"en","translation_key":"typescript-in-react","slug":"typescript-in-react","title":"TypeScript in React: Typing Props, Hooks and Events","summary":"How props and state become verifiable contracts – and your editor reports errors before your users see them. From interface/type through useState generics and event types to useRef and utility types.","tags":["Software","Frontend","React"],"published_at":"2024-02-27T10:00:00+00:00","updated_at":"2026-07-13T08:50:39.319923+00:00","url":"https://www.mikebild.dev/en/blog/typescript-in-react/","audio_url":null,"audio_duration_secs":null,"text":"Someone renames a prop on a button component, the build passes, the page renders. Three days later, a ticket arrives from another team: empty button in the checkout dialog. Five call sites use this component, and none of them complained – JavaScript had no reason to. If you suggest TypeScript after a ticket like that, the first thing you hear is: “Isn’t that just more typing?”\n\nBehind it lies a decision first, not a question of syntax. The decision is: Where do I want to pay for my integration errors? Without types, I pay late, in the browser, at the user’s end, often in a different team than the one that introduced the bug. With types, I pay early, in the editor, with a red squiggly line, before anything is built. The price can be named honestly: a few lines of type declarations and the discipline to keep them current. The effect is usually worth it, because an error the compiler catches never becomes a bug report, never a rollback, never a support request.\n\nSo TypeScript in React is neither an end in itself nor bureaucracy. A props signature becomes a promise that the compiler checks every time you save: “This component expects a `label` string and, optionally, a `disabled` flag.” Anyone who breaks it gets the feedback immediately and in the right place. In everyday work, this happens in five places of a component: the props, the state, the event handlers, the refs, and the types you derive from existing data structures. You rarely need more, and the rest of this article walks through the five one by one.\n\n## The core: errors move forward\n\nBefore we write code, it pays to make the difference in the flow clear. Without types, the app builds no matter what I put into a prop – the error only happens at runtime, when someone uses the page. With types, the compiler checks the JSX usage against the interface, and the error appears before anything is built.\n\n```mermaid\nflowchart TD\n    A[Wrong prop in JSX] --> B{TypeScript active?}\n    B -->|No| C[App builds]\n    C --> D[Runtime error<br/>for the user in the browser]\n    B -->|Yes| E[tsc / editor checks<br/>against the interface]\n    E --> F[Compile error<br/>red in the editor]\n    F --> G[Fix before the commit]\n```\n\nThe left path costs you a bug report, in the worst case an annoyed customer. The right path costs you ten seconds. This shift forward is the real gain – not autocompletion, as nice as it is.\n\n## The UI boundary is the most expensive boundary\n\nBefore getting into the details, it pays to name the place where the effort pays off the most. Every component has a boundary: props flow in, events flow out. This boundary is exactly the seam where two pieces of code meet – often two authors, sometimes two teams. A form that expects an `onSubmit`, a table that reports a row upward through a callback, a design system button that five feature teams consume: these are not internal implementation details, they are interfaces. And interfaces are where the expensive errors come from, because the error happens on one side and shows up on the other.\n\nA type at this boundary is an executable contract. “Executable” means: it is not a comment someone has to maintain, and not a line on a wiki page nobody reads. The compiler runs it every time you save. When I change a button’s props signature, the tool points me, right there, to each of the five call sites that no longer fit – before anyone starts the app. The contract is thus the documentation, the test and the refactoring safety net of this boundary at the same time, in exactly one artifact.\n\nThe trade-off is real and deserves to be said out loud. Types cost typing, they have to be kept current, and in a poorly chosen place they create friction instead of safety. Deciding where to put them is therefore a cost-benefit question. The more consumers a component has, the longer it lives and the more people pass through it, the more clearly the contract pays off – a shared UI building block deserves precise props and event types. A throwaway prototype or a purely internal helper component with a single caller hardly deserves one. The rule of thumb: type the boundaries where responsibilities meet, and let inference handle the rest. Not every local variable needs a contract, but every props and event signature that someone else calls becomes one.\n\n## Props as a contract: interface or type\n\nThe start is unspectacular, and that is exactly why it holds up so well. A component is a function, its props are an object, and that object gets a type.\n\n```tsx\ninterface ButtonProps {\n  label: string;\n  disabled?: boolean;\n}\n\nfunction Button({ label, disabled }: ButtonProps) {\n  return <button disabled={disabled}>{label}</button>;\n}\n```\n\nThe `?` after `disabled` makes the prop optional. If someone forgets `label`, the compiler reports a missing required prop – not an `undefined` that later ends up as an empty button, but an error right where it happens.\n\nIn code reviews, this is where the question reliably comes up: `interface` or `type`? Both work for props, and the pragmatic rule of thumb from the React TypeScript Cheatsheet is: “interface until you need type.” In other words:\n\n- `interface` supports declaration merging, which is handy for public library APIs, and reads a bit more naturally for simple object shapes.\n- `type` is the right choice as soon as you need union types, mapped types or compositions of several types – things an `interface` cannot express.\n\nFor 90 percent of component props, the choice is purely a matter of taste. What matters is consistency in the team, not the debate over principles.\n\n## children is no longer automatic\n\nAs soon as a component wraps other elements, it needs `children`. And this is worth a close look, because something fundamental changed with version 18 of `@types/react`: the implicit `children` declaration was removed. `React.FC` used to bring an automatic `children` along. Today you have to declare it yourself if your component renders children.\n\n```tsx\ninterface CardProps {\n  title: string;\n  children?: React.ReactNode;\n}\n\nfunction Card({ title, children }: CardProps) {\n  return (\n    <section className=\"card\">\n      <h2>{title}</h2>\n      <div className=\"card-body\">{children}</div>\n    </section>\n  );\n}\n```\n\n`React.ReactNode` is the right type for “anything that can be rendered”: strings, numbers, elements, arrays of those, `null`, `boolean`. If instead you want to enforce exactly one single element, you reach for `React.ReactElement`. By the way, in the version 18 types, the JSX namespace lives under `React.JSX`, so a single element can also be described as `React.JSX.Element`. For everyday work, `ReactNode` is almost always enough – it is deliberately generous.\n\nThe fact that `children` no longer appears by magic is one of the reasons `React.FC` has lost importance. More on that shortly.\n\n## Typing state: when inference is enough and when it isn’t\n\n`useState` is a nice example of how TypeScript doesn’t demand manual work everywhere. Most of the time, the compiler infers the type from the initial value:\n\n```tsx\nconst [count, setCount] = useState(0);        // number\nconst [name, setName] = useState('');          // string\nconst [open, setOpen] = useState(false);       // boolean\n```\n\nAdding a generic here would just be ballast. The inference is unambiguous, and `setCount('drei')` still fails at the compiler. It gets interesting when the initial value tells the compiler too little. I have fixed this pitfall in existing code many times:\n\n```tsx\n// Wrong: type is inferred as `null`\nconst [user, setUser] = useState(null);\n// later setUser({ id: 1, name: 'Mike' }) -> compile error\n\n// Correct: specify the generic explicitly\nconst [user, setUser] = useState<User | null>(null);\n```\n\nIf you start with `null`, TypeScript infers the type `null` – and then you can never write anything else into it. The same happens with `useState([])`, which becomes `never[]`, or with an empty object. The rule I have adopted for this: if the initial value is empty, `null` or an empty array, specify the type with the generic.\n\n```tsx\nconst [items, setItems] = useState<string[]>([]);\nconst [selected, setSelected] = useState<User | null>(null);\n```\n\n## Typing events: no more `any`\n\nThe next classic is event handlers. In JavaScript, you write `onChange={(e) => setValue(e.target.value)}` and don’t think further. In TypeScript, `e` without a type is an `any` – and `any` is the hole through which exactly the errors we wanted to get rid of come back. React ships precise types for its synthetic events. You just have to pick the right one.\n\n```tsx\nfunction LoginForm() {\n  const [email, setEmail] = useState('');\n\n  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setEmail(e.target.value);\n  };\n\n  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    console.log('submitting', email);\n  };\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <input type=\"email\" value={email} onChange={handleChange} />\n      <button type=\"submit\">Sign in</button>\n    </form>\n  );\n}\n```\n\nTwo things matter here. First, the generic has to match the element: an `<input>` yields `HTMLInputElement`, and only then is `e.target.value` known at all. If you accidentally write `HTMLElement`, you lose `value`. Second, there are matching types for `onChange`, `onSubmit` and `onClick`:\n\n- `React.ChangeEvent<HTMLInputElement>` for inputs, and likewise `HTMLSelectElement` and `HTMLTextAreaElement`.\n- `React.FormEvent<HTMLFormElement>` for submitting a form.\n- `React.MouseEvent<HTMLButtonElement>` for clicks.\n\nIf you define the handler inline, directly on the JSX attribute, you can often skip the type, because React infers it from the context. But as soon as you pull the handler out into a separate function, you have to specify the event type yourself. For props that take a handler, there are also the shorthands `React.ChangeEventHandler<HTMLInputElement>` and `React.FormEventHandler<HTMLFormElement>` – handy when you pass a callback down as a prop.\n\n## useRef: DOM reference with a null check\n\n`useRef` is confusing at first because it plays two roles. The most common one is the DOM reference, for example to focus a field on mount.\n\n```tsx\nfunction SearchBox() {\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  useEffect(() => {\n    inputRef.current?.focus();\n  }, []);\n\n  return <input ref={inputRef} type=\"search\" />;\n}\n```\n\nThree details count. The generic `<HTMLInputElement>` says what the ref points to. The initial value `null` is intentional: before the first render, the DOM element doesn’t exist yet. This combination produces a read-only `RefObject`, and that is exactly what fits the JSX attribute `ref`. Because `current` can be `null` before mounting, you need a null check on access – hence the `?.` in `inputRef.current?.focus()`. Without the guard, the compiler rightly complains.\n\nThe second role of `useRef` is that of a mutable instance variable that doesn’t trigger a re-render – for example, to hold on to a timer ID or a previous value:\n\n```tsx\nconst timerRef = useRef<number | null>(null);\n\nconst start = () => {\n  timerRef.current = window.setTimeout(() => {\n    console.log('done');\n  }, 1000);\n};\n```\n\nHere `current` is writable. The difference comes from the overload: with `null` in the union type and no DOM reference, you get a `MutableRefObject`. You don’t have to memorize this subtlety, but it helps to know that the DOM case is deliberately read-only.\n\n## Utility types: derive props instead of copying them\n\nWhen data structures grow, you don’t want to update props by hand in three places. That is what the utility types from the TypeScript standard library are for – not from React, but constantly useful in everyday React work. Suppose there is a `User`:\n\n```ts\ninterface User {\n  id: string;\n  name: string;\n  email: string;\n  role: 'admin' | 'member';\n}\n```\n\nA form that only edits name and email doesn’t need the whole `User`. `Pick` cuts out the relevant fields:\n\n```ts\ntype EditUserProps = Pick<User, 'name' | 'email'>;\n```\n\nConversely, `Omit` removes what you don’t want – for example, the server-assigned `id`:\n\n```ts\ntype NewUserProps = Omit<User, 'id'>;\n```\n\n`Partial` makes all fields optional, which fits patch operations or intermediate form states:\n\n```ts\ntype UserDraft = Partial<User>;\n```\n\nThe gain: if `User` changes, the derived types follow automatically. No field gets out of step. Besides `Pick`, `Omit` and `Partial`, `Required<T>` and `Readonly<T>` belong to the standard repertoire.\n\nA React-specific trick rounds out the picture: if your component should inherit the native props of an HTML element – all standard button attributes, for example – you use `React.ComponentPropsWithoutRef`:\n\n```tsx\ntype IconButtonProps = React.ComponentPropsWithoutRef<'button'> & {\n  icon: string;\n};\n\nfunction IconButton({ icon, ...rest }: IconButtonProps) {\n  return (\n    <button {...rest}>\n      <span className=\"icon\">{icon}</span>\n    </button>\n  );\n}\n```\n\nThis way you get `onClick`, `disabled`, `type` and all the other button attributes for free and type-checked, without listing them one by one.\n\n## Everyday types at a glance\n\nThis overview shows the five corners where you deal with types most often in a typed React component.\n\n```mermaid\ngraph TD\n    K[Types in everyday React] --> P[Props<br/>interface / type]\n    K --> S[State<br/>useState&lt;T&gt;]\n    K --> E[Events<br/>ChangeEvent / FormEvent]\n    K --> R[Refs<br/>useRef&lt;HTMLInputElement&gt;]\n    K --> U[Derivation<br/>Pick / Omit / Partial]\n    P --> C[children:<br/>ReactNode]\n```\n\nThese five cover most of the daily work. Everything else builds on them.\n\n## And what about React.FC?\n\nThe question is guaranteed to come up, often with a code example from an older tutorial: `const Button: React.FC<ButtonProps> = (props) => ...`. Is that wrong? No. It works, it is available in 2024, and nobody has to rewrite existing code. But the modern default is the plain function with typed props, and there are reasons for that.\n\nHistorically, the most important one was the implicit `children` that `React.FC` brought along – components accepted children even when they weren’t supposed to render any. With `@types/react` 18, this implicit `children` was removed, which defused one of the main points of criticism. What remains is mainly that `React.FC` gets in the way of generic components. If you want to write a type-safe list component over an arbitrary element type, you are better off with a normal function:\n\n```tsx\ninterface ListProps<T> {\n  items: T[];\n  render: (item: T) => React.ReactNode;\n}\n\nfunction List<T>({ items, render }: ListProps<T>) {\n  return <ul>{items.map((item, i) => <li key={i}>{render(item)}</li>)}</ul>;\n}\n```\n\nSomething like this is awkward to express with `React.FC`. So today `React.FC` is a question of style, not a mistake. Pick one variant in your team and stick with it. I write normal functions myself, because they are more flexible with generics and come with fewer special rules.\n\n## Coming back to hooks\n\nIf you already write your own hooks, you quickly notice that the building blocks shown here carry straight over: a custom hook returns typed state, takes typed arguments and encapsulates event logic. If you haven’t taken the path to reusable logic yet, have a look at [From HOCs and Render Props to Custom Hooks](https://www.mikebild.dev/en/blog/from-hocs-and-render-props-to-custom-hooks/) – the typing from this article is exactly what turns a custom hook from a loose collection of functions into a clear contract.\n\n## Conclusion\n\nThe gain of TypeScript in React can be summed up in four effects, and none of them is in the API documentation. Shorter cycles, because an integration error shows up in the editor in seconds instead of in days via a bug report. Less friction at the most expensive place, the boundary between components and teams, because the contract automatically checks what would otherwise be agreed on verbally and then forgotten. Higher quality, because a wrong prop type, a forgotten required field or a `null` that should never have stayed `null` never makes it into the build in the first place. And clear boundaries, because a typed props and event signature says unambiguously what goes in and what comes out.\n\nGetting started is manageable. Props as `interface` or `type`, `children` declared explicitly as `ReactNode`, `useState` with a generic only where inference is too narrow, the matching event types instead of `any`, `useRef` with a null check, and utility types to derive props instead of copying them. These six moves cover everyday work. Everything beyond that – generic components, complex unions, your own hooks – continues the same idea: type the boundaries where responsibilities meet, say clearly what you expect, and let the compiler make sure everyone sticks to it.\n\n## Further reading\n\n- React TypeScript Cheatsheet: [react-typescript-cheatsheet.netlify.app](https://react-typescript-cheatsheet.netlify.app/) and the repository [github.com/typescript-cheatsheets/react](https://github.com/typescript-cheatsheets/react)\n- react.dev – “Using TypeScript”: [react.dev/learn/typescript](https://react.dev/learn/typescript)\n- react.dev – hooks reference: [useState](https://react.dev/reference/react/useState) and [useRef](https://react.dev/reference/react/useRef)\n- TypeScript Handbook – Utility Types: [typescriptlang.org/docs/handbook/utility-types.html](https://www.typescriptlang.org/docs/handbook/utility-types.html)\n- DefinitelyTyped – `@types/react`: [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/react)"},{"locale":"en","translation_key":"resilience-muster-timeout-retry-circuit-breaker","slug":"resilience-patterns-timeout-retry-circuit-breaker","title":"Resilience Patterns: Timeout, Retry, Circuit Breaker, Idempotency","summary":"Why resilience is no accident: timeout, retry with backoff and jitter, circuit breaker and idempotency as deliberately designed patterns against the failure modes of distributed systems.","tags":["Software","Architecture"],"published_at":"2024-01-30T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/resilience-patterns-timeout-retry-circuit-breaker/","audio_url":null,"audio_duration_secs":null,"text":"A distributed system rarely falls over because of a spectacular crash. It falls over because a service still answers – just a little slower than usual. Add a call that nobody ever gave a time limit. And a client that dutifully keeps pushing requests while the dependency is long since down. That is how a single shaky component drags half the system down with it, without a single process crashing anywhere.\n\nDistributed calls fail. Over a longer period, that is part of normal operation. The network is slow now and then, a node gets restarted, a database hits its limit. The question is never whether a remote call fails, but what happens when it does. And this is exactly where it is decided whether a system is resilient or only looks stable until things get serious for the first time.\n\nResilience is designed, not hoped for. I check four patterns for distributed calls: timeout, retry, circuit breaker and idempotency. Not every call needs all four; the choice depends on the failure mode, the cost and the semantics of the operation. The TypeScript code below is illustrative – it is about the mechanics behind it, not a production-ready library.\n\nThe patterns differ mainly in the failure state they react to. Their names alone don’t tell you whether they make sense at a given boundary.\n\n::::comparison{title=\"Resilience patterns by failure question\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Timeout\"}\n- Question · How long may a single attempt take?\n- Effect · limits blocked resources\n:::\n:::side{label=\"Retry\"}\n- Question · Is the failure transient and the attempt safe to repeat?\n- Effect · repeats with bounded backoff and jitter\n:::\n:::side{label=\"Circuit Breaker\"}\n- Question · Should a visibly impaired target keep getting load?\n- Effect · interrupts calls and checks again later in a controlled way\n:::\n:::side{label=\"Bulkhead\"}\n- Question · How does a failure stay confined to one part of the system?\n- Effect · separates resources and areas of contention\n:::\n:::side{label=\"Dead Letter Queue\"}\n- Question · What happens to messages that can never be processed?\n- Effect · keeps failure cases for inspection and targeted reprocessing\n:::\n::::\n\nOnly the failure question shows which patterns complement each other and which would just create extra traffic or hidden queues.\n\n## The patterns at a glance\n\nBefore I get into the code, a short overview. Four patterns, each with a clear responsibility:\n\n- A timeout limits how long a single call may wait. Without a timeout, a call may wait forever – and block a thread, a connection, a slot in the pool while doing so.\n- A retry repeats a failed call – but only for transient errors, only with exponential backoff and jitter, and only with a limited number of attempts.\n- A circuit breaker stops further calls to a visibly failed dependency so you don’t keep hammering it endlessly.\n- Idempotency is what makes retries safe in the first place: a call sent several times has the same effect as a single one.\n\nThese four can interlock, but they are not an inseparable package. A timeout may deliberately fail fast without a retry. A retry on a non-idempotent operation can produce duplicate effects. A circuit breaker needs a usable failure signal, which often comes from a timeout. You only combine the patterns that fit the call at hand.\n\n## Timeout: never wait forever\n\nThe most expensive timeout is the one that doesn’t exist. A remote call without a time limit isn’t slow, it is potentially infinite. And infinity is a failure mode: threads pile up, connection pools run dry, and a service that is really just waiting on a slow downstream becomes unreachable itself.\n\nThe distinction between the connection timeout (how long may establishing the connection take) and the request timeout (how long may the entire response take) matters. Set both. And both belong to the specific call, not nailed globally to one value – a health check has a different tolerance than a report export.\n\nIn practice, I wrap this in a small helper. `Promise.race` against a timer, plus an `AbortController`, so the underlying operation is actually canceled and doesn’t keep running in the background:\n\n```ts\nexport async function withTimeout<T>(\n  fn: (signal: AbortSignal) => Promise<T>,\n  timeoutMs: number,\n): Promise<T> {\n  const controller = new AbortController();\n  const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n  try {\n    return await fn(controller.signal);\n  } finally {\n    clearTimeout(timer);\n  }\n}\n\n// usage: the signal is forwarded to fetch so the socket is released\nconst result = await withTimeout(\n  (signal) => fetch(\"https://payments.internal/charge\", { signal }),\n  2_000,\n);\n```\n\nThe `AbortSignal` is the part that is easy to forget. A `Promise.race` that only cancels the waiting but leaves the HTTP connection open has merely moved the problem: the socket stays occupied. Only the forwarded signal releases the resource.\n\nA subtle interaction that Marc Brooker points out in the AWS Builders’ Library: a timeout set too low can itself trigger retry storms. If regular latency occasionally exceeds the timeout limit, the client interprets healthy responses as failures and retries – and creates exactly the load that then really tips the server over. You set timeouts based on the real latency distribution, not on wishful thinking.\n\n## Retry: backoff and jitter, but with judgment\n\nRetry is the pattern that backfires fastest. The naive variant – “on error, try again immediately, and again, and again” – has nothing to do with resilience. It is a load weapon aimed at your own downstream. A server that is already under pressure gets finished off by synchronized repetitions from all clients.\n\nThree ingredients make retry usable. **Exponential backoff**: the wait time grows with each attempt (`base * 2^attempt`) so an overloaded service gets some air. A **cap**: the wait time doesn’t run to infinity but toward an upper limit. And **jitter**: a random component that keeps all clients from aligning their retries to the same millisecond and creating synchronized load spikes.\n\nThere are several variants of jitter – Marc Brooker compared them in 2015 on the AWS Architecture Blog: Full Jitter, Equal Jitter, Decorrelated Jitter. The practical recommendation from that analysis is usually Full Jitter, because it spreads the retries most evenly across the time window. The formula is pleasantly simple:\n\n```ts\ntype RetryOptions = {\n  maxAttempts: number;\n  baseDelayMs: number;\n  capMs: number;\n  isRetryable: (error: unknown) => boolean;\n};\n\nexport async function retryWithBackoff<T>(\n  fn: () => Promise<T>,\n  opts: RetryOptions,\n): Promise<T> {\n  let lastError: unknown;\n\n  for (let attempt = 0; attempt < opts.maxAttempts; attempt++) {\n    try {\n      return await fn();\n    } catch (error) {\n      lastError = error;\n      if (!opts.isRetryable(error) || attempt === opts.maxAttempts - 1) {\n        throw error;\n      }\n\n      // full jitter: random point in the exponentially growing window\n      const window = Math.min(opts.capMs, opts.baseDelayMs * 2 ** attempt);\n      const delay = Math.random() * window;\n      await new Promise((resolve) => setTimeout(resolve, delay));\n    }\n  }\n\n  throw lastError;\n}\n```\n\nThe `isRetryable` callback is deliberately pulled out. Not every error is retryable. A `503 Service Unavailable`, a dropped connection or a timeout can be transient. An unchanged `400 Bad Request`, on the other hand, stays wrong. Even `409 Conflict` isn’t a blanket no: after re-reading, with a new version number or an adjusted operation, another attempt can make sense; blindly repeating the identical request usually doesn’t. Retry decisions therefore need the error code, the operation and the remaining time budget.\n\nThe AWS Well-Architected guidance sums this up under REL05-BP03 (“Control and limit retry calls”): backoff, jitter and a maximum number of attempts belong together. The AWS SDKs already implement exactly that in their built-in retry modes `standard` and `adaptive` – if you work at that level, you shouldn’t put a second retry loop of your own on top. Which brings us to the most dangerous pitfall.\n\n## The retry storm\n\nRetries stack up. The client retries, the SDK underneath retries, the API gateway in front retries. Three layers with three attempts each are not three but up to twenty-seven calls for a single user action. If jitter is missing on top of that and all clients start at the same time, you get a retry storm: multiplicative load that hits the server exactly at the moment it can least handle it.\n\nThe remedy is discipline, not more technology. For every call chain, it should be clear which layer owns the retry and which shared time and attempt budget applies. Lower layers such as an SDK may have their own retries if the layers above know about them and don’t multiply them in an uncoordinated way. Jitter and cap belong in the responsible place. If you coordinate many clients, add a retry budget or client-side rate limiting with a token bucket.\n\n## Circuit breaker: stop hammering\n\nRetry with backoff cushions short disruptions. But what if a dependency doesn’t just cough briefly but really fails – for minutes? Then every further attempt is wasted load, wasted latency and wasted resources. This is exactly where the circuit breaker comes in, a pattern that Michael Nygard coined in “Release It!”.\n\nThe idea comes from electrical engineering: a circuit breaker interrupts the circuit before the wire burns through. Applied to software, that means – when a dependency is visibly down, the breaker opens and lets calls fail immediately (fail fast) instead of running them into a dead timeout. The breaker knows three states:\n\n```mermaid\nstateDiagram-v2\n    [*] --> CLOSED\n    CLOSED --> OPEN: Failures >= threshold\n    OPEN --> HALF_OPEN: Cooldown expired\n    HALF_OPEN --> CLOSED: Probe succeeds\n    HALF_OPEN --> OPEN: Probe fails\n```\n\nIn the **CLOSED** state, everything runs normally; the breaker just counts the failures. If the number of failures exceeds a threshold, it switches to **OPEN**: calls are no longer let through but fail immediately – the client gets a quick answer or a fallback instead of a hanging connection. After a cooldown, the breaker moves to **HALF_OPEN** and lets a single probe request through. If it succeeds, it closes again (CLOSED). If it fails, it opens again and waits for the next cooldown.\n\nAs a small state machine, this is manageable:\n\n```ts\ntype BreakerState = \"CLOSED\" | \"OPEN\" | \"HALF_OPEN\";\n\nexport class CircuitBreaker {\n  private state: BreakerState = \"CLOSED\";\n  private failureCount = 0;\n  private openedAt = 0;\n\n  constructor(\n    private readonly failureThreshold: number,\n    private readonly cooldownMs: number,\n  ) {}\n\n  async execute<T>(fn: () => Promise<T>): Promise<T> {\n    if (this.state === \"OPEN\") {\n      if (Date.now() - this.openedAt < this.cooldownMs) {\n        throw new Error(\"circuit is open\");\n      }\n      this.state = \"HALF_OPEN\";\n    }\n\n    try {\n      const result = await fn();\n      this.onSuccess();\n      return result;\n    } catch (error) {\n      this.onFailure();\n      throw error;\n    }\n  }\n\n  private onSuccess(): void {\n    this.failureCount = 0;\n    this.state = \"CLOSED\";\n  }\n\n  private onFailure(): void {\n    this.failureCount++;\n    if (this.state === \"HALF_OPEN\" || this.failureCount >= this.failureThreshold) {\n      this.state = \"OPEN\";\n      this.openedAt = Date.now();\n    }\n  }\n}\n```\n\nAWS files the circuit breaker in Well-Architected under REL05-BP01 – “graceful degradation”, turning a hard dependency into a soft one. Instead of a failed recommendation service dragging down the whole product page, the breaker in the OPEN state delivers a fallback (such as a static list) and the page stays usable. That is the real gain: not the perfect answer, but an acceptable one that keeps the overall system alive.\n\nIn production, you don’t have to write this yourself – established libraries such as `opossum` for Node.js, Polly for .NET or resilience4j for Java come with it, including metrics and half-open sampling. The code above is illustrative so the state logic stays visible.\n\n## Idempotency: what makes retries safe\n\nNow the circle closes back to retry. A retry is only harmless if the repeated operation has the same effect as a single one. That is exactly what idempotency means. For a read, this is trivial – two `GET`s do no harm. For a write, it gets serious: if the first attempt at a payment actually went through but the response got lost in the timeout, the retry charges a second time. The customer pays twice.\n\nHTTP semantics provide a frame here: `GET`, `PUT` and `DELETE` count as idempotent, `POST` in principle does not. Idempotent means the same intended effect on repetition; the status code or response don’t have to be identical. Where you can design operations accordingly – a `PUT` on a natural ID instead of a `POST` that creates a new resource every time – you should. Where that isn’t possible, for example with “charge” or “send”, an explicit **idempotency key** helps. The client generates a unique key per business operation and sends it along; the server remembers key plus result and thereby prevents the second side effect.\n\nThe pattern has been established for years – Stripe, for example, uses an `Idempotency-Key` header. At the time, an IETF standard was merely an Internet-Draft (`draft-ietf-httpapi-idempotency-key-header`), but the pattern itself works regardless. On the server side, the core looks like this:\n\n```ts\ntype Result = { status: string; id: string };\n\ninterface IdempotencyStore {\n  get(key: string): Promise<Result | undefined>;\n  set(key: string, value: Result): Promise<void>;\n}\n\nexport async function handleRequest(\n  key: string,\n  op: () => Promise<Result>,\n  store: IdempotencyStore,\n): Promise<Result> {\n  const existing = await store.get(key);\n  if (existing) {\n    // key already processed: return the stored result, no second side effect\n    return existing;\n  }\n\n  const result = await op();\n  await store.set(key, result);\n  return result;\n}\n```\n\nTwo details matter in real life. First, the store needs an expiry (TTL) – keeping idempotency keys forever is neither necessary nor cheap. Second, there is a concurrency problem: if two retries arrive almost simultaneously, the second can complete its `get` before the first writes its `set`. In production, you solve this with an atomic reservation of the key (for example a conditional insert), not with the naive get-then-set above. The code shows the principle, not the production-ready lock.\n\n## Bulkhead and DLQ, briefly\n\nTwo patterns round out the picture without me going into detail here. The **bulkhead** – named after the watertight compartments in a ship’s hull – isolates resources so that one overloaded path doesn’t flood the whole system. Separate connection pools or thread pools per downstream make sure a hanging dependency only exhausts its own pool and doesn’t drag all other calls into the abyss with it. This also comes from “Release It!”.\n\nAnd the **dead letter queue** (DLQ) is the catch basin for the case where all retries are exhausted. Instead of spinning an unprocessable message in circles forever or losing it silently, it lands in a separate queue – for inspection, for manual intervention or for a later retry. In AWS, this is a standard building block of SQS and SNS. If you want to orchestrate the chaining of such steps cleanly, [Serverless Workflows with AWS Step Functions](https://www.mikebild.dev/en/blog/serverless-workflows-with-aws-step-functions/) gives you the right frame, and I described how to spread load across several processes in [child_process and Scaling](https://www.mikebild.dev/en/blog/child-process-in-nodejs-scaling-without-illusions/).\n\n## Conclusion\n\nThree mistakes show up in post-mortems again and again. No timeout – a call that may wait forever and ties up resources while doing so. Retry without jitter and cap – the well-meant retry that turns into a retry storm and finishes off the weak server for good. And non-idempotent writes that get repeated – the double charge nobody saw coming.\n\nAll three have a common root: resilience was hoped for, not designed. The four patterns – timeout, retry, circuit breaker, idempotency – are not a library you import but decisions per call. Remote calls need a justified time limit. Retries need a budget, backoff and jitter. A breaker pays off for dependencies whose sustained failure would otherwise keep generating load and latency. An idempotency key belongs to operations where repetition is possible and a duplicate effect is harmful. That way, a system under load can degrade in a controlled manner instead of multiplying its failure.\n\n## Further reading\n\n- [AWS Well-Architected, REL05-BP03 – Control and limit retry calls](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_mitigate_interaction_failure_limit_retries.html)\n- [AWS Well-Architected, REL05-BP01 – Graceful degradation (Circuit Breaker)](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_mitigate_interaction_failure_graceful_degradation.html)\n- [AWS Well-Architected, REL05-BP02 – Throttle requests (Token Bucket)](https://docs.aws.amazon.com/wellarchitected/latest/framework/rel_mitigate_interaction_failure_throttle_requests.html)\n- [AWS Builders’ Library – Timeouts, retries, and backoff with jitter (Marc Brooker)](https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/)\n- [AWS Architecture Blog – Exponential Backoff And Jitter](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)\n- [Michael Nygard – Release It! (2nd edition, 2018)](https://pragprog.com/titles/mnee2/release-it-second-edition/)"},{"locale":"en","translation_key":"graphql-subscriptions-ueber-sse","slug":"graphql-subscriptions-over-sse","title":"GraphQL Subscriptions over SSE: Real Time Without Being Forced into WebSocket","summary":"Subscriptions don’t need a WebSocket. Server-Sent Events are enough for the one-way server-to-client channel, while queries and mutations stay plain HTTP, and the schema decides what counts as a domain event in the first place.","tags":["Software","GraphQL","API"],"published_at":"2024-01-12T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/graphql-subscriptions-over-sse/","audio_url":null,"audio_duration_secs":null,"text":"If you set up a WebSocket for a one-way update flow, you bring a second protocol into operations: the upgrade handshake, sticky sessions, proxies and load balancers that need to know about it, plus reconnect and heartbeat as your own responsibility. The reason for it is usually modest – an order changes its status, a dashboard tile updates without a reload. The reason is done after one sprint; the transport stays and needs to be operated for years.\n\nSo behind “real time” there is rarely a syntax problem and almost always an operations decision. A bidirectional full-duplex channel, like the one a WebSocket opens, is not a feature you get for free; it is an operations class of its own, with its own protocol, its own handshake and its own failure patterns. That is why this text is less about how to wire up subscriptions and more about the decision before that: SSE, WebSocket or plain polling – decided by operating cost, complexity and scaling, not by what sounds modern right now.\n\nAnd GraphQL subscriptions don’t even prescribe a WebSocket. The specification is transport-agnostic at this point: it says that a subscription delivers an event stream – not over which wire that stream flows. And for the common case “server informs client,” there is a candidate that has been built into every browser for years and runs over ordinary HTTP: Server-Sent Events.\n\n## Queries and mutations stay as they are\n\nBefore we get to the event stream, it’s worth looking at what doesn’t change at all. A query fetches data, a mutation changes state – both are request and response, one request, one response, done. That is plain HTTP, usually a `POST /graphql`. Nothing about subscription support forces you to touch it. Only the third operation type, the subscription, needs an open channel through which the server sends events over time.\n\nThis is exactly where Server-Sent Events come in. SSE is a one-way channel from the server to the client over ordinary HTTP. The server responds with the content type `text/event-stream` and keeps the connection open; the client opens it through the built-in `EventSource` interface. The browser takes care of quite a lot that you would have to bolt on painfully in a homegrown solution: it reconnects automatically when the connection drops, and on reconnect it sends the last seen event ID in the `Last-Event-ID` header so the server can pick up where it left off.\n\n```mermaid\nflowchart LR\n  subgraph Client\n    UI[Browser app]\n  end\n  subgraph Server\n    GQL[GraphQL server]\n  end\n  UI -- \"HTTP POST /graphql<br/>Query &amp; Mutation\" --> GQL\n  GQL -- \"HTTP response (JSON)\" --> UI\n  GQL -- \"text/event-stream<br/>Events via EventSource\" --> UI\n```\n\nThe diagram shows the core: two channels, one transport. Queries and mutations take the familiar path of request and response. The event stream uses the same HTTP infrastructure; the response just stays open and trickles events through. There is no protocol switch, no upgrade handshake, no special treatment by proxies that don’t know WebSocket frames.\n\n## The server side: an AsyncIterable from PubSub\n\nOn the server side, a subscription resolver is not an ordinary field resolver. Instead of a function that returns a value, it is an object with a `subscribe` method that returns an `AsyncIterable`. The GraphQL server pulls the events from this iterable and sends them to the matching client. The usual tool for this is the `graphql-subscriptions` package, currently at version 2.0.0. It comes with a `PubSub` class whose `asyncIterator(topic)` creates exactly such an iterable.\n\n```ts\nimport { PubSub, withFilter } from 'graphql-subscriptions';\n\nconst pubsub = new PubSub();\n\nconst ORDER_STATUS_CHANGED = 'ORDER_STATUS_CHANGED';\n\nconst resolvers = {\n  Subscription: {\n    orderStatusChanged: {\n      subscribe: withFilter(\n        () => pubsub.asyncIterator(ORDER_STATUS_CHANGED),\n        (payload, variables) =>\n          payload.orderStatusChanged.customerId === variables.customerId,\n      ),\n    },\n  },\n  Mutation: {\n    advanceOrder: (_root, { id }) => {\n      const orderStatusChanged = advanceOrderInStore(id);\n      pubsub.publish(ORDER_STATUS_CHANGED, { orderStatusChanged });\n      return orderStatusChanged;\n    },\n  },\n};\n```\n\nTwo things matter here. First, the `withFilter` helper: it takes the iterator function and a predicate function that decides per event whether it concerns this subscriber at all. That way each customer only gets the status changes of their own orders, even though all of them run over the same topic. Second, the publish point in the mutation: when something happens in the domain – here, an order moves forward – the event is pushed into the stream with `pubsub.publish`. The `subscribe` resolver and the mutation are decoupled through the topic; the mutation knows nothing about who is listening right now.\n\nOne note that in practice often comes up too late: the bundled `PubSub` implementation keeps its state in memory and only works within a single process. As soon as several server instances sit behind a load balancer, events fizzle out – one instance publishes, but the subscribers are attached to another. For production you then need an external backend, such as a Redis-backed variant that distributes the publish across the process boundary. For local development and getting started, the built-in variant is completely sufficient.\n\n## The SSE endpoint: the stream to the outside\n\nFor the events from the iterable to actually reach the browser, you need an endpoint that delivers the stream as `text/event-stream`. Conceptually, in Express it looks like this:\n\n```ts\napp.get('/graphql/stream', (req, res) => {\n  res.set({\n    'Content-Type': 'text/event-stream',\n    'Cache-Control': 'no-cache',\n    Connection: 'keep-alive',\n  });\n  res.flushHeaders();\n\n  const iterator = pubsub.asyncIterator(ORDER_STATUS_CHANGED);\n\n  (async () => {\n    for await (const event of iterator) {\n      res.write(`event: next\\n`);\n      res.write(`data: ${JSON.stringify(event)}\\n\\n`);\n    }\n  })();\n\n  req.on('close', () => {\n    if (typeof iterator.return === 'function') iterator.return();\n  });\n});\n```\n\nThe format of an SSE frame is deliberately simple: lines with field names and a colon. The `data:` field carries the payload, here the serialized event; the browser would join several `data:` lines with a line break. With `event:` you name the event type so the client can listen for it specifically; without that line, everything ends up at the general `onmessage` handler. The `id:` field sets the event ID that the browser sends back as `Last-Event-ID` on reconnect, and `retry:` specifies in milliseconds how long the browser should wait before trying to reconnect. A frame ends with an empty line, that is, a double `\\n`. Lines that start with a colon are comments and work as a heartbeat to keep intermediate layers from cutting a quiet connection.\n\nThe `req.on('close')` part is not an extra. When the client closes the connection, the iterator has to be shut down cleanly; otherwise subscriptions pile up and the process leaks resources. This cleanup is where an SSE integration becomes either solid or brittle.\n\n## The client: EventSource, nothing more\n\nOn the client side, the work is surprisingly small because the browser handles most of it:\n\n```js\nconst es = new EventSource('/graphql/stream', { withCredentials: true });\n\nes.addEventListener('next', (e) => {\n  const payload = JSON.parse(e.data);\n  render(payload.orderStatusChanged);\n});\n\nes.onerror = () => {\n  // The browser reconnects on its own; the retry: field controls the interval.\n};\n```\n\nNo manual reconnecting, no timer, no heartbeat protocol of your own. If the connection fails, the browser tries on its own to rebuild it and sends the last received event ID along. The `withCredentials` option makes sure cookies are sent across the origin boundary – handy when authentication runs over a session cookie and the endpoint needs to know who is listening. If you want to place authorization in the GraphQL server cleanly in the execution context, you’ll find the matching pattern in [GraphQL auth in the context](https://www.mikebild.dev/en/blog/graphql-auth-identity-in-the-context/); the same logic applies to the SSE endpoint – the identity is established at the HTTP layer and is available to the resolver.\n\n```mermaid\nsequenceDiagram\n  participant B as Browser (EventSource)\n  participant S as GraphQL server\n  participant P as PubSub\n  B->>S: HTTP POST advanceOrder (mutation)\n  S->>P: pubsub.publish(topic, payload)\n  P-->>S: asyncIterator delivers event\n  S-->>B: data: frame (event: next)\n  Note over B,S: Connection drops\n  B->>S: Reconnect with Last-Event-ID\n  S-->>B: Events since the last ID\n```\n\n## The schema is a domain model, not an event pipe\n\nThat outlines the technical part, but the more important point from project practice is a different one. As soon as there is an easy way to send events to the client, the temptation grows to pump everything possible through subscriptions: every keystroke, every internal tick, every log line. But the schema is a domain model, not a collection point for technical signals. A subscription should represent an event that means something in the domain – “order changed its status,” “comment was added,” “payment was received.” An `orderStatusChanged` tells a consumer something about the domain. A `serverTick` or `internalMetric` tells them nothing they would look for in the schema.\n\nThe same modeling discipline you apply to lists and paging – see the thoughts in [GraphQL pagination and connections](https://www.mikebild.dev/en/blog/graphql-pagination-cursors-and-connections/) – applies here just the same: the schema describes the language of the domain, not the internals of the transport. If an event is not part of that language, it doesn’t belong in a subscription.\n\n## Avoiding the wrong abstraction\n\nThat brings us to the actual decision, and it happens one level below GraphQL: in the architecture. SSE, WebSocket and messaging solve different problems, and the most common source of errors is treating one as a substitute for the other.\n\n- Server-Sent Events are one-way from server to client, run HTTP-native, reconnect on their own and carry only UTF-8 text. They fit exactly when the UI should show live updates: status changes, notifications, a dashboard that refreshes itself.\n- WebSockets are bidirectional and have their own protocol with their own handshake. They are the right choice when the client itself continuously sends data to the server in real time – chat, collaborative editing, a game state, anything with a busy back channel.\n- Messaging and brokers such as Kafka, AMQP or Redis solve integration between systems. They offer persistence, fan-out and decoupling in the backend. A GraphQL subscription doesn’t replace that. It covers the last mile to the browser; the nervous system between the services remains the broker’s job.\n\nIf you keep these three cleanly apart, you won’t build the wrong thing. If you mix them – say, setting up a WebSocket to serve a purely one-way update flow, or misusing subscriptions to integrate services – you pay later with complexity that no feature justifies.\n\n## Decision framework: SSE, WebSocket or polling\n\nSeparating the transports cleanly is one thing; in a project I eventually have to pick one, and a framework along three axes helps with that: operating cost, complexity and scaling. These three questions answer the transport choice more reliably than any feature list, because they ask about the price in operations, not about the feature set.\n\nPolling is the honest starting point that people skip too quickly. The client asks at an interval, “is there anything new?”, and across HTTP, caching and load balancers that is the best-understood pattern of all. The operating cost is conceptually close to zero, but the load on the server grows linearly with the number of clients and the frequency, and most of the work goes into empty responses. The complexity is minimal because there is no open channel that would need cleanup or reconnects, and scaling horizontally is trivial because each request stands on its own. For updates in the range of seconds to minutes, where a bit of latency hurts no one, polling is often the economically right answer – and the option you should check first, before you build something more elaborate.\n\nSSE sits in the middle and hits exactly the case “server informs client promptly.” The operating cost consists of one open HTTP connection per client, but it stays HTTP-native and requires no special handling in the infrastructure. The complexity is low on the client because `EventSource` comes with reconnect and `Last-Event-ID`; on the server, the effort lies mainly in cleaning up the streams properly. Scaling has its cost center in the many open connections, and the PubSub state has to be distributed across instance boundaries as soon as more than one process runs. The gain over polling is low latency without idle traffic; the price is the open channel you have to operate.\n\nWebSocket is the most expensive class and only justifies itself with a real back channel. The operating cost includes a protocol of its own with a handshake, sticky sessions and proxies that need to know about the upgrade. The complexity rises because reconnect, heartbeat and state recovery are on me, not on the browser. Scaling is hardest because long-lived, stateful connections are the least easy to distribute horizontally. This effort pays off when the client itself sends continuously in real time – chat, collaborative editing, game state. For a one-way update flow, it is effort without return.\n\nSo the decision criterion is short: first check whether polling is enough; if you need prompt server-to-client updates without a back channel, SSE; and WebSocket only for busy, bidirectional traffic. If you ask in this order, you pick the cheapest transport that meets the requirement instead of the most powerful one you know – and exactly this order separates an operations decision from a matter of taste.\n\n## Where the SSE idea comes from – and what applies today\n\nThe combination of GraphQL and SSE is not new, and its history helps put today’s state in context. In the early days of Apollo Client, the 1.x era, there was the `subscriptions-transport-sse` package. Back then, it was plugged into an Apollo Client through the `networkInterface` concept:\n\n```js\n// HISTORICAL — Apollo Client 1.x, not today's API.\nimport {\n  SubscriptionClient,\n  addGraphQLSubscriptions,\n} from 'subscriptions-transport-sse';\n\nconst sseClient = new SubscriptionClient('/subscriptions');\nconst client = new ApolloClient({\n  networkInterface: addGraphQLSubscriptions(httpInterface, sseClient),\n});\n```\n\nThis is explicitly legacy and has no place in a new project. Both `networkInterface` and the `SubscriptionManager` of that time – the predecessor of today’s pattern with `PubSub.asyncIterator` – are concepts of a generation that was replaced long ago. I show the fragment only to make the origin of the idea visible: SSE as a transport for GraphQL events is an old idea, not an experimental one.\n\nOn the WebSocket side, it’s worth looking at the current state because it frames the transport question. The formerly common `subscriptions-transport-ws` is now considered unmaintained; its repository has carried a deprecation notice for quite a while and is no longer actively developed. The recommended successor for the WebSocket path is `graphql-ws`, with a different subprotocol that is not compatible with the old one. That is only context here: `graphql-ws` is the answer when you actually need a WebSocket. It doesn’t compete with SSE; it covers the other, bidirectional case.\n\n## What I take away from practice\n\nWhen someone says “real time” in a requirements conversation, the first useful follow-up question is not “WebSocket or SSE?” but “In which direction does the data flow, and how fast does it need to arrive?” Usually it flows from the server to the client and can tolerate some latency, and then Server-Sent Events are the calmer solution that is easier to operate: ordinary HTTP, built-in reconnect, no special handling in the infrastructure. Queries and mutations stay untouched; only the event stream gets its own open channel. On the server, the `subscribe` resolver returns an `AsyncIterable` from a PubSub, events come in via `publish`, and `withFilter` makes sure everyone only gets what concerns them.\n\nYou can feel the gain of this mapping in everyday project work. If you choose the cheapest viable transport, you shorten the cycles to a working live update, because half of the infrastructure discussion this text started with goes away. You reduce friction in operations, because an HTTP-native stream creates fewer special cases in proxies, load balancers and deployments. And you raise quality, because the schema stays a domain model and only carries events that mean something in the language of the domain. I deliberately keep two limits in view: the built-in PubSub keeps its state in memory and needs an external backend across multiple instances, and the transport choice remains a simple mapping – polling when latency is acceptable, SSE for the one-way path to the client, WebSocket only for a real back channel. These clear limits are what make the shorter cycles and lower friction possible in the first place.\n\n## Further reading\n\n- MDN – Using server-sent events: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events\n- MDN – EventSource: https://developer.mozilla.org/en-US/docs/Web/API/EventSource\n- graphql-subscriptions (README/API): https://github.com/apollographql/graphql-subscriptions\n- graphql-subscriptions (npm): https://www.npmjs.com/package/graphql-subscriptions\n- Apollo Server – Subscriptions: https://www.apollographql.com/docs/apollo-server/data/subscriptions\n- subscriptions-transport-ws (legacy/archived): https://github.com/apollographql/subscriptions-transport-ws\n- subscriptions-transport-sse (historical origin): https://github.com/CodeCommission/subscriptions-transport-sse\n- GraphQL Spec: https://spec.graphql.org/"},{"locale":"en","translation_key":"contract-testing-statt-e2e-marathon","slug":"contract-testing-instead-of-an-e2e-marathon","title":"Contract Testing Instead of an E2E Marathon","summary":"Consumer-Driven Contracts check interfaces at the boundary between services instead of in an expensive, flaky end-to-end suite. The result: a faster, deterministic deploy gate and teams that release independently.","tags":["Software","Delivery"],"published_at":"2023-12-05T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/contract-testing-instead-of-an-e2e-marathon/","audio_url":null,"audio_duration_secs":null,"text":"```text\nFAIL  e2e/checkout.spec.ts\n  ✕ Bestellung abschließen (30014 ms)\n    TimeoutError: waiting for selector \"#order-confirmation\" failed:\n    timeout 30000ms exceeded\n\nTests: 1 failed, 213 passed        Dauer: 46m 08s\n```\n\nThis failure says nothing about whether the code is broken. It says that somewhere in the fully booted system, something took thirty seconds instead of three – a container that starts slowly, an animation, a network hop. On the next run, the same test is green without a single line changed. This is exactly how a nightly end-to-end suite loses its authority: it answers the question of whether you may deploy today with a roll of the dice, and at some point the team just clicks the red runs away.\n\nThe E2E marathon – the suite that boots the entire system at night, clicks through real UIs and shows red or green in the morning – is therefore not a discipline problem. It fails because of its structure. And the question that actually matters is much smaller than what it checks: Do these two services still fit together? The mechanics of the answer are quickly explained; the gain lies elsewhere.\n\nThe key difference is not the number of tests but the place where compatibility is checked.\n\n::::comparison{title=\"Checking compatibility at the right boundary\" role=\"primary\" preferredPattern=\"before-after\"}\n:::side{label=\"Shared E2E environment\"}\n- Setup · start all involved systems at the same time\n- Signal · one complete path just ran through successfully\n- Weakness · the cause of failure, timing and responsible boundary often stay unclear\n- Coupling · releases wait for the same integrated state\n:::\n:::side{label=\"Consumer-Driven Contract\"}\n- Setup · record expectations at a service boundary\n- Signal · consumer and provider fulfill the same contract independently\n- Strength · faster, deterministic and attributable to one boundary\n- Limit · does not replace a small selection of real end-to-end checks\n:::\n::::\n\nThe comparison doesn’t eliminate E2E tests. It moves the frequent compatibility check to the place where the contract actually comes into being.\n\n## Why the E2E marathon fails structurally\n\nWhat a team really needs is a fast, reliable answer to the question of whether a new release breaks the collaboration between services. A large E2E suite is the worst at delivering exactly this answer.\n\nMartin Fowler and Ham Vocke put it precisely in “The Practical Test Pyramid”: UI and end-to-end tests are “brittle, expensive to write, and time consuming to run”. They are prone to non-determinism – timing, animations, browser quirks, a network hop that takes 50 milliseconds one time and 800 the next. And this non-determinism is exactly the poison: as soon as a suite turns red in one out of twenty runs for reasons that have nothing to do with the code, the team starts clicking failures away. The test that was supposed to build trust produces the opposite.\n\nThen there is the coupling effect. An E2E suite needs all involved services at the same time, in compatible versions, booted in the same environment. This forces a lockstep: team A can only deploy once the shared suite is green with team B’s current state. You decoupled the services technically, only to chain them back together through the test infrastructure.\n\nThe DORA research in the book “Accelerate” by Forsgren, Humble and Kim provides the empirical counterpart. Two of the strongest predictors of successful continuous delivery are a “loosely coupled architecture” and “continuous testing”. Elite performers can change and deploy their services independently of each other, without having to synchronize with other teams. The E2E marathon works against exactly this goal. It is the synchronized lockstep in test form.\n\n## Check the boundary, not the whole system\n\nThe crucial insight is one of test abstraction. When two services work together, I don’t have to boot the entire integrated system to check whether they understand each other. I only have to check whether the *boundary* between them is right – whether the consumer sends what the provider expects, and the provider returns what the consumer relies on.\n\nFowler’s definition is precise enough to quote here: “An integration contract test is a test at the boundary of an external service verifying that it meets the contract expected by a consuming service.” The consumer tests against a mock, the provider verifies the recorded interactions – and both sides run fully isolated. No shared environment, no lockstep.\n\nThe pattern behind it is anything but new. Ian Robinson described “Consumer-Driven Contracts: A Service Evolution Pattern” on martinfowler.com back in 2006. The consumer defines its expectations; the provider verifies against the union of all consumer expectations. This is not hype; it is a pattern that has matured for about seventeen years. What has changed is the tooling landscape, which today pours it pragmatically into a CI pipeline.\n\nIn the classic test pyramid, the role becomes visible right away: contract tests sit in the middle, as a fast isolated test between the many unit tests at the base and the narrow, expensive E2E tip.\n\n```mermaid\nflowchart TB\n    subgraph Pyramid[\"Test Pyramid\"]\n        direction TB\n        E2E[\"E2E<br/>slow / flaky<br/>few\"]\n        CT[\"Integration / Contract<br/>fast / isolated<br/>focus\"]\n        UNIT[\"Unit<br/>fast / deterministic<br/>many\"]\n        UNIT --> CT --> E2E\n    end\n```\n\nThe message of the pyramid is not “no E2E tests”. It is: check compatibility where it arises – at the boundary – and not through a fully booted system at the top.\n\n## How a contract comes into being\n\nIn concrete terms, it looks like this. The consumer – let’s say a WebApp – describes in a test what it expects from the provider, here an OrderService. This test runs against a local mock and, as a by-product, generates a contract file, the pact.\n\n```js\nconst provider = new Pact({ consumer: 'WebApp', provider: 'OrderService' });\n\nprovider\n  .given('an order with id 42 exists')          // provider state\n  .uponReceiving('a request for order 42')\n  .withRequest({ method: 'GET', path: '/orders/42' })\n  .willRespondWith({\n    status: 200,\n    body: {\n      id: like(42),                              // type matcher\n      status: term({ matcher: 'PAID|OPEN', generate: 'PAID' }),\n      total: like(19.99),\n    },\n  });\n// the consumer runs against the Pact mock, then publishes the pact file to the broker\n```\n\nTwo details matter here, because they make the difference between “useful” and “brittle”. First, the matchers. `like(42)` doesn’t check for the exact value 42 but for the type – a number. `term(...)` checks against a pattern. This way the consumer states what it needs structurally instead of clinging to concrete example values. Matchers that are too lax give false confidence, matchers that are too strict make the test brittle; getting the granularity right is craft.\n\nSecond, the provider state, the `given('an order with id 42 exists')`. With it, the consumer describes the precondition under which its expectation holds. And this, to be honest, is where the main effort of the whole approach lies – more on that in a moment.\n\nOn the provider side, the contract is not rewritten but verified. The provider actually sets up every requested state and replays the recorded interactions against its real implementation.\n\n```java\n@Provider(\"OrderService\")\n@PactBroker\nclass OrderServiceContractTest {\n\n    @State(\"an order with id 42 exists\")\n    void orderExists() {\n        // set up the provider state so the recorded interaction is reproducible\n        orderRepository.save(new Order(42, \"PAID\", 19.99));\n    }\n}\n```\n\nBoth sides run isolated in their own pipelines. The consumer knows nothing about the provider’s implementation, and the provider doesn’t boot a WebApp. And still you get a reliable statement about their compatibility.\n\n## The deploy gate: a deterministic yes/no question\n\nNow comes the part that actually replaces the marathon. The contracts and the verification results end up in a central Pact Broker. Before every release, this lets you ask a simple, deterministic question: Are these specific versions of consumer and provider compatible with each other?\n\n```bash\n# provider side: verify the recorded interactions and publish results to the broker\npact-provider-verifier --provider OrderService --publish-verification-results\n\n# both sides gate their release on a deterministic check\npact-broker can-i-deploy \\\n  --pacticipant WebApp --version $GIT_SHA \\\n  --to-environment production\n```\n\n`can-i-deploy` is the core. Instead of “we wait until the nightly E2E suite is green”, the pipeline gets an immediate, reproducible answer from the broker: yes, this version of the WebApp is verified against the version of the OrderService currently running in production – deploy. Or: no, a verification is missing – stop.\n\nThe whole flow is a check at the boundary, not a fully booted system:\n\n```mermaid\nsequenceDiagram\n    participant C as Consumer (WebApp)\n    participant B as Pact Broker\n    participant P as Provider (OrderService)\n    C->>B: publish pact (from mock test)\n    P->>B: verify pact, publish results\n    C->>B: can-i-deploy? (WebApp @ sha)\n    B-->>C: yes -> deploy\n    P->>B: can-i-deploy? (OrderService @ sha)\n    B-->>P: yes -> deploy\n```\n\nThe effect is the real argument. Feedback in minutes instead of overnight. A deterministic gate instead of a flaky roll of the dice. And – this is the real lever – every team can deploy independently as soon as its part of the contract is fulfilled. No lockstep, no “we have to sync with team B first”. Exactly the loose coupling that “Accelerate” identifies as a predictor of delivery performance becomes testable here.\n\n## Where contract testing ends – the honest boundary\n\nConsumer-Driven Contracts replace the E2E *marathon* – not every E2E test. If you sell them as a cure-all, you promise too much.\n\nThe most important caveat first: contract tests check interface compatibility. Structure, fields, status codes, the format at the boundary. They do *not* check real end-to-end business flows across several hops, not UI behavior, not network and infrastructure effects in interaction. A narrow E2E smoke set that runs the critical path once through the running system remains sensible and right. The thesis is “instead of an E2E marathon”, not “zero E2E”. You trade a broad, slow, unreliable suite for many fast, isolated contracts plus a handful of targeted smoke tests.\n\nThe second point is where I spend the most time in practice: the provider states. Every `given('...')` must be something the provider can actually set up. If the consumer’s assumptions and the provider’s actual setup drift apart, the supposedly lightweight test becomes laborious after all. This is where the maintenance work lies, and if you underestimate it, you will be disappointed. It pays to keep the states deliberately lean and reusable.\n\nAnd the third point isn’t technical at all. Contract testing without a broker and without `can-i-deploy` in CI remains piecemeal. Contracts that only run locally and aren’t exchanged between pipelines in versioned form give no reliable deploy approval. Above all, though, Consumer-Driven Contracts are as much a question of collaboration as of technology: both teams have to commit to the contract as a binding agreement. The consumer says what it needs; the provider commits to delivering it and not breaking it. That is an organizational agreement, not a library. If the culture doesn’t play along, the best tool won’t help.\n\nA word on choosing tools, without slipping into product advertising: in the JS ecosystem, Pact generates the contracts; WireMock, Nock or MSW serve as consumer mocks there. On the JVM, Spring Cloud Contract is an established alternative to pact-jvm. The Pact Broker is open source and carries the CI mechanics. There are commercial extensions around it – you don’t need them for the core described here. The strategy doesn’t stand or fall with the vendor, but with the discipline to check at the boundary and to agree on contracts as teams.\n\n## Conclusion\n\nThe E2E marathon is not a testing problem but an architecture problem in test form: it couples services back together through the infrastructure that you decoupled for good reason, and in exchange it trades determinism and speed for a deceptive feeling of completeness. Consumer-Driven Contracts turn this around. They check compatibility where it arises – at the boundary between two services – isolated, fast and reproducible. The deploy gate becomes a yes/no question that is answered in minutes, and every team regains the freedom to release independently.\n\nIn the end, the gain doesn’t show up in any test metric; it shows in delivery: shorter cycles, less friction between teams, higher reliability. A narrow E2E smoke set stays alongside – but the marathon can go. You trade one large, slow, unreliable safety net for many small, precisely strung ones.\n\n## Further reading\n\n- [Consumer-Driven Contracts: A Service Evolution Pattern (Ian Robinson, martinfowler.com)](https://martinfowler.com/articles/consumerDrivenContracts.html)\n- [The Practical Test Pyramid (Ham Vocke, martinfowler.com)](https://martinfowler.com/articles/practical-test-pyramid.html)\n- [TestPyramid (Martin Fowler, Bliki)](https://martinfowler.com/bliki/TestPyramid.html)\n- [DORA: Loosely coupled architecture](https://dora.dev/capabilities/loosely-coupled-teams/)\n- [DORA: Continuous delivery](https://dora.dev/capabilities/continuous-delivery/)\n- [pact-jvm (pact-foundation, GitHub)](https://github.com/pact-foundation/pact-jvm)\n- Forsgren, Humble, Kim: *Accelerate* (2018)"},{"locale":"en","translation_key":"nodejs-fehler-als-architektur","slug":"errors-as-architecture-in-nodejs","title":"Errors as Architecture in Node.js: Safety Nets Against the Crash","summary":"Error handling in Node.js is not try/catch cosmetics but a decision about levels, escalation and orderly termination. If you know the four error levels and take graceful shutdown seriously, you build services that die in a controlled way instead of running on in a corrupt state.","tags":["Software","Node.js","Backend"],"published_at":"2023-11-07T10:00:00+00:00","updated_at":"2026-07-13T13:22:07.374858+00:00","url":"https://www.mikebild.dev/en/blog/errors-as-architecture-in-nodejs/","audio_url":null,"audio_duration_secs":null,"text":"A `try/catch` catches synchronous exceptions in the currently running stack and rejections of promises that are `await`ed inside the same block. A later callback, a detached promise and the `'error'` event of an EventEmitter, on the other hand, do not reach this block. A `try/catch` around their mere start call is then just decoration.\n\nThis means a Node.js application has at least four levels at which errors arise, and each of them has its own mechanics. If you only know the first one, you have three holes in the net – and you wonder why the process crashes anyway, even though there is “try/catch everywhere.”\n\nWhere these nets hang is decided at design time, not in the week before go-live when someone quickly layers some error handling on top. It determines whether a service stops under load and is back fresh within seconds – or whether it keeps working half broken and leaves behind data that nobody can straighten out afterward.\n\nTwo axes need to be kept apart here. Callback, promise and EventEmitter describe **how** an error reaches the code. Operational errors and programmer errors describe **whether** the concrete state is still manageable. An expected timeout can be answered or retried at the edge of the request. A broken invariant in your own code should escalate to the process boundary so that the service starts fresh after an orderly shutdown. Not every error demands terminating the process; but an unknown program state must not keep running as if it were a normal operational error.\n\n## The four levels at which errors arise\n\nBefore we talk about nets, it has to be clear which sources of errors exist in a Node.js application in the first place. At the core there are four, and they differ not in severity but in the mechanism by which the error reaches you:\n\n- Synchronous: an error is thrown directly in the current call stack. A classic `try/catch` catches it. If you catch nothing here, the exception is passed up one level – all the way to the top.\n- Error-first callbacks: the old, still ubiquitous Node convention. The error does not come as an exception but as the first argument of the callback function: `callback(err, result)`. No `throw`, no `catch` – just a value you have to check actively.\n- Promises and async/await: an error becomes the rejection of the promise. You catch it with `.catch()` or with `try/catch` around an `await`. If it is not caught anywhere, an `unhandledRejection` occurs.\n- EventEmitter: servers, sockets, streams. The error comes as an `'error'` event. And this is where the nastiest trap lurks: if the `'error'` listener is missing, the error is not silently swallowed – it is thrown as an exception and takes the process down with it.\n\nSeparating these four levels is the first step. The second is understanding that there is a fifth layer above them: the last net, which catches when nobody was responsible on any of the four levels.\n\n## Level by level: where the error really arrives\n\nLet’s go through the levels one by one. Synchronous is simple – everyone knows it:\n\n```js\nfunction parseConfig(raw) {\n  try {\n    return JSON.parse(raw);\n  } catch (err) {\n    // synchronous exception, caught right here\n    return { ok: false, reason: err.message };\n  }\n}\n```\n\nThe flawed thinking starts as soon as asynchrony comes into play. A `try/catch` around an error-first callback has no effect, because the callback is called later and in a different stack:\n\n```js\nconst fs = require('node:fs');\n\n// This try/catch catches NOTHING from the callback below.\ntry {\n  fs.readFile('/etc/config.json', (err, data) => {\n    if (err) return handle(err); // the error arrives HERE, as first argument\n    process.stdout.write(data);\n  });\n} catch (err) {\n  // never reached for the async error\n}\n```\n\nThe error sits in the `err` argument, not in a thrown exception. If you forget the `if (err) return ...`, the code keeps running with `data === undefined` – and the actual crash then happens later in a place that has nothing to do with the cause. This is the most common way errors hide in Node.js.\n\nPromises turn this back toward `try/catch` – but only around `await`:\n\n```js\nasync function loadUser(id) {\n  try {\n    const user = await db.users.findById(id);\n    if (!user) throw new Error(`user ${id} not found`);\n    return user;\n  } catch (err) {\n    // rejection AND thrown error both land here\n    logger.warn({ err, id }, 'loadUser failed');\n    throw err; // re-throw: let the caller decide\n  }\n}\n```\n\nWhat matters is the consequence when nobody observes the rejection. Since Node.js 15, the default mode of `--unhandled-rejections` is `throw`. An unhandled promise rejection is no longer just a warning but terminates the process. In practice, this means: every asynchronous chain must either be returned to a responsible caller or be handled at a clear boundary at the latest, with `.catch` or `try/catch`. Detached promises in timers or callbacks need this boundary explicitly.\n\nThe EventEmitter level is the most underestimated. A stream without an `'error'` listener crashes the process even though the error would have been entirely manageable:\n\n```js\nconst fs = require('node:fs');\n\nconst stream = fs.createReadStream('/does/not/exist');\n\n// WITHOUT this line, the emitted 'error' is thrown and crashes the process.\nstream.on('error', (err) => {\n  logger.error({ err }, 'stream failed, handled gracefully');\n});\n\nstream.on('data', (chunk) => process.stdout.write(chunk));\n```\n\nThis is standard Node semantics: an EventEmitter that emits an `'error'` event without a registered listener throws the error. That is why the `'error'` handler on servers, sockets and streams is not optional but an architectural must. If you work a lot with process boundaries and streams, you know the pattern from dealing with [child_process and scaling](https://www.mikebild.dev/en/blog/child-process-in-nodejs-scaling-without-illusions/) – there too, the `'error'` event on the child process is the difference between “handled cleanly” and “hard crash.”\n\n## The last net – and what it is not there for\n\nWhat happens when nobody was responsible on any of the four levels? Then the last net catches it: `uncaughtException` and `unhandledRejection`.\n\n```mermaid\nflowchart TD\n  E[\"Error occurs\"] --> D{\"Which level<br/>catches it?\"}\n  D -->|\"try/catch\"| H[\"handle &<br/>continue\"]\n  D -->|\"error-first callback\"| H\n  D -->|\"promise .catch\"| H\n  D -->|\"emitter 'error'\"| H\n  D -->|\"nobody responsible\"| ESC[\"escalates to<br/>the last net\"]\n  ESC --> LOG[\"log<br/>uncaughtException /<br/>unhandledRejection\"]\n  LOG --> GS[\"start graceful<br/>shutdown\"]\n  GS --> CLOSE[\"server.close()\"]\n  CLOSE --> EXIT[\"process.exit(1)\"]\n  EXIT --> SUP[\"Supervisor<br/>pm2 / systemd / K8s<br/>starts fresh\"]\n```\n\nThis is the decisive and often misunderstood point. If you register an `uncaughtException` handler, you override Node’s default behavior. Without a handler, Node writes the stack trace to stderr and terminates the process with exit code 1. As soon as a handler exists, this automatic exit no longer happens. The Node documentation is explicit here: “Adding a handler overrides this default behavior.”\n\nThis means: if you register an `uncaughtException` handler, you have to make sure yourself that the process is terminated. If you do not, it keeps running in an undefined state. And that is exactly the anti-pattern I see most often in real codebases:\n\n```js\n// ANTI-PATTERN: swallow and keep running.\nprocess.on('uncaughtException', (err) => {\n  logger.error({ err }, 'oops'); // logged, but then... nothing\n  // no process.exit — the process stays alive in a corrupt state\n});\n```\n\nAfter an uncaught exception, the application’s state is potentially corrupt: half-completed transactions, leaked file handles, a connection pool in an unclear state. The Node docs explicitly warn against resuming normal operation afterward. `uncaughtException` and `unhandledRejection` are a last net for terminating cleanly – not for carrying on.\n\nThe right net looks like this: log, then terminate in a controlled way. For the rejection, I deliberately escalate to an exception so that both paths end in the same shutdown:\n\n```js\nprocess.on('unhandledRejection', (reason) => {\n  logger.error({ reason }, 'unhandled rejection, escalating');\n  // escalate to uncaughtException so we exit through one path\n  throw reason;\n});\n\nprocess.on('uncaughtException', (err, origin) => {\n  logger.fatal({ err, origin }, 'uncaught exception, shutting down');\n  process.exit(1);\n});\n```\n\nThere is a quieter variant you should know: `uncaughtExceptionMonitor`. This handler only serves for observing and logging – it does not change the crash behavior. If no `uncaughtException` handler is registered, the process still crashes, but the monitor has logged beforehand. That is ideal when you want to record the crash without accidentally suppressing it:\n\n```js\n// Log the crash without changing the crash behavior.\nprocess.on('uncaughtExceptionMonitor', (err, origin) => {\n  logger.fatal({ err, origin }, 'about to crash');\n});\n```\n\n## Graceful shutdown: die in a controlled way, don’t repair\n\nThe crash via the last net is the hard variant. The normal case in operations is a different one: the supervisor – pm2, systemd or a Kubernetes orchestrator – wants to terminate the process, for example during a deployment or when scaling down. To do so, it sends a `SIGTERM`. And here the application is responsible for finishing ongoing work cleanly, not for repairing itself.\n\n```mermaid\nsequenceDiagram\n  participant O as Orchestrator\n  participant A as App\n  O->>A: SIGTERM\n  A->>A: stop accepting new requests\n  A->>A: drain in-flight requests\n  A->>A: close DB / pools\n  A-->>O: exit 0\n  O->>O: restart fresh\n```\n\nThe sequence is always the same: catch `SIGTERM`, stop accepting new connections, finish running requests, close resources, then exit. The supervisor then starts a fresh process. What matters is the default you override in doing so: without your own listener, Node exits on `SIGTERM` with exit code `128 + 15 = 143`. As soon as you register a listener, you are responsible for exiting yourself.\n\n```js\nconst http = require('node:http');\n\nconst server = http.createServer(handler);\nserver.listen(3000);\n\nlet isShuttingDown = false;\n\nfunction shutdown(signal) {\n  if (isShuttingDown) return; // guard against double invocation\n  isShuttingDown = true;\n  logger.info({ signal }, 'graceful shutdown started');\n\n  // stop accepting new connections, finish in-flight ones\n  server.close((err) => {\n    if (err) {\n      logger.error({ err }, 'error during server.close');\n      return process.exit(1);\n    }\n    logger.info('all connections drained, exiting');\n    process.exit(0);\n  });\n\n  // fallback: never hang forever if a connection refuses to close\n  setTimeout(() => {\n    logger.error('shutdown timed out, forcing exit');\n    process.exit(1);\n  }, 10_000).unref();\n}\n\nprocess.on('SIGTERM', () => shutdown('SIGTERM'));\nprocess.on('SIGINT', () => shutdown('SIGINT'));\n```\n\nTwo details are decisive here. First, the `isShuttingDown` flag: a container can send `SIGTERM` and shortly afterward another signal; without a guard, the shutdown runs twice and `server.close` is called on a server that is already closing. Second, the timeout with `.unref()`. If a hanging connection causes `server.close` never to return, the process would otherwise stay up forever – until the orchestrator eventually steps in hard with `SIGKILL`. The fallback timeout ensures that we exit on our own in a controlled way before that. The `.unref()` prevents the timer itself from keeping the process alive in case the clean path does finish in time.\n\nThis division of labor is the core of the whole architecture: the application is responsible for finishing its ongoing work cleanly and then dying. The supervisor is responsible for restarting – not the application itself. A process that tries to heal itself after a serious error and keep running makes things worse. A process that dies in a controlled way and is restarted fresh is back in a defined state within seconds.\n\n## Why this is an architecture decision\n\nThe responsibilities are linked as a chain: the error arises on one of the four levels. Ideally, a responsible handler catches it right there – in the `try/catch`, in the `if (err)` check, in the `.catch`, in the `'error'` listener. Only when nobody was responsible does it escalate to the last net, and the last net has exactly one job: log cleanly and terminate in an orderly fashion.\n\nThis is not a collection of individual tricks but a consistent decision about where an error is handled and where it only leads to a controlled end. You decide once how the net is strung, and then it holds everywhere – or you do not decide, and then it tears in the place you never looked at.\n\nIf you want to dig deeper into the interplay of the event loop, callbacks and promises, you will find the foundation in the [Node.js training on event loop architecture](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/). Only once it is clear why a callback runs in a different stack than the `try/catch` around it does it become understandable why error handling in Node.js is not done with “try/catch everywhere.”\n\nHandle every error as close as possible to the level where it arises. String the last net only for dying cleanly, never for living on. And leave the resurrection to the supervisor. A service that knows how to die is more stable than one that wants to stay alive at any cost.\n\n## Further reading\n\n- Repository with examples: [MikeBild/introduction-nodejs](https://github.com/MikeBild/introduction-nodejs)\n- [process – Event: 'uncaughtException'](https://nodejs.org/api/process.html#event-uncaughtexception)\n- [process – Event: 'unhandledRejection'](https://nodejs.org/api/process.html#event-unhandledrejection)\n- [process – signal events](https://nodejs.org/api/process.html#signal-events)\n- [events – EventEmitter 'error' events](https://nodejs.org/api/events.html#error-events)\n- [CLI – --unhandled-rejections=mode](https://nodejs.org/api/cli.html#--unhandled-rejectionsmode)\n- [Node.js Process API](https://nodejs.org/api/process.html)"},{"locale":"en","translation_key":"dora-metriken-was-zyklen-verkuerzt","slug":"dora-metrics-what-really-shortens-cycles","title":"DORA Metrics: What Really Shortens Development Cycles","summary":"Lead time, deploy frequency, change fail rate, and recovery time are diagnostic values, not vanity velocity. They show where the cycle gets stuck – and why speed and stability don’t have to be opposites.","tags":["Software","Delivery"],"published_at":"2023-10-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/dora-metrics-what-really-shortens-cycles/","audio_url":null,"audio_duration_secs":null,"text":"Deployment Frequency, Lead Time for Changes, Change Failure Rate, Failed Deployment Recovery Time: four measurements that nobody has to estimate and nobody has to vote on. They come out of systems that are running anyway – the commit timestamp in version control, the deploy event of the CD pipeline, the incident log. No board, no points, no self-reporting. In older DORA texts, the recovery metric was called “Time to Restore Service.”\n\n**Editorial note (July 2026):** This post describes the model of four delivery metrics as it stood at the time. In 2024, DORA added the **Deployment Rework Rate** as a fifth metric. The current canon thus consists of three throughput and two instability metrics; the historical group of four in the main text remains as the starting point.\n\nA velocity curve comes about the opposite way. It adds up story points that a team has assigned to itself, and it can point steeply upward while releases stay sluggish, hotfixes pile up, and nobody wants to deploy on Fridays. The four measurements above can’t do that. They describe the path of a change from commit to production – and what happens when that change causes damage.\n\nThese four DORA keys come from the DevOps Research and Assessment work around Nicole Forsgren, Jez Humble, and Gene Kim, are backed statistically in the book *Accelerate* (2018), and have been carried forward every year since in the *State of DevOps Report*. Their value lies in diagnosis: they show where in the chain things get stuck. What follows is about exactly where the keys make the bottleneck visible and how to collect them without turning them into a new numbers game.\n\nYou can first sort the measurements by the question they answer. That prevents speed and instability from merging into a seemingly clear-cut overall grade.\n\n::::comparison{title=\"Delivery performance has two axes\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Throughput\"}\n- Deployment Frequency · How often does a change reach production?\n- Lead Time for Changes · How long does the path from commit to deploy take?\n:::\n:::side{label=\"Instability\"}\n- Change Failure Rate · What share of changes causes an incident?\n- Failed Deployment Recovery Time · How long does recovery take after a failed deploy?\n- Deployment Rework Rate · What share creates unplanned rework?\n:::\n::::\n\nThis split isn’t a ranking. Only together do the two sides show whether a team can deliver quickly without hiding the cost of failed changes.\n\n## Two axes instead of one number\n\nThe first reasoning error is treating delivery performance as a single quantity. The four keys deliberately span two axes.\n\nOn the throughput axis are **Deployment Frequency** – how often code goes to production – and **Lead Time for Changes** – how long it takes from commit to a successful deploy. That is the speed side: small batches, short paths.\n\nOn the stability axis are **Change Failure Rate** – what share of deploys triggers an incident or a rollback – and **Failed Deployment Recovery Time** – how long recovery takes after a failed deployment. That is the robustness side: how expensive a failure gets.\n\nThe central, counterintuitive finding from *Accelerate*: these two axes are not in opposition. The data shows that elite teams win on **both** at the same time – they deploy more often *and* fail less often *and* are back online faster. The old reflex “If we deliver faster, quality goes down” has been empirically refuted. That is exactly why it is negligent to measure only two of the four metrics. If you track only deploy frequency and lead time, you optimize for speed and ignore stability – and produce exactly the vanity illusion the DORA keys are meant to counter.\n\n```mermaid\nquadrantChart\n  title Throughput vs. Stability\n  x-axis Low Throughput --> High Throughput\n  y-axis Low Stability --> High Stability\n  quadrant-1 Elite\n  quadrant-2 Slow but Safe\n  quadrant-3 Low Performer\n  quadrant-4 Fragile Speed\n  Elite Team: [0.85, 0.85]\n  Big-Batch Team: [0.2, 0.6]\n  Move-Fast-Break-Things: [0.8, 0.25]\n  Stuck Team: [0.2, 0.2]\n```\n\nThe matrix makes it clear: the goal is the top right, not a compromise on the diagonal. And it explains why a single number is misleading – a team in the “Fragile Speed” quadrant looks brilliant on a pure speed metric and is still on fire.\n\n## Where the cycle gets stuck\n\nThe real value of the keys lies not in the benchmark but in localization. Each metric is attached to a different segment of the value chain from commit to production – and thus shows where things get stuck.\n\n```mermaid\nflowchart LR\n  A[Commit] --> B[CI Build]\n  B --> C[Test]\n  C --> D[Deploy Gate]\n  D --> E[Production]\n  E -->|Incident| F[Restore]\n  F --> E\n  A -. Lead Time for Changes .-> E\n  D -. Deployment Frequency .-> E\n  E -. Change Failure Rate .-> F\n  F -. Failed Deployment Recovery Time .-> E\n  style D fill:#e8543f,color:#fff\n```\n\nAn example from practice: a team complains about “slow releases.” The median lead time is eleven days. If you break it down, nine of those days sit between “feature done” and “deploy gate” – the pipeline and the manual approval step are the bottleneck, not the programming. Another team has a good lead time but a change failure rate of 30 percent and a restore time of hours: here the problem isn’t speed but the reversibility of changes. The same four numbers, completely different treatment. An aggregated velocity would only have said “the team is at full capacity” in both cases.\n\nLead Time for Changes is my most important early indicator here. It is defined as the time from code commit to a successful run in production, and it correlates closely with batch size. Large batches lengthen feedback, increase the risk of failure, and turn every deployment into an event – Donald Reinertsen and Jez Humble have been insisting on this for years, and *Accelerate* backs it with data. A short lead time almost automatically forces small, continuous changes.\n\n## Change Failure Rate and recovery time are coupled\n\nA widespread misunderstanding is that stability means “no failures.” That isn’t what the DORA data says. The coupling of Change Failure Rate and Failed Deployment Recovery Time says something subtler: what counts is not the absence of failures but their price. High deploy frequency plus a low change failure rate plus a short recovery time means that changes are small and reversible. A failure that I roll back in minutes is cheap. A zero-defect standard that turns every release into a nail-biter is expensive – precisely because it forces rarely practiced, risky deploys.\n\nThat is why, in practice, a short restore time beats the demand for zero defects. And that is why the neighboring techniques belong right here: feature flags, to switch changes on or off without a deploy; canary and blue-green releases, to limit the blast radius; circuit breakers and bulkheads from Michael Nygard’s *Release It!*, to contain outages. Not buzzwords: these are exactly the levers that lower the change failure rate and shorten the restore time.\n\nIn code, the coupling of a reversible rollout and automatic recovery looks like this, for example:\n\n```typescript\n// Canary rollout gated by the live error rate.\n// Ties Change Failure Rate and recovery time together in one control loop.\ninterface RolloutConfig {\n  canaryPercentage: number;\n  maxErrorRate: number;      // e.g. 0.02 -> roll back above 2%\n  observationWindowMs: number;\n}\n\nasync function progressiveRollout(\n  release: Release,\n  config: RolloutConfig,\n): Promise<RolloutResult> {\n  await featureFlags.enableForCohort(release.id, config.canaryPercentage);\n\n  const errorRate = await metrics.observeErrorRate(\n    release.id,\n    config.observationWindowMs,\n  );\n\n  if (errorRate > config.maxErrorRate) {\n    await featureFlags.disable(release.id); // instant, no redeploy\n    return { status: \"rolled_back\", observedErrorRate: errorRate };\n  }\n\n  await featureFlags.enableForCohort(release.id, 100);\n  return { status: \"promoted\", observedErrorRate: errorRate };\n}\n```\n\nIt isn’t about the specific library; it is about the principle: recovery happens via a flag toggle in seconds, not via an emergency deploy. That is exactly what later shows up as a low restore time.\n\n## Measuring the metrics without inventing them\n\nFor the keys to stay honest, they have to come from systems that nobody maintains by hand. Lead time, for example, can be derived entirely from two sources: the commit timestamp in version control and the deploy event of the CD pipeline. No estimate, no self-reporting.\n\n```typescript\n// Lead Time for Changes, derived from VCS + deploy events.\n// leadTime = deployedAt(prodDeployment) - firstCommitTime(changeSet)\nfunction leadTimeForChange(deployment: ProdDeployment): number {\n  const firstCommit = deployment.changeSet\n    .map((commit) => commit.authoredAt.getTime())\n    .reduce((min, t) => Math.min(min, t), Infinity);\n\n  return deployment.deployedAt.getTime() - firstCommit;\n}\n\n// Aggregate as a median over a rolling window -- means get skewed by outliers.\nfunction medianLeadTime(deployments: ProdDeployment[]): number {\n  const values = deployments.map(leadTimeForChange).sort((a, b) => a - b);\n  const mid = Math.floor(values.length / 2);\n  return values.length % 2 === 0\n    ? (values[mid - 1] + values[mid]) / 2\n    : values[mid];\n}\n```\n\nTwo details matter. First, the median instead of the mean – a single branch that sat around for a while would ruin any average. Second, the rolling time window: the number is a trend, not a daily hit.\n\nIt gets even more effective when you don’t just display a metric but feed it back into the pipeline. In *Building Evolutionary Architectures*, Neal Ford, Rebecca Parsons, and Patrick Kua call this a fitness function – an executable rule that makes an architectural property verifiable. A DORA fitness function can turn the pipeline red when the change failure rate is above the threshold:\n\n```python\n# Executable fitness function: assert a DORA metric as a CI gate.\ndef assert_change_failure_rate(window_days: int = 30, threshold: float = 0.15):\n    deployments = metrics_db.query_deployments(window_days)\n    failed = [d for d in deployments if d.caused_incident or d.rolled_back]\n\n    if not deployments:\n        return  # nothing to assert yet\n\n    change_failure_rate = len(failed) / len(deployments)\n    assert change_failure_rate < threshold, (\n        f\"Change Failure Rate {change_failure_rate:.0%} \"\n        f\"exceeds threshold {threshold:.0%} over {window_days}d\"\n    )\n```\n\nThis is how DORA connects with the idea of evolutionary architecture: the metric is no longer a slide for the quarterly meeting but a condition that the system places on itself.\n\n## The pitfall: metrics as targets\n\nThat brings us to the biggest danger. As soon as a metric becomes a target, it ceases to be a good measure – Goodhart’s Law in its purest form. Deployment Frequency can be inflated with trivial empty deploys. Change Failure Rate can be prettied up by redefining “failure” until hardly anything falls into it anymore. If you use the keys as a team ranking or a bonus KPI, you get exactly this gaming – and DORA itself explicitly warns against using them to compare teams. The four numbers are diagnosis, not competition.\n\nI often see two other mix-ups. First: the keys are not a replacement for story point velocity in the sense of “same thing, better numbers.” It is a different construct – velocity measures the output of a single team and is neither comparable nor tamper-proof; the keys measure the flow from commit to production across the entire delivery system. Second: fast deploys without impact are “faster to nowhere.” That is why DORA added a fifth dimension in the 2021 and 2022 reports, **reliability**, or operational performance. The statement from 2022: high delivery performance only pays off for organizational success if reliability in operations is right as well. I deliberately treat reliability as a younger, softer addition – not as a fifth, equal-ranking part of the canon. But the idea belongs in the “honest instead of vanity” framing: speed without operational stability is a vanity metric with better marketing.\n\n## Conclusion\n\nThe common thread is simple. Velocity measures what a team claims about itself. The four DORA keys measure what actually happens – from commit to production and back when things break. They do this on two axes, speed and stability, and the core message of *Accelerate* is that these axes are not a tradeoff: the good teams win on both.\n\nIn practice, I use the keys as a searchlight. A long lead time points to large batches or a clogged pipeline. A high change failure rate points to missing reversibility. A long restore time shows that recovery isn’t practiced. Every number points to a concrete, technical countermeasure – small batches, Trunk-Based Development, feature flags, canary releases, circuit breakers. That is the difference between a metric that shortens the cycle and one that just fills a dashboard.\n\nAnd the discipline in all this: the keys diagnose; they don’t reward. The moment they become a target, they lose their value. If you can stand that – looking at numbers without chasing them – you get something rare: an honest view of where your own cycle really gets stuck.\n\n## Further reading\n\n- [DORA Metrics – dora.dev](https://dora.dev/guides/dora-metrics/)\n- [Accelerate State of DevOps Report 2022 – dora.dev](https://dora.dev/research/2022/dora-report/)\n- [DORA 2022 Report – Google Cloud Blog](https://cloud.google.com/blog/products/devops-sre/dora-2022-accelerate-state-of-devops-report-now-out)\n- [Four Keys to measure DevOps performance – Google Cloud](https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance)\n- [A history of DORA's metrics – dora.dev](https://dora.dev/insights/dora-metrics-history/)"},{"locale":"en","translation_key":"nodejs-child-process-und-skalierung","slug":"child-process-in-nodejs-scaling-without-illusions","title":"child_process in Node.js: Scaling Without Illusions","summary":"Node.js runs on a single event loop – CPU work blocks everything. This post shows when fork, cluster, and worker_threads really help and when they are just overhead.","tags":["Software","Node.js","Backend"],"published_at":"2023-09-19T10:00:00+00:00","updated_at":"2026-07-13T08:00:45.524078+00:00","url":"https://www.mikebild.dev/en/blog/child-process-in-nodejs-scaling-without-illusions/","audio_url":null,"audio_duration_secs":null,"text":"Non-blocking doesn’t mean parallel. Node.js accepts thousands of concurrent network connections without breaking a sweat – but that doesn’t mean it spreads computational work across multiple cores. The two properties get lumped together all the time, and this confusion is what produces the endpoint that freezes the entire application under load without anyone understanding why.\n\nThe difference lies in what the work consists of: waiting or computing. Node handles waiting on its own. Computing, it doesn’t. That is what `child_process`, `cluster`, and `worker_threads` are for – three tools with similar names, very different costs, and one shared pattern of misuse.\n\n## One event loop, one thread, one bottleneck\n\nLet’s start at the root. A Node.js process has one event loop, and JavaScript runs in that process on exactly one thread. That isn’t a bug, that is the design principle. As long as the work consists of waiting – for a database response, for a file, for an HTTP response – the event loop can take care of other things in the meantime. The actual input and output happens in the background via libuv, and your code only gets the finished callback at the end. If you want to understand how this machinery works in detail, my [Node.js training on event loop architecture](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/) has the full version.\n\nThe problem begins as soon as the work doesn’t consist of waiting but of computing. Scaling an image, parsing and transforming a large JSON document, verifying a password with an expensive hash function, a cryptographic operation, a synchronous loop over millions of entries. This work happens on the same single thread. And as long as it runs, the event loop can’t do anything else – no accepting new requests, no firing timers, no processing callbacks. Everything stops.\n\nThe following code looks harmless and still slips through code reviews regularly:\n\n```js\nconst http = require('node:http');\n\nfunction fibonacci(n) {\n  if (n < 2) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nhttp\n  .createServer((req, res) => {\n    if (req.url === '/compute') {\n      const result = fibonacci(45); // blocks the event loop for seconds\n      res.end(`result: ${result}`);\n    } else {\n      res.end('ok');\n    }\n  })\n  .listen(3000);\n```\n\nAs long as `fibonacci(45)` is computing, not a single other client gets a response – not even on the harmless `/` path, which would normally finish in microseconds. A single slow request brings down the whole server. That is exactly what the official docs mean by “Don’t Block the Event Loop.”\n\n## Four tools, four jobs\n\nNode.js offers several tools for this problem, and they get mixed up regularly. It pays to keep them cleanly apart:\n\n- `child_process` starts a completely separate operating system process with its own V8, its own heap, and its own event loop. Communication runs over pipes or – with `fork` – over an IPC channel via message passing. No shared memory.\n- `cluster` starts several Node instances behind a shared port and distributes incoming connections among them. Internally, it builds on `child_process.fork()` and serves request throughput.\n- `worker_threads` starts another thread within the same process. Each worker has its own V8 isolate and its own event loop, but can optionally share real memory with the main thread. Meant for CPU work.\n- The regular asynchronous APIs are for everything that is I/O – and that needs none of the three options above.\n\nI emphasize this last point deliberately, because that is where the most common reasoning error lurks. But one thing at a time.\n\n## child_process: spawn, exec, execFile, fork\n\nThe `node:child_process` module offers four ways to start a child process, and the differences matter in practice.\n\n`spawn(command, args, options)` starts a program and gives you its `stdout` and `stderr` as streams. It buffers nothing and doesn’t start a shell by default. That is the right choice when the output can be large or you want to process it as a stream.\n\n`exec(command, options, callback)` starts a real shell and buffers the entire output in memory before the callback is called. That is convenient for short commands but has two catches: the default for `maxBuffer` is 1 MB – if the output gets larger, Node kills the process with `ERR_CHILD_PROCESS_STDIO_MAXBUFFER`. And because a shell is involved, `exec` with unchecked input is an invitation to shell injection.\n\n`execFile(file, args, options, callback)` behaves like `exec` but doesn’t start a shell. That is safer and more efficient when you are only calling a specific program with arguments anyway.\n\n```js\nconst { execFile } = require('node:child_process');\n\nexecFile('git', ['rev-parse', 'HEAD'], (err, stdout) => {\n  if (err) throw err;\n  console.log('current commit:', stdout.trim());\n});\n```\n\nThe choice fits into three lines: short output from a specific program – `execFile`. Large or streaming output – `spawn`. `exec` with a shell only when you really need the shell features (pipes, globbing) and you control the input.\n\nThe most interesting of the four is `fork`. It is a special case of `spawn` that specifically starts a new Node instance – via `process.execPath`, the same Node binary – and automatically sets up an IPC channel. This lets you exchange messages between the parent and child process without handling pipes and serialization by hand.\n\n## The main example: heavy computation in a fork\n\nLet’s take the blocking Fibonacci example from above and move the computation into a child process. The parent process stays responsive because the CPU load lands in an entirely different OS process.\n\nFirst the worker in `worker.js`:\n\n```js\n// worker.js\nfunction fibonacci(n) {\n  if (n < 2) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nprocess.on('message', ({ n }) => {\n  const result = fibonacci(n);\n  process.send({ n, result });\n});\n```\n\nAnd the parent process that starts it and hands it work:\n\n```js\n// main.js\nconst { fork } = require('node:child_process');\nconst http = require('node:http');\n\nconst child = fork('./worker.js');\n\nconst pending = new Map();\nchild.on('message', ({ n, result }) => {\n  const res = pending.get(n);\n  if (res) {\n    res.end(`fibonacci(${n}) = ${result}`);\n    pending.delete(n);\n  }\n});\n\nhttp\n  .createServer((req, res) => {\n    if (req.url === '/compute') {\n      pending.set(45, res);\n      child.send({ n: 45 }); // heavy work happens elsewhere\n    } else {\n      res.end('ok'); // stays responsive during the computation\n    }\n  })\n  .listen(3000);\n```\n\nThe crucial point here: the `/` path now responds immediately, even while `/compute` is still computing. The main process’s event loop is free, because the expensive loop runs in a separate process with its own V8 heap. Communication between the two goes exclusively through messages – here via `child.send()` and the `message` event.\n\nThis is worth a second look: `send` is not shared memory. The message is serialized and rebuilt as a copy in the child process. The default is `serialization: 'json'`, and JSON loses types – a `Date` becomes a string, `undefined` disappears, `BigInt` doesn’t work at all. If you want to send structured values over IPC, you can set `serialization: 'advanced'`, which uses the structured clone algorithm and preserves considerably more types.\n\nThe following flow shows the principle as a sequence:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Main as Main process<br/>(event loop free)\n    participant Child as Forked process<br/>(own V8 heap)\n    Client->>Main: GET /compute\n    Main->>Child: send({ n: 45 })\n    Note over Main: Event loop stays free<br/>for other requests\n    Child->>Child: heavy computation\n    Child-->>Main: message({ result })\n    Main-->>Client: HTTP 200 result\n```\n\n## worker_threads: the same goal, shared memory\n\nA `fork` is robust but expensive. Every child process brings a complete V8 and its own heap – that costs memory and startup time. If you want to parallelize CPU work and don’t need the full isolation of a separate process, `worker_threads` are the lighter alternative. They have been stable since Node 12 and, in 2023, have long been the production standard.\n\nA worker runs in the same process but in its own thread with its own V8 isolate and its own event loop. The same computation looks like this:\n\n```js\n// task.js\nconst { parentPort, workerData } = require('node:worker_threads');\n\nfunction fibonacci(n) {\n  if (n < 2) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nparentPort.postMessage(fibonacci(workerData.n));\n```\n\n```js\n// main-threads.js\nconst { Worker } = require('node:worker_threads');\n\nfunction computeFib(n) {\n  return new Promise((resolve, reject) => {\n    const worker = new Worker('./task.js', { workerData: { n } });\n    worker.on('message', resolve);\n    worker.on('error', reject);\n  });\n}\n\ncomputeFib(45).then((result) => {\n  console.log('fibonacci(45) =', result);\n});\n```\n\nThe big difference from `fork`: worker threads can share real memory. A `SharedArrayBuffer` is the same memory region for the main thread and the worker thread – no copy, no serialization. Alternatively, you can pass an `ArrayBuffer` via `transferList`, which is a zero-copy transfer: the buffer moves to the receiver and is unusable on the sender afterward. For large amounts of data between threads, that is a real advantage that a separate process, by its nature, can’t offer.\n\n## The pitfall that does the most damage\n\nThe mistake that burns the most time in real codebases is this one: trying to “speed up” I/O-bound work with `worker_threads` or `cluster`. I have run into it in several projects, each time with the same justification.\n\nThe motivation is understandable. Someone has heard that workers parallelize, sees an endpoint that makes many database queries or HTTP calls, and puts the whole thing into a worker pool. The result is regularly slower than before. The reason: network and file I/O in Node.js is already asynchronous and doesn’t block the event loop at all. There is nothing to offload. The docs say it unambiguously: worker threads don’t help much with I/O-intensive work. What you get is the overhead of thread creation and message passing – with no gain whatsoever.\n\nSo the rule is simple and still gets violated all the time:\n\n- Is the work I/O-bound – database, network, file system? Then stick with the regular asynchronous APIs. Workers and processes bring nothing here except complexity.\n- Is the work CPU-bound – hashing, image processing, compression, crypto, large synchronous transformations? Only then are `worker_threads` or `child_process` the right tool.\n\nA second pitfall sits right next to it: creating a worker or process per task. Creation is expensive – V8 has to be initialized, memory gets allocated. If you start a fresh worker on every request, you often make things slower, not faster. The answer is a worker pool: a fixed number of reusable workers that process tasks from a queue. The same consideration applies to `fork` – keep the child processes alive and send them work one after another instead of restarting them constantly.\n\n## cluster: throughput, not relief\n\nThat leaves `cluster`, and here, too, there is a persistent misunderstanding. `cluster` doesn’t solve the problem of the single blocking computation. It solves the problem of throughput: a single Node process uses only one core, but your machine has several. `cluster` starts one Node instance per core, all of them listen behind the same port, and the primary distributes incoming connections round-robin.\n\n```js\nconst cluster = require('node:cluster');\nconst http = require('node:http');\nconst os = require('node:os');\n\nif (cluster.isPrimary) {\n  for (let i = 0; i < os.cpus().length; i++) {\n    cluster.fork();\n  }\n  cluster.on('exit', (worker) => {\n    console.log(`worker ${worker.process.pid} died, restarting`);\n    cluster.fork();\n  });\n} else {\n  http\n    .createServer((req, res) => res.end(`handled by pid ${process.pid}`))\n    .listen(3000);\n}\n```\n\nThis doubles or quadruples the throughput of concurrent requests. But if a single request triggers a synchronous computation that takes seconds, it still blocks the worker handling it. `cluster` only turns many slow requests into many parallel ones if each lands on a different worker – and the limited number of workers runs out at some point. For the actual CPU problem per request, you still need `worker_threads` or offloaded processes. By the way, `cluster.isPrimary` has been the preferred name since Node 16; `isMaster` still exists but is considered deprecated.\n\n## What to use when: the decision at a glance\n\nThe decision boils down to a few questions:\n\n```mermaid\nflowchart TD\n    A[Classify the work] --> B{I/O-bound?}\n    B -->|Yes| C[Regular async APIs<br/>no workers needed]\n    B -->|No, CPU-bound| D{Shared memory<br/>or lightweight?}\n    D -->|Yes| E[worker_threads<br/>SharedArrayBuffer possible]\n    D -->|No, isolation<br/>or external script| F[child_process / fork<br/>own process + IPC]\n    A --> G{Just more throughput<br/>on all cores?}\n    G -->|Yes| H[cluster<br/>multiple instances, one port]\n```\n\nThe three tools answer different questions – they don’t compete for the same one:\n\n- `child_process` / `fork` gives you a separate process with its own heap and communication via copied IPC messages – maximum isolation, ideal for external programs or standalone Node scripts.\n- `cluster` gives you several Node instances behind one port for more request throughput – it scales instances, not individual computations.\n- `worker_threads` gives you threads in the same process with optionally shared memory – the right choice for parallelizing CPU work without spinning up a whole process.\n\n## Conclusion\n\nThe illusion this post argues against is the most comfortable one: that Node.js somehow spreads CPU work across all cores on its own. It doesn’t. One process, one event loop, one JS thread – and every synchronous computational load blocks everything else. Once you accept that, the right decisions almost make themselves: I/O doesn’t need workers, just the asynchronous APIs that Node already ships with. Only CPU work justifies heavier artillery – `worker_threads` for in-process parallelism with shared memory, `fork` for isolated processes, `cluster` for pure throughput.\n\nThe most expensive mistake is not choosing the wrong tool. It is reaching for a tool where there is no problem at all – “speeding up” I/O with workers and buying complexity and overhead in exchange, without gaining a single millisecond. First measure whether you are CPU-bound at all. If you are, you now know where the work belongs. If you push large amounts of data through your application anyway, my post on [Node.js streams and backpressure](https://www.mikebild.dev/en/blog/nodejs-streams-understanding-backpressure/) is the right complement – because often the best scaling is the kind where you never load the data completely into memory in the first place.\n\n## Further reading\n\n- Repository with the code examples: [github.com/mikebild/introduction-nodejs](https://github.com/mikebild/introduction-nodejs)\n- [child_process – official Node.js docs](https://nodejs.org/api/child_process.html)\n- [worker_threads – official Node.js docs](https://nodejs.org/api/worker_threads.html)\n- [cluster – official Node.js docs](https://nodejs.org/api/cluster.html)\n- [Don't Block the Event Loop – Node.js Learn](https://nodejs.org/en/learn/asynchronous-work/dont-block-the-event-loop)"},{"locale":"en","translation_key":"lambda-performance-und-cold-starts","slug":"understanding-lambda-performance-and-cold-starts","title":"Understanding Lambda Performance and Cold Starts","summary":"What a cold start in AWS Lambda really is, which levers you control – from bundle size through init code and memory to Provisioned Concurrency – and how to measure all of it properly.","tags":["Software","AWS","Cloud"],"published_at":"2023-08-08T10:00:00+00:00","updated_at":"2026-07-13T10:04:44.118576+00:00","url":"https://www.mikebild.dev/en/blog/understanding-lambda-performance-and-cold-starts/","audio_url":null,"audio_duration_secs":null,"text":"An endpoint responds in 40 milliseconds, on the next call in 900 – nothing changed in the code, and monitoring reports no error. The difference lies solely in whether AWS Lambda could reuse an existing execution environment or had to create a new one. And every millisecond of work that happens outside the handler is paid by the first caller of that new environment – fully and visibly.\n\nThis outlier is called a cold start, and its bad reputation is undeserved. It is neither a bug nor a sign of a poorly built function, but a direct consequence of Lambda’s execution model. Once you see through this model, the vague “sometimes slow” breaks down into a handful of concrete adjustment knobs – and a few stubborn misconceptions sort themselves out along the way.\n\n## What really happens during a cold start\n\nLambda doesn’t run your code in a permanently running process but in a so-called execution environment. This is an isolated, short-lived runtime that Lambda creates on demand, keeps alive for a while and eventually throws away. The lifecycle of this environment consists of three phases: Init, Invoke and Shutdown.\n\nA cold start is nothing other than the Init phase of a freshly created environment. Quite a lot happens before your actual logic even starts:\n\n- Lambda downloads your code – from internal storage or, for container images, from the registry.\n- The runtime is initialized, for example by starting the Node.js process.\n- Your function init code runs: everything you wrote at module level outside the handler – imports, creating SDK clients, reading configuration.\n\nOnly then does the Invoke phase follow, in which your handler is called with the concrete event. An important detail for practice: the Init phase has a hard timeout of 10 seconds. If you do expensive work at module level, you can actually hit this limit – more on that later.\n\nAfter the invoke, Lambda doesn’t throw the environment away immediately. It is frozen and thawed again for another call within a short time. Then we speak of a warm invoke: the entire Init phase is skipped because the runtime and init code have already run. Only your handler runs. That is why the same endpoint sometimes takes 40 and sometimes 900 milliseconds – the difference is simply whether a warm environment was ready or a new one had to be created.\n\n```mermaid\nflowchart TD\n    Req[Incoming invoke] --> Q{Warm environment<br/>available?}\n    Q -->|No: cold start| C1[Download code]\n    C1 --> C2[Initialize runtime]\n    C2 --> C3[Run init code outside<br/>the handler]\n    C3 --> H[Run handler]\n    Q -->|Yes: warm invoke| H\n    H --> F[Freeze environment<br/>for later invokes]\n    F -.reuse.-> Q\n```\n\nThe diagram makes the central point visible: the expensive part – download, runtime init, function init – only happens on the cold path. The “Init Duration” you’ll find in the logs in a moment is exactly the sum of these three steps. On every warm invoke, Lambda jumps straight to the handler.\n\n## The first lever: keep the bundle small\n\nThe most obvious contribution to the cold start is the time it takes to load your code and parse the modules. The bigger the bundle and the more branched the import graph, the longer that takes. That sounds trivial, but I regularly see deployment packages of several megabytes in which a complete SDK, three date libraries and unused parts of a framework travel along.\n\nThe pragmatic answer is bundling with tree shaking. A bundler like esbuild throws out everything that isn’t actually reached and packs the rest into a compact file. A typical call looks like this:\n\n```bash\nesbuild src/handler.ts \\\n  --bundle \\\n  --minify \\\n  --platform=node \\\n  --target=node18 \\\n  --external:@aws-sdk/* \\\n  --outfile=dist/handler.js\n```\n\nTwo things here are deliberate choices. The target is `node18` – Lambda’s current LTS runtime at this point. And AWS SDK v3 is kept out of the bundle via `--external:@aws-sdk/*`, because it is preinstalled in the Node18 runtime anyway. Packing it in would only bloat the package unnecessarily without any benefit.\n\nIf you work with AWS SAM or the CDK, you often don’t have to take care of the call yourself: the `NodejsFunction` construct uses esbuild internally and bundles automatically. The point stays the same – less code and fewer dependencies mean a shorter download and faster module loading, and therefore a shorter cold start.\n\n## The second lever: init code in the right place\n\nNow comes the part that makes the biggest difference in practice and at the same time is most often done wrong: where do you create your clients and connections?\n\nEverything you write at module level outside the handler runs exactly once per execution environment – in the Init phase. On every following warm invoke, the result is reused. That is exactly where everything belongs that is reusable and stable across calls: SDK clients, database pools, parsed configuration.\n\n```ts\n// module scope — runs once per execution environment (Init phase)\nimport { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\nimport { GetItemCommand } from \"@aws-sdk/client-dynamodb\";\n\n// created once, reused across every warm invoke\nconst client = new DynamoDBClient({});\n\nexport const handler = async (event: { id: string }) => {\n  const result = await client.send(\n    new GetItemCommand({\n      TableName: \"orders\",\n      Key: { id: { S: event.id } },\n    })\n  );\n\n  return { statusCode: 200, body: JSON.stringify(result.Item) };\n};\n```\n\nThe `DynamoDBClient` is created once here and then stays in the environment. Every warm invoke accesses the same instance – including the HTTP connections already established. This is where an often overlooked advantage of AWS SDK v3 lies: HTTP keep-alive is enabled by default. So the TCP and TLS handshakes only happen on the first call and are reused afterwards.\n\nA short but practically relevant note on migration: with the older AWS SDK v2, keep-alive was not on automatically. There you have to set the environment variable `AWS_NODEJS_CONNECTION_REUSE_ENABLED=1` (available from v2.463.0) to get the same behavior. If you still run v2 code, you should check this – it’s one of the cheapest latency improvements there is.\n\n### Lazy init for what not every invoke needs\n\nNot every resource should go into the Init phase. If you only actually need an expensive connection in one out of twenty calls, building it at module level lengthens every single cold start – including those that never use it. This is where lazy init pays off: the resource is only created when it’s first actually needed and is then cached for the lifetime of the environment.\n\n```ts\nimport { createPool, type Pool } from \"./db\";\n\nlet dbPromise: Promise<Pool> | undefined;\n\n// created on first use, then cached for the environment's lifetime\nconst getDb = (): Promise<Pool> => (dbPromise ??= createPool());\n\nexport const handler = async (event: { needsDb: boolean }) => {\n  if (!event.needsDb) {\n    return { statusCode: 204 };\n  }\n\n  const db = await getDb();\n  const rows = await db.query(\"SELECT 1\");\n  return { statusCode: 200, body: JSON.stringify(rows) };\n};\n```\n\nThe `??=` operator makes sure the pool is built only a single time. The first call that really needs it incurs a small delay – in return, the Init phase stays lean and fast, and all invokes that don’t need the pool pay nothing for it. It’s the balance between “everything up front” and “everything per call,” and the right boundary depends on how often a resource is actually needed.\n\n## The third lever: memory is also CPU\n\nThis is the knob that is underestimated the most because it has a misleading name. The configuration value is called `MemorySize` and can be set between 128 MB and 10,240 MB in 1 MB steps. But it doesn’t only control memory: CPU is allocated linearly in proportion to memory. At exactly 1,769 MB, your function gets one full vCPU; at the top end, up to 6 vCPUs are available.\n\nThat has immediate consequences. A function that does CPU-bound work – parsing JSON, cryptography, data preparation – gets faster with more memory, even though it doesn’t need the extra memory at all. And interestingly, this also applies to the cold start itself: loading and initializing the runtime is CPU work that benefits from more allocated computing power.\n\nThe mistake I see most often here is one of two extremes. Either the function stays at 128 MB to save money and is therefore unnecessarily slow under CPU load – or someone blindly cranks memory up to a high level in the hope that “more helps more.” Both are guessing. More memory costs more per millisecond, and beyond a certain point it brings no latency gain because the function is no longer CPU-bound but I/O-bound. Then you’re waiting for a database or an external API, and no extra vCPU helps with that.\n\nThe only serious answer is measuring. For exactly this purpose, there is the open-source tool AWS Lambda Power Tuning, which tries your function with different memory values and plots cost against latency. Instead of guessing, you see the actual curve for your specific workload and pick the point that fits your goal.\n\n## The fourth lever: Provisioned Concurrency for predictable latency\n\nSometimes shortening the cold start isn’t enough – you want to avoid it entirely for certain functions. That’s the case for latency-critical, well-predictable loads: a function behind a login flow, an endpoint that gets a predictable load peak at nine o’clock on weekdays.\n\nThat’s what Provisioned Concurrency is for. Using `ProvisionedConcurrentExecutions`, you configure a number of environments that Lambda keeps permanently pre-initialized – with the Init phase already run. Calls then hit a warm environment without a cold start occurring. The important detail is that Provisioned Concurrency is configured on an alias or a specific version, not on `$LATEST`. If you also want to adapt these environments to a fluctuating load, you can scale them dynamically with Application Auto Scaling.\n\nThat costs real money, though, and independently of load: pre-provisioned environments are billed even when they sit idle. Provisioned Concurrency is therefore not a cure-all you lay over every function, but a targeted tool for the few places where predictable, low latency justifies the surcharge. For most background and event-driven functions, the occasional cold start is completely uncritical – there, Provisioned Concurrency would be money thrown away.\n\nA side note, because the question often comes up in reviews: for Java, there has also been Lambda SnapStart since the end of 2022, which works from a snapshot of the initialized environment. For Node.js, it’s currently not an option – SnapStart is Java-only at this point. For our TypeScript functions, the levers above remain the relevant ones.\n\n## Measure, don’t guess\n\nThe common thread through all these levers is the same: without measurement, every optimization remains a gut feeling. Fortunately, Lambda delivers the decisive numbers for free. Every invoke writes a REPORT line to the CloudWatch logs, and for a cold start it contains an additional field:\n\n```json\n{\n  \"Duration\": \"42.11 ms\",\n  \"BilledDuration\": \"43 ms\",\n  \"MaxMemoryUsed\": \"98 MB\",\n  \"InitDuration\": \"312.44 ms\"\n}\n```\n\nThe `InitDuration` field appears only on a cold start – it is exactly the time for the download, runtime init and your function init code. If you find this line in the logs, you know two things: first, this was a cold start. Second, the number shows you how expensive your Init phase really is. If `InitDuration` climbs toward seconds, that’s a clear signal that too much is happening at module level.\n\nIf you want to look deeper, enable AWS X-Ray. There, initialization shows up as its own subsegment in the trace, cleanly separated from handler time. This is especially valuable when you want to find out whether your latency comes from the cold start or from a slow downstream call in the handler – two completely different problems that can’t be told apart in the plain total.\n\n## The levers at a glance\n\nIf I had to summarize the concrete knobs, I’d end up with a compact list that I like to use as a checklist in reviews:\n\n- Keep the bundle small with esbuild and tree shaking; mark the AWS SDK available in the runtime as `external`.\n- Use few dependencies and keep the import graph deliberately lean.\n- Create reusable clients and connections outside the handler and reuse them across warm invokes.\n- Lazy init for expensive, rarely used resources so the Init phase stays lean.\n- Understand memory as a CPU dial and tune it empirically – with Lambda Power Tuning instead of gut feeling.\n- Use Provisioned Concurrency selectively for the few latency-critical, predictable functions.\n- Measure Init Duration in CloudWatch and X-Ray instead of guessing.\n\n## Conclusion\n\nCold starts are not a flaw but a property of Lambda’s execution model – and that is exactly why they can be controlled once you understand the model. The Init phase runs once per execution environment, warm invokes skip it, and almost everything you can adjust about latency depends on how heavy or light you make this Init phase.\n\nIn practice, there’s no single big solution here. What works is an interplay of small, understandable decisions: a lean bundle, clients in the right place, a sensibly chosen memory value and – only where it really pays off – Provisioned Concurrency. And above all of it is always measurement. If you keep an eye on Init Duration, you turn the vague “sometimes slow” into a number you can work on. That is the real gain: a gut feeling becomes an engineering problem with clear levers.\n\nIn the bigger picture, Lambda remains just one building block. API, persistence, identity, asynchronous processing and observability have to be considered together; a fast function alone doesn’t make a resilient system.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-aws-serverless.en.html\n- [Lambda execution environment lifecycle](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html)\n- [Configure function memory (Memory = CPU)](https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html)\n- [Understanding and remediating cold starts (AWS Compute Blog)](https://aws.amazon.com/blogs/compute/understanding-and-remediating-cold-starts-an-aws-lambda-perspective/)\n- [Operating Lambda: Performance optimization – Part 1](https://aws.amazon.com/blogs/compute/operating-lambda-performance-optimization-part-1/)\n- [Reuse connections with keep-alive (AWS SDK v3)](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-reusing-connections.html)\n- [Reuse connections with keep-alive (AWS SDK v2)](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-reusing-connections.html)\n- [Lambda function scaling and Provisioned Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html)"},{"locale":"en","translation_key":"rxjs-in-node-ereignisstroeme","slug":"rxjs-in-nodejs-event-streams","title":"RxJS in Node.js: Processing Event Streams Reactively","summary":"RxJS in Node.js: how fromEvent turns an EventEmitter into an observable, how operators transform server-side streams declaratively and why RxJS has no real backpressure.","tags":["Software","Node.js","Backend"],"published_at":"2023-07-25T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/rxjs-in-nodejs-event-streams/","audio_url":null,"audio_duration_secs":null,"text":"```js\nlet buffer = [];\nlet timer = null;\n\nemitter.on('data', line => {\n  const entry = JSON.parse(line);\n  if (entry.level !== 'error') return;\n  buffer.push(entry);\n  if (!timer) {\n    timer = setTimeout(() => {\n      saveErrors(buffer);\n      buffer = [];\n      timer = null;\n    }, 1000);\n  }\n});\n```\n\nThere are three requirements in this handler: parse, filter, write out in bundles once per second. The intermediate state lives in two module variables, and the only way left to test it is with fake timers. If a second consumer comes along tomorrow, or you also need to group by service, the nesting keeps growing – and with it the number of places where the shared state can tip over.\n\nThis is exactly where RxJS comes in: wherever an event stream should become a composable program. If you’ve already looked at the imperative foundation – for example in the post on [EventEmitter and the event model](https://www.mikebild.dev/en/blog/eventemitter-the-event-model-at-the-core-of-nodejs/) – you’ll recognize the same idea in RxJS, just approached from the other side.\n\n## From on/emit to declarative streams\n\nThe `EventEmitter` is imperative. I say: “When `data` happens, run this function.” That is a command. Each handler is its own little island, and if I want to chain several steps, I connect them by hand through shared state.\n\nRxJS describes the same event stream declaratively. I no longer say “do this when that happens” but “this stream is the source, transformed by this chain of steps.” The chain is a description, not an execution. It only gets activated on `subscribe`.\n\nThe bridge between the two worlds is `fromEvent`. The operator takes a Node `EventEmitter` and an event name and returns an observable:\n\n```js\nconst { EventEmitter } = require('events');\nconst { fromEvent } = require('rxjs');\n\nconst emitter = new EventEmitter();\nconst data$ = fromEvent(emitter, 'data');\n\nconst subscription = data$.subscribe({\n  next: value => console.log('received', value),\n});\n\nemitter.emit('data', { level: 'info', message: 'server started' });\n```\n\n`fromEvent(emitter, 'data')` doesn’t change anything about the emitter’s semantics. On every `subscribe` it registers a listener via `addListener` and removes it again on `unsubscribe`. That makes the observable an adapter: the emitter stays the source, and RxJS just puts a composable layer on top. If you want to dig deeper into the difference between the push model of observables and the pull model of iterators, you’ll find it in the post on [RxJS: push and pull](https://www.mikebild.dev/en/blog/rxjs-telling-push-and-pull-apart/).\n\nA note on convention: I append a `$` to variables that hold an observable (`data$`). It isn’t required, but it has become common in the RxJS world and makes it immediately visible in the code what is a stream and what is a single value.\n\n## The pipeline: operators as pure functions\n\nThe real gain lies in the operators. They are pure functions that take an observable and return a new one. You chain them with `.pipe(...)`. In RxJS 7, I import everything – creation functions like `fromEvent` and operators like `map` – directly from `'rxjs'`. The old import from `'rxjs/operators'` still works but is outdated.\n\nA typical server-side example is log processing. I want to parse incoming raw lines into objects, keep only the errors and write them out in bundles once per second, instead of touching the database for every single line:\n\n```js\nconst { fromEvent } = require('rxjs');\nconst { map, filter, bufferTime } = require('rxjs');\n\nconst logStream$ = fromEvent(logEmitter, 'line').pipe(\n  map(line => JSON.parse(line)),\n  filter(entry => entry.level === 'error'),\n  bufferTime(1000),\n);\n\nconst subscription = logStream$.subscribe({\n  next: batch => saveErrors(batch),\n  error: err => console.error('stream failed', err),\n});\n```\n\nWhat’s written here reads almost like a description of the requirement. `map` transforms every value, `filter` lets only matching ones through, `bufferTime(1000)` collects over a one-second time window and then emits an array. So the `next` handler doesn’t receive individual entries but one bundle at a time – or an empty array if nothing came in during the window.\n\nEach step is understandable on its own and testable on its own. And if tomorrow the requirement comes to also group by service, I insert an operator instead of restructuring a nested callback structure.\n\nA second pattern from practice: throttling sensor data while computing a running average. Suppose a device fires much more often than I want to process:\n\n```js\nconst { fromEvent } = require('rxjs');\nconst { throttleTime, scan } = require('rxjs');\n\nconst average$ = fromEvent(sensor, 'reading').pipe(\n  map(event => event.value),\n  throttleTime(500),\n  scan((sum, value, index) => (sum * index + value) / (index + 1), 0),\n);\n\naverage$.subscribe({ next: avg => console.log('running average', avg) });\n```\n\n`throttleTime(500)` lets one value through and then ignores all others for 500 milliseconds. `scan` behaves like `reduce` but emits every intermediate result – so with every measurement that gets through, I get the updated average. This combination of running aggregation and time window is sketched in the repository under `operators.js`, although there it still uses the older RxJS 6 import style.\n\nIf I want to trigger asynchronous follow-up processing for each event – such as loading details – `mergeMap` helps. It maps every value to an inner observable and flattens the results concurrently. The second parameter limits how many inner operations may run at the same time:\n\n```js\nconst { mergeMap } = require('rxjs');\n\nconst details$ = ids$.pipe(\n  mergeMap(id => fetchDetails(id), 4),\n);\n```\n\nWith `mergeMap(id => fetchDetails(id), 4)`, at most four requests run in parallel. This limit matters, for a reason that will play its own role in a moment.\n\nThe rough flow through such a pipeline always looks the same:\n\n```mermaid\nflowchart LR\n  E[EventEmitter] -->|emit data| F[\"fromEvent<br/>(Observable)\"]\n  F --> M[map]\n  M --> FI[filter]\n  FI --> B[bufferTime]\n  B --> S[Subscriber]\n```\n\n## A Subject: turning one stream into many consumers\n\nSo far, every stream had exactly one consumer. As soon as several parts of the application need the same event stream, the `Subject` comes into play. A `Subject` is both an Observer and an Observable: I can push values into it, and others can subscribe to it. It distributes every value to all subscribers at the same time – multicast.\n\n```js\nconst { fromEvent, Subject } = require('rxjs');\n\nconst bus = new Subject();\n\n// one source feeds the bus\nfromEvent(emitter, 'data').subscribe(bus);\n\n// multiple consumers share the same stream\nconst loggerSub = bus.subscribe({ next: v => logger.write(v) });\nconst metricsSub = bus.subscribe({ next: v => metrics.record(v) });\n\n// clean up later\nloggerSub.unsubscribe();\nmetricsSub.unsubscribe();\n```\n\nThe difference from subscribing directly to the source observable is fundamental. If `logger` and `metrics` both subscribed to `fromEvent(emitter, 'data')`, the emitter would have two listeners and the source would run twice. With the `Subject`, there is one execution whose values are distributed to all subscribers.\n\nThat is the core of the distinction between unicast and multicast:\n\n```mermaid\nflowchart LR\n  P[Producer] --> SUB[Subject]\n  SUB --> C1[Logger subscriber]\n  SUB --> C2[Metrics subscriber]\n  SUB --> C3[Audit subscriber]\n```\n\nBesides the plain `Subject`, there are variants that fit different use cases:\n\n- `BehaviorSubject(seed)` holds the last value and delivers it to every new subscriber immediately. Handy for state that a late consumer needs to know.\n- `ReplaySubject(bufferSize)` buffers the last n values and replays them to new subscribers.\n- `AsyncSubject` emits only the very last value, and only on `complete`.\n\nIn the repository under `subject.js`, you can see the basic principle: the same source, several `subscribe` calls. It still uses the positional `subscribe(next, error, complete)` form there. In RxJS 7, I use the object observer `subscribe({ next, error, complete })` throughout instead – more on that in a moment under pitfalls.\n\n## Hot and cold: the difference that skews results\n\nOne point that reliably causes confusion in teams is the question of when an observable’s source comes into existence.\n\nA cold observable creates its producer per `subscribe`. Every subscriber gets its own fresh execution – unicast. A `from([1, 2, 3])` is cold: everyone who subscribes sees the values 1, 2, 3 from the start.\n\nA hot observable has its producer outside. The values are produced whether or not anyone is listening. If you subscribe late, you miss what happened before – multicast. A `Subject` is hot, and a `fromEvent` over an emitter that’s already running behaves hot as well: the events fire anyway, and I just hook in.\n\nThis distinction is not theory. If you expect that “every subscriber starts fresh” but are actually looking at a hot stream, late consumers simply get wrong results – missing initial values, an aggregation that starts in the middle of the stream. If I want a late subscriber to also see the latest state or the history, that is exactly the case for `BehaviorSubject`, `ReplaySubject` or the `shareReplay` operator.\n\n## The important distinction: RxJS has no real backpressure\n\nThis point should be cleared up early; otherwise expectations arise that the tool doesn’t meet. If you know Node streams, you know backpressure: a readable stream can pause, a `highWaterMark` limits the buffer, `pipe` regulates the flow between producer and consumer automatically. The fast producer gets slowed down when the slow consumer can’t keep up.\n\nRxJS doesn’t have this. There is no built-in mechanism for a subscriber to force the source to slow down. A `Subject` or a `fromEvent` pushes values as soon as they’re there, whether or not processing keeps up.\n\nWhat RxJS offers instead are time-based and buffering operators:\n\n- `throttleTime(ms)` lets one value through and then drops all others for a while.\n- `debounceTime(ms)` waits for a quiet period and then emits the last value.\n- `sampleTime(ms)` takes the current value at fixed intervals.\n- `bufferTime(ms)` collects over a window and delivers bundles.\n- the `concurrent` limit of `mergeMap` caps the number of parallel inner operations.\n\nThe key difference: these operators drop or aggregate values, but they don’t slow down the source. The producer keeps firing unchanged; I only reduce what arrives at the end. For a log display or sensor data, that’s often exactly right – dropping a few intermediate values is harmless. For processing where every single value must count and the source really needs to be throttled, Node streams are the right tool, not RxJS.\n\nYou can connect both worlds. The repository shows the bridge via `rxjs-stream` under `node.js`:\n\n```js\nconst { spawn } = require('child_process');\nconst { streamToRx } = require('rxjs-stream');\nconst { map } = require('rxjs');\n\nstreamToRx(spawn('ls', ['-lha']).stdout)\n  .pipe(map(chunk => chunk.toString()))\n  .subscribe({ next: text => console.log(text) });\n```\n\n`streamToRx` turns a Node readable into an observable while keeping the stream’s backpressure in the lower part. That way, I get the composability of RxJS for the transformation without giving up the stream’s flow control. If you want to refresh the basics of the event loop and the stream architecture behind it, you’ll find them in the [Node.js training](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/).\n\n## Pitfalls I run into again and again\n\nTwo mistakes show up so regularly that I’ll name them explicitly here.\n\nThe first is the subscription leak. `fromEvent` registers a listener on the emitter with every `subscribe`. Without `unsubscribe()`, this listener stays attached – even when the processing is long no longer needed. The result is a memory leak and a pipeline that keeps running unnoticed. The rule is simple: I keep the subscription that `.subscribe()` returns and call `unsubscribe()` when I’m done. Alternatively, I limit the stream declaratively with `take(n)` or `takeUntil(stop$)` so that it ends itself:\n\n```js\nconst { fromEvent, timer } = require('rxjs');\nconst { takeUntil } = require('rxjs');\n\nconst stop$ = timer(60000);\n\nfromEvent(emitter, 'data')\n  .pipe(takeUntil(stop$))\n  .subscribe({ next: v => process(v) });\n```\n\nHere `takeUntil` cleans up after 60 seconds without me having to manage the subscription myself. On long-running servers, one of these two strategies is mandatory; otherwise listeners pile up over time.\n\nThe second pitfall is mixing up hot and cold, which I described above – it almost always shows up as “my second subscriber doesn’t get the same values.” The answer is usually a `Subject` of the right variant or `shareReplay`.\n\nAnd a third, more craft-related point: many examples on the web, and the older snippets in the repository too, still use RxJS 6 patterns. Concretely, for RxJS 7 that means:\n\n- Instead of `subscribe(next, error, complete)` with separate arguments, use the object observer `subscribe({ next, error, complete })` – the positional form has been deprecated since 6.4.\n- Instead of `tap(fn, errFn)` with several callbacks, also use the object observer.\n- Import operators from `'rxjs'` instead of `'rxjs/operators'`.\n\nThese changes are mechanical but important, so that the code doesn’t build on a pattern that is going away.\n\n## When RxJS instead of a raw EventEmitter?\n\nNot every Node application needs RxJS. A single `on('data', ...)` handler stays leaner with a plain `EventEmitter` and has no extra dependency. I reach for RxJS when at least one of these points applies:\n\n- I have to chain several processing steps – transform, filter, aggregate – and don’t want to solve that with nested callbacks and shared state.\n- I need time-based control: throttling, debouncing, bundling in windows.\n- Several consumers should process the same event stream independently (multicast via a `Subject`).\n- The stream should end cleanly and declaratively, for example via `takeUntil`.\n- The processing code should break down into small building blocks that are testable on their own.\n\nConversely, I stick with the raw emitter or reach for Node streams when it’s just a single simple handler or when I need real backpressure all the way through.\n\n## Conclusion\n\nIn Node.js, RxJS shifts the perspective from command to description. The `EventEmitter` says what to do on every event; RxJS describes the whole event stream as a composable chain of pure functions. `fromEvent` is the bridge there without changing anything about the emitter’s semantics, and a `Subject` turns one stream into many consumers.\n\nTwo things you should never forget. First, discipline when cleaning up: without `unsubscribe`, `take` or `takeUntil`, listeners and processing stay alive. Second, the honest limit of the tool: RxJS handles overload only in a time-based and buffering way, not through real backpressure. If you keep these two points in mind, RxJS gives you a very pleasant way to process server-side event streams – readable, testable and extensible, without sinking into a thicket of callbacks.\n\n## Further reading\n\n- Repository examples: `/Users/mikebild/Documents/introduction-nodejs/EXAMPLES/RXJS/operators.js`, `.../subject.js`, `.../node.js`\n- [fromEvent](https://rxjs.dev/api/index/function/fromEvent)\n- [Subject guide](https://rxjs.dev/guide/subject)\n- [Observable guide](https://rxjs.dev/guide/observable)\n- [Operators guide](https://rxjs.dev/guide/operators)\n- [mergeMap](https://rxjs.dev/api/operators/mergeMap)\n- [throttleTime](https://rxjs.dev/api/index/function/throttleTime)\n- [bufferTime](https://rxjs.dev/api/operators/bufferTime)\n- [scan](https://rxjs.dev/api/operators/scan)\n- [subscribe arguments (deprecation)](https://rxjs.dev/deprecations/subscribe-arguments)\n- [Glossary and semantics: hot/cold, unicast/multicast](https://rxjs.dev/guide/glossary-and-semantics)\n- [Node.js events](https://nodejs.org/docs/latest-v18.x/api/events.html)"},{"locale":"en","translation_key":"evolutionary-architecture-wandel-einplanen","slug":"evolutionary-architecture-systems-allowed-to-change","title":"Evolutionary Architecture: Systems That Are Allowed to Change","summary":"Architecture is not an end state that you lock down once. Small changes and suitable fitness functions make selected risks visible earlier, but they guarantee neither speed nor quality.","tags":["Software","Architecture"],"published_at":"2023-06-26T10:00:00+00:00","updated_at":"2026-07-13T08:50:24.240283+00:00","url":"https://www.mikebild.dev/en/blog/evolutionary-architecture-systems-allowed-to-change/","audio_url":null,"audio_duration_secs":null,"text":"Evolutionary Architecture is not a license for uncontrolled growth, nor is it another word for “agile.” In *Building Evolutionary Architectures* (O'Reilly 2017, second edition 2022), Neal Ford, Rebecca Parsons and Patrick Kua define it as an architecture that supports “guided, incremental change across multiple dimensions.” Three words carry this definition. Guided: there are named characteristics that are protected. Incremental: each individual change is small enough to be rolled back. Multiple dimensions: this means not just the code but equally data, operations and the organization that carries both.\n\nThe counter-model is the frozen system. Cleanly designed three years ago, for a world that no longer exists in that form – and not moved since, because every change seemed too risky. The diagrams still hang on the wall, but they describe a car nobody drives anymore. Behind this lies a stubborn basic assumption: that architecture is something you get right once and then defend, a target picture you reach. But no system in production use stands still. Requirements shift, load profiles change, teams grow, dependencies age. The question is never whether a system changes, only whether the architecture accompanies this change or stands in its way.\n\nEvolutionary Architecture therefore turns the perspective around: instead of treating change as an exception to avoid as much as possible after go-live, it makes change the norm that you build for from the start. A system that is allowed to change – in small steps, and without breaking the characteristics that make it valuable.\n\n## Why end-state thinking gets expensive\n\nThe classic reflex is called Big Design Up Front. You think as far ahead as possible, decide everything important early and cast the result into a target picture. That feels responsible. And thinking early is not fundamentally wrong – quite the opposite. What is wrong is the expectation that these early decisions will hold for good.\n\nThe flaw lies in the timing. At the very beginning of an undertaking, you know the least about the domain, the users and the real behavior under load. That is exactly when you make the most far-reaching decisions. Every later insight then has to assert itself against a structure that was not made for it. This is the moment when teams start working around the architecture instead of with it. The technical term for this is architectural drift or erosion: the real system moves away, piece by piece, from the intended one, until the diagram on the wall is mere folklore.\n\nThe business damage is rarely a spectacular outage. It creeps in. Changes take longer. Every adjustment needs more coordination. New features collide with old assumptions. Time to market rises while confidence falls. And at some point the question comes up whether it would be better to rebuild everything – the most expensive of all options.\n\n## The shift in perspective: guided evolution instead of a fixed target\n\nThe way out is not a different target picture but a different way of dealing with target pictures. Instead of defining and defending an end state, you define the characteristics the system should keep and let the structure evolve within these guardrails.\n\n```mermaid\nflowchart LR\n  A[Change<br/>small increment] --> B[Deployment pipeline]\n  B --> C{Fitness functions<br/>guardrails}\n  C -->|pass| D[Learn & Adjust]\n  C -->|fail| E[Stop & Fix]\n  E --> A\n  D --> A\n```\n\nThe core is a feedback loop, not a waterfall. A small change runs through the deployment pipeline, is checked against defined guardrails, delivers clear feedback – passed or not – and the team learns from it for the next step. Small, guided, repeatable. That is the difference between a system that evolves and one that just gets older.\n\nThe emphasis on guided is important. Evolutionary explicitly does not mean “no architecture” or “we let it grow however it wants.” That is the most common fallacy. Uncontrolled growth is not evolution but its opposite. Without consciously named, prioritized architecture characteristics, there is nothing to protect and nothing to measure. The first step is therefore not a technique but a decision: What exactly must distinguish this system? Response time under a certain limit? Loose coupling between business areas? Demonstrable security at the edges? Only when these goals are explicit can you defend them.\n\n## Fitness functions: architecture you can measure\n\nThe mechanism used to defend these goals is called a fitness function. The term is borrowed from evolutionary algorithms, where a fitness function evaluates how close a solution is to the desired result. Applied to architecture, according to the authors, it means: “any mechanism that provides an objective integrity assessment of some architectural characteristic(s).” In other words, any mechanism that objectively checks whether an architectural characteristic is still intact.\n\nThe decisive word here is objective. A fitness function is not a meeting, not a gut feeling and not an architecture review board that meets once a quarter and passes judgment on slides. It is an automated test that runs in the pipeline and delivers an unambiguous result. This shifts governance from manual control toward something versioned, executable and repeatable at any time – not for nothing does the second edition carry the subtitle “Automating Software Governance.”\n\nThe simplest and best-known example is structural rules. With a library like ArchUnit, you can express an architecture rule as a perfectly ordinary unit test:\n\n```java\n@ArchTest\nstatic final ArchRule domain_must_not_depend_on_infrastructure =\n    noClasses().that().resideInAPackage(\"..domain..\")\n      .should().dependOnClassesThat().resideInAPackage(\"..infrastructure..\");\n```\n\nThis rule says: the domain layer must not access the infrastructure. Until now, something like that lived in a wiki and was hopefully noticed in code reviews. Now the build breaks as soon as someone violates the boundary – on the same day it happens, not three months later in a refactoring retrospective. The intent turns from a comment into an executable fact.\n\nAnd this is exactly where the second big fallacy lies: fitness functions are not limited to such package and layering checks. That is just the most visible category. Anything you can check objectively about an architecture is a candidate – performance budgets, security scans, checks for cyclic dependencies, even chaos experiments or monitoring-based checks in live operation.\n\nThe authors organize this into a small taxonomy that helps you spot gaps in everyday work. Fitness functions can be atomic (checking a single characteristic) or holistic (checking how several work together). They can be triggered (running on an event, for example in the build) or continual (running permanently in production). And they can be static (fixed threshold) or dynamic (threshold depending on context). If you only have structural, atomic, triggered rules, you cover one corner and miss the rest.\n\nA performance budget, for example, is rather holistic and can be expressed as a gate in the pipeline:\n\n```yaml\nfitness_functions:\n  - name: p95_latency_budget\n    metric: http_request_duration_p95_ms\n    threshold: 300\n    on_breach: fail_build\n  - name: max_module_coupling\n    metric: afferent_efferent_coupling_ratio\n    threshold: 0.7\n    on_breach: warn\n```\n\nThe pattern is always the same: an architectural characteristic, an objective threshold, a defined consequence. If the 95th percentile latency breaks the budget, the build fails. If coupling rises above the limit, there is a warning at first. You do not have to enforce everything strictly – but you make the characteristic visible and decide consciously how strictly you treat it.\n\n## Coupling is the real brake\n\nWhen a system can no longer be changed in small steps, coupling is almost always the reason. Not only the obvious kind between classes, but also hidden temporal coupling and data coupling. Two services that always have to be deployed together. A schema that three teams have to touch at the same time to change one field. As long as these ties exist, incremental change is impossible, no matter how good the intent.\n\nThat is why controlling coupling itself is one of the most important fitness functions. And that is why a few proven patterns make the difference here. Martin Fowler’s Strangler Fig Application describes how to replace a legacy system incrementally by letting new functionality grow around the old core like a strangler fig until the core can eventually disappear – without the one big, risky switchover. At the data level, the expand-contract pattern (also called parallel change) does the same: you expand a schema, migrate step by step and remove the old part only when nobody needs it anymore. This makes refactoring a normal, safe movement instead of a feat of strength.\n\nAt the operations level, resilience patterns such as Circuit Breaker and Bulkhead from Michael Nygard’s *Release It!* make sure that the loosely coupled parts do not drag each other down during failures. And at the service edges, Consumer-Driven Contract Testing keeps the boundaries honest: every consumer describes what it expects from a service, and this contract is checked automatically. If the service changes incompatibly, the test fails before the user notices. That too is a fitness function – one that safeguards changeability at the most expensive breaking points.\n\nA word on Conway’s Law, because coupling is not only technical. Systems mirror the communication structures of the organizations that build them. If you want loosely coupled software, you also have to cut the teams accordingly. That is not a side note but often the precondition for the technical guardrails to take effect at all.\n\n## The proof that it pays off\n\nAt this point comes the objection: sounds good, but all this automation and constant change – doesn’t it come at the expense of stability? Faster means riskier, doesn’t it?\n\nThe data says the opposite. The DORA research, summarized in *Accelerate* (Forsgren, Humble, Kim, 2018), shows across thousands of organizations that speed and stability are not opponents but rise together. The highest-performing teams deploy more often *and* have fewer outages *and* recover faster. The supposed trade-off between pace and reliability is an artifact of the old thinking – the result of rare, large, risky releases.\n\nThe four classic DORA metrics read like system-wide fitness functions themselves:\n\n```text\nDeployment Frequency     - wie oft deployen wir?\nLead Time for Changes    - wie lange von Commit bis Produktion?\nChange Failure Rate      - wie viele Deployments verursachen einen Fehler?\nTime to Restore Service  - wie schnell sind wir wieder online?\n```\n\nThey do not measure a single module but the changeability of the whole system. Shorter cycles, less friction and higher quality thus become quantities you can hook into the same feedback loop logic as a latency limit.\n\n```mermaid\nflowchart TB\n  subgraph Old[Architecture as end-state]\n    O1[Big Design Up Front] --> O2[freeze] --> O3[drift & erosion]\n  end\n  subgraph New[Architecture as guarded evolution]\n    N1[named characteristics] --> N2[fitness functions] --> N3[small guarded change] --> N1\n  end\n```\n\nIncidentally, this frame of thinking is not limited to technology. It is the same principle that *The Lean Startup* formulated for products – Build, Measure, Learn: a hypothesis, a small step, a measurement, an adjustment. Architecture evolution is the technical expression of the same attitude. You do not claim to know the right structure. You build in a way that lets you find it out cheaply.\n\n## Conclusion\n\nArchitecture is not an end state. It is a system’s ability to keep changing without losing the characteristics that make it valuable. If you take this seriously, you stop defending a target picture and start protecting the right things.\n\nThe way there is surprisingly concrete. First: name the architecture characteristics that really count – not all of them, but the few that make the difference. Second: for each of these characteristics, build a fitness function that checks objectively, automatically and in the pipeline whether it still holds – structurally, but also for performance, security and coupling. Third: actively keep coupling low, technically and organizationally, so that small steps remain possible at all. And fourth: trust the whole thing, because the data shows that pace and stability grow together.\n\nThe approach does not create short cycles by itself, and it does not guarantee stable quality. It makes named characteristics verifiable earlier when you make small changes. Whether that reduces friction or speeds up changes only shows in the real delivery flow. For me, the best architecture is therefore not the one that is supposed to be right forever, but one whose assumptions can be checked and changed when new insights arrive.\n\n## Further reading\n\n- Neal Ford, Rebecca Parsons, Patrick Kua: *Building Evolutionary Architectures*, O'Reilly, 1st ed. 2017 / 2nd ed. 2022 (with Pramod Sadalage)\n- Martin Fowler: [Foreword to Building Evolutionary Architectures](https://martinfowler.com/articles/evo-arch-forward.html)\n- [DORA – Four Key Metrics](https://dora.dev/guides/dora-metrics-four-keys/)\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate*, IT Revolution, 2018\n- [ArchUnit – unit tests for architecture rules](https://www.archunit.org/)\n- [InfoQ – Fitness Functions for Your Architecture](https://www.infoq.com/articles/fitness-functions-architecture/)\n- Michael Nygard: *Release It!*, Pragmatic Bookshelf, 2nd ed. 2018"},{"locale":"en","translation_key":"von-hocs-und-render-props-zu-custom-hooks","slug":"from-hocs-and-render-props-to-custom-hooks","title":"From HOCs and Render Props to Custom Hooks","summary":"How do I share logic between components without copy-paste? Custom hooks usually avoid nested wrappers for this; HOCs and render props keep a few specific composition tasks.","tags":["Software","Frontend","React"],"published_at":"2023-06-20T10:00:00+00:00","updated_at":"2026-07-13T08:50:07.649617+00:00","url":"https://www.mikebild.dev/en/blog/from-hocs-and-render-props-to-custom-hooks/","audio_url":null,"audio_duration_secs":null,"text":"Four levels in the React DevTools tree before the first one appears that actually renders something visible: `withRouter`, below it `withLoading`, below that `withData`, and at the very bottom the actual page. Three of these levels contribute nothing to the output. They exist only to pass state and behavior from the outside in.\n\nThis tree is no accident but the logical consequence of a decision React carried around for years. Reusing stateful logic in several places without duplicating it is something the framework solved differently in three generations – and the first two solutions pay for it with exactly such levels. If you know the sequence, you also understand why the older patterns are still not worthless.\n\n## The same old question\n\nAn example that shows this well: a component needs to know whether the browser is currently online. That takes state, it takes an effect with event listeners, and it takes cleanup. If three components need this, nobody wants to write the same block three times.\n\nThe naive solution is copy-paste. It works exactly until the logic changes – then you change it in one place and forget the other two. From that point on, React developers look for a mechanism that keeps the logic in exactly one place.\n\nHistorically, the path there looked like this:\n\n```mermaid\ngraph LR\n  A[Copy-Paste] --> B[Mixins<br/>deprecated]\n  B --> C[HOCs &<br/>Render Props]\n  C --> D[Custom Hooks<br/>React 16.8 / 2019]\n```\n\nMixins were the first answer in the very early days of `createClass`, but they were quickly discarded as problematic – unclear origin of properties, name collisions, implicit dependencies. After that came two patterns that dominated for a long time: higher-order components and render props. And since React 16.8 – stable since February 2019 – there are custom hooks. Let’s look at the three relevant answers in order.\n\n## Answer 1: Higher-order components\n\nA higher-order component is basically an old acquaintance from functional programming. Just as a higher-order function takes a function and returns a new function, a HOC takes a component and returns a new, enhanced component. The signature is:\n\n```js\n// a function that takes a component and returns a new component\nconst withSomething = (Component) => EnhancedComponent;\n```\n\nThe naming convention is `withXxx`. Let’s take the classic example `withLoading`, which encapsulates a loading state:\n\n```jsx\nimport { Fragment } from \"react\";\n\nfunction withLoading(Wrapped) {\n  return function WithLoading(props) {\n    if (props.loading) {\n      return <Spinner />;\n    }\n    return <Wrapped {...props} />;\n  };\n}\n```\n\nThe whole thing is applied at module level, not in render:\n\n```jsx\nconst UserPageWithLoading = withLoading(UserPage);\n```\n\nThat reads cleanly. And it composes: you can stack several HOCs, `withRouter(withLoading(withData(Page)))`. But that is exactly where it has its price.\n\nThe fact that application has to happen outside of render seems like a formality – until you violate it once. If you create a HOC directly in `render()`, a new component identity is created on every pass. React sees a different type, unmounts the entire subtree and rebuilds it – all the state below it is lost. That is one of those bugs you debug live once and then never produce again.\n\nOn top of that come two more pitfalls you need to know:\n\n- Static methods of the original component disappear, because the wrapper doesn’t copy them along automatically – you need something like `hoist-non-react-statics`.\n- Refs don’t pass through the wrapper as a normal prop. If you need a ref to the inner component, you have to resort to `React.forwardRef` (available since React 16.3).\n\nAnd the basic rule that holds it all together: composition instead of mutation. A HOC doesn’t mutate the component passed in; it wraps it in a container. As soon as someone starts changing the original component directly, the pattern is broken.\n\n## Answer 2: Render props\n\nThe second pattern turns the tables. Instead of wrapping one component in another, you give a component a function that tells it what to render. That is a render prop: “a function prop that a component uses to know what to render”. Often you use `children` directly as a function for this.\n\n```jsx\nclass OnlineStatus extends React.Component {\n  state = { isOnline: false };\n\n  handleOnline = () => this.setState({ isOnline: true });\n  handleOffline = () => this.setState({ isOnline: false });\n\n  componentDidMount() {\n    window.addEventListener(\"online\", this.handleOnline);\n    window.addEventListener(\"offline\", this.handleOffline);\n  }\n\n  componentWillUnmount() {\n    window.removeEventListener(\"online\", this.handleOnline);\n    window.removeEventListener(\"offline\", this.handleOffline);\n  }\n\n  render() {\n    return this.props.children(this.state.isOnline);\n  }\n}\n```\n\nIt is then called like this:\n\n```jsx\n<OnlineStatus>\n  {(isOnline) => (\n    <span>{isOnline ? \"Online\" : \"Offline\"}</span>\n  )}\n</OnlineStatus>\n```\n\nThat is more flexible than a HOC, because the caller keeps full control over rendering. But here too there is a price: if you create the function inline in the JSX, it is recreated on every render. For a `PureComponent` or a child component optimized with `memo`, that is poison – the shallow compare fails because the function reference is new every time, and the optimization comes to nothing. You would have to move the function out into a stable instance method, which eats up the supposed elegance again.\n\n## The shared problem: wrapper hell\n\nBoth patterns – HOCs and render props – share logic through the same mechanism: additional levels in the component tree. Every HOC is a wrapper, every render prop another level of nesting. With one or two levels, you don’t notice anything. With five, the React DevTools tree looks like an onion, and that is affectionately called “wrapper hell”.\n\nThis tree is exactly the crucial point. Let’s look at it:\n\n```mermaid\ngraph TD\n  subgraph HOC[\"HOC / render props: nested\"]\n    R1[withRouter] --> L1[withLoading]\n    L1 --> D1[withData]\n    D1 --> P1[Page]\n  end\n```\n\nEvery intermediate level exists only to pass logic in. It has no domain meaning of its own; it is pure infrastructure in the tree. And because the data is passed through from the outside in, intermediate layers with stale closures arise easily – another debugging classic.\n\n## Answer 3: Custom hooks\n\nCustom hooks solve the problem in a different place. A custom hook is simply a normal JavaScript function whose name starts with `use` and which may call other hooks. No wrapper, no additional component, no new level in the tree. The logic moves into a function, the component calls it – done.\n\nThe same `withLoading` problem looks like this as a hook: the hook supplies the state and the component itself decides what to render with it:\n\n```jsx\nimport { useState, useEffect } from \"react\";\n\nfunction useOnlineStatus() {\n  const [isOnline, setIsOnline] = useState(true);\n\n  useEffect(() => {\n    const handleOnline = () => setIsOnline(true);\n    const handleOffline = () => setIsOnline(false);\n\n    window.addEventListener(\"online\", handleOnline);\n    window.addEventListener(\"offline\", handleOffline);\n\n    return () => {\n      window.removeEventListener(\"online\", handleOnline);\n      window.removeEventListener(\"offline\", handleOffline);\n    };\n  }, []);\n\n  return isOnline;\n}\n```\n\nAnd the usage is as unspectacular as it should be:\n\n```jsx\nfunction StatusBar() {\n  const isOnline = useOnlineStatus();\n  return <span>{isOnline ? \"Online\" : \"Offline\"}</span>;\n}\n```\n\nCompare this with the `OnlineStatus` render prop above: the same logic, but without the nesting, without the inline function, without the class. The tree stays flat:\n\n```mermaid\ngraph TD\n  Page2[Page] -.calls.-> H1[useData]\n  Page2 -.calls.-> H2[useLoading]\n  Page2 -.calls.-> H3[useRouter]\n```\n\nThe hooks hang off the side of the component – they are function calls, not tree levels. That is the whole trick, and it is a big one.\n\nTwo properties of custom hooks are worth spelling out explicitly, because they are often misunderstood:\n\n- Custom hooks share **logic, not state**. If two components call `useOnlineStatus()`, each has its own, independent state. The hook is a recipe, not a shared pot.\n- Custom hooks re-render with their component. On every re-render, the hook gets fresh props and current state – the “stale closures” that arise so easily in HOC intermediate layers are much less of an issue here.\n\n## Rules that apply to custom hooks too\n\nThe `use` prefix is not cosmetic. It signals to the linter and to readers that this function may itself call hooks – and that the Rules of Hooks apply to it. Concretely, that means:\n\nOnly React components and other hooks may call hooks. An ordinary function without `use` may not contain a `useState`. The reverse applies just as much: a function that doesn’t call any hooks at all shouldn’t be called `use`. Otherwise you take away your freedom to call it conditionally or in a loop – which is forbidden for real hooks. So the prefix is a contract in both directions. The whole thing is enforced by `eslint-plugin-react-hooks`, which I never leave out of a React project.\n\nA trap that is less technical than conceptual is one I see in codebases again and again: the urge to immediately build generic “lifecycle” hooks, such as a `useMount` that wraps an effect on mount. That is usually a bad trade. A custom hook should represent a concrete, nameable use case – `useOnlineStatus`, `useChatRoom`, `useFormInput`. If the hook’s name already explains what it does in domain terms, it is cut well. If it only renames a React mechanism, you’ve gained nothing, and the abstraction will get in your way later.\n\n## When HOCs still make sense today\n\nAfter all this, it sounds as if custom hooks had completely replaced the two older patterns. For sharing stateful logic, that is largely true. But there is a handful of tasks for which HOCs are still the right form – namely real cross-cutting concerns that are brought to a component from the outside.\n\nThe classic example is context injection: a HOC that makes a value from context available to any component as a prop, without the component itself having to know about the context. You often run into such `withXxx` wrappers in older libraries, and there they serve a purpose that a hook doesn’t cover cleanly – for example when class components are involved, which can’t call hooks at all. So if you maintain an existing codebase with class components, you’ll keep running into HOCs for a while.\n\nWhat I no longer recommend, on the other hand, is reaching for HOC toolkits like `recompose`. In its time, the library was a clever tool for composing functions such as `withState` or `withReducer`:\n\n```js\n// recompose - historical, deprecated since 2018\nimport { compose, withState } from \"recompose\";\n\nconst enhance = compose(\n  withState(\"count\", \"setCount\", 0)\n);\n```\n\nHowever, the author himself marked `recompose` as deprecated back in 2018 and explicitly pointed to hooks as its successor. So you only come across the package as historical context in older repositories – it is no good as a current recommendation.\n\n## The common thread\n\nThree answers to one question, and the order tells a clear story. HOCs and render props showed that logic can be shared without copying it – but they solved it through the component tree and paid for it with nesting, lost refs and static methods, defeated `memo` optimizations and “wrapper hell”. Custom hooks solve the same task with a simple function call and keep the tree flat.\n\nFor shared logic, the first choice today is therefore a custom hook with a `use` prefix that encapsulates a concrete use case. HOCs stay in the toolbox for the cross-cutting cases and for work on existing code with class components. And render props still show up where a component really wants to hand control over rendering back to the caller. But the standard case – the same logic in several components – has had a good, unspectacular answer since 2019. You just have to know why the other two were there before.\n\n## Further reading\n\n- [Reusing Logic with Custom Hooks](https://react.dev/learn/reusing-logic-with-custom-hooks) – the current chapter on custom hooks\n- [Higher-Order Components](https://legacy.reactjs.org/docs/higher-order-components.html) – the historical HOC documentation\n- [Render Props](https://legacy.reactjs.org/docs/render-props.html) – the original render props pattern\n- [Hooks – Custom Hooks (Legacy)](https://legacy.reactjs.org/docs/hooks-custom.html) – the historical custom hooks chapter\n- [Rules of Hooks / Invalid Hook Call Warning](https://react.dev/warnings/invalid-hook-call-warning) – why the `use` prefix and the rules matter"},{"locale":"en","translation_key":"nodejs-async-context-mit-asynclocalstorage","slug":"async-context-in-nodejs-with-asynclocalstorage","title":"Async Context in Node.js: AsyncLocalStorage, async_hooks and diagnostics_channel","summary":"How to carry request-scoped context such as request ID, user and trace through deep asynchronous call chains without threading it through every function signature – with AsyncLocalStorage, the underlying async_hooks and diagnostics_channel for decoupled tracing.","tags":["Software","Node.js","Backend"],"published_at":"2023-05-16T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/async-context-in-nodejs-with-asynclocalstorage/","audio_url":null,"audio_duration_secs":null,"text":"`AsyncLocalStorage` is not a global variable with a better name. Every `run` call holds its own store, and two concurrent requests don’t get in each other’s way – exactly where the global variable you would otherwise reach for by reflex fails. The confusion persists anyway, because from the outside both look the same: put something down at the top, pick it up again far below.\n\nWhat this is good for shows in operations, not in the code. Whether finding a root cause takes minutes or hours depends on whether you can follow a single request seamlessly through logs, services and traces. Node.js ships three building blocks for this: `AsyncLocalStorage`, the underlying `async_hooks` and `diagnostics_channel`. In the post on [debugging and observing Node.js](https://www.mikebild.dev/en/blog/debugging-and-profiling-nodejs-locally/), I saved async context for later; I’m catching up on that here.\n\nThis is not a niche problem. As soon as an application has more than a few endpoints, you want to know which log line belongs to which request. You want to see the logged-in user in the error report. You want to hold a trace together across several services. And all these values simply belong to the request, not to whatever function happens to be running.\n\n## The problem: threading context through the depths\n\nLet’s look at what this looks like without any help. I have a handler that calls a service that calls a repository that, at the end, wants to log something. The request ID is created at the very top – it is needed at the very bottom.\n\n```js\nfunction handler(req, res) {\n  const requestId = randomUUID();\n  serviceA(req.body, requestId);\n}\n\nfunction serviceA(input, requestId) {\n  // serviceA doesn't need requestId itself\n  return repository(input, requestId);\n}\n\nfunction repository(input, requestId) {\n  // repository doesn't either\n  log('writing record', requestId);\n}\n\nfunction log(message, requestId) {\n  console.log(`[${requestId}] ${message}`);\n}\n```\n\nThat works – but it’s unpleasant. Every function in between gets a parameter forced on it that it never uses itself. It just passes it along. If a user object comes along tomorrow and a trace ID the day after, every signature grows with it. And the one library function you can’t change will, of course, not pass the parameter along – that’s where the chain breaks.\n\nYou can work around it: attach the context to a class instance, pass along an object that collects all the extra data, or even set a global variable. The class instance route forces you into an object model you may not want at all. The context object is just a more nicely packaged version of the same passing along. And the global variable is simply wrong with concurrent requests – the next request overwrites it while the first one is still running. None of these variants really holds up.\n\nFor exactly this “context threading” problem, Node.js has a clean answer.\n\n## AsyncLocalStorage: the practical way\n\n`AsyncLocalStorage` lives in the `node:async_hooks` module and has been stable since Node v16.4.0. The idea is simple: you run a callback in a so-called store, and this store is preserved for all asynchronous operations created inside that callback. You read it back as deep down as you like – without a single extra parameter.\n\nAn honest note up front: there is no example from a specific project codebase for this post. The following code blocks are generic Node.js examples that I checked against the official documentation.\n\n```js\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\n\nconst als = new AsyncLocalStorage();\n\nfunction handler(req, res) {\n  const store = { requestId: randomUUID(), user: req.user };\n  als.run(store, () => {\n    serviceA(req.body);\n  });\n}\n\nfunction serviceA(input) {\n  return repository(input);\n}\n\nfunction repository(input) {\n  log('writing record');\n}\n\nfunction log(message) {\n  const { requestId } = als.getStore() ?? {};\n  console.log(`[${requestId}] ${message}`);\n}\n```\n\nThe difference is clear. `serviceA` and `repository` no longer know anything about the request ID. They know their actual job and nothing else. Only at the very top is the store set – with `als.run(store, callback)` – and only where it is really needed is it read with `als.getStore()`.\n\nTwo details matter. First, `run` is synchronous: the callback’s return value is passed through, and if the callback throws, the error is passed on as well and the context is exited again. Second, outside a `run` call, `getStore()` simply returns `undefined`. That’s why the example has the `?? {}` – you should never assume a store is always there.\n\nAny object works as a store. In practice, I like to use a `Map` when values should be added during a request, or a plain object when the content is fixed from the start. The only thing that matters is that every `run` call gets its own store – then concurrent requests are cleanly separated from each other without you having to take care of the separation yourself. That is exactly the gain over the global variable from before.\n\nThe following diagram shows this level. The store is set at the top, the deep calls read it, and no parameter is ever passed along.\n\n```mermaid\nflowchart TD\n  Req[\"HTTP Request\"] --> Run[\"als.run(store)\"]\n  Run --> A[\"serviceA()\"]\n  A --> R[\"repository()\"]\n  R --> L[\"log()\"]\n  Store[(\"Store<br/>requestId, user\")]\n  Run -.-> Store\n  L -.->|\"reads store\"| Store\n```\n\n### enterWith – the risky shortcut\n\nBesides `run`, there is `enterWith(store)`. The appeal is obvious: you don’t have to indent the rest of the code into a callback; you just set the context and carry on normally. But that is exactly the danger. `enterWith` applies to the entire rest of the synchronous execution plus all following asynchronous calls – there is no natural bracket that closes the context again. If you set it in an event handler, subsequent handlers may end up in the same context.\n\n`enterWith` is marked as experimental, and the documentation is unusually direct: you should use `run()` unless there are strong reasons against it. In practice that means: start with `run`. `enterWith` is reserved for rare special cases and is not the normal path.\n\n## async_hooks: the foundation underneath\n\nHow does `AsyncLocalStorage` even know which asynchronous operations belong to which `run` call? Underneath sits `async_hooks`, the actual low-level layer. It provides lifecycle hooks for asynchronous resources: for each such resource, Node goes through the phases `init`, `before`, `after` and `destroy`. You can hook into these phases.\n\n```js\nimport { createHook, executionAsyncId } from 'node:async_hooks';\nimport { writeSync } from 'node:fs';\n\nconst hook = createHook({\n  init(asyncId, type, triggerAsyncId) {\n    writeSync(1, `init ${type} id=${asyncId} trigger=${triggerAsyncId}\\n`);\n  },\n  destroy(asyncId) {\n    writeSync(1, `destroy id=${asyncId}\\n`);\n  },\n});\n\nhook.enable();\n```\n\nWhy `writeSync` instead of `console.log`? Because `console.log` itself creates asynchronous resources, and in an `init` hook you would write yourself into an infinite loop. That alone shows how delicate this layer is to work with directly.\n\nAnd here I have to be clear: `async_hooks` is experimental, and the Node documentation explicitly advises against using it directly – because of “usability issues, safety risks, and performance implications.” The `destroy` hook is especially expensive because it enables tracking of promises through the garbage collector. That costs measurable performance.\n\nSo the message is not “learn async_hooks and use it.” The message is: `AsyncLocalStorage` stands on this foundation, but it is the stable, recommended and practical API. As a rule, you don’t reach for `createHook` yourself. I only show it here to make clear what happens one level down – not as a recommendation for production code.\n\n## diagnostics_channel: decoupled instrumentation\n\nThe third building block solves a different problem. Say a library wants to report that it is starting a request – but it shouldn’t dictate who hears about it or what happens with it. A logger? A tracer? A metric counter? The library shouldn’t have to know.\n\n`diagnostics_channel` has been stable since Node v18.13.0 and exists for exactly this: a decoupled publish/subscribe channel. Producers publish messages on a named channel, observers subscribe to it. Neither side knows the other.\n\n```js\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('app:request:start');\n\nfunction handleRequest(req) {\n  if (channel.hasSubscribers) {\n    channel.publish({\n      requestId: req.id,\n      route: req.url,\n      startedAt: Date.now(),\n    });\n  }\n  // ... actual work\n}\n```\n\nOn the other side, in a completely separate piece of code – maybe in the observability layer, maybe in a plugin – you subscribe to the same channel:\n\n```js\nimport diagnostics_channel from 'node:diagnostics_channel';\n\ndiagnostics_channel.subscribe('app:request:start', (message, name) => {\n  console.log(`[${name}] request ${message.requestId} on ${message.route}`);\n});\n```\n\nThe `hasSubscribers` guard is not a detail but the heart of the matter. Without subscribers, nothing should cost anything. If you build the message object unconditionally – possibly with expensive fields or serialized payloads – you pay that price even when no one is listening. With the guard, there is practically no overhead at zero subscribers.\n\nA note on the API: the channel object also has `channel.subscribe(...)`, but this variant has been marked as deprecated since v18.7.0. In your own code, use the module-level functions, that is, `diagnostics_channel.subscribe(name, onMessage)`.\n\n## Three levels, three jobs\n\nThe three modules sound similar and do fundamentally different things – this is exactly where the confusion comes from. The division of roles:\n\n- `AsyncLocalStorage` carries context: stable since v16.4.0, the practical high-level API. Request ID, user and trace through deep async chains – without passing parameters along.\n- `async_hooks` is the foundation: experimental and explicitly not recommended for direct use. It provides the resource lifecycle that `AsyncLocalStorage` builds on.\n- `diagnostics_channel` reports events in a decoupled way: stable since v18.13.0. Producers and consumers don’t know each other – ideal for instrumentation and tracing.\n\nThe following diagram arranges the three relative to each other: the context layer on its foundation, and next to it the independent event bus.\n\n```mermaid\nflowchart TB\n  subgraph Context[\"Kontext tragen\"]\n    ALS[\"AsyncLocalStorage<br/>Stable\"]\n    AH[\"async_hooks<br/>Experimental\"]\n    ALS --> AH\n  end\n  subgraph Bus[\"Ereignisse entkoppelt melden\"]\n    Pub[\"Publisher\"] --> Ch[\"diagnostics_channel\"]\n    Ch --> S1[\"Subscriber: Logger\"]\n    Ch --> S2[\"Subscriber: Tracer\"]\n  end\n```\n\n## Request correlation as a measurable operational quality\n\nThe three modules are a means, not an end. The end is a property of the running system: can every operation be clearly assigned to a request? Once that is the case, a vague “the system feels slow” turns into a question you can answer. You grab a correlation ID, filter logs, metrics and traces by it and see that one request in all its depth – across service boundaries.\n\nThis traceability is measurable, and that is exactly what makes it an operational quality rather than a gut feeling. The share of log lines assigned to a request ID is a metric. The time from the error report to the root cause found – the mean time to resolution – is a metric. Both move noticeably when correlation is complete instead of full of holes. `AsyncLocalStorage` provides the load-bearing building block for this: the key that reaches the deepest function without passing parameters along. `diagnostics_channel` provides the second: the decoupling that lets an observability layer pick up this key without the application code having to know who is listening.\n\nThe trade-off should be named honestly. Context via `AsyncLocalStorage` costs a small but real overhead per asynchronous operation – negligible compared to the gain for the vast majority of backends, but in exceptional cases with extremely high throughput, something you measure rather than assume. The bigger price is discipline: the `run` call has to sit reliably at the entry of every execution chain; otherwise correlation breaks exactly where you need it most.\n\nSo the decision isn’t made at the API but at the level of ambition. A handful of endpoints without real operational load can do without all this. But as soon as several services work together, there is an on-call rotation or errors cost money, request correlation goes from nice-to-have to foundation. It is the building block on which logging, tracing and alerting grow together into one picture – the bridge from individual signals to real observability.\n\n## Pitfalls from practice\n\nThe most common pain with `AsyncLocalStorage` is context loss: `getStore()` suddenly returns `undefined` even though you’re sure you’re inside a `run` call. This typically happens with certain callback-based APIs or with your own homegrown “thenable” objects, where Node can’t properly follow the asynchronous chain. The documentation names two remedies: convert such APIs into real promises with `util.promisify()`, or bind the resource with `AsyncResource`. A practical debugging trick: log `getStore()` at suspicious transitions. If the store is gone right after a particular call, you’ve found the transition where the chain breaks.\n\nI already hinted at the `enterWith` leak above – here it is once more, concretely, as a warning: the context runs through the entire remaining synchronous execution and beyond. Set in an event handler, subsequent handlers can inherit the same context even though they belong to an entirely different request. Those are the bugs you hunt at three in the morning. Prefer `run()`.\n\nAnd finally, the cost of `async_hooks`: the overhead is real, especially from promise tracking in the `destroy` hook. Together with the fact that the API is experimental and, according to the Node team, risky, that gives a clear line – don’t use it as a context mechanism in production. If you need context, use `AsyncLocalStorage`. `async_hooks` is something you know in order to understand what happens underneath, and otherwise leave alone.\n\nA side note for the curious: v18.16.0 added `AsyncLocalStorage.bind(fn)` and `AsyncLocalStorage.snapshot()` to bind the current context to a function. Both are still experimental and not needed to get started – I only mention them for completeness.\n\n## Conclusion\n\nThe common thread is layering. At the very bottom, `async_hooks` makes it possible for Node to track the lifecycle of asynchronous resources at all – a powerful but experimental and expensive layer that you rarely touch directly. On top of it stands `AsyncLocalStorage` as the stable, recommended API you use to carry request-scoped context through call chains of any depth without threading it through every signature. And next to it stands `diagnostics_channel` as a decoupled event bus that libraries and applications use for structured instrumentation without producer and consumer having to know about each other.\n\nThe effect shows less in the code than in operations. Where context is carried cleanly, debugging cycles get shorter because every log line knows its request. Friction drops because no signature drags along a parameter it never uses. And quality rises measurably because traceability turns from chance into a property. For daily work, that means: `als.run(store, cb)` at the top, `als.getStore()` at the bottom – and you’re rid of the tedious passing of parameters. If you want to decouple observability, reach for `diagnostics_channel` with a `hasSubscribers` guard. `async_hooks` remains the foundation you should understand but don’t operate yourself day to day. The limit is just as clear: no mechanism replaces the discipline of setting the `run` call reliably – if the chain breaks there, the best API won’t help.\n\nIf you want to dig deeper into Node’s event model at this point, the post on [EventEmitter and the event model](https://www.mikebild.dev/en/blog/eventemitter-the-event-model-at-the-core-of-nodejs/) is a good fit. And if you want to understand the architecture around the Event Loop and asynchronous execution from the ground up, the [Node.js training](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/) gives you the bigger picture.\n\n## Further reading\n\n- [AsyncLocalStorage and async context (Node.js v18.x)](https://nodejs.org/docs/latest-v18.x/api/async_context.html)\n- [async_hooks (Node.js v18.x)](https://nodejs.org/docs/latest-v18.x/api/async_hooks.html)\n- [diagnostics_channel (Node.js v18.x)](https://nodejs.org/docs/latest-v18.x/api/diagnostics_channel.html)"},{"locale":"en","translation_key":"graphql-auth-im-context","slug":"graphql-auth-identity-in-the-context","title":"GraphQL Auth: Identity in the Context, Authorization in the Domain Logic","summary":"The GraphQL context carries the identity of a request. Whether that identity may perform an operation is decided by a central policy in the domain logic.","tags":["Software","GraphQL","API"],"published_at":"2023-04-18T10:00:00+00:00","updated_at":"2026-07-13T08:49:33.50578+00:00","url":"https://www.mikebild.dev/en/blog/graphql-auth-identity-in-the-context/","audio_url":null,"audio_duration_secs":null,"text":"A resolver that only checks whether a token is present grants every logged-in user access to everything the schema offers. That isn’t a minor flaw in the auth, that is an open backend with a login form in front of it.\n\nThe cause is almost always in the same place: this one check holds two questions that deal with entirely different things – and in the code, they have been fused into one. “We check that in the resolver” is therefore an answer that leaves everything open: is it checking whether someone is logged in, or whether they may see this field? As long as that isn’t answered, nobody knows what the application is actually protected against.\n\n## Two questions, not one\n\nAuthentication answers the question: **Who are you?** A token becomes an identity – a `user`. Authorization answers an entirely different question: **What are you allowed to do?** Whether this specific user may call this specific field or this specific mutation.\n\nThese are different responsibilities, and they even have different failure modes. If you send no token or an invalid one, you get a `401` – not authenticated. If you have a valid token but the wrong role, you get a `403` – authenticated but not authorized. In code reviews, I regularly see the two mixed up, and then both end up at the client as HTTP `500` because an error wasn’t caught. That isn’t a cosmetic problem – a client can react sensibly to `401` and `403` (login flow vs. “no access”), but not to `500`.\n\nOnce this separation is in place, the real architecture question comes up: where does the identity belong, and how does it reach every resolver that needs it?\n\n## Why the context is the right place\n\nIn GraphQL, a `contextValue` is built per request – an object that is passed to **every** resolver of the same request. That isn’t an incidental detail; it is the ideal hook for auth.\n\nThe reason is the lifetime. The context is created anew once per request and lives exactly as long as that request. No state leaks between two requests, no cleanup is necessary, and I am guaranteed a freshly determined identity for every request. That is exactly where the `user` belongs.\n\nIn Apollo Server 4 – the current major version – this is an `async` function that you pass in when starting the server. Important: in Apollo Server 4, the context function moves out of the `new ApolloServer({...})` constructor to `startStandaloneServer` or `expressMiddleware`. If you still have older examples from AS2/AS3 in mind, where `context` sat directly in the constructor: conceptually identical, it just gets hooked in somewhere else today.\n\n```ts\nimport { ApolloServer } from '@apollo/server';\nimport { startStandaloneServer } from '@apollo/server/standalone';\n\nconst server = new ApolloServer({ typeDefs, resolvers });\n\nconst { url } = await startStandaloneServer(server, {\n  context: async ({ req }) => {\n    const raw = req.headers.authorization || '';\n    const token = raw.replace('Bearer ', '');\n    const user = await getUserFromToken(token);\n    return { user };\n  },\n});\n```\n\nTwo details that regularly trip someone up in projects. First: in Express, `req.headers.authorization` is always lowercase – HTTP header keys end up there in lowercase, no matter how the client sends them. Second: an empty header must never pass as “logged in.” The `|| ''` fallback yields an empty string, `getUserFromToken('')` then cleanly returns `null` – and `null` means “unknown,” not “admin.”\n\nWith that, the flow looks the same for every request:\n\n```mermaid\nflowchart LR\n  C[Client] -- \"Authorization:<br/>Bearer token\" --> S[GraphQL server]\n  S --> CTX[\"context()<br/>token to user\"]\n  CTX --> R[Resolver]\n  R --> BL[Business logic<br/>checks user + role]\n  BL -- allowed --> DATA[Data]\n  BL -- denied --> ERR[\"GraphQLError<br/>403 FORBIDDEN\"]\n```\n\nYou can see it clearly here: authentication happens exactly once, right at the front in `context()`. From then on, the request carries an identity with it, and everything else is authorization.\n\n## What belongs in the context – and what doesn’t\n\nBecause the context is so temptingly practical, it easily turns into a junk room. It pays to keep its contents deliberately short. What belongs in it:\n\n- the identity – `user` or `viewer`, determined from the token\n- this user’s permissions – `roles` or `scopes`\n- request-bound infrastructure – DataLoader instances, so that batching and deduplication work per request\n- access to the data layer – a `db` handle or repositories\n- request-specific values such as the locale or an auth token to pass on to downstream services\n\nAnd just as clearly, what does **not** belong in it:\n\n- global state that lives across requests\n- cross-request caches (that is exactly why a DataLoader is per request, not global)\n- plaintext secrets that have no business being there\n\nThe rule of thumb behind it: anything that applies to exactly this one request and may disappear afterward is in good hands in the context. Anything long-lived belongs elsewhere. If you put DataLoader instances in the context per request, you already know the pattern from the world of efficient data access, by the way – I described it in more detail in connection with lists and cursors in [GraphQL pagination](https://www.mikebild.dev/en/blog/graphql-pagination-cursors-and-connections/).\n\n## Authorization in the resolver\n\nNow the `user` is in the context, and every resolver can read it – as the **third argument**, `(parent, args, contextValue, info)`. That is the simplest, most direct form of authorization.\n\n```ts\nimport { GraphQLError } from 'graphql';\n\nconst resolvers = {\n  Query: {\n    me: (parent, args, { user }) => {\n      if (!user) {\n        throw new GraphQLError('Not authenticated', {\n          extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },\n        });\n      }\n      return user;\n    },\n    adminReport: (parent, args, { user }) => {\n      if (!user?.roles.includes('ADMIN')) {\n        throw new GraphQLError('Forbidden', {\n          extensions: { code: 'FORBIDDEN', http: { status: 403 } },\n        });\n      }\n      return buildAdminReport();\n    },\n  },\n};\n```\n\nImportant for anyone still working with older Apollo examples: the former classes `AuthenticationError` and `ForbiddenError` from the old `apollo-server` package no longer exist in Apollo Server 4. The way to go today is `GraphQLError` from `graphql` with an `extensions.code` – `UNAUTHENTICATED` for the missing login, `FORBIDDEN` for the missing permission – and optionally the matching HTTP status.\n\nYou can already see the separation in the two resolvers: `me` only checks **whether** anyone is there at all (authentication enforced), `adminReport` checks **what** this someone is allowed to do (authorization). Two questions, two error codes.\n\n## Field level versus query level\n\nAuthorization isn’t just a matter of “whole query allowed or not.” GraphQL allows checks at the field level, and that is one of its stronger properties.\n\nBecause every field has its own resolver and the check takes effect while the request is being executed, **partial responses** are possible: the client queries ten fields, the server delivers seven, and for three it gets an error and `null` – in a single response. That is exactly the behavior you want. A user should see their own name but not the internal credit rating field that only admins are entitled to.\n\nIn the grounding repo, a declarative approach shows up for this: an `@auth` directive with a role enum.\n\n```graphql\nenum Role {\n  ADMIN\n  OWNER\n  USER\n}\n\ndirective @auth(requires: Role!) on FIELD_DEFINITION\n\ntype User {\n  id: ID!\n  name: String!\n  role: String @auth(requires: ADMIN)\n}\n\ntype Query {\n  me: User @auth(requires: USER)\n}\n```\n\nHere you can see both levels: `me @auth(requires: USER)` protects an entire query field, `role @auth(requires: ADMIN)` protects a single field within the type. The directive itself is only a declaration – someone also has to enforce it at runtime. In the current generation of graphql-tools, you do that with a schema transformer.\n\n```ts\nimport { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';\nimport { defaultFieldResolver, GraphQLError } from 'graphql';\n\nfunction authDirectiveTransformer(schema) {\n  return mapSchema(schema, {\n    [MapperKind.OBJECT_FIELD]: (fieldConfig) => {\n      const directive = getDirective(schema, fieldConfig, 'auth')?.[0];\n      if (!directive) return fieldConfig;\n\n      const { requires } = directive;\n      const { resolve = defaultFieldResolver } = fieldConfig;\n\n      fieldConfig.resolve = (source, args, context, info) => {\n        if (!context.user) {\n          throw new GraphQLError('Not authenticated', {\n            extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },\n          });\n        }\n        if (!context.user.roles.includes(requires)) {\n          throw new GraphQLError('Forbidden', {\n            extensions: { code: 'FORBIDDEN', http: { status: 403 } },\n          });\n        }\n        return resolve(source, args, context, info);\n      };\n      return fieldConfig;\n    },\n  });\n}\n```\n\nA note for anyone who comes across older tutorials: the former `SchemaDirectiveVisitor` is long gone – it hasn’t existed since graphql-tools v6. The approach via `mapSchema` and `getDirective` is the current one. If you google `SchemaDirectiveVisitor` and copy it, you will wonder why nothing can be imported.\n\nAs elegant as the directive looks: it is only half the truth. And this is exactly where the interesting discussions in the team begin.\n\n## Why auth doesn’t belong in the schema\n\nThe `@auth` directive feels like the perfect solution at first – permissions sit right on the field, declarative, readable. For prototypes and for learning, that is perfectly fine. But as the **sole** strategy, it leads into a dead end, and the official GraphQL docs are surprisingly clear about it: authorization belongs in the business logic layer, not in the schema.\n\nThe reason is duplication. Let’s take a typical rule: `OWNER` – a user may only edit their own posts. This rule can hardly be expressed purely declaratively, because it depends on the concrete data: does *this* post belong to *this* user? A directive knows the role but not the relationship between the user and the resource.\n\nAnd even simple role checks drift apart as soon as the same logic is needed in several places. If the same “may read the post” decision hangs on three fields and at some point is also needed by a REST endpoint or a background job, then you have the rule three or four times – and it drifts apart. That is the core of the argument: a single source of truth instead of scattered copies.\n\nSo the clean variant is this: the resolver doesn’t decide on its own; it **delegates** to a business logic function that receives the context and makes the decision.\n\n```ts\nconst resolvers = {\n  Query: {\n    posts: (parent, args, context) => postRepository.getPosts(context),\n  },\n  Mutation: {\n    updatePost: (parent, { id, input }, context) =>\n      postRepository.updatePost(id, input, context),\n  },\n};\n\n// Business logic layer – authorization lives here\nconst postRepository = {\n  async getPosts(context) {\n    if (!context.user) {\n      throw new GraphQLError('Not authenticated', {\n        extensions: { code: 'UNAUTHENTICATED', http: { status: 401 } },\n      });\n    }\n    // Owner rule: only the user's own posts\n    return db.posts.findMany({ where: { authorId: context.user.id } });\n  },\n};\n```\n\nThe resolver stays thin and dumb – it takes args and context and passes them on. The actual decision, including the data-dependent OWNER rule, lives in a single place. If another entry point is added tomorrow, it calls the same function. No duplication, no drift.\n\nI like to picture this as three layers, with the schema deliberately in the middle and without any decision-making power:\n\n```mermaid\nflowchart TB\n  subgraph Transport[\"Transport layer\"]\n    A[\"Authentication<br/>token to user in the context\"]\n  end\n  subgraph Schema[\"Schema layer\"]\n    B[\"Declarative only<br/>optional @auth as a hint\"]\n  end\n  subgraph Domain[\"Business logic layer\"]\n    D[\"Authorization<br/>may user access this resource?\"]\n  end\n  Transport --> Schema --> Domain\n```\n\nThe message of this picture: identity is determined at the top, the permission decision is made at the bottom. The schema in the middle only describes; it doesn’t decide.\n\n## The pitfall that gets most expensive\n\nThere is one mistake I see again and again, and it really hurts: enforcing authorization in the client. The UI hides the “Delete” button if the user isn’t an admin – and everyone is happy. Except that the resolver behind it checks nothing at all.\n\nThat isn’t security, that is cosmetics. Anyone who opens the developer tools or sends a GraphQL mutation directly bypasses this “check” in seconds. Hidden buttons are a matter of user guidance, not security. Enforcement **must** happen on the server – in the resolver or in the business logic layer behind it. The client is welcome to hide buttons as well, so that the UI stays tidy. But the only thing you can rely on is the server.\n\nThat also answers the opening question. “We check that in the resolver” isn’t enough as an architecture decision. The identity goes into the context once per request. For the specific operation, the resolver calls a central policy or domain function; that is where the data-dependent permission decision is made. Directives and hidden buttons can make this visible, but they don’t replace this check.\n\nIn the projects where auth ended up running quietly, it was never a schema question but a question of lifecycles and responsibilities. The context knows who you are. The business logic knows what you are allowed to do. If the two stay separate, the rest becomes simple.\n\n## Further reading\n\n- [Grounding repository MikeBild/introduction-graphql](https://github.com/MikeBild/introduction-graphql) – `introduction-graphql/auth.md` and `recipes/auth/`\n- [graphql.org – Authorization](https://graphql.org/learn/authorization/) – why authorization belongs in the business logic layer\n- [Apollo Server – Authentication and authorization](https://www.apollographql.com/docs/apollo-server/security/authentication) – GraphQLError codes, `UNAUTHENTICATED` vs. `FORBIDDEN`\n- [Apollo Server – The context object](https://www.apollographql.com/docs/apollo-server/data/context) – context and contextValue, once per request"},{"locale":"en","translation_key":"nodejs-debuggen-und-beobachten","slug":"debugging-and-profiling-nodejs-locally","title":"Debugging and Profiling Node.js Locally","summary":"From the console.log reflex to the built-in inspector: node --inspect, the debug module, nodemon and first CPU and memory profiles for local diagnosis.","tags":["Software","Node.js","Backend"],"published_at":"2023-02-14T10:00:00+00:00","updated_at":"2026-07-13T08:00:08.673184+00:00","url":"https://www.mikebild.dev/en/blog/debugging-and-profiling-nodejs-locally/","audio_url":null,"audio_duration_secs":null,"text":"```js\nconsole.log(x);\nconsole.log('HIER');\nconsole.log('HIER 2');\n```\n\nThese three lines can do exactly one thing: show a value at a place you guessed in advance. The only way to turn them off is for someone to touch the file again. They can’t pause the process. They say nothing at all about memory usage. For all three gaps, Node.js has shipped its own tools since version 6.3, without any extra package to install – they are just rarely used.\n\nYou can sort them as an escalation ladder. At the bottom is `console.log` – always on, unstructured, but immediately available. One step up is the `debug` module, which you can switch on and off through an environment variable without touching the code. Above that sits the built-in inspector with interactive breakpoints in Chrome DevTools or VS Code. And at the top, when performance or memory is the issue, I use the same inspector as a profiler. If you can keep these four steps cleanly apart, you stop guessing blindly.\n\n## Why console.log hits its limits\n\n`console.log` has two properties that make it handy in the small and unpleasant in the large. First, it is always active: whatever is in the code runs on every pass, including in production, where it pollutes the output and, depending on volume, even costs performance. Second, it is unstructured – I see a value, but I can’t decide with a switch whether I want to see the HTTP layer or the database access right now without commenting lines out again.\n\nIf you have ever dealt with the [event model of Node.js](https://www.mikebild.dev/en/blog/eventemitter-the-event-model-at-the-core-of-nodejs/), you know the problem in a sharper form: with asynchronous code, the order of the output isn’t always what you expect, and a `console.log` in the middle of a callback tells only a fraction of the story. This is exactly where it pays to move to tools that can pause and examine the running process.\n\n## The built-in inspector: --inspect and --inspect-brk\n\nThe most important thing first, because it keeps surprising teams: the debugger is already built into Node.js. There is no extra package to install. Historically, there was once a separate module (`node-inspector` with the command `node-debug app.js`), but it has been obsolete since Node 6 and is only a footnote today. Since Node 6.3, the process itself speaks the Chrome DevTools Protocol over a WebSocket – and that is exactly why both Chrome DevTools and VS Code work as clients.\n\nYou start it with a flag:\n\n```bash\nnode --inspect ./src/server.js\n```\n\nA line like this then appears on stderr:\n\n```text\nDebugger listening on ws://127.0.0.1:9229/8f2c...-uuid\nFor help, see: https://nodejs.org/en/docs/inspector\n```\n\nBy default, the process binds to `127.0.0.1:9229`. The difference between the two central flags matters:\n\n- `--inspect` only starts the debug server; the code keeps running normally. I use it for a server that runs permanently anyway and waits for requests.\n- `--inspect-brk` also starts the debug server, but pauses before the first line of my own code. That is ideal for short-running scripts that would otherwise have rushed through before I could even connect a client.\n\n```bash\nnode --inspect-brk ./src/server.js\n```\n\nFor a script that finishes after 200 milliseconds, `--inspect-brk` is practically the only sensible choice – with `--inspect` alone, the process would have long since ended before I clicked “connect” in DevTools. Knowing this difference has saved me a lot of time in practice.\n\nIf you want to activate the inspector not at startup but on a process that is already running, you can send the `SIGUSR1` signal on Unix systems. This route isn’t available on Windows.\n\n## From flag to client\n\nThe open inspector port is only half the battle – I still need a client that connects. I regularly use two ways.\n\nIn Chrome (or Edge), I open `chrome://inspect` or `edge://inspect`. The running Node process shows up under “Remote Target”, and a click on “inspect” opens the familiar DevTools with sources, breakpoints, call stack and console. Under “Configure”, you can adjust host and port if you don’t use the default values.\n\nIn VS Code, I create an attach configuration in `.vscode/launch.json`:\n\n```json\n{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"type\": \"node\",\n      \"request\": \"attach\",\n      \"name\": \"Attach to Node\",\n      \"port\": 9229\n    }\n  ]\n}\n```\n\nWith it, I attach to a process that I previously started with `--inspect`. Alternatively, VS Code has an “Auto Attach” mode that automatically attaches to Node processes started from the integrated terminal. Both ways end up in the same place: interactive breakpoints where I can inspect variables and step through the code.\n\nThe following flow summarizes how flag, agent and client work together:\n\n```mermaid\nflowchart LR\n  A[\"node --inspect<br/>or --inspect-brk\"] --> B[\"Inspector agent<br/>CDP via ws://127.0.0.1:9229\"]\n  B --> C[\"Chrome DevTools<br/>chrome://inspect\"]\n  B --> D[\"VS Code<br/>request: attach\"]\n  C --> E[\"Breakpoints<br/>CPU profile<br/>Heap snapshot\"]\n  D --> E\n```\n\nBoth clients speak the same protocol with the same built-in agent. So I don’t have to commit to one ecosystem – I pick whichever client suits me better at the moment.\n\n## The debug module: switchable logging without code changes\n\nNot every problem deserves a breakpoint. Often I just want to trace which path a request takes through my layers – but only while I’m investigating, and without anchoring the output in the code permanently. That is exactly what the `debug` module is for, at version 4.3.4 as of this writing. Many well-known libraries use it internally, and it’s quick to add to your own code.\n\nThe core is a factory that you call with a namespace:\n\n```js\nconst debug = require('debug')('app:http');\n\nfunction handleRequest(req, res) {\n  debug('incoming request %s %s', req.method, req.url);\n  // ... handle the request ...\n}\n```\n\nThe trick isn’t in the code but in the startup. By default, this line prints nothing. Only when I set the `DEBUG` environment variable does the matching namespace become visible:\n\n```bash\nDEBUG=app:* node server.js\n```\n\nThe `*` is a wildcard, and with a leading minus I exclude namespaces specifically. That way I see, for example, everything from `app` but not the chatty database layer:\n\n```bash\nDEBUG=app:*,-app:db node server.js\n```\n\nThat achieves the central advantage: I switch logging on and off without changing a single line of code. The `debug` module also adds automatic time differences between outputs (the `+0ms` values), colors the namespaces in a real terminal and knows format placeholders such as `%s`, `%d`, `%j`, `%o` and `%O`.\n\nOne detail regularly causes confusion: the output of `debug` goes to **stderr**, not stdout. If you want to redirect the output or filter it with `grep` and only look at stdout, you simply see nothing. And `DEBUG` only applies to libraries that use `debug` themselves – it isn’t a global switch for every log output.\n\n## nodemon: auto-reload during development\n\nA tool that strictly speaking isn’t part of debugging but shortens the feedback loop enormously is nodemon (around version 2.0.20 as of this writing). It watches files and restarts the process on every change, so I don’t have to press `Ctrl+C` and restart by hand all the time. I add it to the project as a dev dependency:\n\n```bash\nnodemon --watch ./ --ignore ./node_modules ./bin/www\n```\n\nA `nodemon.json` in the project root is nicer, because it captures the configuration and combines well with the inspector:\n\n```json\n{\n  \"watch\": [\"src\"],\n  \"ext\": \"js,json\",\n  \"ignore\": [\"node_modules\"],\n  \"exec\": \"node --inspect src/server.js\"\n}\n```\n\nThrough `exec`, I start the process directly with `--inspect`, so I get auto-reload and the debugger together. As of this writing, Node.js itself already shipped an experimental watch mode, but for everyday work I still rely on nodemon because it is mature and flexible to configure.\n\n## A quick look at memory\n\nBefore I get to actual profiling, there is a very cheap intermediate step that needs no tool at all: `process.memoryUsage()`. This function returns an object with several values, all in bytes:\n\n```js\nconst { rss, heapTotal, heapUsed, external } = process.memoryUsage();\n\nconsole.error(\n  `rss=${(rss / 1e6).toFixed(1)}MB ` +\n  `heapUsed=${(heapUsed / 1e6).toFixed(1)}MB ` +\n  `heapTotal=${(heapTotal / 1e6).toFixed(1)}MB`\n);\n```\n\nThe most important fields in practice: `heapUsed` and `heapTotal` concern the JavaScript heap managed by V8, while `rss` (resident set size) gives the process’s total memory, including native parts. If I watch `heapUsed` keep rising in a loop or across several requests and not coming back down after garbage collection, I have a first, very concrete hint of a memory leak. For a quick RSS value alone, there has also been `process.memoryUsage.rss()` since Node 15.6.\n\nThat doesn’t replace real profiling, but it is a cheap early-warning value – especially for long-running processes or when processing large amounts of data, as happens when dealing with [streams and backpressure](https://www.mikebild.dev/en/blog/nodejs-streams-understanding-backpressure/).\n\n## Profiling through the same inspector\n\nWhen the rough look with `process.memoryUsage()` isn’t enough, the next step leads back to the inspector. The same connection I use for setting breakpoints also opens the analysis tabs in DevTools: under “Memory”, I take a heap snapshot and see which objects occupy how much memory. Under “Profiler” or “Performance”, I record a CPU profile and find out in which functions the time is actually spent.\n\nIf you prefer to work without a graphical frontend, there are CLI alternatives. `node --prof` writes a V8 log that I then turn into a readable report with `node --prof-process`:\n\n```bash\nnode --prof ./src/server.js\n# ... generate load, then stop the process ...\nnode --prof-process isolate-0x*.log > processed.txt\n```\n\nIn addition, since Node 12 there are the still experimental flags `--cpu-prof` and `--heap-prof`, which produce profile files in DevTools format directly. On teams, though, the interactive route through DevTools has usually won out, because it uses the same UI that is already familiar from the frontend.\n\n## The four steps at a glance\n\nBack to the escalation ladder from the beginning. I deliberately summarize the four tools as steps, because each has its own purpose and none fully replaces another:\n\n- `console.log` – always active, unstructured, immediately available. Good for a quick one-off look, bad as a permanent solution and out of place in production.\n- `debug` – controlled by namespace, switchable via the `DEBUG` environment variable without code changes, output on stderr. Ideal for making specific layers visible during development.\n- Inspector – interactive breakpoints in Chrome DevTools or VS Code, via `--inspect` or `--inspect-brk`. The step from guessing to investigating.\n- Profiler – the same inspector, but for CPU profiles and heap snapshots. Used when it is not about correctness but about performance and memory.\n\n```mermaid\nflowchart TB\n  A[\"console.log<br/>always on, unstructured\"] --> B[\"debug<br/>DEBUG env, namespace-controlled\"]\n  B --> C[\"Inspector<br/>interactive breakpoints\"]\n  C --> D[\"Profiler<br/>CPU profile and heap snapshot\"]\n```\n\n## Two pitfalls that can get expensive\n\nFinally, two things I explicitly raise in code reviews because they do real damage in production.\n\nThe first concerns `console.log` in production. What looks harmless during development becomes a problem in continuous operation: the output is unstructured, can’t be turned off with a switch, pollutes stdout and, depending on volume, costs performance. For development, `debug` is the better choice, and production needs a proper logger that handles log levels, structured output and targeted switching on and off.\n\nThe second pitfall is more dangerous and often underestimated: leaving an open `--inspect` port behind or binding it to `0.0.0.0`. The debug port allows executing arbitrary code in the process – whoever reaches it can take over the server. That is why Node.js binds only to `127.0.0.1` out of the box, and as a rule it should stay that way. If I really have to debug a remote process, I tunnel the port over SSH instead of exposing it publicly:\n\n```bash\nssh -L 9229:localhost:9229 user@remote-host\n```\n\nAnd the debug flag has no business in any production start script. This separation between development and production operation is closely tied to what already comes up in the [Node.js training on the event loop architecture](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/): tools that reach into the running process are powerful – and that is exactly why access to them must stay narrow.\n\n## An outlook\n\nIf you want to go even deeper, Node.js has two advanced building blocks that I only mention here as an outlook, because they deserve posts of their own: `async_hooks` to track the lifecycle of asynchronous resources, and `diagnostics_channel` to exchange structured diagnostic events between libraries and observers. Both are more for tool builders and library authors than for everyday bug hunting.\n\n## Conclusion\n\nThe way from the `console.log` reflex to deliberate debugging isn’t a big leap but a small ladder with four rungs. `console.log` remains for a quick look, but as soon as things get more structured, `debug` takes over with its switchable logging. When it gets really tricky, the built-in inspector pauses the process and lets me examine variables and call stacks – in Chrome DevTools or VS Code, whichever you prefer, because both speak the same protocol. And when performance or memory is the topic, the same inspector switches into profiler mode, while `process.memoryUsage()` already provides a cheap early-warning value beforehand. If you know these steps and keep the debug port consistently closed, you stop guessing and start investigating.\n\n## Further reading\n\n- Grounding from the repository: `introduction-nodejs/19-quality-tools.md` (chapter “Quality Tools”)\n- Debugging Node.js (official guide): https://nodejs.org/en/learn/getting-started/debugging\n- CLI options (`--inspect`, `--inspect-brk`, `--prof`, `--cpu-prof`, `--heap-prof`): https://nodejs.org/api/cli.html\n- Inspector module: https://nodejs.org/api/inspector.html\n- `process.memoryUsage()`: https://nodejs.org/api/process.html#processmemoryusage\n- debug module: https://www.npmjs.com/package/debug or https://github.com/debug-js/debug\n- nodemon: https://github.com/remy/nodemon\n- Outlook – diagnostics_channel: https://nodejs.org/api/diagnostics_channel.html · async_hooks: https://nodejs.org/api/async_hooks.html"},{"locale":"en","translation_key":"developer-productivity-verkuerzte-zyklen","slug":"developer-productivity-shorter-cycles","title":"Developer Productivity: Shorter Cycles with High Quality","summary":"Short feedback loops with reliable quality are my mental model for developer productivity. Where the waiting actually happens has to be shown by your own lead time.","tags":["Software","Delivery"],"published_at":"2022-12-26T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/developer-productivity-shorter-cycles/","audio_url":null,"audio_duration_secs":null,"text":"Lead time and processing time are two different quantities. Processing time is the span in which someone actually works on a change – reading, writing, testing. Lead time is the span from the first line to the feedback from production. The difference between the two is idle time: hours and days in which a finished change exists and nothing happens to it.\n\nTake a change with two hours of processing time and three days in queues: before the build, before the review, before a free test environment. In this example, the call for more people targets the smaller quantity. Whether your own system looks the same can be read from the timestamps of commit, review, build and deployment – not from a general claim about developer work.\n\nMy mental model for this is: **short feedback loops with reliable quality**. That is not a measurable formula but a reminder of two limits. Speed without a quality net produces faster failures; quality assurance without timely feedback produces large queues. Which side is slowing you down right now is shown by the measured cycle time.\n\nProductivity emerges in two connected feedback loops whose rhythm and result must not be confused.\n\n::::comparison{title=\"Two loops, two kinds of feedback\" role=\"primary\" preferredPattern=\"split-comparison\"}\n:::side{label=\"Delivery loop\"}\n- Question · How quickly does a small change reliably reach production?\n- Sequence · Code, build, test, review and deploy\n- Time scale · Minutes to hours\n- Signal · Technical feedback and production behavior\n:::\n:::side{label=\"Discovery loop\"}\n- Question · Does the change solve the right problem?\n- Sequence · Hypothesis, implementation, measurement and learning\n- Time scale · Days to weeks\n- Signal · Observed impact and validated learning\n:::\n::::\n\nA fast delivery loop without discovery may quickly ship the wrong thing. A good hypothesis without a short delivery loop waits too long for reliable feedback.\n\n## Speed and stability are not a trade-off\n\nThe most persistent fallacy in this discussion is the assumption that you have to choose between speed and stability. “We could deliver faster, but then more things break” – I hear this sentence regularly in steering meetings. The data says the opposite.\n\nThe central finding of *Accelerate* (Forsgren, Humble, Kim, 2018), the book version of the DORA research with over 23,000 responses from more than 2,000 organizations, is unambiguous: high performers are better at speed **and** quality. Nowhere in the data does a team buy one at the expense of the other. The fast teams are also the stable ones. That is a statistical correlation, not a question of attitude – and the foundation for the thesis that cycles and quality support each other.\n\nThis is operationalized through the four DORA metrics, which measure exactly these two dimensions. For throughput: *Deployment Frequency* and *Lead Time for Changes* – the time from commit to production. For stability: *Time to Restore Service* (the time to recover after an incident) and *Change Failure Rate* – the share of deployments that cause a failure. Lead time is the measurable version of the “short feedback loop” from my formula. If you lower it, you lower exactly the waiting time this is about.\n\nA note on precision, because this is often quoted sloppily: for years, the State of DevOps reports sorted teams into clusters – in 2021 still with a separate “elite” group. The 2022 report found only three clusters (high, medium, low), no “elite” anymore. If you argue today with “according to DORA, elite teams…,” you should know which year the number comes from.\n\n## Why the bottleneck is waiting\n\nContinuous integration is often understood as “tooling” – you set up a build server and check the box. The point is a different one. Martin Fowler defines CI as a practice where members of a team integrate their work frequently and each integration is verified by an automated build, including tests, to detect integration errors as quickly as possible. The decisive word is “quickly.” CI is a latency machine: it shortens the time between a defect and its discovery. The bottleneck CI addresses is waiting and integration latency – not code volume.\n\nThe deployment pipeline (also Fowler) is the deliberate handling of this latency. You break the path to production into stages: early stages give initial confidence in seconds to minutes, later ones are more thorough and may be slower for it. This turns where feedback should be fast and where it should be thorough into a design decision.\n\n```yaml\npipeline:\n  - stage: commit          # target: < 10 min  -> fastest feedback\n    steps: [compile, unit_tests, static_analysis]\n  - stage: acceptance      # target: minutes   -> contract & integration\n    steps: [contract_tests, integration_tests]\n  - stage: deploy_staging  # ephemeral environment on demand\n    steps: [provision_env, smoke_tests]\n  - stage: production      # gated by feature_flag, not by branch age\n    steps: [progressive_rollout, health_check]\n```\n\nIn front of such a skeleton, exactly one question matters: where is time really lost? The answer is rarely `unit_tests`. It is `compile` when the commit build takes twelve minutes instead of under ten. It is `review` when a pull request sits in the queue for two days. It is `provision_env` when a test environment is requested by hand and provided overnight. Those are the real latency levers. Writing the tests, meaning the time at the keyboard, is almost never the problem.\n\nThis also explains why “shift left” is more than a buzzword. A contract break between two services that only shows up in a nightly end-to-end environment costs a day. The same break showing up in the commit build costs minutes. It is the same defect – only the feedback latency differs by orders of magnitude.\n\n## The two loops\n\nShort cycles exist on two levels, and I often see teams optimizing only one of them. The inner loop is delivery: `code → commit → build → automated tests → review → deploy`, measured in minutes. The outer loop is discovery: `hypothesis → build → measure → learn`, measured in days to weeks. The inner loop makes sure you ship something quickly and safely. The outer one makes sure it is the right thing.\n\nThis outer loop is easily forgotten, even though it is the same idea at the product level. Eric Ries described it in *The Lean Startup* (2011) as *Build–Measure–Learn* with the goal of *validated learning*. Teresa Torres made it concrete in *Continuous Discovery Habits* (2021): weekly customer interviews, the opportunity solution tree that brings opportunities and solution ideas into a visible order, systematic assumption testing. Here, too, what counts is not more output but shorter learning cycles. A team that pushes its inner loop down to minutes but waits half a year before noticing that nobody needs the feature has optimized the wrong bottleneck.\n\n```mermaid\nflowchart LR\n  subgraph inner[\"Inner loop – Delivery (minutes)\"]\n    code[\"code\"] --> commit[\"commit\"]\n    commit -->|\"wait: build\"| build[\"build\"]\n    build --> tests[\"automated tests\"]\n    tests -->|\"wait: review\"| review[\"review\"]\n    review -->|\"wait: provision env\"| deploy[\"deploy\"]\n  end\n  subgraph outer[\"Outer loop – Discovery (days / weeks)\"]\n    hypothesis[\"hypothesis\"] --> buildit[\"build\"]\n    buildit --> measure[\"measure\"]\n    measure --> learn[\"learn\"]\n    learn --> hypothesis\n  end\n  deploy --> measure\n  learn -.-> code\n```\n\nThe labeled edges in this sketch are deliberately the waiting edges: `build`, `review`, `provision env`. That is where cycle time is decided. DORA lead time measures the inner loop, discovery cadence the outer one. Together they give the number that counts: how often per week a team learns something validated.\n\n## Quality is the net, not the brake\n\nNow the part that is easily skipped in the euphoria about speed. The formula is multiplicative. Short cycles without a quality net do not mean “delivering faster” but “breaking faster.” If you reduce batch size and deploy more often without automated tests, contract tests and a real deployment pipeline, you mainly lower one thing: the time to the next incident. Reducing batch size without stability mechanisms only shifts the bottleneck – from waiting before the deploy to cleaning up after it.\n\nThat is why quality belongs in the same pipeline as speed. Where services talk to each other across system boundaries, consumer-driven contract testing carries a large part of this load. The idea (it goes back to Ian Robinson and Fowler, 2006, and is widely established with frameworks like Pact): the consumer describes what it expects from the provider, and this expectation is verified independently on both sides – without having to spin up a shared, slow end-to-end environment.\n\n```javascript\n// consumer side: describe the expectation, generate a pact file\nconsumerTest(\"fetches a user by id\", () => {\n  provider\n    .given(\"a user exists\")\n    .uponReceiving(\"a request for user 42\")\n    .withRequest({ method: \"GET\", path: \"/users/42\" })\n    .willRespondWith({\n      status: 200,\n      body: { id: 42, name: like(\"Ada\") }, // matcher, not a fixed value\n    });\n  // -> produces a pact contract, verified in the provider's own pipeline\n});\n```\n\nThe gain is twofold. The contract test runs in the `acceptance` stage in seconds instead of an end-to-end test running for minutes in a specially provisioned environment – the feedback loop at the service boundary gets shorter. And it is more precise: it does not just say “something is red,” but “the provider no longer returns `name`.” That is quality that enables speed instead of slowing it down.\n\nThe same idea belongs at the architecture level. Michael Nygard described the stability patterns in *Release It!* (2007, 2nd edition 2018) – circuit breaker, bulkhead and relatives – so that a failure in one part does not drag down the whole. And Neal Ford, Rebecca Parsons and Patrick Kua introduced the idea of fitness functions in *Building Evolutionary Architecture* (2017): automated, executable checks for architectural properties such as latency, coupling or security. Both are the same movement as with tests – quality is turned into something executable that gives fast feedback in the pipeline instead of gathering dust in a review document.\n\n## How to actually build short cycles\n\nFrom practice, a few levers that work reliably – ordered by what hits the waiting edges most directly.\n\nThe commit build has to be fast. Fowler’s rule of thumb of the “ten-minute build” is not nostalgia but a psychological limit: if the build takes longer, the team stops integrating frequently, and the batches grow again. A fast, broad base of unit tests and a narrow top of slow end-to-end tests – the classic test pyramid – keeps the build fast without losing coverage.\n\nKeep branches short. Trunk-Based Development with short-lived feature branches and feature flags decouples “code is merged” from “feature is on.” This is the point at which `production` is gated by a feature flag, not by the age of a branch. Long-lived branches are the classic way integration waiting time builds up invisibly until the merge becomes a day-long project.\n\nEnvironments on demand. If `provision_env` is a ticket to another team, your lead time is not a technical quantity but an organizational one. Ephemeral, script-generated environments take this edge out of the queue.\n\nAnd the point that causes the most conflict: measure the system, not the person. The four DORA metrics are team and system outcome metrics. Misused as an individual developer ranking, they immediately produce Goodhart effects – you optimize the number instead of the thing. If you are measured by “deployments per developer,” you produce micro-deploys; if you are measured by change failure rate, you relabel incidents. Forsgren and colleagues explicitly warned against such vanity and individual metrics. The metrics show the health of a flow, not the performance of an individual.\n\n## Conclusion\n\nProductivity in software development cannot be described meaningfully by hours worked alone. In many flows, a large part of the lead time is spent waiting for build, review or environment; whether that is the bottleneck here has to be shown by measurement. DORA metrics describe the delivery capability of the system. Contract tests, stability patterns and fitness functions can make selected quality risks visible earlier, while the discovery loop checks whether the team is working on the right problem at all.\n\nIf you want to start tomorrow: draw your inner loop and write the real waiting time on every edge. The longest of them is a good candidate for the next improvement. Then measure again. Short cycles and reliable quality remain two separate quantities; neither may hide the other.\n\n## Further reading\n\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate* (2018) – the finding that speed and stability are not a trade-off: <https://itrevolution.com/product/accelerate/>\n- Four Keys / DORA metrics explained: <https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance>\n- DORA metrics and the cluster classification: <https://dora.dev/guides/dora-metrics-four-keys/>\n- Martin Fowler: *Deployment Pipeline*: <https://www.martinfowler.com/bliki/DeploymentPipeline.html>\n- Martin Fowler: *Continuous Delivery*: <https://martinfowler.com/bliki/ContinuousDelivery.html>\n- Teresa Torres: *Continuous Discovery Habits* (2021): <https://businessofsoftware.org/talks/continuous-discovery/>"},{"locale":"en","translation_key":"svelte-slots-context-und-web-components","slug":"slots-context-and-web-components-in-svelte","title":"Slots, Context and Web Components in Svelte","summary":"Three composition tools in Svelte 3: slots pass content in from the outside, the Context API avoids prop drilling, and custom elements make a component reusable independently of any framework.","tags":["Software","Frontend","Svelte"],"published_at":"2022-11-22T10:00:00+00:00","updated_at":"2026-07-13T07:59:51.626923+00:00","url":"https://www.mikebild.dev/en/blog/slots-context-and-web-components-in-svelte/","audio_url":null,"audio_duration_secs":null,"text":"A reusable card into which every team can put its own header and its own content: the requirement sounds harmless, and yet you cannot solve it cleanly with props alone. In review, the evasive maneuvers then show up – a store where a slot would have been enough; a prop threaded through seven components even though the Context API would have been the shorter route; a component library that only runs under Svelte even though framework-neutral reuse was the actual goal.\n\nSlots, the Context API and custom elements appear side by side in the same components and are therefore easily confused. What tells them apart is the direction in which something flows: markup from the outside into a component, data from the inside back to that markup, values downward through any number of levels of the component tree. If you briefly clarify which of these directions you need before choosing a tool, you have usually made the decision already.\n\n**Editorial note (July 2026):** The title explicitly refers to Svelte 3. In Svelte 5, snippets and `{@render ...}` are the preferred way of composition instead of slots; callback props replace many component events in new code. Context and custom elements remain. The historical syntax stays here; the sources also show today’s counterparts.\n\n## Slots: passing content in from the outside\n\nA slot is a placeholder in a component that the caller fills from the outside. The card component decides on the frame, spacing and layout – the caller determines what goes inside. The simplest case is the default slot:\n\n```svelte\n<!-- Card.svelte -->\n<div class=\"card\">\n  <slot>Nothing here yet</slot>\n</div>\n\n<style>\n  .card {\n    border: 1px solid #ddd;\n    border-radius: 8px;\n    padding: 1rem;\n  }\n</style>\n```\n\nThe content between the `<slot>` tags is the fallback: it only appears when the caller passes nothing. The card is then used like this:\n\n```svelte\n<Card>\n  <p>This paragraph lands inside the card.</p>\n</Card>\n```\n\nIt gets interesting with named slots. A card often has more than one zone – a header and a body, for example. In the child component you assign names for them; in the call you assign markup to those names:\n\n```svelte\n<!-- Card.svelte -->\n<div class=\"card\">\n  {#if $$slots.header}\n    <header class=\"card-header\">\n      <slot name=\"header\"></slot>\n    </header>\n  {/if}\n  <div class=\"card-body\">\n    <slot></slot>\n  </div>\n</div>\n```\n\n```svelte\n<Card>\n  <h2 slot=\"header\">Release notes</h2>\n  <p>Everything else fills the default slot.</p>\n</Card>\n```\n\nThe `$$slots` object deserves a quick look. Its keys are the slot names that were actually passed, and that lets you render the structure conditionally. The `<header>` frame only appears if the caller really passed a header – otherwise you would have an empty, bordered box. That is the difference between a component you enjoy using and one you find awkward.\n\nWhat matters here is that `$$slots` only reports the presence of a slot, not its content at runtime. Whether a named slot is filled is decided at compile time based on the call, not by what the caller renders into it later. For the typical task – leaving out the frame when nobody supplies a header – that is exactly enough, and you should not confuse `$$slots` with a reactive check for empty content. A second point that comes up regularly in reviews: a named slot can only be output in one place in a component. If you render the same named slot twice, you do not get duplicated content but behavior you should not rely on. If you need the same passed-in content in several places, the way forward is slot props or restructuring the component, not a second `<slot name=\"…\">`.\n\n### Slot props: data from the inside out\n\nUp to this point, content flows in only one direction: from the outside in. The second part reverses that direction, and this is exactly what gets confused most often. Slot props allow the child component to pass data outward to the inserted markup. The classic case is a list that takes care of iterating but leaves the rendering of each entry to the caller:\n\n```svelte\n<!-- List.svelte -->\n<script>\n  export let items = [];\n</script>\n\n<ul>\n  {#each items as item, index}\n    <li>\n      <slot name=\"item\" {item} {index}>\n        {item}\n      </slot>\n    </li>\n  {/each}\n</ul>\n```\n\nThe child component passes `item` and `index` outward through the slot. The caller receives these values with the `let:` directive and is free to decide what an entry looks like:\n\n```svelte\n<List items={users}>\n  <span slot=\"item\" let:item let:index>\n    {index + 1}. {item.name} – {item.role}\n  </span>\n</List>\n```\n\nThe list takes care of the loop, keys and structure; the caller brings the concrete rendering and in return receives exactly the data it needs. Keeping these two directions cleanly apart is the core of understanding slots: markup flows in from the outside, data flows from the inside out via slot props. The following diagram captures both paths side by side.\n\n```mermaid\nflowchart LR\n  Parent[\"Parent<br/>&lt;List let:item&gt;\"]\n  Child[\"List.svelte<br/>&lt;slot name='item' {item}&gt;\"]\n  Render[\"Rendered &lt;li&gt;\"]\n\n  Parent -- \"markup (outside in)\" --> Child\n  Child -- \"slot props: item, index (inside out)\" --> Parent\n  Child --> Render\n```\n\n## Context: passing through the tree without prop drilling\n\nSlots solve the question of how to give content to a direct child component. They do not help when a value is needed several levels deep. Imagine a toolbar whose individual buttons want to register with it. Between the toolbar and the button there may be groups, dividers, wrappers. Passing the registration callback through each of these levels as a prop is tedious and makes intermediate components depend on details that are none of their business. This passing along is called prop drilling, and the Context API is the direct answer to it.\n\nThe provider component stores a value under a key, and every descendant component can retrieve it under the same key:\n\n```svelte\n<!-- Toolbar.svelte -->\n<script>\n  import { setContext } from 'svelte';\n\n  const buttons = [];\n  function registerButton(id) {\n    buttons.push(id);\n  }\n\n  setContext('toolbar', { registerButton });\n</script>\n\n<div class=\"toolbar\">\n  <slot></slot>\n</div>\n```\n\n```svelte\n<!-- ToolbarButton.svelte -->\n<script>\n  import { getContext } from 'svelte';\n\n  export let id;\n  const toolbar = getContext('toolbar');\n  toolbar.registerButton(id);\n</script>\n\n<button on:click>\n  <slot></slot>\n</button>\n```\n\nThe button finds its toolbar no matter how many levels lie in between. No prop travels through the intermediate components. By the way, the key may be any value – a string as here, a symbol or an object; a symbol reliably protects against name collisions in larger repositories.\n\nThe scope of context is strictly limited to the subtree below the provider. A sibling component that does not hang under the same `setContext` component does not see the value – context flows only downward, never sideways and never upward. If a child component itself calls `setContext` with the same key, it shadows the value for its own subtree without changing the value further up; resolution therefore follows the instance hierarchy, not the order in the source code. If you are not sure whether a key was set at all, you can check with `hasContext` instead of relying on an `undefined` from `getContext` – that makes the failure case explicit instead of silent.\n\nTwo pitfalls come up with remarkable regularity. The first: `setContext` has to be called synchronously during the component’s initialization. If you move the call into `onMount`, an event handler or an `async` function, you do not get an error but something worse – the children simply receive `undefined` on their later `getContext`, and the cause is hard to find. The second pitfall concerns reactivity.\n\n```mermaid\ngraph TD\n  Provider[\"Toolbar<br/>setContext('toolbar', …)\"]\n  Group[\"ButtonGroup<br/>(no props)\"]\n  Divider[\"Divider<br/>(no props)\"]\n  Consumer[\"ToolbarButton<br/>getContext('toolbar')\"]\n\n  Provider --> Group --> Divider --> Consumer\n```\n\n### Context is not the same as a store\n\nContext is bound to the component instance and is not reactive on its own. If I put a plain number into the context and change it later, the children do not update – they read their copy at init, and that is where it stays. A store, in contrast, can be shared globally and is reactive; with `$store` you subscribe to changes and re-render on every update. I have written in more detail about state outside the component and the store mechanics in [Svelte Stores](https://www.mikebild.dev/en/blog/svelte-stores-state-outside-the-component/), and the underlying reactivity is the topic of [Svelte reactivity](https://www.mikebild.dev/en/blog/svelte-reactivity-the-compiler-instead-of-a-virtual-dom/).\n\nThe two do not exclude each other; on the contrary. The most useful combination in practice puts a store *into* the context. That gives you both: the implicit distribution through the tree from context and the reactivity of a store.\n\n```svelte\n<!-- ThemeProvider.svelte -->\n<script>\n  import { setContext } from 'svelte';\n  import { writable } from 'svelte/store';\n\n  const theme = writable('light');\n  setContext('theme', theme);\n</script>\n\n<slot></slot>\n```\n\n```svelte\n<!-- ThemeToggle.svelte -->\n<script>\n  import { getContext } from 'svelte';\n\n  const theme = getContext('theme');\n</script>\n\n<button on:click={() => theme.update((t) => (t === 'light' ? 'dark' : 'light'))}>\n  Current theme: {$theme}\n</button>\n```\n\nNow context passes the store to every descendant component, and because it is a store, `{$theme}` reacts to every change – without threading a single prop through the tree.\n\n## Web Components: framework-neutral reuse\n\nSlots and context solve composition problems inside a Svelte application. The third tool aims outward. Sometimes a component should also work where no Svelte runs – in an existing page, in another framework, in plain HTML. Svelte can compile a component as a custom element, that is, as a real Web Component according to the browser standard.\n\nYou need two things for this. In the component, you assign a tag name via `<svelte:options>`, and when compiling you enable the `customElement` option:\n\n```svelte\n<!-- UserBadge.svelte -->\n<svelte:options tag=\"user-badge\" />\n\n<script>\n  export let name = 'Unknown';\n  export let status = 'offline';\n</script>\n\n<span class=\"badge\" data-status={status}>\n  {name}\n</span>\n\n<style>\n  .badge {\n    display: inline-flex;\n    padding: 0.25rem 0.5rem;\n    border-radius: 999px;\n  }\n  .badge[data-status='online'] {\n    background: #d1fae5;\n  }\n</style>\n```\n\nWhen bundling, you switch the compiler to custom element output. With Rollup and the official plugin, the relevant part looks like this:\n\n```js\n// rollup.config.js\nimport svelte from 'rollup-plugin-svelte';\n\nexport default {\n  // ...\n  plugins: [\n    svelte({\n      compilerOptions: {\n        customElement: true,\n      },\n    }),\n  ],\n};\n```\n\nAfter that, `<user-badge>` is a perfectly normal HTML element. You can use it in any page, without any Svelte runtime on the caller’s side:\n\n```html\n<script src=\"./user-badge.js\"></script>\n\n<user-badge name=\"Ada\" status=\"online\"></user-badge>\n```\n\nThe exported props become element properties and attributes, so you can address the element like any other DOM element. Svelte encapsulates the styles via Shadow DOM – the badge styles do not spill over onto the surrounding page, and page styles do not leak in uncontrolled. That is usually desired, but it surprises you if you expect global styles; `:global` rules behave differently here.\n\nAt this point it is worth taking an honest look at the rough edges, because at the end of 2022, Svelte’s custom element mode is functional but not free of tension. The most important point concerns passing data: HTML attributes are always strings. A `name=\"Ada\"` in the markup arrives cleanly, but you cannot pass an object or an array as an attribute. You have to set such values as a JavaScript property on the element, such as `el.items = [...]` – a detail that is easy to overlook if you only use the element declaratively in HTML. Second, custom elements are registered globally once defined; the same tag name cannot be used twice in the same document, which can lead to conflicts when you include several bundles. And third, Shadow DOM encapsulation is a gain for isolation, but it takes away the convenient reach from the outside: if you want to style the element from the page, you have to open the intended places yourself and pass CSS custom properties in deliberately. None of this is a knockout criterion, but these are the places where practice deviates from the first smooth demo.\n\nA practical tip from projects: `customElement: true` belongs only on the components you actually want to export, not project-wide. Otherwise you compile the whole app into custom elements and lose the regular Svelte component mode with its advantages. In practice, I maintain a separate build entry for this that bundles exactly the components to be exported.\n\n## When to use which tool\n\nThe three mechanisms can be sorted clearly by their purpose:\n\n- You choose slots when a component dictates its layout but should get its content from the caller – with slot props also when the caller needs data from the inside for rendering.\n- You choose context when a value or a function is needed several levels deeper and prop drilling would burden the intermediate components unnecessarily; for reactive values, you put a store into the context.\n- You choose Web Components when a component should run outside the Svelte world – in other frameworks or in plain HTML.\n\nA brief note on context at the end of 2022: throughout, I refer to Svelte 3, the current version these days. The syntax shown, `tag=\"user-badge\"`, is the state of Svelte 3; later versions brought changes at this point that are deliberately left out here. If you keep the repository you work on at Svelte 3, you are on safe ground with everything shown here.\n\n## Conclusion\n\nSlots, context and Web Components seem at first like three unrelated features, but they are a coherent set of composition tools, each with its own direction. Slots pass markup in from the outside and, via slot props, data back out from the inside. Context distributes values implicitly through the component tree and saves you from prop drilling – it only becomes reactive with a store inside. And custom elements lift a component out of the Svelte world so that it runs wherever standard HTML runs. If you briefly ask yourself with every composition problem in which direction content or data should flow and how far it needs to reach, you will reach for the right one of the three tools almost by yourself. This one question saves you most of the detours in a project.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-svelte.en.html\n- [Svelte 5: Snippets](https://svelte.dev/docs/svelte/snippet)\n- [Svelte: slots in legacy mode](https://svelte.dev/docs/svelte/legacy-slots)\n- [Svelte: Context API](https://svelte.dev/docs/svelte/context)\n- [Svelte: custom elements](https://svelte.dev/docs/svelte/custom-elements)\n- [Svelte: `<svelte:options>`](https://svelte.dev/docs/svelte/svelte-options)"},{"locale":"en","translation_key":"build-vs-runtime-webprojekte","slug":"build-vs-runtime-in-web-projects","title":"Build vs. Runtime in Web Projects","summary":"The rendering time is decided per route. Static, dynamic and incremental models can be combined according to data shelf life, cost and failure behavior.","tags":["Software","Frontend"],"published_at":"2022-11-12T10:00:00+00:00","updated_at":"2026-07-13T08:48:49.883691+00:00","url":"https://www.mikebild.dev/en/blog/build-vs-runtime-in-web-projects/","audio_url":null,"audio_duration_secs":null,"text":"# Build vs. Runtime in Web Projects\n\nWhen you set up a project, this decision takes one second: you pick a framework, accept the default and from then on render everything on the server. You only notice that second months later – when the build takes twenty minutes or the servers fill up at the first traffic spike.\n\nThe rendering time of a page is an architectural boundary, not a setting you configure away in the build setup. It determines when a page is created, how fresh its data is, what a failure costs and how fast a team can deliver. Still, the question – do we render at build time or at runtime? – usually gets answered implicitly. If you draw the boundary deliberately, you shorten cycles, cut costs and take friction out between content, development and operations.\n\n## The two points in time\n\nEvery piece of output on the web is created at one of two points in time. At **build time**, work runs once, before any user arrives: templates become HTML, data gets frozen, assets get bundled and optimized. At **runtime**, work runs per request or in the browser while a user waits: data gets fetched, permissions checked, HTML assembled, state hydrated.\n\nThe key difference is not “fast vs. slow” but **who waits and how often the work happens**. Build work happens once and is delivered any number of times – the user never waits for it. Runtime work happens again on every request – in return, it knows the current moment, the logged-in user and the latest data.\n\n```mermaid\nflowchart LR\n  subgraph Build[\"Build-Zeit (einmal)\"]\n    Content --> Prerender\n    Prerender --> StaticHTML[\"Static HTML + Assets\"]\n  end\n  subgraph Runtime[\"Laufzeit (pro Request)\"]\n    Request --> Fetch[\"Fetch data + auth\"]\n    Fetch --> Render[\"Render + hydrate\"]\n  end\n  StaticHTML --> CDN\n  CDN --> User\n  Render --> User\n```\n\nBetween these poles lies a spectrum, not an either-or: static site generation freezes everything at build time. Server-side rendering rebuilds per request. Client-side rendering pushes the work into the browser. And hybrid forms – prerendering plus client-side loading, or static HTML with incremental revalidation – mix both points in time per route. The art lies in drawing the boundary in the right place for each page instead of proclaiming one approach for everything.\n\n## The trade-off, concretely\n\nI tie the trade-off to three quantities, because exactly these three carry or slow down a product: freshness of data, cost per request and time to feedback in the team.\n\nA marketing or documentation page rarely changes and is the same for everyone. Freezing it at build time is almost always right: afterward it sits as a static file in the CDN, costs practically nothing per request, has no server latency and no server that can fail.\n\n```js\n// Build-time: runs once, per deploy\nexport async function getStaticProps() {\n  const posts = await cms.getPublishedPosts();\n  return { props: { posts } };\n}\n```\n\nAn account balance, a personalized dashboard or a price list that changes every hour can’t be frozen. This data belongs at runtime – either per request on the server or as a client-side fetch after the first paint.\n\n```js\n// Runtime: runs on every request, knows \"now\" and the user\nexport async function getServerSideProps(ctx) {\n  const user = await auth(ctx.req);\n  const balance = await ledger.getBalance(user.id);\n  return { props: { balance } };\n}\n```\n\nThe real question is not “SSG or SSR?” but: **How old may this output be without becoming wrong?** I call that the data shelf life. If the shelf life is practically infinite (a blog post from 2019), the page belongs in the build. If the shelf life is zero (the current account balance), it belongs at runtime. And in between – the shelf life is minutes or hours – it gets interesting: then I want the delivery cost of a static asset, but a controlled refresh. That’s exactly what caching with revalidation and incremental regeneration exist for. They are the technical answer to a finite data shelf life, not a framework gimmick.\n\n## What this changes, measurably\n\nThe reason I take this boundary so seriously is its effect on hard numbers.\n\nA statically delivered page responds with the latency of the nearest CDN node – double-digit milliseconds, regardless of load. Rendering the same page on the server per request means database round trips, template rendering and a server that has to scale with traffic. During a traffic spike, that’s the difference between “the CDN delivers a file” and “our instances are maxed out and the autoscaling bill explodes.” For pages without a real data shelf life, runtime rendering is therefore not only more expensive but also more fragile – you buy complexity without getting anything in return.\n\nConversely, too much build work costs feedback. If every change to a post triggers a full rebuild of ten thousand pages, the build becomes the bottleneck: an editorial typo takes 20 minutes to become visible, and nobody dares to deploy shortly before the end of the day anymore. That’s not just a performance problem but a productivity problem. The consequence is not “more runtime” but a finer boundary: regenerate only the affected pages instead of everything. Shorter feedback loops are the real gain here – they decide how often a team ships and how calmly it does so.\n\nA case I’ve come across in projects: a content-heavy portal historically renders everything on the server because that was once the framework default. Under normal load it works, but the server bill grows linearly with traffic, and every press release that makes the portal go briefly viral turns into an incident. If you move the dozen or so truly static page types – articles, categories, landing pages – into the build and leave only search and personalized areas at runtime, the curve changes fundamentally. The lion’s share of the traffic becomes a CDN file, the servers only carry the small dynamic remainder, and the traffic spike is suddenly a non-event. Not a single line of domain logic was rewritten – only the boundary between build and runtime was adjusted to the actual data shelf life.\n\nThat’s why I like to summarize the decision in a small table before I touch any tool:\n\n| Page | Data shelf life | Point in time |\n| --- | --- | --- |\n| Landing page, docs | practically infinite | Build |\n| Product catalog | hours | Build + revalidation |\n| Search result, feed | seconds | Runtime (server) |\n| Dashboard, account balance | zero, personalized | Runtime (server/client) |\n\nThe table is deliberately simple. It forces exactly the one question you’d otherwise skip: how old may this be?\n\n## How I draw the boundary\n\nBefore the tooling question, I clarify per route: is the output the same for all users or personalized? How old may it be? What happens if the data source doesn’t respond during rendering? And can the point in time be changed later without rebuilding half the application? If I slice a page so that I can move its rendering time in isolation – from build to runtime, to incremental or back – without touching neighboring routes, then the boundary is usable.\n\nAn often underestimated part of this is the lifetime of state. In the frontend, the hardest decision is rarely the component tree but the question of where state lives: in a component, in the URL, in a cache, on the server or in a local model. That question is the build-vs-runtime question in miniature. State that belongs in the URL can be rendered on the server and shared. State that exists only on the client requires runtime in the browser and is simply not present in the static HTML. If you get this mapping right, you get shareable, indexable, testable pages almost for free.\n\n## Progressive enhancement as the same boundary\n\nThis way of thinking isn’t new; it has just grown old. Progressive enhancement has always asked: what do I deliver as a robust baseline, and what do I add at runtime if the client can handle it? Even a canvas element carries this attitude – first check whether a capability is there, then enable a behavior, otherwise offer a fallback.\n\n```html\n<canvas id=\"clock\" width=\"150\" height=\"150\">\n  <img src=\"clock.png\" alt=\"Clock fallback\" />\n</canvas>\n```\n\n```js\nconst canvas = document.getElementById(\"clock\");\nif (canvas.getContext) {\n  const ctx = canvas.getContext(\"2d\");\n  // enhance at runtime, only when supported\n}\n```\n\nExactly the same order – capability, boundary, behavior – applies to server-delivered HTML plus client-side hydration. The static baseline is the build output. The enhancement is the runtime. If both layers are cleanly separated, the page works even when the runtime layer is slow or fails. That’s not outdated knowledge but the conceptual root of the whole rendering discussion.\n\n## The failure path decides\n\nA rendering decision only holds up once its failure path is described. What happens if the CMS doesn’t respond during the build – does the deploy abort, or does the page go live with a gap? What happens if an API hangs during server-side rendering – does the whole response block, or does the page render without that part and load it on the client? These questions seem dry, but they’re the difference between a demo and production.\n\nBuild rendering moves the risk of failure into the deploy pipeline: failures happen once, visibly, before any user sees them. Runtime rendering spreads the risk across every single request: failures happen live, under load, at the worst moment. Both are legitimate – but you should know which risk you’re buying. That’s why I always check whether the decision is reversible: can I switch a route from runtime to build when load increases? Can I invalidate a cache selectively without rebuilding everything? If the answer is no, part of the architecture is still missing.\n\n## Typical mistakes\n\nThe first mistake is confusing the tool with the decision. An SSG framework is not an architecture, SSR is not a data model, a CDN is not a freshness strategy. These tools can express the boundary between build and runtime cleanly, but they don’t draw it for you. If you accept a framework’s default, you haven’t made a decision; you’ve skipped one.\n\nThe second mistake is orienting yourself on the happy path. In demo mode, every variant looks fast – one record, one user, no load. It gets interesting with ten thousand pages, with traffic spikes, with a slow upstream API, with an editor who wants to see a correction immediately. That’s exactly where it shows whether the boundary between build and runtime is in the right place.\n\n## Validation\n\nThree checks are usually enough for me. First: for every route, it’s stated whether it’s created at build time or at runtime – and why, expressed as a data shelf life. Second: for every runtime route, the failure path is described, including the behavior when the data source is down. Third: the decision can be switched per route without touching neighboring routes. Once these three points are in place, the architecture is robust against exactly the surprises that otherwise catch up with such projects late and expensively.\n\n## Further reading\n\n- React: Thinking in React: https://react.dev/learn/thinking-in-react\n- React: Managing State: https://react.dev/learn/managing-state\n\nThe sources help you cross-check standards and platform behavior. The actual point remains the architecture decision in the concrete project.\n\n## Conclusion\n\nIn the end, build vs. runtime is a question about the data shelf life of each individual page. An immutable post can go into the CDN as a file, an account balance needs current data, and many routes lie in between with revalidation. If this decision stays movable per route, a new need for freshness doesn’t have to overturn the rendering of the entire application."},{"locale":"en","translation_key":"nodejs-streams-im-objektmodus","slug":"streams-in-object-mode","title":"Streams in Object Mode: Data Pipelines Beyond Bytes","summary":"Node.js streams carry more than bytes: with objectMode:true they become composable data pipelines that parse, filter and aggregate – including the bridge to async iterators.","tags":["Software","Node.js","Backend"],"published_at":"2022-11-08T10:00:00+00:00","updated_at":"2026-07-13T07:59:30.815444+00:00","url":"https://www.mikebild.dev/en/blog/streams-in-object-mode/","audio_url":null,"audio_duration_secs":null,"text":"If you switch a stream to `objectMode: true` and bring along your usual `highWaterMark: 16384`, you no longer buffer 16 KiB but 16,384 records. Same number, different unit, and a memory footprint that is off by orders of magnitude. Object mode looks like an incidental constructor option, but it changes what a stream pushes through the pipeline at all – and with it, when throttling kicks in.\n\nIn the [earlier post on Node.js streams and backpressure](https://www.mikebild.dev/en/blog/nodejs-streams-understanding-backpressure/), everything revolved around bytes: buffers flowing through a pipe, and the art of throttling the flow before memory overflows. That is the standard case for file and network I/O. But as soon as you are not copying files but processing records – CSV lines, JSON objects, log entries – that picture no longer goes far enough.\n\nWhen a stream works in object mode, it no longer carries buffers or strings, but arbitrary JavaScript values – whole objects, arrays, numbers. That turns a tool for raw byte streams into a tool for data processing. And the nice part: the mechanics stay the same. You chain stages, each stage does one thing, and in the end you have a pipeline that passes one record after another without loading everything into memory at once.\n\n## What object mode really changes\n\nA stream in standard mode knows exactly two data types: `Buffer` and `String`. Everything you push into it has to be one of the two. Object mode lifts this restriction. A `new stream.Transform({ objectMode: true })` accepts and emits arbitrary JS values. The only exception is `null` – this value is reserved and signals the end of the stream. More on that later, because this is exactly where a pitfall lies.\n\nObject mode is set per stream via the constructor option, and the default is `false`. So you turn it on deliberately. The pattern already shows up throughout the examples in my [Node.js repository](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/) – there, however, still in the ES5 style with `util.inherits` and `Readable.call(this, { objectMode: true })`. A `Readable` that passes on two small objects looks like this there:\n\n```javascript\nconst { Readable } = require('stream');\nconst util = require('util');\n\n// ES5 pattern from the training repo\nconst ReadStream = function () {\n  Readable.call(this, { objectMode: true });\n  this.data = [\n    { id: 0, value: 1 },\n    { id: 1, value: 2 },\n  ];\n  this.curIndex = 0;\n};\nutil.inherits(ReadStream, Readable);\n\nReadStream.prototype._read = function () {\n  if (this.curIndex === this.data.length) {\n    return this.push(null); // signals end of stream\n  }\n  this.push(this.data[this.curIndex++]);\n};\n```\n\nThat works and grew historically. Still, I prefer to show it in modern class syntax, because it is closer to what you find in codebases today. With `class ... extends Transform`, the constructor ritual becomes a `super({ objectMode: true })`, and the processing logic sits in a clearly named method.\n\n## The one core method: `_transform`\n\nAt its core, a transform stream has a single method you write yourself: `_transform(chunk, encoding, callback)`. It is called once for every incoming value. You emit results with `this.push(value)` and report with `callback()` that this value has been fully processed. In object mode, `chunk` is the raw JS value – the `encoding` argument is ignored because there is nothing to decode here.\n\nThe key point: `push` and `callback` are two separate things. `push` sends output to the next stage, `callback` signals “I am done with this input value.” You can `push` zero, one or several times per input and call `callback` exactly once at the end. If you only call `callback()` without `push`, the value disappears – that is the natural way to leave something out in a filter.\n\nHere is a processing stage that parses raw CSV lines into objects:\n\n```javascript\nconst { Transform } = require('stream');\n\nclass ParseRow extends Transform {\n  constructor() {\n    super({ objectMode: true });\n  }\n\n  _transform(line, _encoding, callback) {\n    const [id, name, status] = String(line).split(',');\n    this.push({ id: Number(id), name, status });\n    callback();\n  }\n}\n```\n\nAnd a filter stage that only lets active records through. This is where leaving out shows: if the condition is not met, nothing is pushed; only `callback()` is called.\n\n```javascript\nconst { Transform } = require('stream');\n\nclass FilterActive extends Transform {\n  constructor() {\n    super({ objectMode: true });\n  }\n\n  _transform(record, _encoding, callback) {\n    if (record.status === 'active') {\n      this.push(record);\n    }\n    // no push means the record is dropped\n    callback();\n  }\n}\n```\n\nA formatting stage rounds out the picture. It takes the object and shapes an output line from it:\n\n```javascript\nconst { Transform } = require('stream');\n\nclass FormatOutput extends Transform {\n  constructor() {\n    super({ objectMode: true });\n  }\n\n  _transform(record, _encoding, callback) {\n    this.push(`#${record.id} ${record.name}\\n`);\n    callback();\n  }\n}\n```\n\nThree small stages, each with a single responsibility. That is exactly how composability comes about.\n\n## Chaining stages: parse, filter, format\n\nThe actual pipeline is then almost unremarkable – and that is a good sign. I chain the stages with `pipeline()` from the `stream` module, not with a chain of `pipe()` calls. The reason: `pipeline()` propagates errors and cleans up the streams involved when one fails. A plain `pipe()` chain does not – there you have to handle errors and cleanup at every seam yourself, and that is exactly what gets forgotten in practice.\n\n```javascript\nconst { Readable, pipeline } = require('stream');\n\nconst csvLines = ['0,Ada,active', '1,Linus,inactive', '2,Grace,active'];\n\npipeline(\n  Readable.from(csvLines),\n  new ParseRow(),\n  new FilterActive(),\n  new FormatOutput(),\n  process.stdout,\n  (err) => {\n    if (err) {\n      console.error('pipeline failed:', err);\n    } else {\n      console.log('pipeline finished');\n    }\n  }\n);\n```\n\nThe source here is `Readable.from(csvLines)` – more on that in a moment. The sink is `process.stdout`, a perfectly ordinary writable stream. In between, one record after another flows through: first as a string, after `ParseRow` as an object, filtered by `FilterActive`, shaped back into a line in `FormatOutput`. At no point is the entire data set in memory – there is only ever a small supply of buffered values in flight.\n\nAs a diagram, this data flow looks like this:\n\n```mermaid\nflowchart LR\n  A[\"Source<br/>Readable.from\"] -->|\"CSV line (string)\"| B[\"Parse<br/>_transform\"]\n  B -->|\"JS object\"| C[\"Filter<br/>_transform\"]\n  C -->|\"JS object\"| D[\"Format<br/>_transform\"]\n  D -->|\"output line\"| E[\"Sink<br/>Writable\"]\n```\n\nThe edges show what actually flows: first a line as a string, then JS objects through the middle stages, and text again at the end. Each stage only takes care of its own conversion and knows nothing about its neighbors.\n\n## Aggregating with `_flush`\n\nFiltering and reshaping work record by record. For aggregations – sums, counts, groupings – you need a different rhythm: collect while the values arrive, and emit the result only once the source is exhausted. That is what `_flush(callback)` is for. This method is called exactly once, just before the stream ends. You collect in `_transform` and emit in `_flush`.\n\n```javascript\nconst { Transform } = require('stream');\n\nclass CountByStatus extends Transform {\n  constructor() {\n    super({ objectMode: true });\n    this.counts = {};\n  }\n\n  _transform(record, _encoding, callback) {\n    this.counts[record.status] = (this.counts[record.status] || 0) + 1;\n    callback(); // nothing pushed yet, just accumulate\n  }\n\n  _flush(callback) {\n    this.push(this.counts); // emit the aggregate once at the end\n    callback();\n  }\n}\n```\n\nThis stage swallows many objects and emits a single one at the end – the aggregate. It shows nicely that a stream stage does not have to keep its input and output counts one to one.\n\n## Backpressure now counts objects\n\nIn object mode, `highWaterMark` means something different than in byte mode – people regularly read past this, with noticeable consequences. `highWaterMark` is the threshold at which a stream counts as “full enough” and triggers backpressure. In byte mode, this threshold is measured in bytes; in 2022 the general default was 16 KiB, since Node 22 it has been 64 KiB. In object mode it is measured in objects, still with a default of 16 objects.\n\nThat is no small detail. If you come from byte mode and read `highWaterMark: 16`, you reflexively think of 16 bytes and consider it absurdly small. In object mode, though, it means 16 buffered objects – a perfectly sensible supply. Conversely, a `highWaterMark: 16384` set out of byte-mode habit can mean in object mode that you buffer 16,384 objects before backpressure kicks in. That is rarely what you want.\n\nIt is also important that `highWaterMark` is a threshold, not a hard barrier. The buffer may exceed it – the threshold is the signal from which `push()` returns `false` and asks upstream stages to throttle. With `pipeline()` and `pipe()`, this pausing and resuming happens automatically. So normally you rely on this automatic interplay and only have to check the return value of `push` yourself when you drive a source by hand. Backpressure works just as reliably in object mode as in byte mode; only the unit is different.\n\nTo tell them apart, here are the two modes side by side:\n\n- Byte mode (standard) carries `Buffer` or `String`; `highWaterMark` counts bytes here. The general default depends on the Node version and has been 64 KiB since Node 22.\n- Object mode (`objectMode: true`) carries arbitrary JS values except `null`, `highWaterMark` counts objects here with a default of 16, and the typical uses are data pipelines that parse, filter, transform and aggregate.\n\n## The bridge to async iterators\n\nSo far I have built streams as classes. That is not always necessary, and it is often even cumbersome. Node offers two modern connectors that bring object mode together with the world of async iterators: `Readable.from(iterable)` and `for await ... of`.\n\n`stream.Readable.from(iterable)` takes any iterable or async iterable – an array, a generator, an async generator – and turns it into a readable stream. By default, this stream works in object mode. It is the most elegant way to feed a data source into a pipeline without writing your own `Readable` class. That is exactly what I already used above with `Readable.from(csvLines)`.\n\nThe other direction is at least as handy: a readable stream is itself an async iterable. So you can consume it directly with `for await ... of`, and the language construct takes care of pausing, resuming, backpressure and the end – all automatically.\n\n```javascript\nconst { Readable } = require('stream');\n\nasync function* generateRecords() {\n  yield { id: 0, value: 1 };\n  yield { id: 1, value: 2 };\n  yield { id: 2, value: 3 };\n}\n\nasync function main() {\n  const source = Readable.from(generateRecords());\n\n  for await (const record of source) {\n    console.log('received:', record);\n  }\n}\n\nmain();\n```\n\nYou can even use async generators as a pipeline stage. A generator that consumes a source and passes on filtered values replaces an entire transform class with a few lines:\n\n```javascript\nasync function* filterEven(source) {\n  for await (const n of source) {\n    if (n % 2 === 0) {\n      yield n;\n    }\n  }\n}\n```\n\nWhether you write a transform class or an async generator is to a good extent a matter of taste. I reach for the class when I have to keep internal state across many values, for example in an aggregation with `_flush`. For pure filters and reshaping, async generators are often the shorter, more readable way.\n\n## Two pitfalls that strike again and again\n\nThe first pitfall is mixing byte and object mode in one pipeline. You start with `fs.createReadStream(...)`, which is a byte stream and delivers buffers. Right after it you attach an object mode stage that wants to work with `record.status` – and get a buffer instead of an object. Between a byte readable and the first object stage there always has to be a parse layer that decodes buffers into values. The reverse seam is just as tricky: if you push an object into a non-object-mode writable, Node answers with a type error (`ERR_INVALID_ARG_TYPE`) that demands a string, Buffer or Uint8Array. At every seam you should be aware of what data type is flowing right now.\n\nThe second concerns `null` as a legitimate payload value. Because `push(null)` means the end of the stream, you cannot send a real `null` value through an object mode stream – it would be mistaken for the end signal and cut off the remaining data. If `null` has a real meaning in your payload, you need a stand-in object, a so-called sentinel, such as `{ value: null }` instead of a bare `null`.\n\nA third point is a matter of diligence: you pass errors in `_transform` to `callback(err)` instead of throwing them. Only then do they end up in the stream’s error channel and get propagated cleanly by `pipeline()`. An error thrown in the middle of asynchronous processing is much harder to catch – another argument for `pipeline()` over a bare `pipe()` chain.\n\n## Conclusion\n\nObject mode turns Node.js streams from an I/O tool for bytes into a tool for data processing. The mechanics stay familiar – `_transform` with `push` and `callback`, `_flush` for aggregating, chaining via `pipeline()` – but the content is now whole JS values. This lets you build pipelines that parse, filter, transform and aggregate as separate, composable stages that only ever hold a small supply of records in memory.\n\nI take away two things as the core message. First: in object mode, `highWaterMark` counts objects, not bytes – mix that up and you size your buffer wrong by orders of magnitude. Second: `Readable.from` and `for await ... of` are the modern bridge between streams and async iterators and in many cases save you from writing your own stream class. If you have understood the byte-oriented part from the post on [buffers and binary data](https://www.mikebild.dev/en/blog/buffers-in-nodejs-working-with-binary-data/) and add object mode to it, you have both halves of the stream world together – the raw one and the structured one.\n\n## Further reading\n\n- [Node.js Stream API – Object mode](https://nodejs.org/api/stream.html#object-mode)\n- [Node.js Stream API – Buffering](https://nodejs.org/api/stream.html#buffering)\n- [Node.js Stream API – stream.Readable.from](https://nodejs.org/api/stream.html#streamreadablefromiterable-options)\n- [Node.js Stream API – readable[Symbol.asyncIterator]](https://nodejs.org/api/stream.html#readablesymbolasynciterator)\n- [Node.js Stream API – Class: stream.Transform](https://nodejs.org/api/stream.html#class-streamtransform)"},{"locale":"en","translation_key":"reproduzierbare-testpipelines-kein-flaky","slug":"reproducible-test-pipelines","title":"Reproducible Test Pipelines: No Flakiness, No Chance","summary":"Flakiness points to uncontrolled inputs or dependencies. If you make time, data and isolation visible, you can narrow down the cause and make the merge gate trustworthy again.","tags":["Software","Delivery"],"published_at":"2022-10-26T10:00:00+00:00","updated_at":"2026-07-13T13:23:46.335954+00:00","url":"https://www.mikebild.dev/en/blog/reproducible-test-pipelines/","audio_url":null,"audio_duration_secs":null,"text":"```text\n$ git rev-parse HEAD\n9f2c1ab\n\nLauf 412   FAIL  checkout.spec.ts › Rabatt gilt bis Monatsende   (2.1s)\nLauf 413   PASS  checkout.spec.ts › Rabatt gilt bis Monatsende   (2.0s)\n```\n\nThe same commit, two runs, two results. If nothing in the code has changed and the result flips anyway, then the test reads another input that isn’t in the repository. “Just run the build again, it’s sometimes red for no reason” is therefore not a diagnosis. It is an admission that nobody knows which input that is.\n\nA test that changes its result without a code change is reacting to another input. Often it hides in time, data or missing isolation. With integration tests, the network, cloud services or other external systems can also genuinely fluctuate. Not every dependency can be frozen; I still have to make it visible, limit it and name it in the test type. Otherwise the team gets used to its own test suite reporting green one time and red the next, and loses trust in its merge gate.\n\n## Why this is a business problem, not a test detail\n\nBefore we get to the mechanics, here’s why the topic doesn’t end in the test directory: a flaky suite doesn’t stay a developer nuisance. It slows down the entire ability to deliver.\n\nMartin Fowler nailed this back in 2011. A non-deterministic test is not just useless – it is a “virulent infection”. As soon as a single test occasionally turns red for no reason, everyone gets used to ignoring red builds. At exactly that moment the suite no longer protects anything, because a real failure now looks like the usual noise. The damage is not the one flaky test but the loss of trust that spreads to the whole suite.\n\nThis is not an academic argument. In 2016, Google published numbers on its Testing Blog: around 1.5 % of all test runs are flaky. That sounds like little until you scale it up. Flaky tests clog the pipeline, block branches, create duplicate bug tickets and burn developer time on a large scale – time that flows into diagnosing failures that aren’t failures at all.\n\nAnd this is exactly where the loop closes to delivery performance. Accelerate (Forsgren, Humble, Kim, 2018) connects the four well-known metrics – Deployment Frequency, Lead Time for Changes, Change Failure Rate and Time to Restore – with practiced continuous integration and *reliable* test automation. The word “reliable” matters. An elite team that deploys on demand can only do so because the suite is a trustworthy gate. A flaky suite is not a gate but a traffic light that switches randomly – and nobody deploys based on a random traffic light. Incidentally, I deliberately always read the four metrics together: a high deploy frequency combined with a high change failure rate is worthless. Determinism in the suite is one of the conditions under which these metrics become honest at all.\n\nSo the gain doesn’t lie in “prettier tests”. It lies in shorter cycles, less friction in the team and higher delivery quality. That’s why determinism belongs in the architecture discussion and not on the QA checklist.\n\n## The three axes as a gate\n\nThe discussion can be reduced to a simple picture. A pipeline runs from left to right: commit, build, test, merge. Above the test stage there are three dials. Only if all three are set to “controlled” does the gate turn green and the merge become possible. If one tips to “uncontrolled”, you get flaky red.\n\n```mermaid\nflowchart LR\n  C[commit] --> B[build] --> T[test gate] --> M[merge]\n  A1[TIME<br/>frozen clock] --> T\n  A2[DATA<br/>seeded fixtures] --> T\n  A3[ISOLATION<br/>hermetic sandbox] --> T\n  T -->|all three controlled| M\n  T -->|any axis uncontrolled| F[flaky red]\n```\n\nThe value of this picture lies in diagnosis. When a build is flaky, I don’t ask “which test is acting up” but “which of the three axes is uncontrolled”. That almost always leads to the cause faster, because it structures the search. Let’s go through the axes one by one.\n\n## Axis 1: Time\n\nThe most common hidden cause. As soon as domain code calls `new Date()` or `Instant.now()` directly, it is coupled to the wall clock – and the wall clock is guaranteed to change between two test runs. A test that checks “the discount applies until the end of the month” will behave differently on the 31st than on the 1st; a test with `expiresAt` in exactly 24 hours flips at time zone and DST boundaries.\n\nThe solution is not a library but a design decision: the clock becomes an injected service. Domain code never asks the operating system but always the abstraction.\n\n```typescript\ninterface Clock {\n  now(): Date;\n}\n\nclass SystemClock implements Clock {\n  now(): Date {\n    return new Date();\n  }\n}\n\nclass FixedClock implements Clock {\n  constructor(private readonly instant: Date) {}\n  now(): Date {\n    return this.instant;\n  }\n}\n\n// domain code never calls `new Date()` directly:\nfunction isExpired(subscription: Subscription, clock: Clock): boolean {\n  return subscription.expiresAt.getTime() <= clock.now().getTime();\n}\n```\n\nIn production the `SystemClock` runs, in the test a `FixedClock(new Date(\"2022-01-01T00:00:00Z\"))`. This is not an exotic idea: Java has had exactly this abstraction built in with `java.time.Clock` since version 8, in Ruby Timecop has done it since 2011, in JavaScript Sinon’s fake timers provide the same. I prefer the injected clock over global time freezing because it is more honest: it makes the time dependency visible in the code instead of overriding it globally.\n\nSo that it doesn’t sound too simple: time determinism is more than freezing the clock. Time zones, DST transitions, locale-dependent formatting and the iteration order of maps or sets are sources of non-determinism of their own. The frozen clock solves the big chunk, not everything.\n\n## Axis 2: Data\n\nThe second axis is inconspicuous and does silent damage: random data. A `faker.name()` or an unseeded random number makes every test run unique. Most of the time that goes fine – until the one record shows up that breaks the sorting, a length limit or a Unicode edge case. Then the build is red, green on the next run, and nobody can reproduce it.\n\nThe rule is simple: deterministic data. Either fixed fixtures or a seeded random generator. The seeded route is often the better one, because it keeps the variation and still stays reproducible.\n\n```typescript\nimport seedrandom from \"seedrandom\";\n\nfunction makeRng(seed = \"1337\") {\n  return seedrandom(seed);\n}\n\n// same seed -> same sequence -> reproducible failures\nfunction buildUser(rng: () => number): User {\n  return {\n    id: Math.floor(rng() * 1_000_000),\n    tier: rng() > 0.5 ? \"premium\" : \"free\",\n  };\n}\n```\n\nInterestingly, exactly this rule is explicitly codified in contract testing. Pact – in use for consumer-driven contracts since 2013 – states the rule “use deterministic data, avoid random data” with no ifs or buts. The reason is revealing: if a contract contains random data, it is marked as “changed” on every run even though nothing has changed in the domain. So non-deterministic data produces not only flaky tests but flaky contracts.\n\nContract testing deserves a brief appreciation here, because it connects the data axis with the isolation axis. Instead of one service starting the other to test “for real”, each consumer-provider pair is checked in isolation against a shared, deterministic contract. No network, no foreign runtime, no timing – the classic sources of flakiness are ruled out by construction.\n\n## Axis 3: Isolation\n\nThe third axis is the most fundamental and carries the fitting name hermeticity. The Bazel documentation uses “hermeticity” for builds and tests whose tools and inputs are known and controlled. This sealing off from the network, a shared database and host state removes important hidden influences; on its own, it doesn’t yet guarantee determinism if, for example, races, randomness or time remain uncontrolled in the test. A non-hermetic test can be reproducible, but it depends more strongly on its environment.\n\nThe two practical enemies of isolation are shared state and test order dependency. If test B is only green because test A wrote a row into the database beforehand, the suite is a chain that breaks with every reordering. The antidote is called shared-nothing: each test builds up its state and tears it down again.\n\nFor real dependencies such as a database or message broker, Testcontainers have become established since 2015: an ephemeral, throwaway instance per test instead of a shared, long-lived environment. The following skeleton shows the isolation discipline compactly – and it deliberately combines all three axes:\n\n```typescript\nlet db: EphemeralDatabase;\nlet clock: Clock;\nlet rng: () => number;\n\nbeforeEach(async () => {\n  rng = makeRng(\"1337\");                       // DATA: seeded\n  clock = new FixedClock(FIXED_INSTANT);       // TIME: frozen\n  db = await startEphemeralContainer();         // ISOLATION: hermetic\n  await db.beginTransaction();\n});\n\nafterEach(async () => {\n  await db.rollbackTransaction();               // state reset, shared-nothing\n  await db.stop();\n});\n```\n\nThe transaction rollback per test is my preferred reset mechanism where it works: fast and complete. Where transactions aren’t enough, truncation between tests does the job. Only the principle matters: no test may depend on what another one left behind.\n\nFowler’s list of causes, by the way, maps exactly onto these three axes. He names lack of isolation, time, asynchrony or remote services, and resource leaks. Drawn as a fishbone:\n\n```mermaid\nflowchart LR\n  ISO[lack of isolation] --> S[flaky build]\n  TIME[time / clock] --> S\n  ASYNC[async / remote services] --> S\n  LEAK[resource leaks] --> S\n```\n\nAsynchrony deserves a sentence of its own, because it is the classic generator of flakiness. The most common mistake is a `sleep(500)` in the hope that an asynchronous operation is “probably done”. On a slow CI runner, sometimes it isn’t. The fix is never a longer wait but polling against a real condition – waiting until the state has actually been reached, with a timeout as an upper limit. “Wait until” instead of “wait how long”.\n\n## Dealing honestly with retries\n\nThat leaves the topic everyone talks around in such discussions: the automatic retry. Almost every CI system offers to simply rerun failed tests, and if the second run is green, the build counts as green. That is tempting, because it makes the red builds disappear immediately.\n\nThe assessment is clear: retries hide non-determinism, they don’t eliminate it. As a short-term emergency patch to keep a team from grinding to a halt completely, a limited retry can be acceptable. As a permanent solution, it switches off exactly the signal you need for root cause analysis. A time-limited quarantine can be more honest: the test keeps running in a separate job and gets a named owner and a deadline. The main build doesn’t turn red because of it; the missing coverage in the merge gate, however, remains a deliberately accepted risk until the fix.\n\n```yaml\n# conceptual pipeline stages\nstages:\n  - name: test\n    fail_on_red: true          # the trustworthy merge gate\n  - name: contract-verify\n    run: pact can-i-deploy --to prod\n  - name: quarantine\n    tests: tagged(\"flaky\")\n    fail_on_red: false         # does not block merge\n    on_red: open_bug_ticket    # but never silently ignored\n```\n\nThe difference between retry and quarantine is a question of attitude. Retry says: “I hope it was chance.” Quarantine says: “I know the gap, its owner and its deadline.” Without these three pieces of information, quarantine too becomes nothing more than permanent ignoring.\n\n## Conclusion\n\nThe common thread is simpler than the number of libraries suggests. Flakiness has a cause, but not every cause lies entirely within the test function. Freezing time, fixing data and establishing isolation clears out the most common homemade sources. External dependencies are simulated, deliberately observed or moved into a dedicated integration test whose range of fluctuation is known.\n\nAnd the payoff is not “greener dashboards”. The payoff is a merge gate whose verdict the team can assess. If you dismiss flaky tests as “bad luck”, you hand your quality control over to chance. If you look for the hidden input and openly state the remaining uncertainty, you can react sensibly to a red build again.\n\n## Further reading\n\n- Martin Fowler: “Eradicating Non-Determinism in Tests” (2011) – https://martinfowler.com/articles/nonDeterminism.html\n- Google Testing Blog: “Flaky Tests at Google and How We Mitigate Them” (2016) – https://testing.googleblog.com/2016/05/flaky-tests-at-google-and-how-we.html\n- Google Testing Blog: “Where do our flaky tests come from?” (2017) – https://testing.googleblog.com/2017/04/where-do-our-flaky-tests-come-from.html\n- Bazel: Hermeticity – https://bazel.build/basics/hermeticity and Test Encyclopedia – https://bazel.build/reference/test-encyclopedia\n- Pact: consumer-driven contracts, deterministic data – https://docs.pact.io/\n- Forsgren, Humble, Kim: “Accelerate” (2018), DORA metrics – https://www.atlassian.com/devops/frameworks/dora-metrics\n- Ford, Parsons, Kua: “Building Evolutionary Architectures” (1st edition, 2017) – https://nealford.com/books/buildingevolutionaryarchitectures.html\n- Trunk-Based Development – https://trunkbaseddevelopment.com"},{"locale":"en","translation_key":"adapter-design-framework-grenzen","slug":"adapter-design-where-frameworks-end","title":"Adapter Design: Where Frameworks End","summary":"What a framework adapter really does: the contract over the build output, the translation of request and response, and the silent environment assumptions at the boundary between SvelteKit and AWS.","tags":["Software","AWS","Cloud"],"published_at":"2022-10-12T10:00:00+00:00","updated_at":"2026-07-14T17:20:29.175417+00:00","url":"https://www.mikebild.dev/en/blog/adapter-design-where-frameworks-end/","audio_url":null,"audio_duration_secs":null,"text":"# Adapter Design: Where Frameworks End\n\nAn adapter in the SvelteKit sense is neither a textbook design pattern nor a deployment tool. It is a piece of code that runs after the build, takes the framework’s output and turns it into something a concrete platform can execute: a Node server, a Lambda function, a worker at the network edge. It starts no processes, it serves no requests, and at its core it provisions no infrastructure. It translates.\n\nThe definition sounds harmless. What is interesting is what it implies: an adapter is exactly the place where a framework stops taking responsibility – and the platform begins. Everything before this place belongs to the framework: routing, rendering, data loading, the semantics of a page. Everything after it belongs to the platform: process model, network, file system, limits, price tag. If you write an adapter, you do not draw this boundary yourself, but you have to trace it precisely. And in doing so, you notice how many decisions were made silently on both sides.\n\nSince the beginning of the year, I have been maintaining such an adapter: `sveltekit-adapter-aws` brings SvelteKit applications to Lambda, S3 and CloudFront via CDK. [I have already introduced the project itself](https://www.mikebild.dev/en/blog/sveltekit-adapter-aws-framework-meets-cloud/) – this post is about what I learned about the interface while building it. Because the real insight is not in the AWS part but in the question every adapter has to answer: what belongs on which side?\n\n## The contract over the build output\n\nSvelteKit gives an adapter surprisingly little – and that is exactly what is good about it. The interface consists of an object with a name and an `adapt` function that receives a `builder` object. The builder is the complete contract: it provides the client assets, the prerendered pages and the server code, plus a manifest with the route metadata. Nothing more.\n\n```js\nimport { writeFileSync } from 'node:fs';\n\nexport function adapter(options = {}) {\n  return {\n    name: 'sveltekit-adapter-aws',\n    async adapt(builder) {\n      const out = 'build';\n      builder.rimraf(out);\n\n      builder.writeClient(`${out}/assets`);        // static files for the CDN\n      builder.writePrerendered(`${out}/prerendered`);\n      builder.writeServer(`${out}/server`);        // the SSR part\n\n      const manifest = builder.generateManifest({ relativePath: './' });\n      writeFileSync(\n        `${out}/server/manifest.js`,\n        `export const manifest = ${manifest};`\n      );\n    }\n  };\n}\n```\n\nWith this, the framework says: there are three kinds of artifacts, and I write them wherever you want them. Where they ultimately belong, how they are delivered, what a “server” even is on your platform – your problem. For AWS, this concretely means: client assets and prerendered pages go into an S3 bucket behind CloudFront, the server code is built into a Lambda bundle with esbuild, and the routing rules of the CDN distribution have to decide which request goes to S3 and which to the function.\n\n```mermaid\nflowchart LR\n  subgraph FW[Framework-Seite]\n    SRC[Quellcode] --> VITE[Vite-Build]\n    VITE --> CL[Client-Assets]\n    VITE --> PR[Prerenderte<br/>Seiten]\n    VITE --> SV[Server-Code +<br/>Manifest]\n  end\n  subgraph AD[Adapter]\n    CL --> MAP[Zuordnung,<br/>Bundling]\n    PR --> MAP\n    SV --> MAP\n  end\n  subgraph PF[Plattform-Seite]\n    MAP --> S3[S3-Bucket]\n    MAP --> LB[Lambda-Bundle]\n    S3 --> CF[CloudFront]\n    LB --> CF\n  end\n```\n\nThe mapping in the middle box is the part nobody sees and where most of the work lies. Which paths are static, which are dynamic? What happens to a prerendered page that also has a server route? Who sets the cache headers? The framework has an opinion on this, but it does not enforce it – it cannot enforce it, because it does not know the platform. The adapter has to translate the framework’s opinion into the platform’s mechanics without inventing a third opinion of its own.\n\n## Request and response as a common language\n\nAt runtime, the contract is even narrower. The SvelteKit server speaks the web standards: it takes a `Request` object from the Fetch API and returns a `Response` object. That is a deliberate and, in my view, smart decision – the same types that have existed in the browser for years and that Deno Deploy and Cloudflare Workers use as their native format anyway. The newly founded WinterCG is currently trying to standardize exactly this core of server-side web APIs across runtimes. SvelteKit committed to it even before that.\n\nFor the adapter, this means: its runtime job is one translation there and one back. AWS does not speak Fetch; AWS speaks API Gateway events. The handler in my Lambda bundle therefore essentially does only this:\n\n```js\nimport { Server } from './index.js';\nimport { manifest } from './manifest.js';\n\nconst server = new Server(manifest);\nawait server.init({ env: process.env });\n\nexport async function handler(event) {\n  const request = toRequest(event); // API Gateway event -> fetch Request\n  const response = await server.respond(request, {\n    getClientAddress: () => event.requestContext.http.sourceIp\n  });\n  return toLambdaResult(response); // fetch Response -> Lambda result\n}\n```\n\nThe two inconspicuous functions `toRequest` and `toLambdaResult` are where the platform shows its quirks. An API Gateway event carries query parameters already split up; the `Request` wants a complete URL. Binary responses have to be Base64-encoded, and whether something is “binary” is decided by the adapter based on the content type – a heuristic you get wrong for the first time at some point. And `Set-Cookie` is the classic: several cookies in one response are merged into one line by the `Headers` implementation, while API Gateway expects them as a separate array.\n\n```js\nasync function toLambdaResult(response) {\n  const contentType = response.headers.get('content-type') || '';\n  const isBinary = !/^(text\\/|application\\/(json|javascript))/.test(contentType);\n\n  return {\n    statusCode: response.status,\n    headers: Object.fromEntries(response.headers.entries()),\n    // API Gateway expects cookies as a separate array\n    cookies: splitSetCookie(response.headers.get('set-cookie')),\n    body: isBinary\n      ? Buffer.from(await response.arrayBuffer()).toString('base64')\n      : await response.text(),\n    isBase64Encoded: isBinary\n  };\n}\n```\n\nNone of this is difficult. But all of it is responsibility that the framework explicitly does not take on – and should not take on either. If SvelteKit started knowing API Gateway quirks, tomorrow it would also have to know those of Azure, Google and every host that invents its own event structure. The narrow Fetch API is the boundary that keeps both sides independent.\n\n```mermaid\nsequenceDiagram\n  participant C as Client\n  participant CF as CloudFront\n  participant L as Lambda-Handler\n  participant K as SvelteKit-Server\n  C->>CF: HTTP-Request\n  CF->>L: API-Gateway-Event\n  L->>K: fetch Request\n  K-->>L: fetch Response\n  L-->>CF: statusCode, headers,<br/>cookies, body\n  CF-->>C: HTTP-Response\n```\n\n## The silent assumptions of the environment\n\nThe third part of the boundary is the most unpleasant because it appears in no interface signature: the assumptions about the environment. A SvelteKit application may run almost arbitrary Node code in its server routes. Which of it works on the target platform only the adapter knows – and often only operations.\n\nOn Lambda, I kept running into three points:\n\n- The file system is read-only, except for `/tmp`. If your server code stores files, writes caches to disk or expects an SQLite file next to the code, it falls flat on its face with the first real request – locally with `vite dev`, everything works.\n- Environment variables come from the function configuration, not from a `.env` file. SvelteKit now has the hook `server.init({ env })` for this, through which the adapter passes the variables in explicitly. It is exactly such small handover points that make the boundary honest: the environment is a parameter, not global state.\n- There is no streaming. Lambda behind API Gateway buffers the complete response and delivers it in one piece, with hard size limits. A `Response` with a slow stream as its body simply cannot be represented on this platform – the adapter has to collect the stream and materialize it.\n\nThe last point shows why adapter design is more than format conversion. With the `Response` type, the framework promises a capability – streaming bodies – that the platform cannot deliver. The adapter cannot fix that; it can only make it visible: document it, warn during the build if in doubt, and buffer the response correctly instead of cutting it off. Where framework promises and platform capabilities diverge, the adapter is the one that has to explain the difference.\n\n## When the framework side moves\n\nIn October 2022, SvelteKit is still pre-1.0, and as an adapter author you notice that more clearly than as an application developer. Since the beginning of the year, I have had to touch the adapter integration several times: `app.render(request)` became `server.respond(request, options)`, the manifest format and the builder methods shifted, and the big routing overhaul in late summer changed what ends up in the server output at all. The switch to Vite 3 added the tooling level on top.\n\nI do not want this to be understood as a complaint – a framework before 1.0 may change its interfaces; that is what this phase is for. Something else was revealing: each of these changes showed me which of my assumptions belonged to the contract and which I had only imagined. If you have to catch up with an interface three times, you understand it better afterward than someone who has read it once.\n\nIn practice, I drew two consequences from this. First: the SvelteKit version is pinned exactly in the adapter project, and every update is a deliberate step with its own commit instead of an incidental `npm update`. Second: the most important test is not a unit test of the conversion functions but an example project that is actually built and deployed with every change. An adapter is a consumer of an unstable API; the only reliable check is the one that goes the whole way – from `vite build` to the HTTP response from CloudFront. Everything else only tests your own idea of the contract, not the contract.\n\n## The same boundary, other frameworks\n\nThe question “what belongs on which side” comes up everywhere; the frameworks just answer it differently – and the answers are revealing.\n\nNext.js has no adapter interface. The platform is implicitly Vercel, and if you deploy elsewhere, you struggle with an output that was never meant for it. What I find remarkable is that Vercel turned the tables this year with the Build Output API: there, the platform defines a documented directory format, and any framework can build toward it. That is the same boundary, just drawn from the other side – instead of “the framework defines, the adapter translates,” it is “the platform defines, the framework delivers.” Whoever owns the contract holds power over the boundary.\n\nRemix, in turn, built in the translation from the start: `createRequestHandler` takes platform-specific requests, and official adapters exist for Express, Architect and Cloudflare Workers. There, too, the core is identical to what SvelteKit does – web standard `Request` in, web standard `Response` out, and around it a thin layer of platform dialect. The more consistently frameworks commit to these standards, the thinner the adapters become. In the best case, the runtime translation shrinks to zero, as with Deno Deploy and the Workers, which speak Fetch natively, and only the build output part remains.\n\n## What I take away from this\n\nAn adapter is the most honest place in a framework architecture because nothing can be abstracted away there. On one side stands what the framework really guarantees: three kinds of artifacts, a manifest, a Fetch API. On the other side stands what the platform really demands: its event format, its file system, its limits. The adapter in between should be boring and thin. If it gets thick, that is a finding – then either the framework guarantees too little or the platform demands too much, and you should know both before you build an application on it.\n\nThat is why looking into the adapter is worthwhile even for those who will never write one. If you understand what `adapter-node` or an AWS adapter does in detail, you know exactly which assumptions your own application makes about its environment – and which of them will break at the next platform change. The boundary between framework and platform does not disappear because you ignore it. It just becomes invisible. A good adapter makes it visible again, and that is worth more than any other feature it brings along.\n\n## Further reading\n\n- My adapter project: https://github.com/MikeBild/sveltekit-adapter-aws\n- SvelteKit docs on adapters: https://svelte.dev/docs/kit/adapters\n- SvelteKit docs “Writing adapters”: https://svelte.dev/docs/kit/writing-adapters\n- Remix Server Adapters: https://v2.remix.run/docs/other-api/adapter"},{"locale":"en","translation_key":"rxjs-in-react-datenfluss","slug":"rxjs-in-react-observables-in-the-ui-data-flow","title":"RxJS in React: Observables in the UI Data Flow","summary":"RxJS does not shine everywhere in React, only where asynchronous events have to be coordinated – debounced input, canceled autocomplete requests, continuous streams. The post shows the few places where observables really pay off, and where useState is perfectly enough.","tags":["Software","Frontend","React"],"published_at":"2022-10-05T10:00:00+00:00","updated_at":"2026-07-13T10:04:28.27524+00:00","url":"https://www.mikebild.dev/en/blog/rxjs-in-react-observables-in-the-ui-data-flow/","audio_url":null,"audio_duration_secs":null,"text":"An observable is not a state container. It holds no value that a component could read, and it does not replace `useState`. It describes an execution that pushes values to its subscribers over time and that can be canceled at any moment. If you take this definition seriously, you have half answered the question of RxJS in React: where it is only about the current value of a field, an observable contributes nothing. It only pays off where the timeline itself becomes the problem.\n\n**Editorial note (July 2026):** The component-local subscriptions with `useEffect` and cleanup shown here remain sensible. If, on the other hand, RxJS-based state is read by several components as an external store, React needs a stable snapshot contract, typically via `useSyncExternalStore` or an adapter library built on it. The post deliberately stays with the coordination of events and does not turn RxJS into a general state solution.\n\nThe whole discussion, which usually gets stuck in React teams, hinges on this distinction. If you know RxJS from the Angular world, you often associate it with pipelines that ran across the entire application and that nobody could follow anymore. If you only know streams from the outside, you find them elegant and would pour the entire component state into observables. Both positions miss the narrow area that actually matters: keystrokes that arrive faster than an API responds. Responses that arrive in the wrong order. Connections that just keep sending. I take these three cases apart here – and after that, the places where React’s built-in tools remain the better choice.\n\n## A quick framing: what an observable is in this context\n\nI assume the basics from [RxJS: Push and Pull](https://www.mikebild.dev/en/blog/rxjs-telling-push-and-pull-apart/) here – that post explains why an observable is a push producer and how it differs from promises and iterators. For the React context, three properties are decisive.\n\nFirst, an observable is *lazy*: the code in the `subscribe` callback only runs when someone actually calls `subscribe()`. An observable that nobody subscribes to does nothing. Second, a normal observable is *cold* and *unicast* by default – every subscription starts its own execution. Third, `subscribe()` returns a `Subscription`, and its `unsubscribe()` ends the execution again.\n\nTaken together, these three points explain why RxJS and the `useEffect` lifecycle fit together so well: an effect has exactly the structure “set up on mount, clean up on unmount” that an observable needs.\n\n```ts\nimport { Observable } from 'rxjs';\n\n// A cold observable: the callback runs once per subscriber\nconst ticker$ = new Observable<number>((subscriber) => {\n  let count = 0;\n  const id = setInterval(() => subscriber.next(count++), 1000);\n\n  // teardown logic runs on unsubscribe\n  return () => clearInterval(id);\n});\n\nconst subscription = ticker$.subscribe((value) => console.log(value));\n// later, to stop and clean up:\nsubscription.unsubscribe();\n```\n\nOnce you have internalized the structure of this `subscribe`/`unsubscribe` pattern, you immediately recognize the parallel to the cleanup function of `useEffect`. That is no coincidence but the actual reason why the integration is so straightforward.\n\n## The first sensible case: debouncing input\n\nThe classic example is a search field. Firing an HTTP request on every keystroke is wasteful – the user types “React,” and six requests are already on their way, five of which are outdated immediately. The naive React solution cobbles together a `setTimeout` with `clearTimeout` in the effect. That works, but it quickly becomes confusing as soon as more than just debouncing comes into play.\n\nWith RxJS, debouncing becomes a single declarative operator. `debounceTime(300)` only emits a value once no new value has followed for 300 milliseconds. I feed the input in through a `Subject` – a Subject is both an Observable and an Observer, so I can call `next()` in the `onChange` handler and subscribe to the pipeline at the other end.\n\n```tsx\nimport { useEffect, useRef, useState } from 'react';\nimport { Subject } from 'rxjs';\nimport { debounceTime, distinctUntilChanged } from 'rxjs/operators';\n\nfunction SearchField() {\n  const query$ = useRef(new Subject<string>()).current;\n  const [debounced, setDebounced] = useState('');\n\n  useEffect(() => {\n    const subscription = query$\n      .pipe(debounceTime(300), distinctUntilChanged())\n      .subscribe(setDebounced);\n\n    return () => subscription.unsubscribe();\n  }, [query$]);\n\n  return (\n    <input\n      type=\"search\"\n      onChange={(event) => query$.next(event.target.value)}\n      placeholder=\"Enter search term\"\n    />\n  );\n}\n```\n\nTwo details regularly get lost in code reviews. I create the `Subject` with `useRef` so that it stays stable across re-renders – if I created it anew in the render body, every render would have its own Subject, and the connection between handler and pipeline would break. And `distinctUntilChanged()` filters out identical consecutive values so that a focus change without a text change does not trigger a new run.\n\n## The case where RxJS really shines: autocomplete with switchMap\n\nDebouncing alone does not justify RxJS yet – you can do that with a timeout too. What carries RxJS is discarding outdated requests. This is exactly where the real race condition of an autocomplete lies: I type “re,” and a request goes out. I type “rea,” and a second request goes out. If the response to “re” now arrives *after* the response to “rea,” the outdated result overwrites the current one. The UI shows hits for a search term that is no longer in the field at all.\n\n`switchMap` solves this by construction. The operator subscribes to the inner observable – here the HTTP request – and cancels the previous inner subscription as soon as a new value comes from the outside. Combined with `fromFetch` and its `AbortController`, the outdated request is not just ignored but actually aborted.\n\n```tsx\nimport { useEffect, useRef, useState } from 'react';\nimport { Subject } from 'rxjs';\nimport { fromFetch } from 'rxjs/fetch';\nimport {\n  debounceTime,\n  distinctUntilChanged,\n  filter,\n  switchMap,\n} from 'rxjs/operators';\n\ntype Hit = { id: string; label: string };\n\nfunction Autocomplete() {\n  const query$ = useRef(new Subject<string>()).current;\n  const [results, setResults] = useState<Hit[]>([]);\n\n  useEffect(() => {\n    const subscription = query$\n      .pipe(\n        debounceTime(300),\n        distinctUntilChanged(),\n        filter((term) => term.length > 1),\n        switchMap((term) =>\n          fromFetch(`/api/search?q=${encodeURIComponent(term)}`).pipe(\n            switchMap((response) => response.json() as Promise<Hit[]>),\n          ),\n        ),\n      )\n      .subscribe(setResults);\n\n    return () => subscription.unsubscribe();\n  }, [query$]);\n\n  return (\n    <div>\n      <input onChange={(event) => query$.next(event.target.value)} />\n      <ul>\n        {results.map((hit) => (\n          <li key={hit.id}>{hit.label}</li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n```\n\nThe decisive difference hinges on a single operator name. If you write `mergeMap` here out of habit, all requests keep running in parallel, and the race condition described above is back. For “only the last input counts,” `switchMap` is the right choice. The difference becomes tangible if you deliberately build the pipeline with `mergeMap` once and run it against an artificially slowed-down API: the outdated hits then visibly flash up in the list before the current result replaces them.\n\nThe following diagram shows the data flow of the pipeline from input to re-render.\n\n```mermaid\nflowchart LR\n  A[\"Input event<br/>onChange\"] --> B[\"Subject.next(term)\"]\n  B --> C[\"debounceTime(300)<br/>wait for a quiet period\"]\n  C --> D[\"distinctUntilChanged<br/>filter duplicates\"]\n  D --> E[\"switchMap<br/>discard old request\"]\n  E --> F[\"subscribe<br/>setResults\"]\n  F --> G[\"React re-render\"]\n```\n\nThe cancellation semantics of `switchMap` are important because they are the core of the whole thing. The second diagram shows them as a sequence: the input “rea” cancels the still open inner stream of “re,” so that only the response to the last input lands in the state.\n\n```mermaid\nsequenceDiagram\n  participant U as User\n  participant P as Pipeline (switchMap)\n  participant A as API\n  U->>P: Input \"re\"\n  P->>A: Request \"re\"\n  U->>P: Input \"rea\"\n  Note over P: switchMap cancels<br/>inner stream \"re\"\n  P--xA: Request \"re\" aborted\n  P->>A: Request \"rea\"\n  A-->>P: Response \"rea\"\n  P->>U: setResults (only last response)\n```\n\n## Continuous streams: WebSockets and events\n\nThe third case where RxJS pays off is sources that do not deliver a single result but keep emitting over time. WebSockets are the obvious example. With `webSocket` from `rxjs/webSocket`, RxJS comes with a bidirectional wrapper that is both an Observable and an Observer – I can subscribe to incoming messages and send my own via `next()`. The detail that is worth its weight in gold here: `unsubscribe()` closes the connection cleanly.\n\n```tsx\nimport { useEffect, useState } from 'react';\nimport { webSocket } from 'rxjs/webSocket';\n\ntype Message = { id: string; text: string };\n\nfunction LiveFeed() {\n  const [messages, setMessages] = useState<Message[]>([]);\n\n  useEffect(() => {\n    const socket$ = webSocket<Message>('wss://example.com/feed');\n\n    const subscription = socket$.subscribe((message) =>\n      setMessages((prev) => [...prev, message]),\n    );\n\n    // unsubscribe closes the underlying socket\n    return () => subscription.unsubscribe();\n  }, []);\n\n  return (\n    <ul>\n      {messages.map((message) => (\n        <li key={message.id}>{message.text}</li>\n      ))}\n    </ul>\n  );\n}\n```\n\nI describe the basics behind such message streams in [RxJS: Push and Pull](https://www.mikebild.dev/en/blog/rxjs-telling-push-and-pull-apart/). Bidirectional channels do not change anything about this model: sending and receiving remain two separate streams.\n\nA variant with `fromEvent` belongs here too, because it reveals a stumbling point. `fromEvent` attaches to a real DOM node, not to React’s synthetic event system. So you need a `ref`, and it is only set after mount:\n\n```tsx\nimport { useEffect, useRef, useState } from 'react';\nimport { fromEvent } from 'rxjs';\nimport { map, debounceTime } from 'rxjs/operators';\n\nfunction ScrollTracker() {\n  const boxRef = useRef<HTMLDivElement>(null);\n  const [position, setPosition] = useState(0);\n\n  useEffect(() => {\n    const node = boxRef.current;\n    if (!node) return;\n\n    const subscription = fromEvent(node, 'scroll')\n      .pipe(\n        map((event) => (event.target as HTMLElement).scrollTop),\n        debounceTime(50),\n      )\n      .subscribe(setPosition);\n\n    return () => subscription.unsubscribe();\n  }, []);\n\n  return <div ref={boxRef}>{/* scrollable content */}</div>;\n}\n```\n\n## The pitfall that gets everyone once: a missing unsubscribe\n\nWhen an RxJS React component inexplicably eats memory or throws a “setState on an unmounted component” warning, the cause is almost always the same: the cleanup function is missing or does not release the subscription. Without `unsubscribe()`, the stream keeps running after unmount. The event listener stays attached, the timer keeps ticking, the WebSocket stays open – and every emitted value calls a `setState` on a component that no longer exists.\n\n```tsx\n// Wrong: no cleanup, the stream keeps running after unmount\nuseEffect(() => {\n  interval(1000).subscribe((n) => setTick(n)); // memory leak\n}, []);\n\n// Right: keep the subscription and release it in cleanup\nuseEffect(() => {\n  const subscription = interval(1000).subscribe((n) => setTick(n));\n  return () => subscription.unsubscribe();\n}, []);\n```\n\nThe second related mistake is more subtle: building the pipeline in the render body instead of in the effect. A `fromEvent(...).pipe(...)` that is created anew on every render produces duplicate listeners and duplicate subscriptions. The order that works reliably: keep the source stable (via `useRef` or outside the component), set up the subscription in the effect, tear it down in the cleanup, and maintain the dependency array carefully.\n\nAs a side note for 2022: with `useSyncExternalStore`, React 18 brings a mechanism for binding cleanly to external stores – including RxJS-based ones. For the cases shown here, though, the `useEffect` route is entirely sufficient, and I would only reach for `useSyncExternalStore` when a store really lives outside the component and is used from several places.\n\n## When RxJS pays off – and when it does not\n\nThe most common wrong decision is pulling RxJS in everywhere. Two short lists help you avoid it.\n\nRxJS pays off when:\n\n- input has to be debounced or throttled over time before an expensive effect runs.\n- outdated asynchronous results should be actively discarded (autocomplete, competing requests) – the core case for `switchMap`.\n- continuous streams such as WebSockets, server-sent events or timers are processed.\n- several event and time sources have to be combined, merged or coordinated in time.\n\nRxJS does not pay off when:\n\n- it is about simple local component state – that is what `useState` and `useReducer` are for.\n- a single request is loaded on mount; a `fetch` with `AbortController` in the effect is enough, or you reach for a data-fetching library.\n- the team has not mastered RxJS and the requirement contains no real asynchronous coordination – then the learning curve does not pay off.\n\nThis separation is the actual core of the post. RxJS is not a replacement for React’s state model but a complement for a narrow but important slice: coordinating asynchronous events over time. If you use observables deliberately in these few places and stick with React’s built-in tools everywhere else, you get both: declarative streams where they solve real problems, and lean components in the rest of the application. And if you consistently call `unsubscribe()` in the cleanup, you avoid the one mistake that otherwise reliably comes back.\n\n## Further reading\n\n- [RxJS: Push and Pull](https://www.mikebild.dev/en/blog/rxjs-telling-push-and-pull-apart/) – the basics of observables as push producers.\n- [Observable guide (rxjs.dev)](https://rxjs.dev/guide/observable)\n- [Operators guide / pipe (rxjs.dev)](https://rxjs.dev/guide/operators)\n- [Subject (rxjs.dev)](https://rxjs.dev/guide/subject)\n- [switchMap (rxjs.dev)](https://rxjs.dev/api/operators/switchMap)\n- [debounceTime (rxjs.dev)](https://rxjs.dev/api/operators/debounceTime)\n- [fromEvent (rxjs.dev)](https://rxjs.dev/api/index/function/fromEvent)\n- [Subscription / unsubscribe (rxjs.dev)](https://rxjs.dev/guide/subscription)\n- [React: Using the Effect Hook (reactjs.org)](https://reactjs.org/docs/hooks-effect.html)"},{"locale":"en","translation_key":"svelte-motion-transitions-animationen","slug":"motion-transitions-and-animations-in-svelte","title":"Motion, Transitions and Animations in Svelte","summary":"How Svelte ships motion declaratively and without an extra library: transition directives for fading in and out, svelte/motion for smoothly interpolated values and animate:flip for reordering lists.","tags":["Software","Frontend","Svelte"],"published_at":"2022-09-27T10:00:00+00:00","updated_at":"2026-07-13T07:58:57.049025+00:00","url":"https://www.mikebild.dev/en/blog/motion-transitions-and-animations-in-svelte/","audio_url":null,"audio_duration_secs":null,"text":"A notice appears above the list, and it is simply there – abruptly, without a transition. An entry is deleted, and everything below it jumps up one line at once. In React projects, at this point at the latest, `react-transition-group` or an animation runtime lands in `package.json`. In Svelte, it takes three imports from the standard toolkit, and the dependency list stays as it was.\n\nThe three modules are designed to work together and between them cover almost everything that comes up in everyday work. If you have already understood why [Svelte does without a Virtual DOM and generates code at compile time instead](https://www.mikebild.dev/en/blog/svelte-reactivity-the-compiler-instead-of-a-virtual-dom/), you can already guess where this is heading: motion is also closely woven into the compiler – it translates the directives into code that, where possible, runs the animation through CSS keyframes instead of JavaScript per frame.\n\n**Editorial note (July 2026):** The examples are written in Svelte 3 style. `svelte/transition`, `svelte/animate` and `svelte/motion` also exist in Svelte 5; what has mainly changed is the surrounding reactivity model. The old tutorial URLs have been replaced with today’s API pages.\n\n## Three tools, three jobs\n\nBefore we write code, it pays to separate things cleanly in your head. The three modules have different responsibilities, and most of the misunderstandings I have come across arise from someone reaching for the wrong tool for the wrong job.\n\n- `transition:` (from `svelte/transition`) describes how a single element enters and leaves the DOM. It is about appearing and disappearing.\n- `animate:` (from `svelte/animate`) describes how elements move that stay in the DOM but change their position – that is, when reordering a list.\n- `svelte/motion` (with `tweened` and `spring`) initially has nothing to do with the DOM at all. It is about values that interpolate smoothly from one state to the next – a number, a color, a coordinate.\n\nThis three-way split is the common thread for everything that follows. As soon as it is clear whether you are making an element appear, moving it within a list or letting a value glide, the right module almost picks itself.\n\n## Transitions: fading in and out\n\nIn Svelte, you attach a transition to an element as a directive. It is triggered as soon as the element enters or leaves the DOM through control flow – an `{#if}`, an `{#each}`. That is the crucial point: I do not call an animation; the state change does. I only describe what it looks like.\n\n```svelte\n<script>\n  import { fade, fly } from 'svelte/transition';\n  let visible = true;\n</script>\n\n<label>\n  <input type=\"checkbox\" bind:checked={visible} />\n  toggle\n</label>\n\n{#if visible}\n  <p transition:fade={{ duration: 300 }}>\n    fades in and out\n  </p>\n\n  <div transition:fly={{ y: 20, duration: 300 }}>\n    flies in from below, flies back down on exit\n  </div>\n{/if}\n```\n\n`transition:` is bidirectional – the same motion runs forward when fading in and backward when fading out. That is often exactly right. But sometimes you want to be asymmetric: fly in, but fade out. For that, there are the separate directives `in:` and `out:`.\n\n```svelte\n<script>\n  import { fly, fade } from 'svelte/transition';\n  let visible = true;\n</script>\n\n{#if visible}\n  <div in:fly={{ y: 20, duration: 300 }} out:fade={{ duration: 200 }}>\n    enters flying, leaves fading\n  </div>\n{/if}\n```\n\nThe built-in selection is manageable and well coordinated: `fade`, `blur`, `fly`, `slide`, `scale`, `draw` and `crossfade`. For everyday use, the first five are almost always enough. `fly` takes `x` and `y` as numbers in pixels, `slide` opens and closes vertically, `scale` scales from a starting value.\n\nOne detail only became clear to me when I looked closely: an out transition takes time, and the element stays in the DOM for that duration. Svelte removes it only when the motion has finished. So if you think an element is already gone while it is still fading out, you will be surprised by briefly duplicated entries. That is not a bug but the precondition for being able to see the disappearance at all.\n\n## What the compiler makes of it internally\n\nThe reason these transitions run without performance worries lies in how they are generated. At its core, a transition function returns a `css` function that produces a CSS string for a progress value `t` (from 0 to 1). From this function, Svelte builds real CSS keyframes. The animation thus runs through the browser’s CSS engine and does not block the main thread with JavaScript per frame.\n\n```mermaid\nflowchart LR\n  A[\"State change<br/>{#if} / {#each}\"] --> B[\"Svelte compiler\"]\n  B --> C[\"transition: / animate:<br/>directive\"]\n  C --> D{\"css function<br/>available?\"}\n  D -->|yes| E[\"CSS keyframes<br/>off main thread\"]\n  D -->|no| F[\"tick per frame<br/>JS on main thread\"]\n  E --> G[\"DOM update\"]\n  F --> G\n```\n\nOnly when a motion cannot be expressed purely in CSS – for example because you want to change text content per frame – does the second path kick in, via a `tick` function that actually runs in JavaScript per frame. But the default case is the performant CSS path, and you get it for free without writing keyframes yourself.\n\n## animate:flip for lists\n\nLet’s get to the second tool. `transition:` takes care of elements that come and go. But what about elements that stay and just swap places? When I sort or shuffle a list, the entries jump hard to their new position on their own. This is exactly where `animate:flip` comes in.\n\nThe name FLIP stands for “First, Last, Invert, Play” – a well-known technique in which the old and new positions of an element are compared and the difference is animated away. Svelte does this calculation for us. Only one condition matters: `animate:` works exclusively in a keyed `{#each}` block, that is, an `{#each}` with a stable key. Without this key, Svelte cannot know which element was where before.\n\nThe following example brings both tools together – `transition:fly` for fading new or removed entries in and out, and `animate:flip` for smoothly reordering the ones that stay:\n\n```svelte\n<script>\n  import { fly } from 'svelte/transition';\n  import { flip } from 'svelte/animate';\n\n  let items = [\n    { id: 1, label: 'apples' },\n    { id: 2, label: 'oranges' },\n    { id: 3, label: 'bananas' },\n    { id: 4, label: 'pears' }\n  ];\n\n  function shuffle() {\n    items = items\n      .map((item) => ({ item, sort: Math.random() }))\n      .sort((a, b) => a.sort - b.sort)\n      .map(({ item }) => item);\n  }\n\n  function remove(id) {\n    items = items.filter((item) => item.id !== id);\n  }\n</script>\n\n<button on:click={shuffle}>shuffle</button>\n\n<ul>\n  {#each items as item (item.id)}\n    <li\n      transition:fly={{ y: 20, duration: 300 }}\n      animate:flip={{ duration: 300 }}\n    >\n      {item.label}\n      <button on:click={() => remove(item.id)}>x</button>\n    </li>\n  {/each}\n</ul>\n```\n\nThe key `(item.id)` is not decorative here; it carries the whole mechanism. It lets Svelte recognize the same DOM `<li>` as the same element across the reordering and animate the difference in position. The animated element must also be a direct child of the `{#each}` block. If you put a wrapper in between instead and attach `animate:flip` to the wrong element, you simply see no motion – a classic I keep stumbling over in reviews.\n\nBy the way, combining `transition` and `animate` in the same list is intentional and well coordinated: new entries fly in, removed ones fly out and stay in the DOM briefly to do so, and all the others slide smoothly into their new places. Three motions, one declarative block.\n\n## svelte/motion: values that glide\n\nThe third tool leaves the DOM aside at first. `tweened` and `spring` are stores – writable stores, as I described them in the article about [state outside the component with Svelte stores](https://www.mikebild.dev/en/blog/svelte-stores-state-outside-the-component/), with one special feature: when you set their value, they do not jump to the target immediately but interpolate toward it. In the markup, you read them like any store with the `$` prefix.\n\n`tweened` interpolates over a fixed duration and an easing function – good for anything that should follow a clear timeline, such as a progress bar.\n\n```svelte\n<script>\n  import { tweened } from 'svelte/motion';\n  import { cubicOut } from 'svelte/easing';\n\n  const progress = tweened(0, {\n    duration: 400,\n    easing: cubicOut\n  });\n</script>\n\n<progress value={$progress}></progress>\n\n<button on:click={() => progress.set(0)}>0%</button>\n<button on:click={() => progress.set(0.5)}>50%</button>\n<button on:click={() => progress.set(1)}>100%</button>\n```\n\n`spring`, on the other hand, does not interpolate over a duration but via physics – stiffness and damping. The result feels more alive because it bounces slightly instead of arriving at an exact point in time. For things that should feel “natural,” such as an element that follows the mouse or reacts to input, `spring` is usually the nicer choice.\n\n```svelte\n<script>\n  import { spring } from 'svelte/motion';\n\n  const size = spring(1, {\n    stiffness: 0.1,\n    damping: 0.4\n  });\n</script>\n\n<div class=\"box\" style=\"transform: scale({$size})\">\n  {$size.toFixed(2)}\n</div>\n\n<button on:click={() => size.set(0.5)}>small</button>\n<button on:click={() => size.set(1)}>normal</button>\n<button on:click={() => size.set(2)}>large</button>\n\n<style>\n  .box {\n    width: 80px;\n    height: 80px;\n    background: #ff3e00;\n    display: grid;\n    place-items: center;\n    color: white;\n  }\n</style>\n```\n\nTwo details only become apparent when you work with them. First, `.set()` and `.update()` return a promise that only resolves when the interpolation has finished – so if you want to wait for a value to have “arrived,” you can `await` it. Second, Svelte automatically interpolates numbers, arrays and objects of numbers; for other value types, such as colors in a particular notation, you give `tweened` your own interpolation function via the `interpolate` option.\n\nThe `stiffness` and `damping` parameters can even be adjusted at runtime. You can bind them to sliders and experience live how the spring’s behavior changes. That is the fastest way to get a feel for what the two numbers actually do – faster, in any case, than guessing values in code and reloading.\n\n## Writing your own transitions\n\nPerhaps the nicest proof that no black box is at work here: a transition is nothing more than a function. It gets the DOM node and its parameters and returns an object that contains, among other things, a `css` function. This function receives the progress `t` from 0 to 1 as well as the counter value `u`, which equals `1 - t`, and returns a CSS string.\n\n```js\nfunction spin(node, { duration = 400 }) {\n  return {\n    duration,\n    css: (t, u) => `\n      transform: rotate(${u * 360}deg) scale(${t});\n      opacity: ${t};\n    `\n  };\n}\n```\n\nYou can use this custom transition exactly like the built-in ones:\n\n```svelte\n<script>\n  import { spin } from './spin.js';\n  let visible = true;\n</script>\n\n{#if visible}\n  <div in:spin={{ duration: 600 }}>\n    spins into view\n  </div>\n{/if}\n```\n\nOnce you have written this, the rest demystifies itself. `fade`, `fly` and `scale` are exactly such functions – they just live in the library. There is no second, hidden mechanism. This consistency is exactly what I appreciate so much about Svelte’s motion model: from the ready-made one-liner to your own function, it is one continuous concept, not a break.\n\nTo put it in context, here are the three tools compared directly once more, so the mapping sticks for good:\n\n- `transition:` / `in:` / `out:` – for the appearing and disappearing of individual elements, triggered by `{#if}` or `{#each}`.\n- `animate:flip` – for elements that stay in the DOM and only swap positions in a keyed `{#each}`.\n- `tweened` / `spring` from `svelte/motion` – for interpolated values that you read as a store with `$` and bind into the markup.\n\n## Conclusion\n\nIn Svelte, motion is not an extra decision you retrofit later with a library; it is part of the language. That changes how you approach the topic. Instead of asking “Which package do I use?”, you ask “Is something appearing here, is something moving, or is a value gliding?” – and the answer leads directly to `transition:`, `animate:flip` or `svelte/motion`.\n\nThe common denominator is the declarative approach: I describe what a motion looks like, and the compiler makes sure it is triggered when the state changes and that it runs performantly via CSS keyframes where possible. Because custom transitions are the same simple functions as the built-in ones, the whole thing can be learned right down to the bottom. For everyday project work, this means: fewer dependencies, less boilerplate and more time for the question of which motion really makes a UI easier to understand – instead of the question of which framework makes it possible at all.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-svelte.en.html\n- Repository for the article series with the runnable Svelte examples\n- [`svelte/transition` – official documentation](https://svelte.dev/docs/svelte/svelte-transition)\n- [`svelte/animate` – official documentation](https://svelte.dev/docs/svelte/svelte-animate)\n- [`svelte/motion` – official documentation](https://svelte.dev/docs/svelte/svelte-motion)"},{"locale":"en","translation_key":"nodejs-buffers-und-binaerdaten","slug":"buffers-in-nodejs-working-with-binary-data","title":"Buffers in Node.js: Working with Binary Data","summary":"Why JS strings don’t work for raw bytes and Buffer is Node’s tool for them: alloc versus allocUnsafe, reading and writing encodings cleanly, and the memory trap behind slice and subarray.","tags":["Software","Node.js","Backend"],"published_at":"2022-08-09T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/buffers-in-nodejs-working-with-binary-data/","audio_url":null,"audio_duration_secs":null,"text":"A `Buffer` isn’t a broken string. If `<Buffer 89 50 4e 47 0d 0a 1a 0a ...>` shows up in the console after reading a file, nothing went wrong: Node shows exactly what’s in the file – a sequence of bytes that has no meaning as text and isn’t supposed to get one.\n\nIn Node, such bytes come from many directions: from `fs`, from open network connections, from `crypto`. The `Buffer` is the type Node holds them in. What makes it interesting are mainly the places where it behaves differently from what you’re used to with strings and arrays – when creating it and when splitting it up.\n\n## Why strings aren’t enough here\n\nA JavaScript string is a sequence of Unicode characters, not a sequence of bytes. That sounds like hair-splitting, but it’s the core of the problem. As soon as I have a string, the runtime has already made an interpretation: these bytes are text, in a specific encoding. But raw binary data – a PNG header, a compressed block, a cryptographic key – has no meaning as text at all. If I force it through a string, I lose or corrupt bytes, because invalid byte sequences get replaced with replacement characters. Often this is only noticed late, for example when an uploaded file arrives damaged at the other end.\n\nNode solves this with `Buffer`: a region of fixed byte length that contains exactly the bytes you put into it, without any reinterpretation. One detail is crucial here and explains a lot: a `Buffer` is a subclass of `Uint8Array`, so it’s a TypedArray itself. Everything you know from `Uint8Array` – index access, `length`, `for` loops, the TypedArray methods – works on a Buffer too. `Buffer` merely adds the extras that are practical for Node, first and foremost the encodings.\n\n```js\nconst fs = require('node:fs');\n\nconst data = fs.readFileSync('image.png');\n\nconsole.log(Buffer.isBuffer(data));        // true\nconsole.log(data instanceof Uint8Array);   // true\nconsole.log(data.length);                  // number of bytes\nconsole.log(data.subarray(0, 8));          // <Buffer 89 50 4e 47 0d 0a 1a 0a>\n```\n\nBy the way, the first eight bytes are the fixed signature of a PNG file. In practice, you read exactly such headers to detect file types without relying on the extension.\n\n## Creating a buffer: alloc, allocUnsafe, from\n\nThere are three ways to get a Buffer, and the differences matter – for security reasons too.\n\n- `Buffer.alloc(size)` reserves `size` bytes and sets them all to `0`. Optionally, you pass a fill byte and an encoding. This is the safe default when you need an empty buffer of a certain size.\n- `Buffer.allocUnsafe(size)` also reserves `size` bytes but doesn’t initialize them. The content is old memory – whatever was there before is still there. In return, creating it is measurably faster, because zeroing is skipped and the memory may come from an internal pool.\n- `Buffer.from(...)` creates a buffer from existing data: from a string (with an encoding), from an array of byte values, from another buffer (copied) or from an `ArrayBuffer`.\n\nThe difference between the first two isn’t a detail. `allocUnsafe` returns memory that may contain leftovers from earlier allocations – possibly data from completely different parts of the program.\n\n```js\nconst zeroed = Buffer.alloc(8);\nconsole.log(zeroed);        // <Buffer 00 00 00 00 00 00 00 00>\n\nconst uninitialized = Buffer.allocUnsafe(8);\nconsole.log(uninitialized); // <Buffer ?? ?? ?? ?? ?? ?? ?? ??> old memory\n```\n\nThat’s why `alloc` is the default; `allocUnsafe` is only worth it where the buffer is completely overwritten right afterward anyway. If you use `allocUnsafe` and only partially fill the memory, you must never output or send the rest, because sensitive data may be in there. That’s the first of the two classic traps, and it’s treacherous because it never shows up in a local test – in a freshly started process, the memory often happens to be zeroed. Only under load, when the pool is reused, do the data leftovers appear.\n\nAs an aside, because it still haunts old code: the former `new Buffer(...)` call has been deprecated at runtime since Node 10 (DEP0005) and shouldn’t be used anymore. And `Buffer.from(10)` doesn’t create a buffer of size 10 but throws a `TypeError` – a number isn’t a valid argument for `Buffer.from`. If you mean a size, use `alloc` or `allocUnsafe`.\n\n## Encodings: the same bytes, different glasses\n\nThe second big benefit of `Buffer` over a bare `Uint8Array` is the encodings. An encoding isn’t a conversion of the bytes but a rule for how to read the same bytes as text or how to break text down into bytes. The round trip between the two sides looks like this:\n\n```mermaid\ngraph LR\n  S[\"String<br/>(Unicode text)\"] -->|\"Buffer.from(str, enc)\"| B[\"Buffer<br/>(raw bytes)\"]\n  B -->|\"buf.toString(enc)\"| S\n  B -->|\"buf.toString('hex')\"| H[\"Hex text\"]\n  B -->|\"buf.toString('base64')\"| B64[\"Base64 text\"]\n```\n\nWhen writing in with `Buffer.from(str, enc)`, I say: break this text down into bytes according to this rule. When reading out with `buf.toString(enc)`, I say: interpret these bytes as text according to this rule. What matters is that both sides mean the same encoding, otherwise you get nonsense.\n\nThe common encodings fall into two groups. The first describe text to bytes: `utf8` (the default), `utf16le`, `latin1` (also called `binary`) and `ascii`. The others are byte-to-text representations that make arbitrary binary data printable: `hex`, `base64` and `base64url`. You need `hex` and `base64` in particular all the time, for example to make a hash readable or to transport binary data in JSON.\n\n```js\nconst buf = Buffer.from('Grüße', 'utf8');\n\nconsole.log(buf.length);            // 7 bytes, not 5\nconsole.log('Grüße'.length);        // 5 characters\n\nconsole.log(buf.toString('hex'));     // 4772c3bcc39f65 byte view as hex\nconsole.log(buf.toString('base64'));  // R3LDvMOfZQ== byte view as base64\n\nconst b64 = buf.toString('base64');\nconst back = Buffer.from(b64, 'base64').toString('utf8');\nconsole.log(back);                    // 'Grüße' again\n```\n\nThe interesting point is in the first two lines: the string has five characters, but the buffer has seven bytes. The ü and the ß each take up two bytes in UTF-8. Bytes and characters simply aren’t the same thing, and if you mix up `length`, you calculate offsets wrong. In practice, a related problem arises from exactly this: with streams, a multibyte character can be cut apart at the point where one data chunk ends and the next begins. For clean decoding across such chunk boundaries, there is the `string_decoder`, which buffers half characters in between – but that’s a topic of its own, covered in more detail in the post [Node.js streams and backpressure](https://www.mikebild.dev/en/blog/nodejs-streams-understanding-backpressure/).\n\n## Numbers as bytes: byte order\n\nEncodings take care of text. But as soon as you take apart a binary format – a file header, a network protocol, a frame – it’s about numbers spread across several bytes. For this, `Buffer` comes with a series of read and write methods that interpret a fixed number of bytes at an offset as an integer: `readUInt8`, `readUInt16BE`, `readUInt32LE`, plus the signed variants and, for 64 bits, the `BigInt` versions such as `readBigUInt64BE`. The counterpart for writing is called `writeUInt32BE` and so on.\n\nThe suffix at the end is where many people stumble: `BE` stands for big-endian, `LE` for little-endian – that is, for the question of whether the most significant byte comes first or last. If you pick a different order when reading than the writer used, you get a completely different number, without any error being thrown. Network protocols are traditionally big-endian, and many file formats define their own order; so you have to look it up in the respective format and must not guess.\n\n```js\nconst buf = Buffer.alloc(4);\n\nbuf.writeUInt32BE(0x89504e47, 0); // PNG signature bytes as one number\nconsole.log(buf);                 // <Buffer 89 50 4e 47>\n\nconsole.log(buf.readUInt32BE(0).toString(16)); // 89504e47\nconsole.log(buf.readUInt32LE(0).toString(16)); // 474e5089, reversed bytes\n```\n\nThe same four bytes produce two different numbers depending on the chosen order. The buffer itself doesn’t know what’s right – the meaning lies in the format, not in the bytes.\n\n## The memory trap: slice and subarray share memory\n\nNow to the second big trap, and it snaps shut especially often because arrays behave differently. When you call `slice` on an ordinary JavaScript array, you get a copy. With a buffer, it’s different: `buf.subarray(start, end)` and the older `buf.slice(start, end)` both create no copy but a view onto the same underlying memory. If you write into the view, you change the original too.\n\n```mermaid\ngraph TD\n  M[\"Byte block in memory<br/>[1, 2, 3, 4, 5]\"]\n  O[\"original<br/>(whole block)\"] --> M\n  V[\"view = original.subarray(1, 3)<br/>(bytes 1 and 2)\"] --> M\n```\n\nBoth names, `original` and `view`, point to the same memory. A write through one is visible through the other.\n\n```js\nconst original = Buffer.from([1, 2, 3, 4, 5]);\n\nconst view = original.subarray(1, 3); // shares memory, no copy\nview[0] = 99;\n\nconsole.log(view);      // <Buffer 63 03>\nconsole.log(original);  // <Buffer 01 63 03 04 05> byte 1 changed too!\n```\n\nThe byte at position 1 in the original has changed, even though I seemingly only wrote into `view`. In a function that returns a partial buffer which the caller then modifies, this leads to bugs that are hard to find, because cause and effect sit in completely different places in the code.\n\nIf you need an independent copy, you have to create it explicitly – for example with `Buffer.from` over the view or with `buf.copy` into a freshly reserved target buffer.\n\n```js\nconst original = Buffer.from([1, 2, 3, 4, 5]);\n\nconst copy = Buffer.from(original.subarray(1, 3)); // independent copy\ncopy[0] = 99;\n\nconsole.log(copy);      // <Buffer 63 03>\nconsole.log(original);  // <Buffer 01 02 03 04 05> untouched\n```\n\nOn the naming question, because it comes up often: the Node documentation now recommends `subarray`. The name `slice` only still exists on buffers for compatibility reasons and deliberately differs from the behavior of `TypedArray.prototype.slice`, which returns a copy. This inconsistency grew historically and is a common source of confusion. I recommend consistently writing `subarray` for buffers – then anyone reading the code immediately knows that memory is shared here and no copy is created.\n\n## Where buffers show up in everyday work\n\nYou rarely create buffers by hand; usually the platform hands them to you. The `fs` module returns a buffer when reading without an encoding. Streams deliver their data in buffer chunks unless you configure them as text. The `net` network module passes received packets on as buffers. And `crypto` works with buffers almost throughout – a hash, for example, is created as a buffer that you then make readable with `toString('hex')`.\n\n```js\nconst crypto = require('node:crypto');\n\nconst hash = crypto.createHash('sha256')\n  .update('hello world')   // accepts string or Buffer\n  .digest();               // returns a Buffer\n\nconsole.log(Buffer.isBuffer(hash)); // true\nconsole.log(hash.toString('hex'));  // b94d27b9934d3e08a52e52d7da7dabfa...\n```\n\nHere you can see the two roles of the buffer nicely together: `update` accepts text or bytes, `digest` returns raw bytes, and `toString('hex')` makes those bytes readable for logs and comparisons. If you want to understand which execution model these inputs and outputs run in and why that doesn’t block, you’ll find the background in the post [Node.js Training](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/) on event loop architecture.\n\n## What sticks\n\nThree things go a long way. First: a buffer is a `Uint8Array` with Node extras – if you keep that in mind, you immediately understand index access and length and don’t expect any string magic. Second: `alloc` is the safe default, `allocUnsafe` a deliberate compromise for cases where you overwrite the memory completely anyway; anything else risks exposing old data. Third: `subarray` and `slice` share memory and don’t copy – if you need an independent version, copy by hand.\n\nThe two traps – uninitialized memory from `allocUnsafe` and the shared view from `subarray` – have one thing in common: they don’t show up in a quick test and only strike later or under load. That’s exactly why it pays to play through the behavior deliberately once instead of leaving it to chance. File access, networking and cryptography in Node run on raw bytes; once you have understood the buffer, you read their output in the console as what it is: a representation of the data without any reinterpretation.\n\n## Further reading\n\n- [Node.js Training: Event Loop architecture](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/)\n- [Node.js streams and backpressure](https://www.mikebild.dev/en/blog/nodejs-streams-understanding-backpressure/)\n- [Node.js documentation: Buffer](https://nodejs.org/api/buffer.html)\n- [Buffer.alloc(size, fill, encoding)](https://nodejs.org/api/buffer.html#static-method-bufferallocsize-fill-encoding)\n- [Buffer.allocUnsafe(size)](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize)\n- [Buffers and character encodings](https://nodejs.org/api/buffer.html#buffers-and-character-encodings)\n- [buf.slice() – legacy note, prefer subarray](https://nodejs.org/api/buffer.html#bufslicestart-end)\n- [MDN: Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)"},{"locale":"en","translation_key":"svelte-stores-zustand-ausserhalb-der-komponente","slug":"svelte-stores-state-outside-the-component","title":"Svelte Stores: State Outside the Component","summary":"Svelte stores are a minimal model for state that doesn’t fit into a single component: writable, readable, derived – plus the $ shorthand that subscribes and cleans up on unmount.","tags":["Software","Frontend","Svelte"],"published_at":"2022-07-19T10:00:00+00:00","updated_at":"2026-07-13T13:25:28.073895+00:00","url":"https://www.mikebild.dev/en/blog/svelte-stores-state-outside-the-component/","audio_url":null,"audio_duration_secs":null,"text":"If you install a state management library before the ownership question is settled, you have already paid the price: an extra dependency, a second mental model, and boilerplate – for a problem your project may not even have. The trigger is usually harmless. Two components that aren’t directly related need to share a value; reactivity inside a component works beautifully, but there is no mechanism across the component boundary. From the React world, you know the move of reaching for the big library, and it happens by reflex, even though the real question isn’t an API question: who owns this state, and how much machinery is it allowed to cost?\n\nSvelte already ships with a tool for this case that consists of barely a handful of functions – stores. They answer the ownership question with the smallest possible means and let the cost rise only when a concrete problem forces it. The real gain lies less in the functions themselves than in the discipline they allow: start small and draw the line to “more” deliberately instead of crossing it by reflex.\n\nA store is state that lives outside the component. It doesn’t belong to any single `.svelte` file but sits in a separate module and can be subscribed to from anywhere. That solves a problem that quickly becomes annoying in component trees: passing values down through several levels just so a deeply nested child can get hold of a piece of information. If you have read my article on [Svelte reactivity](https://www.mikebild.dev/en/blog/svelte-reactivity-the-compiler-instead-of-a-virtual-dom/), you already know the foundation: the compiler builds reactivity in at build time, without a virtual DOM. Stores are the logical continuation of that idea for state that has to cross the component boundary.\n\n**Editorial note (July 2026):** This text uses the store model of Svelte 3/4. Stores are still supported in Svelte 5 and are especially useful for asynchronous streams or manually controlled subscriptions. For shared state, though, a `.svelte.js` or `.svelte.ts` file with runes can be enough today; stores are no longer the only built-in answer outside a component.\n\n## The ownership question comes before the tool question\n\nBefore I get to the concrete Svelte functions, one principle that has nothing to do with Svelte itself and applies to every component-based frontend – React, Vue, or Svelte. I derived it in detail for React elsewhere, in the [state management comparison](https://www.mikebild.dev/en/blog/state-management-in-react/), and the core carries over one to one: the deciding question is not “which state library” but “who owns this state?” State belongs at the lowest point where everyone involved can still reach it. As long as that is a single component, it stays there – local, without any ceremony. Only when several unrelated components share the same value, or the value comes from outside the tree, does it leave the component. A global or module-wide store is therefore the exception you justify, not the default you fall into.\n\nWhy I stress this so much is a cost argument. Every level I lift state to makes it more expensive: more places that are allowed to write, changes that are harder to trace, a larger surface for bugs. In projects, I have gone the opposite way often enough – first the big library is chosen, then state gets pushed into it until everything is global. The counter-check goes the other way: does this value really need several components, and are they so decoupled that a shared parent component wouldn’t connect them anyway? In my experience, after asking this question, far less global state remains than initially assumed.\n\nTo decide whether a value should leave the component, I use three criteria. Reach: do at least two components share it that aren’t in a clean parent-child relationship? Origin: is the value written from outside the tree – a timer, a WebSocket, a sensor? And lifetime: does it have to exist regardless of whether a particular component is currently mounted? If none of these applies, the state stays local, and any solution above that is paid-for complexity with nothing in return. If one applies, a lean, module-wide store is the right answer – in Svelte, literally one line of code. The real work lies in the decision before, not in the API after.\n\n## The contract, not the class\n\nIn Svelte, a store is not a special type and not a class you have to inherit from. A store is any object that provides a `.subscribe` method according to a fixed contract – and optionally a `.set` method if it should be writable. `subscribe` must deliver the current value to the subscriber synchronously and return a function for unsubscribing. That contract is what counts. Anything that fulfills it works with the `$` syntax.\n\nIn practice, you almost never write this `.subscribe` method yourself. Svelte ships three factory functions that do the work for you. They all come from the same module:\n\n```js\nimport { writable, readable, derived, get } from 'svelte/store';\n```\n\nThe three store types cover three different roles:\n\n- `writable` – readable and writable. The default case for shared state that any component or function may change. Provides `.set(value)`, `.update(fn)`, and `.subscribe(run)`.\n- `readable` – read-only from the outside. The value is set internally via a start callback, ideal for external sources such as a clock, a WebSocket, or an event listener.\n- `derived` – derived. Computes its value reactively from one or more other stores and updates automatically when one of its sources changes.\n\n## The writable store and the $ shorthand\n\nLet’s start with the most common case – a shared counter that several components use. The store lives in its own module so that every component can import it:\n\n```js\n// stores.js\nimport { writable } from 'svelte/store';\n\nexport const count = writable(0);\n```\n\nThat is the complete store. One module, one line, one initial value. Now any component can read and write this counter – and this is where Svelte’s most elegant idea comes into play, the `$` shorthand:\n\n```svelte\n<script>\n  import { count } from './stores.js';\n</script>\n\n<button on:click={() => $count++}>\n  Clicked {$count} times\n</button>\n```\n\nThe `$count` in the template is not a magic global variable but an instruction to the compiler. It recognizes the `$` prefix in front of a store reference and generates two things from it: first, a `count.subscribe(...)` that writes the current value into a local variable and re-renders the template on every change; second – and this is the crucial part – an automatic `unsubscribe` as soon as the component is destroyed. So you don’t have to take care of cleanup; the compiler does it for you.\n\nWriting is covered by the shorthand, too. The compiler translates `$count++` into a `count.set(...)` call with the incremented value. If you prefer to be more explicit or need a more complex change, you use the methods directly:\n\n```svelte\n<script>\n  import { count } from './stores.js';\n\n  function increment() {\n    count.update(n => n + 1);\n  }\n\n  function reset() {\n    count.set(0);\n  }\n</script>\n\n<button on:click={increment}>+1</button>\n<button on:click={reset}>Reset</button>\n<p>Current value: {$count}</p>\n```\n\nThe difference between `set` and `update` is quickly explained. `set` overwrites the value unconditionally, `update` receives the current value as an argument and returns the new one – handy whenever the new value depends on the old one.\n\nAnd now the core of it all: as soon as a second component imports the same store and uses `$count`, both share the same state. If one changes the value, the other sees it immediately. No prop is passed down the tree, no shared parent component has to hold the state. The store is the shared source that everyone involved hangs on.\n\n```mermaid\ngraph TD\n  S[\"writable count<br/>(stores.js)\"]\n  A[\"Component A<br/>read + write $count\"]\n  B[\"Component B<br/>display $count\"]\n  C[\"Component C<br/>display $count\"]\n  S --> A\n  S --> B\n  S --> C\n  A -. \"count.set()\" .-> S\n```\n\nYou can see clearly here what the store does: it decouples the components from each other. A, B, and C don’t have to be related or know about each other. They only know the store.\n\n## Derived state with derived\n\nOften you need a value that follows from another one. You could recompute it in every component – or you derive it once, centrally, and everyone benefits. That is exactly what `derived` is for:\n\n```js\n// stores.js\nimport { writable, derived } from 'svelte/store';\n\nexport const count = writable(0);\n\nexport const doubled = derived(count, $count => $count * 2);\n```\n\n`doubled` is itself a store again, but a read-only one. It has no `.set` method, because its value follows entirely from `count`. When `count` changes, `derived` recomputes the value and notifies its subscribers. In the component, it then looks just like a regular store:\n\n```svelte\n<script>\n  import { count, doubled } from './stores.js';\n</script>\n\n<p>{$count} doubled is {$doubled}</p>\n<button on:click={() => $count++}>+1</button>\n```\n\n`derived` can also derive from several sources. In that case, you pass an array of stores and get an array of values in the callback:\n\n```js\nimport { writable, derived } from 'svelte/store';\n\nexport const price = writable(100);\nexport const quantity = writable(2);\n\nexport const total = derived(\n  [price, quantity],\n  ([$price, $quantity]) => $price * $quantity\n);\n```\n\nBesides this synchronous form, there is a second one that receives a `set` callback. With it, you can set the derived value with a delay or conditionally – for example after a timeout or only once a certain condition is met:\n\n```js\nimport { derived } from 'svelte/store';\n\n// Sets the value one second after each change of 'count'\nexport const delayed = derived(\n  count,\n  ($count, set) => {\n    const id = setTimeout(() => set($count), 1000);\n    return () => clearTimeout(id);\n  }\n);\n```\n\nThe return value of the callback function here is a cleanup function that Svelte runs before the next computation and on the last unsubscribe. That way, no timeout is left hanging.\n\n## readable for external sources\n\nNot all state is written by the application itself. Sometimes it comes from outside – a clock that ticks, a WebSocket that delivers messages, a sensor. For cases like these, there is `readable`. From the outside, you can only read it; what feeds it is a start callback that sets up the source:\n\n```js\nimport { readable } from 'svelte/store';\n\nexport const time = readable(null, set => {\n  const id = setInterval(() => set(new Date()), 1000);\n\n  return () => clearInterval(id);\n});\n```\n\nThe timing is worth a close look here, because it reveals a central principle of stores. The start callback doesn’t run immediately when the store is created. It only runs when the first subscriber arrives – when the number of subscribers jumps from zero to one. And the returned function – the stop part – runs when the last subscriber leaves, that is, from one to zero. As long as nobody is listening, no interval ticks and no socket opens for this `readable`. With `writable`, `set` and `update` stay effective even without subscribers; only an optional start/stop piece of work is lazy. `derived`, in turn, computes for its subscribers and unsubscribes from its sources when there are none.\n\nIn the component, handling it is trivial again, because `$time` subscribes automatically and cleans up on unmount:\n\n```svelte\n<script>\n  import { time } from './stores.js';\n</script>\n\n<p>The time is {$time?.toLocaleTimeString()}</p>\n```\n\n## The pitfall: subscribe without unsubscribe\n\nSo far, everything ran through the `$` shorthand, and there, cleanup is not an issue. But stores aren’t limited to components. You can use them just as well in a plain JavaScript module – in a utility function, a service, anywhere outside of Svelte. And that is exactly where the most common mistake lurks.\n\nOutside a component, there is no `$` and no compiler that cleans up. You call `subscribe` by hand, and the method returns an unsubscribe function. You **must** keep this function and call it, or you have a leak:\n\n```js\n// utils.js\nimport { count } from './stores.js';\n\n// WRONG: the callback runs forever.\ncount.subscribe(value => {\n  console.log('count is now', value);\n});\n```\n\nThe return value of `subscribe` is simply ignored here. As long as the module or this usage context lives, the callback stays registered. The store keeps counting one subscriber, the 1→0 stop callback is never triggered – with a `readable` that has an interval, the timer would keep running accordingly. This is the right way:\n\n```js\n// utils.js\nimport { count } from './stores.js';\n\nconst unsubscribe = count.subscribe(value => {\n  console.log('count is now', value);\n});\n\n// ... later, when no longer needed:\nunsubscribe();\n```\n\nThe same rule applies within components, too, if for some reason you use `subscribe` manually there instead of `$`: then you have to call the unsubscriber in `onDestroy`. But honestly, that is almost always a sign that you should simply have used the `$` syntax. That bookkeeping is exactly what it takes off your hands.\n\nIf you want to read the value only once – without a subscription, without reactivity – there is a clean way that doesn’t let the leak problem arise in the first place:\n\n```js\nimport { get } from 'svelte/store';\nimport { count } from './stores.js';\n\nconst current = get(count);\n```\n\n`get` subscribes briefly under the hood, reads the current value, and unsubscribes right away. The value is a snapshot and doesn’t update anymore. That is exactly why `get` fits well for a one-time read in a JS module – and precisely not in a hot path that runs constantly.\n\n```mermaid\nsequenceDiagram\n  participant C as First subscriber\n  participant S as Store\n  participant Q as External source\n  C->>S: subscribe(run)\n  S->>Q: start callback (0 -> 1)\n  Q-->>S: Values flow\n  S-->>C: run(value)\n  C->>S: unsubscribe()\n  S->>Q: stop callback (1 -> 0)\n```\n\n## When to use a store, and when not\n\nThe store is the right tool as soon as state no longer fits cleanly into a single component – when several components that aren’t directly related share the same value, or when a value comes from outside the component tree. The classic symptom that calls for a store is prop drilling: you pass a value through three or four levels even though only the bottom component really needs it. A store cuts off this pass-through path. The affected components import the store directly, and the intermediate levels don’t need to know anything about the value.\n\nThat leaves the question of whether you also need a big state management library. For the vast majority of Svelte applications: no. The three store types cover a surprising amount. `writable` for the state you change, `derived` for everything that follows from it, `readable` for external sources. That is no compromise, no “good enough for now” – for most real applications, it is simply sufficient. A central store module that exports the individual stores gives the application a clear, manageable structure without you having to drag along another mental model and another dependency.\n\nSo where is the edge beyond which you think about more? I would say: only when the state gets truly complex – many interdependent transitions, strict traceability of every change, sophisticated time-travel debugging across a large domain. Requirements like these are rare, and even then you often build a thin layer on top of stores instead of replacing them. But as long as the question is just “How do my components share a value?”, the answer is a store – and you don’t need more.\n\nWhat remains after several projects with Svelte is less an API recommendation than an order: first determine the owner of the state, then the tool. For the model shown in 2022, `writable`, `readable`, and `derived` are often enough. The `$` shorthand handles the subscription bookkeeping in components; outside them, the simple rule remains to pair every manual `subscribe` with an `unsubscribe`.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-svelte.en.html\n- Repository: [mikebild.dev](https://www.mikebild.dev) – this and other articles on Svelte and frontend architecture\n- [Svelte Reactivity: The Compiler Instead of a Virtual DOM](https://www.mikebild.dev/en/blog/svelte-reactivity-the-compiler-instead-of-a-virtual-dom/)\n- [Svelte docs – stores and runes](https://svelte.dev/docs/svelte/stores)"},{"locale":"en","translation_key":"nodejs-streams-und-backpressure","slug":"nodejs-streams-understanding-backpressure","title":"Node.js Streams: Understanding and Using Backpressure","summary":"Why a fast producer must not overrun a slow consumer – and how pipe, pipeline, the return value of write() and the drain event handle flow control in Node.js.","tags":["Software","Node.js","Backend"],"published_at":"2022-06-21T10:00:00+00:00","updated_at":"2026-07-13T07:58:20.382471+00:00","url":"https://www.mikebild.dev/en/blog/nodejs-streams-understanding-backpressure/","audio_url":null,"audio_duration_secs":null,"text":"```\nFATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory\n```\n\nThis crash does not come from processing too much data. It comes from data arriving too fast. A source reads a log file from a fast SSD, every chunk goes via `write()` to a slow destination – and because nobody looks at what `write()` returns, the internal buffer grows until the heap is full. The amount of data does not matter; what matters is the speed gap between the two ends.\n\nMany people think of streams as file stuff around `createReadStream`. But they are the fundamental model of how Node.js pushes data piece by piece through a pipeline without ever holding everything in memory at once. The part of it that decides in real systems between “runs stable” and “process dies at three in the morning” is called backpressure. The stream API looks harmless: you chain a few `pipe` calls, and it works – until the day the source delivers faster than the destination can swallow.\n\n## Why streams at all\n\nThe classic way to process a file is `fs.readFile`. The function reads the entire file into a buffer and then calls the callback. For a 2 MB configuration file, that is perfectly fine. For a 4 GB log file, you have a problem: Node.js tries to load four gigabytes into the heap, and the process falls over long before a single line has been processed.\n\nA stream does it differently. It reads the file in small bites – chunks – and passes each chunk on individually. At any point in time, only a small buffer sits in memory, regardless of whether the file is two megabytes or two terabytes. Memory consumption stays constant. That is the core benefit, and it applies not only to files: HTTP requests, TCP sockets, compression, encryption – all of these are streams in Node.js.\n\n## The four types\n\nBefore we get to flow control, an overview of the four stream types is worthwhile. All four inherit from `EventEmitter`, so they communicate through events – that is the common thread running through the entire asynchronous side of Node.js, which I describe in more detail in [Node.js Training: From the Event Loop to Architecture Decisions](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/).\n\n- A Readable is a source you read from. `fs.createReadStream()` returns a Readable, as does the incoming body of an HTTP request.\n- A Writable is a destination you write to. `fs.createWriteStream()` or the HTTP response are Writables.\n- A Duplex is readable and writable at the same time, but with separate channels. A `net.Socket` is the prime example: in and out over the same connection.\n- A Transform is a Duplex whose output is a function of its input. `zlib.createGzip()` takes raw bytes in and puts compressed ones out. This is exactly where you add your own processing logic.\n\nYou combine these types into a pipeline: a source, any number of Transforms in the middle, a destination at the end.\n\n```mermaid\nflowchart LR\n    A[\"Readable<br/>fs.createReadStream\"] -->|chunks| B[\"Transform<br/>gzip / uppercase\"]\n    B -->|chunks| C[\"Writable<br/>fs.createWriteStream\"]\n    C -.->|drain signal| A\n    style A fill:#2b6cb0,color:#fff\n    style B fill:#2f855a,color:#fff\n    style C fill:#c05621,color:#fff\n```\n\nThe solid arrows are the forward data flow. The dashed arrow going back is the decisive one – it is backpressure. More on that in a moment.\n\n## The naive approach and why it tips over\n\nSuppose we want to copy a large file into another one and process each chunk along the way. The intuitive code looks like this:\n\n```js\nconst fs = require('node:fs');\n\nconst source = fs.createReadStream('huge-input.log');\nconst target = fs.createWriteStream('huge-output.log');\n\nsource.on('data', (chunk) => {\n  target.write(chunk);\n});\n```\n\nThat runs. Most of the time. And then comes the case where `huge-input.log` comes from a fast SSD and `huge-output.log` is written to a slow network drive. The source fires `data` events as fast as it can, and `target.write()` accepts every chunk. If the destination cannot write fast enough, Node.js buffers the chunks internally – and this buffer has no upper limit. Memory fills up, `RSS` climbs, the garbage collector works against an ever-growing pile, and at some point the operating system kills the process.\n\nThat is the pitfall in one sentence: **If you ignore the return value of `write()` and just keep writing, you produce unlimited buffering.**\n\n## What write() actually tells you\n\n`writable.write(chunk)` returns a Boolean, and this Boolean is half the battle:\n\n- `true` means: the internal buffer is still below `highWaterMark`; you may keep writing.\n- `false` means: the buffer has reached or exceeded `highWaterMark`. Stop writing, or Node.js will buffer into the void.\n\n`highWaterMark` is the buffer limit. In the Node 16/18 covered here, the general default for byte streams was 16384 bytes, that is 16 KiB; since Node 22 it is 64 KiB. In object mode – more on that later – the default stays at 16 objects. It is important to understand: this limit is a **threshold, not a hard wall**. Node.js does not stop buffering when you exceed `highWaterMark`. It just politely tells you with a `false` return value that it has had enough. If you ignore the warning, it keeps buffering anyway – at your own risk.\n\nOnce `write()` has returned `false`, you should pause and wait for the `'drain'` event. The Writable emits `'drain'` as soon as its buffer has been emptied again – the signal that you may continue writing. Done by hand, the correct cycle looks like this:\n\n```js\nsource.on('data', (chunk) => {\n  const ok = target.write(chunk);\n  if (!ok) {\n    source.pause();\n    target.once('drain', () => source.resume());\n  }\n});\n```\n\nWe write, check the return value, pause the source on `false` and resume it only after `'drain'`. That is exactly flow control: a fast producer is slowed down so that it does not overrun a slow consumer.\n\nYou can also draw the cycle as a state machine:\n\n```mermaid\nstateDiagram-v2\n    [*] --> Schreiben\n    Schreiben --> Schreiben: write() returns true\n    Schreiben --> Pausiert: write() returns false<br/>source.pause()\n    Pausiert --> Schreiben: 'drain' event<br/>source.resume()\n```\n\n## pipe does this automatically\n\nThe good news: in practice, you rarely have to write this whole `pause`/`resume` dance by hand. `pipe()` does exactly that in the background.\n\n```js\nconst fs = require('node:fs');\n\nfs.createReadStream('huge-input.log')\n  .pipe(fs.createWriteStream('huge-output.log'));\n```\n\n`pipe()` connects source and destination, checks the return value of `write()` internally, pauses the Readable on backpressure and resumes it after `'drain'`. So backpressure is solved without you writing a single line of flow control yourself. `pipe()` also returns the destination so that you can chain – handy when a Transform sits in between:\n\n```js\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\nfs.createReadStream('huge-input.log')\n  .pipe(zlib.createGzip())\n  .pipe(fs.createWriteStream('huge-input.log.gz'));\n```\n\nAnd yet I advise against just chaining `pipe()` in production. The reason is error handling.\n\n## Why pipeline is the better choice\n\n`pipe()` has a treacherous weakness: it does not propagate errors. If a stage in the middle of the chain throws an error – the network connection drops, the disk is full – a `pipe()` chain does not notice it cleanly. The other streams are not destroyed, file descriptors stay open, the stream hangs. In a long-running server process, such leaks accumulate until the resources eventually run out.\n\n`stream.pipeline()` solves this. It chains the stages the same way, but it propagates errors across all stages and calls `destroy()` on every stream involved on error or regular end. Nothing leaks. There is the callback variant:\n\n```js\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst { pipeline } = require('node:stream');\n\npipeline(\n  fs.createReadStream('huge-input.log'),\n  zlib.createGzip(),\n  fs.createWriteStream('huge-input.log.gz'),\n  (err) => {\n    if (err) {\n      console.error('pipeline failed', err);\n      return;\n    }\n    console.log('pipeline succeeded');\n  }\n);\n```\n\nSince Node.js 15 – and thus firmly established in the release lines 16 and 18 that are current in 2022 – there is also a promises variant from `node:stream/promises`. It reads much more cleanly in async functions because you catch errors with try/catch:\n\n```js\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst { pipeline } = require('node:stream/promises');\n\nasync function compress() {\n  try {\n    await pipeline(\n      fs.createReadStream('huge-input.log'),\n      zlib.createGzip(),\n      fs.createWriteStream('huge-input.log.gz')\n    );\n    console.log('done');\n  } catch (err) {\n    console.error('pipeline failed', err);\n  }\n}\n\ncompress();\n```\n\nThe promises variant also takes options, such as a `signal` for an `AbortSignal` that lets you abort the pipeline from the outside. The point that tips the scales for me: `pipeline()` handles backpressure just as automatically as `pipe()` – but it also cleans up. For production code, `pipeline()` is the default choice; `pipe()` at most for short, isolated scripts.\n\n## Writing your own Transform\n\nThe point where streams become really useful is your own Transform in the middle. A Transform takes chunks in, processes them and pushes the result out. The skeleton consists of a `transform` function that receives three things: the chunk, the encoding and a callback you have to call at the end.\n\n```js\nconst { Transform } = require('node:stream');\n\nconst upperCase = new Transform({\n  transform(chunk, encoding, callback) {\n    const transformed = chunk.toString().toUpperCase();\n    this.push(transformed);\n    callback();\n  }\n});\n```\n\n`this.push()` passes the result on to the next stage; `callback()` signals that this chunk has been fully processed. If you call `callback()` with an error – `callback(err)` – `pipeline()` propagates this error cleanly through the entire chain. Built into a pipeline, it looks like this:\n\n```js\nconst fs = require('node:fs');\nconst { pipeline } = require('node:stream/promises');\n\nawait pipeline(\n  fs.createReadStream('input.txt'),\n  upperCase,\n  fs.createWriteStream('output.txt')\n);\n```\n\nAnd because the `upperCase` Transform takes part in flow control like any stream, backpressure applies here too: if the destination is slow, the pipeline slows down across the Transform back to the source. You do not have to do anything extra for that.\n\n## Async iteration as a modern alternative\n\nSince Node.js 10, every Readable implements `Symbol.asyncIterator`, so you can consume it directly with `for await ... of`. In async functions, this often reads more clearly than `on('data')` and keeps flow control intact without you having to touch `pause` and `resume`.\n\n```js\nconst fs = require('node:fs');\n\nasync function countLines(path) {\n  const stream = fs.createReadStream(path, { encoding: 'utf8' });\n  let lines = 0;\n  for await (const chunk of stream) {\n    lines += chunk.split('\\n').length - 1;\n  }\n  return lines;\n}\n```\n\nBackpressure arises implicitly here: as long as the loop body is busy with a chunk – and an `await` inside it holds it up further – the loop does not request a new chunk, and the Readable only delivers the next one then on its own. So you get the same brake as with `pipe()`, just in ordinary async/await code. The rule that comes up next still applies: if you iterate like this, you should not also consume the stream in parallel via `on('data')`.\n\n## Object mode and a few rules\n\nBy default, streams work with buffers and strings. If you set `objectMode: true`, the chunks may be arbitrary JavaScript objects – useful when you build a pipeline of parsed records instead of raw bytes. Note that in object mode, `highWaterMark` counts the number of objects, not bytes; the default is 16 objects. And an existing stream cannot be safely switched to object mode afterward – you decide that at construction.\n\nA rule that keeps snagging in reviews: do not mix consumption methods. Per Readable, you choose exactly one way of reading – either `on('data')`, or `on('readable')`, or `pipe()`, or async iteration. If you combine two of them, you produce race conditions, lost chunks and bugs that are hard to reproduce. One Readable, one consumption method.\n\n## What should stick\n\nStreams are the tool for processing arbitrarily large amounts of data with constant memory – the buffer stays small no matter how large the source is. Backpressure is the mechanism that makes this work: the return value of `write()` and the `'drain'` event form the flow control that keeps a fast producer from overrunning a slow consumer. `highWaterMark` is the threshold at which `write()` flips from `true` to `false` – a warning, not a constraint.\n\nYou rarely have to write this cycle by hand, because `pipe()` and above all `pipeline()` handle it automatically. The decisive difference lies in error handling: `pipeline()` propagates errors and cleans up all streams; `pipe()` does not. With this difference in mind, you get Node.js processing code that does not fall over even with four gigabytes and a slow destination – it just gets a bit slower, the way it should.\n\n## Further reading\n\n- Repository for the Node.js introduction: [mikebild/introduction-nodejs](https://github.com/mikebild/introduction-nodejs) – teaching material on async patterns including `10-streams.md`.\n- [Node.js Stream API (v18)](https://nodejs.org/docs/latest-v18.x/api/stream.html) – Readable, Writable, Duplex, Transform, `pipe`, `pipeline`, `write`, `drain`, `highWaterMark`.\n- [Current Node.js Stream API – today’s defaults](https://nodejs.org/api/stream.html)\n- [stream.pipeline in the official docs](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-callback)\n- [Guide: Backpressuring in Streams](https://nodejs.org/learn/modules/backpressuring-in-streams)"},{"locale":"en","translation_key":"fitness-functions-messbare-architektur","slug":"fitness-functions-checking-architecture-properties","title":"Fitness Functions: Checking Selected Architecture Properties","summary":"Fitness functions make selected properties such as coupling, dependencies and latency continuously checkable. They don’t replace domain quality or architectural trade-offs.","tags":["Software","Architecture"],"published_at":"2022-05-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/fitness-functions-checking-architecture-properties/","audio_url":null,"audio_duration_secs":null,"text":"A fitness function is not a complete quality model. It evaluates one specific architecture property that can be operationalized – such as freedom from cycles, coupling, latency or compatibility between two services. In this post, I focus on automated checks that are as unambiguous as possible and deliver a narrowly scoped verdict on every commit. Properties such as understandability or domain appropriateness still need human judgment.\n\nHow big the difference from common practice is shows in a sentence that comes up regularly in architecture reviews: “Of course the domain must not access the infrastructure.” Everyone nods. A diagram gets drawn, maybe a Confluence entry created. Three sprints later, an import statement points from the domain layer straight into the database adapter. No one did it maliciously. It was Friday afternoon, the bugfix had to go out, and the rule simply wasn’t in the code but in meeting minutes that no one reads anymore. Where an architecture property can be checked unambiguously, an automatic check is more reliable than memory in a review.\n\nA fitness function closes the path from a desired property to a repeatable decision.\n\n:::process{title=\"From architecture statement to gate\" role=\"primary\" preferredPattern=\"connected-process\"}\n1. Property · name an architecture quality that matters to the domain\n2. Observation · pick a reproducible signal for it\n3. Threshold · explicitly define the range that is still acceptable\n4. Check · evaluate the signal automatically and repeatably\n5. Gate · make a violation visible or let the change pass\n6. Adjustment · re-examine property and threshold when conditions change\n:::\n\nThe order preserves the domain reason for the measurement. An existing tool alone doesn’t define a meaningful fitness function.\n\n## From wish to mechanical check\n\nThe term comes from *Building Evolutionary Architectures* by Neal Ford, Rebecca Parsons and Patrick Kua (O’Reilly, 2017), borrowed from evolutionary computing, where a fitness function measures how close a solution is to the goal. Applied to software, this means: an architectural fitness function is an objective, mechanical integrity test for one or more architectural characteristics – that is, for the properties that used to be called, somewhat clumsily, “-ilities”: performance, scalability, coupling, security.\n\nThe change of perspective that makes the difference in practice is this: architecture is no longer treated as a state you decide on once, but as a property you maintain continuously. That sounds like a nuance, but it’s a break in the way of working. A diagram describes what the system should look like. A fitness function describes what it must look like – and breaks the build if it doesn’t.\n\nThis moves part of governance from the meeting into the pipeline. The rules that can be automated run along with every commit; reviews remain necessary where trade-offs, context and domain appropriateness matter. The gain is above all early feedback: an explicitly agreed rule doesn’t depend on whether it gets noticed again in the next review. If you have ever seen a single creeping coupling violation block a refactoring for months, you know the price of after-the-fact control.\n\n## The first fitness function is a unit test\n\nGetting started is unspectacular, and that’s the good news. The simplest category is static, atomic fitness functions – rules about the structure of the code that can be expressed as a completely normal test. In the Java world, ArchUnit by TNG has become established for this; it checks package and layer dependencies through bytecode analysis. For .NET there is NetArchTest, in the JavaScript world dependency-cruiser. The principle is the same everywhere.\n\nThe rule invoked at the beginning – the domain knows no infrastructure – looks like this as a fitness function:\n\n```java\n@ArchTest\nstatic final ArchRule domain_must_not_depend_on_infrastructure =\n    noClasses().that().resideInAPackage(\"..domain..\")\n        .should().dependOnClassesThat().resideInAPackage(\"..infrastructure..\");\n\n@ArchTest\nstatic final ArchRule no_cyclic_dependencies =\n    slices().matching(\"..(*)..\").should().beFreeOfCycles();\n```\n\nThe nice thing about it: this rule documents itself. It lives in the repository, it runs in CI, and it’s not negotiable without someone visibly changing it. The Confluence entry from above describes an intention. The test makes the same chosen rule executable and its violation visible.\n\nThe second block – `no_cyclic_dependencies` – addresses a classic that is notoriously hard to spot in reviews. Cyclic dependencies rarely arise in one big step. They grow out of many small imports, each harmless on its own. A human no longer sees the cycle in the diagram when it runs across seven modules. The machine does. Exactly such properties – afferent/efferent coupling, instability, freedom from cycles – are the ideal case for static fitness functions, because they are deterministic and cheap to check.\n\n## More than a list of tools\n\nIf you only think of ArchUnit when you hear fitness functions, you underestimate the reach of the concept. Ford, Parsons and Kua propose a taxonomy that works well as a sorting aid because it suggests the right type of test for each property. Two axes are enough to start with:\n\n```mermaid\nquadrantChart\n    title Classifying fitness functions\n    x-axis \"atomic (one characteristic)\" --> \"holistic (interplay)\"\n    y-axis \"triggered (on demand)\" --> \"continuous (ongoing)\"\n    quadrant-1 \"Latency/load tests in prod\"\n    quadrant-2 \"Chaos/resilience checks\"\n    quadrant-3 \"ArchUnit dependency rules\"\n    quadrant-4 \"Security scan per commit\"\n```\n\n*Atomic* measures a single property in isolation, *holistic* checks the interplay of several – such as security and latency together under load. *Triggered* runs on demand, for example in the build; *continuous* runs permanently against the production system. On top of that, the book adds further dimensions: static versus dynamic, automated versus manual, and temporal fitness functions, which deliberately apply only for a limited time – for example a reminder to finish a library migration by a deadline.\n\nThe practical value of this classification doesn’t lie in classifying for its own sake. It lies in forcing a question you would otherwise dodge: which concrete architectural characteristic is this check actually tied to? If you can’t answer that, you’re probably building a vanity metric right now.\n\n## When the property is dynamic\n\nNot everything can be checked statically. Latency, for example, is not a property of the source code but of the running system. This is where dynamic fitness functions come in, which measure against a deployment. Conceptually it stays the same – a threshold, a comparison, a verdict:\n\n```python\ndef latency_fitness(service):\n    p95 = measure_p95_ms(service, window=\"5m\")\n    assert p95 < LATENCY_BUDGET_MS, f\"p95 {p95} exceeds budget\"\n```\n\nAs clean as this looks, it’s just as dangerous to hang this assert blindly into CI as a hard gate. Latency values fluctuate. A p95 over a five-minute window can break because of a single garbage collection peak or a slow neighbor in the cluster without anything in your software having changed. If you ignore that, you produce flaky builds – and a flaky gate gets clicked away or commented out within two weeks. Then you have the friction of the check but no longer its benefit.\n\nThe pragmatic answer is a separation: static, deterministic properties may block the build. Dynamic, statistically fluctuating properties run as observing, triggered checks with statistical windows and raise alerts instead of breaking hard. The same idea, two operating modes – depending on how deterministic the measured characteristic is.\n\nFor resilience-related properties, it’s worth looking into Michael Nygard’s *Release It!*. The stability patterns described there – Circuit Breaker, Bulkhead, Timeout – provide not only building blocks for robust systems but also checkable expectations: does the circuit breaker open as intended under simulated overload? That is a fitness function too, just a dynamic one.\n\n## Measuring coupling between services\n\nThe most interesting coupling in distributed systems doesn’t run within one deployable but between them. Two teams, two services, one contract – and the silent assumption that the other side won’t break its API. Consumer-driven contract testing makes this assumption checkable. With Pact and a Pact Broker, the consumer describes its expectation of the provider, and the provider verifies against exactly this expectation.\n\nAs a fitness function, this lands directly as a step in the deployment pipeline:\n\n```bash\npact-broker can-i-deploy \\\n    --pacticipant Checkout \\\n    --version \"$GIT_SHA\" \\\n    --to-environment production\n```\n\nThe question “can I deploy this without breaking a consumer?” thus turns from a gut decision into a mechanical answer. The assumption of staying compatible becomes evidence – coupling as governance-as-code. In practice, this is often the moment when teams can really deploy independently for the first time, because the fear of an unnoticed break has been taken out of the process.\n\n## The place where everything comes together\n\nA loose collection of rules has little effect. Fitness functions only become effective as a gate in delivery. The deployment pipeline – conceptually established since Humble and Farley – is the natural place for this. Between build and deploy lies a barrier that checks several categories in parallel:\n\n```mermaid\nflowchart LR\n    commit[\"commit\"] --> build[\"build\"]\n    build --> gate{\"Fitness<br/>Functions<br/>Gate\"}\n    gate -->|static / atomic| s[\"Dependency &amp; Cycle Rules\"]\n    gate -->|dynamic / holistic| d[\"Latency p95 &amp; Load\"]\n    gate -->|contract| c[\"Pact can-i-deploy\"]\n    s -->|fail = break build| commit\n    d -->|fail = break build| commit\n    c -->|fail = break build| commit\n    gate -->|all green| deploy[\"deploy\"]\n```\n\nThe red return arrows are the core of the idea: a violation doesn’t lead to a ticket that gets prioritized at some point, but to a broken build that is fixed by whoever caused it – immediately, with full context, before the error sinks into the history. This is the same mechanism that makes continuous integration effective, applied to architecture properties.\n\nAnd this is where the circle closes to measurable delivery quality. *Accelerate* by Forsgren, Humble and Kim and the DORA Four Key Metrics – Deployment Frequency, Lead Time for Changes, Change Failure Rate, Time to Restore – provide metrics for the delivery level. Fitness functions can check matching technical guardrails for them. A violated coupling rule is then noticed early; whether that lowers lead time or failure rate is something the team has to verify against its own data.\n\n## Where it tips over in practice\n\nAs convincing as the concept is, its naive implementation fails reliably in three places – and I’ve seen all of them in projects.\n\nFirst, the vanity metric. A green fitness function that checks a pure test coverage threshold feels like safety and yet measures nothing architectural. Coverage says how much code is executed, not whether the dependencies are right. Every function has to be tied to a concrete architectural characteristic; otherwise it’s theater.\n\nSecond, the maintenance burden. Fitness functions are code and age like code. I’ve seen codebases in which every second rule carried an `@ArchIgnore`, because under deadline pressure it was faster to add the exception than to solve the problem. Without ownership and regular cleanup of the exception list, the meaningfulness erodes until only green noise remains. These rules need the same care as production code – otherwise they are worse than nothing, because they create false safety.\n\nThird, starting too late. If you unleash fitness functions on a grown legacy codebase, you get thousands of violations on the first run – and guaranteed frustration. The way out is a baseline: you freeze the current state, declare fitness from now on and only allow improvement, no deterioration. “Declare fitness from now on” is not a betrayal of purity. In grown systems, it’s the only way something like this gets started at all.\n\n## Conclusion\n\nThe common thread of these three building blocks – static rules, dynamic measurements, contract checks – is a single idea: architecture is a property you maintain, not a decision you make once. Fitness functions shift control from the review into the pipeline, and with it from hope to certainty.\n\nThe gain is rarely the individual rule. It lies in the changed way of working. Teams that secure their most important architecture properties mechanically no longer discuss import directions in reviews, but the domain. They deploy more often because the silent fear of an unnoticed break has been taken out of the process. And they refactor more boldly because a net of green checks reports immediately when a restructuring violates a property.\n\nThe start may be small: a single atomic, static rule that secures a property you really care about. A dependency rule that breaks the build is worth more than twenty rules in a document no one reads. The rest grows from there – as plain code that runs with every build and forces no extra process on anyone.\n\n## Further reading\n\n- Neal Ford, Rebecca Parsons, Patrick Kua: *Building Evolutionary Architectures* (O’Reilly, 2017) – [chapter on fitness functions](https://www.oreilly.com/library/view/building-evolutionary-architectures/9781491986356/ch02.html)\n- [ArchUnit (TNG)](https://www.archunit.org/) – static architecture tests for Java\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate* (2018) and the DORA Four Key Metrics – [martinfowler.com: StateOfDevOpsReport](https://www.martinfowler.com/bliki/StateOfDevOpsReport.html)\n- Michael Nygard: *Release It!* (2nd edition, 2018) – stability patterns for resilience-related fitness functions\n- [Pact](https://docs.pact.io/) – consumer-driven contract testing with `can-i-deploy`"},{"locale":"en","translation_key":"svelte-reaktivitaet-compiler-ohne-virtual-dom","slug":"svelte-reactivity-the-compiler-instead-of-a-virtual-dom","title":"Svelte Reactivity: The Compiler Instead of a Virtual DOM","summary":"Svelte compiles components at build time into targeted DOM code instead of diffing a virtual DOM at runtime. I show the mental model, reactive assignment with $: and the classic push trap that I keep running into in projects.","tags":["Software","Frontend","Svelte"],"published_at":"2022-04-26T10:00:00+00:00","updated_at":"2026-07-13T13:25:08.920456+00:00","url":"https://www.mikebild.dev/en/blog/svelte-reactivity-the-compiler-instead-of-a-virtual-dom/","audio_url":null,"audio_duration_secs":null,"text":"Two rules carry a large part of Svelte 3’s legacy model. First: the compiler recognizes assignments such as `count += 1`, `obj.key = value` or `array[index] = value`; a mere method call such as `array.push(...)` is not such an assignment. Second: a `$:` statement depends on the variables the compiler statically recognizes in its body. The direct syntax and some typical surprises follow from that.\n\nBoth rules come from the same source. Svelte decides while compiling a component which variable touches which DOM node. What arrives in the browser are finished update instructions; there is no tree comparison at runtime. So `count += 1` really is enough – but only as long as you know how the compiler recognizes a change.\n\nThe basis is Svelte 3, the current major version in April 2022. Everything that follows is based on the assignment-based reactivity model and the `$:` declarations. This isn’t complete; it’s the slice that lets you grasp the mental model the fastest.\n\n**Editorial note (July 2026):** For new code, Svelte 5 preferably works with runes such as `$state`, `$derived` and `$effect`. The `$:` and assignment model explained here belongs to the legacy mode, which is still supported. “Without a Virtual DOM” is still true, but on its own it no longer describes today’s reactivity API.\n\n## The mistake in thinking almost everyone brings along\n\nIf you come from React, you carry a certain picture in your head: a component is a function that runs again on every state change and returns a description of the desired UI state – a virtual DOM tree. The framework compares this new tree with the old one, finds the differences and transfers only those to the real DOM. This diffing is clever, but it’s work that happens in the user’s browser on every update. Rich Harris put it sharply in his often-quoted text “Virtual DOM is pure overhead”: the virtual DOM is not a feature to be grateful for, but a means to an end – and a means with a price.\n\nSvelte asks the question differently. If it’s already clear at build time which parts of the markup depend on which variables, why recompute this mapping in the browser on every update? The Svelte compiler analyzes the component statically and generates imperative JavaScript code that updates exactly the affected DOM nodes. No diff tree, no comparison at runtime. The compiler already knows that when `count` changes, exactly this one text node has to change, and it writes down exactly that instruction.\n\nOne clarification matters to me here, because it tends to blur in blog posts: Svelte is not “no runtime at all.” The compiled code brings along a small core of helper functions, on the order of a few kilobytes. What’s missing is the runtime diff algorithm and a heavyweight framework traveling along in the bundle. So the correct sentence is: no virtual DOM, no runtime diffing – not: zero runtime.\n\n## What the compiler takes over\n\nBefore I get to the code, it’s worth looking at which tasks in Svelte are done by the compiler instead of by a runtime library. Exactly this shift explains why the whole thing means less overhead in the browser:\n\n- The static analysis of which DOM node depends on which state variable – the result ends up as fixed code in the bundle, not as a computation at runtime.\n- The generation of targeted update instructions that touch only the nodes actually affected, instead of comparing a complete tree.\n- The resolution of `$:` dependencies: the compiler determines from the source code which variables a reactive statement reads and generates the code for re-evaluation from that.\n\nThis last point is where most of the traps lie, and I devote most of what follows to it.\n\n## Reactivity through assignment\n\nLet’s look at the simplest reactive component. A file with the `.svelte` extension bundles script, markup and style. A completely normal `let` variable at the top level of the `<script>` block is already component state.\n\n```svelte\n<script>\n  let count = 0;\n\n  function handleClick() {\n    count += 1;\n  }\n</script>\n\n<button on:click={handleClick}>\n  Clicked {count} times\n</button>\n```\n\nThere’s no special state API here. `count` is a variable, `count += 1` is an assignment. The point on which everything hinges for me: it’s not the variable itself that is reactive; the assignment to it is the triggering event. The compiler has seen that `count` is referenced in the markup. So around every assignment, it generates the code that marks the component as “dirty” and rewrites the affected text node. What looks like an ordinary change of value is accompanied by a targeted update in the compiled result.\n\nThat also explains why some changes go nowhere. If you only read `count` or pass it around in a helper function, nothing is triggered. Only the assignment operator is the signal.\n\n## Derived values with `$:`\n\nThe next building block is values that follow from other values. In React you reach for `useMemo` or compute in the render body. In Svelte 3 there is the reactive declaration with the `$:` label.\n\n```svelte\n<script>\n  let count = 0;\n  $: doubled = count * 2;\n\n  function handleClick() {\n    count += 1;\n  }\n</script>\n\n<button on:click={handleClick}>\n  Clicked {count} times\n</button>\n\n<p>{count} * 2 = {doubled}</p>\n```\n\n`$: doubled = count * 2;` reads like a normal assignment with a strange prefix, but it’s an instruction to the compiler: “Keep `doubled` up to date as soon as one of its dependencies changes.” I don’t have to specify the dependencies myself. The compiler determines them at compile time from the source code – they are all variables that are read in the statement but not assigned. Here, that’s `count`. If `count` changes through an assignment, the declaration runs again, `doubled` gets a new value, and the dependent text node updates.\n\n`$:` can do more than derived values. You can also use it to couple side effects to state changes:\n\n```svelte\n<script>\n  let count = 0;\n\n  $: if (count >= 10) {\n    alert(\"count is dangerously high!\");\n  }\n\n  $: console.log(`count is ${count}`);\n</script>\n```\n\nBoth forms run again as soon as `count` changes. The mechanism is the same as for the declaration: variables that are read become dependencies, assignments to them trigger re-evaluation. A detail for practice: these statements also run once during server-side rendering and before the first client render. They are part of the reactivity flow itself and not a replacement for a mount hook.\n\nThe following diagram shows this flow from the assignment to the DOM update – including the side path that later becomes the trap.\n\n```mermaid\nflowchart TD\n  A[Assignment: count += 1] --> B[Variable marked as dirty]\n  B --> C[reactive $: declarations<br/>re-evaluated]\n  C --> D[targeted DOM update<br/>only affected nodes]\n  E[array.push item] -.-> F[no assignment<br/>no reference change]\n  F -.-> G[no update triggered]\n```\n\n## Build time versus runtime\n\nThe contrast with React becomes clear when you put both tracks side by side. Svelte determines dependencies and generates update code at build time; the browser still executes that code on every change. React creates a new element tree when rendering and reconciles it at runtime. So Svelte moves the analysis into the build, not all of the update work.\n\n```mermaid\nflowchart LR\n  subgraph Build[Build time – Svelte]\n    S1[.svelte component] --> S2[Svelte compiler]\n    S2 --> S3[targeted update code<br/>optimized vanilla JS]\n  end\n  subgraph Runtime[Runtime – React]\n    R1[Render function] --> R2[new virtual DOM tree]\n    R2 --> R3[Diff against old tree]\n    R3 --> R4[Patch to the real DOM]\n  end\n```\n\nThe core of the picture is not “Svelte good, React bad,” but a different division of labor. React reconciles element trees at runtime. Svelte already knows the statically visible dependencies after the build and ships targeted update code for them. The user still runs this code, just not a virtual DOM diff for this update.\n\nOn bundle sizes, I deliberately stay cautious. The Svelte core is on the order of a few kilobytes, React plus ReactDOM considerably more. I give that as an order of magnitude, not as an exact measurement – the concrete numbers depend on the version, the bundler and what you actually use, and if you need a hard number, measure your own project.\n\n## The push trap\n\nNow to the flip side of the same model – the part this is really about for me. Because reactivity is tied to assignment, there is a class of changes that Svelte 3 simply doesn’t notice: in-place mutations without an assignment. The classic is `Array.push`.\n\n```svelte\n<script>\n  let numbers = [1, 2, 3, 4];\n\n  function addBroken() {\n    numbers.push(numbers.length + 1);\n  }\n</script>\n\n<button on:click={addBroken}>Add number</button>\n\n<p>{numbers.join(\", \")}</p>\n```\n\nYou click, the console confirms that the array grows – and nothing happens in the browser. No error, no warning, just no update. The reason follows consistently from the model: `numbers.push(...)` changes the existing array, but there is no assignment to `numbers`. Without an assignment, Svelte doesn’t mark the variable as dirty, and without the dirty mark, no update runs. The compiler can’t know that a method has touched the inside of the array – it only sees assignments.\n\nThe fix is as simple as the problem once you’ve internalized the model: you have to force an assignment. Two approaches are common.\n\n```svelte\n<script>\n  let numbers = [1, 2, 3, 4];\n\n  function addWorking() {\n    numbers = [...numbers, numbers.length + 1];\n  }\n\n  function addAlsoWorking() {\n    numbers.push(numbers.length + 1);\n    numbers = numbers;\n  }\n</script>\n\n<button on:click={addWorking}>Add number</button>\n\n<ul>\n  {#each numbers as n}\n    <li>{n}</li>\n  {/each}\n</ul>\n```\n\n`numbers = [...numbers, ...]` creates a new array and assigns it – the clean variant familiar from other frameworks. `numbers = numbers`, on the other hand, looks like a no-op but is exactly what the compiler needs: an assignment to `numbers` that sets the dirty mark. So for Svelte to notice a change at all, the variable’s name has to end up on the left side of an `=`.\n\nWith objects, the situation differs from the method call: Svelte’s legacy compiler recognizes a direct assignment such as `obj.key = value` and updates dependent places. What stays invisible is a mutation that only happens inside a called function or method. Then you need an assignment visible to the compiler afterwards, or an immutable replacement via spread.\n\n## The quiet sibling: indirect dependencies\n\nThere is a second trap that follows from the same principle and is less often recognized right away in reviews. The compiler determines the dependencies of a `$:` statement from which variables are directly referenced in the body. If you hide a variable behind a function call, it doesn’t appear in the body – and isn’t recognized as a dependency.\n\n```svelte\n<script>\n  let count = 0;\n\n  function getCount() {\n    return count;\n  }\n\n  // count is not read directly here,\n  // so it is not a detected dependency\n  $: label = `value is ${getCount()}`;\n</script>\n```\n\n`label` is computed on the first pass and never updated after that, because `count` isn’t visible in the body of the reactive declaration – only `getCount()` is there. The compiler has no way to recognize the dependency through the function boundary. The solution is to make the dependency visible, that is, to reference `count` directly in the statement. This isn’t a weakness; it’s the logical consequence of a model that analyzes statically at compile time instead of tracking dynamically at runtime.\n\n## What this means in practice\n\nIf I pull these two traps together, I get a surprisingly compact mental model for Svelte 3 that boils down to two points:\n\n- In legacy mode, reactivity is triggered by statically visible assignments. That includes direct property and index assignments, but not arbitrary method calls with internal mutations.\n- Dependencies of `$:` have to be directly visible in the body. Whatever disappears behind a function call isn’t tracked.\n\nThese two rules cover a large part of the surprises I run into in legacy Svelte projects. Both follow from the same design decision: dependencies are analyzed statically at build time. That calls for vigilance at function boundaries and with methods that mutate internally.\n\nIn a small data client, exactly these reactive assignments carry the data flow: a response replaces the previous value, and the compiler updates the dependent expressions in a targeted way.\n\n## Conclusion\n\nSvelte reverses a basic assumption of many frontend frameworks: instead of comparing a virtual DOM at runtime, it lets the compiler determine at build time which state touches which DOM node, and generates targeted update code from that. This eliminates this category of runtime diffing; how big the practical advantage is depends on the application and the update pattern. Everyday code stays pleasantly direct – `count += 1` is enough. In legacy mode, reactivity hinges on statically visible assignments. Once you’ve internalized that, you understand both the `push` trap and indirect dependencies.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-svelte.en.html\n- [Svelte Docs](https://svelte.dev/docs) – the `$:` syntax and the dependencies determined at compile time in the component format\n- [Svelte Tutorial](https://svelte.dev/tutorial) – the chapters on Reactivity, Assignments and Updating arrays and objects\n- [Virtual DOM is pure overhead](https://svelte.dev/blog/virtual-dom-is-pure-overhead) – Rich Harris on the motivation behind the compiler approach\n- [Write less code](https://svelte.dev/blog/write-less-code) – Svelte’s guiding principle of shipping less runtime code"},{"locale":"en","translation_key":"nodejs-eventemitter-und-ereignismodell","slug":"eventemitter-the-event-model-at-the-core-of-nodejs","title":"EventEmitter: The Event Model at the Core of Node.js","summary":"EventEmitter is the common denominator beneath streams, HTTP servers and processes: I show on/once/off/emit, the special behavior of 'error' and how to avoid listener leaks.","tags":["Software","Node.js","Backend"],"published_at":"2022-04-19T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/eventemitter-the-event-model-at-the-core-of-nodejs/","audio_url":null,"audio_duration_secs":null,"text":"That `.on('data', …)` on a stream, `.on('request', …)` on an HTTP server and `.on('exit', …)` on a child process look the same is not a convention that module authors follow voluntarily. The similarity has a technical reason: all of these objects inherit from the same class – the `EventEmitter`. Once you have mastered this one class, you understand a large part of the standard library.\n\nThis article takes the `EventEmitter` apart: first the idea behind it, then the concrete API, then the two or three places where it hurts in practice. If you want to read up first on why Node is event-driven at all, you will find that in the post on [Node.js training around the event loop](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/). This one is about the layer directly above it.\n\n## The common denominator beneath everything\n\nAt its core, Node.js is event-driven. An HTTP server does not wait in a loop for the next request; it registers: “When a request comes in, call this function.” A read stream does not say “give me the data” but “let me know when a chunk of data is there.” This pattern – register interest, get notified later – runs through the entire platform.\n\nSo that this pattern is not reinvented in every module, there is a shared base class. `net.Server`, `http.Server`, the stream classes `Readable` and `Writable`, the global `process` object, the objects from `child_process` – they are all emitters or inherit from `EventEmitter`. That explains why `.on()` feels the same everywhere: it is literally the same method.\n\n```mermaid\nclassDiagram\n  class EventEmitter {\n    +on(event, listener)\n    +once(event, listener)\n    +off(event, listener)\n    +emit(event, ...args)\n  }\n  EventEmitter <|-- HttpServer\n  EventEmitter <|-- Readable\n  EventEmitter <|-- Writable\n  EventEmitter <|-- Process\n  EventEmitter <|-- MyEmitter\n  class HttpServer[\"http.Server\"]\n  class Readable[\"stream.Readable\"]\n  class Writable[\"stream.Writable\"]\n  class Process[\"process\"]\n  class MyEmitter[\"custom class\"]\n```\n\nThe class itself lives in the built-in module `events`. You get it the classic way via `require('events')` or – possible since Node 16 – with the prefix `require('node:events')`. Both forms return the same class; the prefix just makes it unmistakably clear that a built-in module is meant and not a package from `node_modules`.\n\n## The four methods everything revolves around\n\nThe emitter’s API is surprisingly small. Four methods are enough for everyday work. Three of them – `on`, `once` and `off` – return the emitter itself and can therefore be chained; `emit` is the exception and returns a `boolean` instead, as we will see in a moment.\n\n```js\nconst { EventEmitter } = require('node:events');\n\nconst emitter = new EventEmitter();\n\nfunction onTask(job) {\n  console.log('received task', job.id);\n}\n\nemitter.on('task', onTask);        // register a listener\nemitter.emit('task', { id: 1 });   // trigger it synchronously\nemitter.off('task', onTask);       // remove it again\n```\n\n`on(eventName, listener)` appends a listener to the end of the list for this event. `emit(eventName, ...args)` calls all registered listeners and passes the additional arguments through. `off(eventName, listener)` – alias `removeListener` – takes a listener out again. And `once(eventName, listener)` registers a listener that disappears automatically after it fires the first time.\n\nTwo properties of `emit` are crucial for understanding, and both are often overlooked:\n\n- `emit` calls the listeners **synchronously**. There is nothing asynchronous here, no detour through the event loop, no delay. When `emit` returns, all listeners have run.\n- The listeners run **in the order they were registered**. Whoever called `on()` first has their function run first.\n\n```mermaid\nsequenceDiagram\n  participant C as Caller\n  participant E as EventEmitter\n  participant L1 as Listener 1\n  participant L2 as Listener 2\n  C->>E: emit('task', data)\n  E->>L1: listener(data)\n  L1-->>E: done\n  E->>L2: listener(data)\n  L2-->>E: done\n  E-->>C: return true\n```\n\nThe return value of `emit` is a `boolean`: `true` if there was at least one listener for this event, otherwise `false`. What the listeners themselves return does not interest the emitter – return values from listeners are simply ignored. If you want to report something to the outside from within a listener, you have to do it another way, such as another event or shared state.\n\n## on, once and off working together\n\nThe difference between `on` and `once` sounds harmless but has consequences. A listener registered with `once` is removed from the list **before** its own call and then executed. So it is guaranteed to fire exactly once, no matter how often the event is triggered afterward.\n\n```js\nconst { EventEmitter } = require('node:events');\nconst queue = new EventEmitter();\n\nlet handled = 0;\nqueue.on('task', () => { handled += 1; });\n\nlet drained = 0;\nqueue.once('drain', () => { drained += 1; });\n\nqueue.emit('task');   // handled = 1\nqueue.emit('task');   // handled = 2\nqueue.emit('drain');  // drained = 1\nqueue.emit('drain');  // drained stays 1 - the listener is gone\n```\n\nRemoval deserves a close look. `off` removes **at most one** instance of a listener. If you accidentally registered the same function twice with `on`, you also need two `off` calls to get rid of it completely. And you can only remove what you can name – an anonymous arrow function that you pass directly to `on` is out of your hands afterward. That is why I always register listeners that I want to unregister later as a named function or as a variable.\n\nHere are the semantics of the four at a glance:\n\n- `on` – the listener stays registered and runs again on every `emit`.\n- `once` – the listener runs exactly once and removes itself beforehand.\n- `off` – removes one instance of a named listener; you cannot get rid of anonymous functions this way.\n- `emit` – calls all listeners synchronously in registration order and returns `true`/`false`.\n\nBesides these four, there are some useful side methods: `prependListener` adds a listener to the beginning instead of the end, `removeAllListeners` cleans up completely, `listeners(eventName)` returns a copy of the current listener list and `eventNames()` tells you which events anyone is registered for at all. You rarely need them, but when you do, they are worth their weight in gold – for example when debugging the question “who is actually listening here?”\n\n## The error event is a special case\n\nThis quirk once cost a running process in a project: the `'error'` event behaves differently from all others. For an ordinary event without listeners, nothing happens – `emit` returns `false`, and that is that. Not so for the `'error'` event.\n\nIf an emitter calls `emit('error', ...)` and **no** listener is registered for `'error'`, the error is thrown. And because it is thrown inside the emitter machinery and nobody catches it, it can take down the whole process. This turns “a stream complained” into a complete crash of the Node process.\n\n```js\nconst { EventEmitter } = require('node:events');\nconst source = new EventEmitter();\n\n// Without this listener the next line would crash the process:\nsource.on('error', (err) => {\n  console.error('handled:', err.message);\n});\n\nsource.emit('error', new Error('boom'));  // handled cleanly\n```\n\nBy the way, this is not harassment but a deliberate decision by the Node team. An error that nobody handles should be loud and not silently swallowed. This leads to a simple rule: for every emitter that can report errors – and that is practically all streams, all network objects, all child processes – I register an `'error'` listener before the actual work starts. It is the safety net without which the whole application breaks on a single unhandled message.\n\nThere are two more special events used internally: `'newListener'` fires before a new listener is added, and `'removeListener'` fires after one has been removed. Both are meant more for tools and diagnostics than for everyday use, but it is good to know they exist if you ever want to watch who registers or unregisters when.\n\n## Too many listeners: the leak warning\n\nNode keeps track, for every emitter, of how many listeners are registered per event. If this number exceeds a threshold – 10 by default – Node prints a warning to stderr: the `MaxListenersExceededWarning`.\n\nThis warning is not an error and stops nothing. It is a heuristic against a very common class of bugs: the listener leak. The typical case is that somewhere, per request, per loop iteration or per retry, an `on()` is called, but the matching `off()` is missing. The listeners pile up, memory grows, and at some point Node speaks up.\n\n```js\nconst { EventEmitter } = require('node:events');\nconst bus = new EventEmitter();\n\n// Optional: make the warning itself visible\nprocess.on('warning', (warning) => {\n  console.log(warning.name, '- count:', warning.count);\n});\n\n// Anti-pattern: a new, never-removed listener on every iteration\nfor (let i = 0; i < 12; i += 1) {\n  bus.on('data', (chunk) => processChunk(chunk));\n}\n// From the 11th listener on, the MaxListenersExceededWarning appears.\n```\n\nWhat matters is this: the warning is the symptom, not the cause. The cause is the registration that is never removed. If you silence the warning with `emitter.setMaxListeners(Infinity)`, you have only taped over the warning light – the leak keeps running, memory keeps growing. The right fix is to unregister listeners when you no longer need them, or to register them as `once` right away if they should only fire once anyway.\n\n```js\nfunction onData(chunk) {\n  processChunk(chunk);\n}\n\nbus.on('data', onData);\n// ... later, when done:\nbus.off('data', onData);   // cleanly removed, no pile-up\n```\n\nThat does not mean the threshold of 10 is set in stone. There are legitimate cases where an emitter deliberately has more listeners. Then you adjust it intentionally: `emitter.setMaxListeners(n)` raises the limit for a single emitter, `events.defaultMaxListeners = n` moves the global default. The value `0` or `Infinity` turns the warning off entirely. The only important thing is that this decision is a conscious one and not a reflex to get rid of the message in the log.\n\n## Building your own class\n\nThe `EventEmitter` is not just something the standard library inherits from – you can just as well use it as a base yourself. Whenever a component of yours should inform its surroundings about things without knowing the receivers in advance, an emitter is the obvious choice.\n\nThe pattern is `class MyThing extends EventEmitter` with a `super()` call in the constructor. Here is a small task queue that reports when a task is added, when it is done and when something goes wrong:\n\n```js\nconst { EventEmitter } = require('node:events');\n\nclass TaskQueue extends EventEmitter {\n  constructor() {\n    super();\n    this.pending = [];\n  }\n\n  add(job) {\n    this.pending.push(job);\n    this.emit('task', job);\n  }\n\n  run() {\n    while (this.pending.length > 0) {\n      const job = this.pending.shift();\n      try {\n        job.handler();\n        this.emit('done', job);\n      } catch (cause) {\n        // Only emit 'error' when a listener exists -\n        // otherwise it crashes the process:\n        if (this.listenerCount('error') > 0) {\n          this.emit('error', cause);\n        } else {\n          throw cause;\n        }\n      }\n    }\n    this.emit('drain');\n  }\n}\n\nconst queue = new TaskQueue();\n\nqueue.on('task', (job) => console.log('queued', job.id));\nqueue.on('done', (job) => console.log('done', job.id));\nqueue.once('drain', () => console.log('all work finished'));\nqueue.on('error', (err) => console.error('failed:', err.message));\n\nqueue.add({ id: 1, handler: () => {} });\nqueue.add({ id: 2, handler: () => { throw new Error('bad job'); } });\nqueue.run();\n```\n\nThis example shows several things working together. The queue does not know its listeners – it calls `emit`, and whoever wants to listens. `once('drain', ...)` makes sure the completion message arrives exactly once. And in the error case, I check with `listenerCount('error')` whether anyone is listening at all before I call `emit('error', ...)`. That way I avoid the crash from an unhandled `'error'` event and instead let the error continue as an ordinary exception if nobody catches it.\n\nA small but recurring stumbling block with your own classes concerns `this`. In a classic function listener, `this` points to the emitter that triggered the event – handy if you want to access the emitter from inside. In an arrow function, that does not apply; there, `this` keeps its meaning from the surrounding context. Both are legitimate; you just need to be aware of which variant you choose.\n\n## Synchronous means synchronous\n\nFinally, one clarification that prevents bugs in everyday work. Because Node is so strongly associated with asynchrony, many people intuitively assume that `emit` calls the listeners at some later point. It does not. The call is synchronous, and the listeners block the calling code until they are done.\n\nMost of the time, that is exactly right, because it makes the flow predictable. But if, inside a listener, you deliberately want to move something out of the current flow – so that long work does not hold up the `emit` caller – you have to do that explicitly, for example with `setImmediate` or `process.nextTick`. The emitter itself reschedules nothing; it just calls, in order, whatever is registered.\n\n## Conclusion\n\nThe `EventEmitter` is a small class with a big reach. Four methods – `on`, `once`, `off`, `emit` – carry everyday work, and because a large part of the standard library inherits from exactly this class, the understanding carries over directly to streams, servers and processes. Two things you should never lose sight of: without a listener, the `'error'` event crashes the process, so an `'error'` listener belongs wherever errors can be reported. And the `MaxListenersExceededWarning` is an honest warning sign of a leak, not an annoying notice you configure away. With these two reflexes, you write event-driven Node code that keeps running stably even when things get uncomfortable.\n\n## Further reading\n\n- Node.js docs: [Events API](https://nodejs.org/docs/latest-v16.x/api/events.html)\n- Node.js guide: [The Node.js Event emitter](https://nodejs.org/en/learn/asynchronous-work/the-nodejs-event-emitter)\n- Node.js docs: [Stream API](https://nodejs.org/docs/latest-v16.x/api/stream.html) (inherits from `EventEmitter`)\n- My own post: [Node.js training around the event loop](https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/)"},{"locale":"en","translation_key":"graphql-paginierung-und-connections","slug":"graphql-pagination-cursors-and-connections","title":"GraphQL Pagination: Cursors, Connections and the Relay Pattern","summary":"Why offset/limit produces duplicates and gaps in changing lists, and how cursor-based pagination with the connections pattern stays stable – including the schema, a resolver sketch and the pitfalls from real projects.","tags":["Software","GraphQL","API"],"published_at":"2022-03-08T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/graphql-pagination-cursors-and-connections/","audio_url":null,"audio_duration_secs":null,"text":"If you page through a list by position, you silently rely on nobody writing in the meantime. In production, this assumption rarely holds. A position is not an anchor in the data; it is a count – and counts shift as soon as a record is added or removed at the front. The follow-up request then no longer asks the question the client meant to ask.\n\nThat’s why pagination is one of the places where it shows whether an API is robust or only works in the demo case. As long as the list stands still, offset/limit does its job flawlessly. As soon as it changes under the paging client – and that is the normal case, not the exception – errors arise that are hard to reproduce and even harder to explain. For exactly this, the GraphQL community established a convention of its own: the connections pattern. That’s what this post is about.\n\n## Why offset/limit fails with changing lists\n\nLet’s make the problem concrete. I have a list sorted by creation date in descending order and page through it two at a time. The client requests the first page: `offset: 0, limit: 2`. It gets the entries at positions 0 and 1. For the next page it asks for `offset: 2, limit: 2`.\n\nThe insidious part: `offset` is a pure position count. It says “skip the first two elements” – but it has no idea *which* two elements those were on the first call. If a new entry is inserted at the front between the two requests, the whole list slides back by one position. The element that was just at position 1 is now at position 2 – and is delivered to the client a second time at `offset: 2`. A duplicate.\n\nThe reverse case is just as annoying: if an entry at the front is deleted, everything moves forward by one position. The element that was at position 2 jumps to position 1 – and is skipped at `offset: 2`. A gap. The user never sees an entry, even though it exists.\n\n```mermaid\nflowchart TB\n  subgraph stabil[\"Stable: cursor-based\"]\n    direction LR\n    a1[\"Request 1<br/>first: 2\"] --> a2[\"returns A, B<br/>endCursor = B\"]\n    a2 --> a3[\"Request 2<br/>after: cursor of B\"]\n    a3 --> a4[\"returns C, D<br/>no duplicate\"]\n  end\n  subgraph kaputt[\"Shifted: offset/limit\"]\n    direction LR\n    b1[\"Request 1<br/>offset 0, limit 2\"] --> b2[\"returns A, B\"]\n    b2 --> b3[\"new entry X<br/>inserted at the front\"]\n    b3 --> b4[\"Request 2<br/>offset 2, limit 2\"]\n    b4 --> b5[\"returns B, C<br/>B duplicated\"]\n  end\n```\n\nThe core is always the same: offset counts positions, and positions are not a stable anchor as soon as the front of the list changes. Offset is like the train announcement “get off at the third stop” – wonderful, as long as nobody adds an extra stop.\n\n## The cursor-based way out\n\nThe solution is to change the question. Instead of “give me the elements from position N”, the client asks “give me the elements *after this specific element*”. This “specific element” is represented by a **cursor** – an opaque pointer that the server hands out and the client passes back unchanged.\n\nThe crucial difference: a cursor is bound to an element or its sort value, not to a position. When the client says “continue after the element with cursor X”, this statement stays correct no matter how many entries are inserted or deleted before it. The window doesn’t shift, because it doesn’t depend on a count but on an anchor in the data.\n\nA point that regularly comes up in code reviews: the cursor is **opaque**. The client must not assume any structure and must not do any arithmetic with it. It may only hand it back. This is deliberate – the server alone decides what a cursor means. Today it may contain an ID, tomorrow a combination of sort field and ID, the day after something completely different. As long as the client only passes the cursor through, the server can change its cursor implementation without breaking a single client. Base64 encoding is common – but that’s convention, not a rule, and only serves to keep anyone from being tempted to interpret the content.\n\n## The connections pattern: edges, node, pageInfo\n\nThis brings us to the actual topic. Around cursor-based pagination, the GraphQL community formalized a convention: the Relay Cursor Connections Specification. You don’t have to use Relay as a framework to benefit from the pattern – it has established itself as a de facto standard because it cleanly solves an important question: where do I actually put the cursor?\n\nThe naive answer would be to stick the cursor directly onto the record. But the cursor is not a property of the user or the article – it is a property of *this position in this list*. That’s why the pattern introduces an intermediate layer, the **edge**. An edge connects the actual record (`node`) with its `cursor`. The `node` stays clean, and the list-specific information sits on the edge.\n\nAbove it sits the **connection**. It bundles the list of edges and an object called `pageInfo`, which carries the metadata for paging further.\n\nWhat exactly do the individual building blocks provide?\n\n- `edges` is the list of edges. Each edge contains `node` (the plain record, without a list wrapper) and `cursor` (the opaque pointer to exactly this edge).\n- `pageInfo.hasNextPage` says whether there are more elements after the current page. This is the authoritative stop condition for paging.\n- `pageInfo.hasPreviousPage` is the counterpart for the backward direction.\n- `pageInfo.endCursor` is the cursor of the last element of the current page – exactly the value the client puts into the follow-up request as `after`.\n- `pageInfo.startCursor` is its counterpart at the start of the page, relevant for paging backward with `before`.\n\nOn naming conventions: the connection type ends in `Connection`, the edge type in `Edge`. `pageInfo` is non-null, and so are the two booleans in `PageInfo`. The two cursor fields `startCursor` and `endCursor`, by contrast, are nullable – on an empty page there simply is no cursor.\n\nA commonly seen field is `totalCount`, the total number of hits. It is handy, but it has a catch: `totalCount` is **not** part of the connections specification. It is a widespread optional extension, and depending on the data source, an exact `COUNT` can be expensive. If you include it, do so deliberately and not under the assumption that it belongs to the standard.\n\n## An example schema\n\nEnough prose, let’s look at SDL. A query that returns users with pagination looks like this in the connections pattern:\n\n```graphql\ntype Query {\n  users(first: Int, after: String): UserConnection!\n}\n\ntype UserConnection {\n  edges: [UserEdge!]!\n  pageInfo: PageInfo!\n  totalCount: Int\n}\n\ntype UserEdge {\n  node: User!\n  cursor: String!\n}\n\ntype PageInfo {\n  hasNextPage: Boolean!\n  hasPreviousPage: Boolean!\n  startCursor: String\n  endCursor: String\n}\n\ntype User {\n  id: ID!\n  name: String!\n  createdAt: String!\n}\n```\n\nThe arguments follow the specification. For forward pagination there is `first: Int` (the desired page size, non-negative) and `after: String` (the cursor after which to continue). For the backward direction, there are `last: Int` and `before: String` accordingly. Sending `first` and `last` at the same time is explicitly discouraged by the specification – the result would be ambiguous.\n\nA query from the client then reads like this:\n\n```graphql\nquery FirstPage {\n  users(first: 2) {\n    edges {\n      cursor\n      node {\n        id\n        name\n      }\n    }\n    pageInfo {\n      hasNextPage\n      endCursor\n    }\n  }\n}\n```\n\nAnd the follow-up request takes the `endCursor` from the previous response as `after`:\n\n```graphql\nquery NextPage {\n  users(first: 2, after: \"dXNlcjpjdXJzb3I6NDI=\") {\n    edges {\n      cursor\n      node {\n        id\n        name\n      }\n    }\n    pageInfo {\n      hasNextPage\n      endCursor\n    }\n  }\n}\n```\n\nMany introductory examples – including my own fundamentals material – show simplified variants, such as `skip`/`take` or an `after: 99` where the cursor looks suspiciously like an ID or an offset. That’s fine for explaining, but it isn’t the real Relay pattern. A production cursor is opaque and does *not* look like a readable number. This distinction is worth the extra sentence; otherwise someone will later start calculating with the cursor on the client.\n\n## The resolver sketch\n\nOn the server side, the resolver has to do three things: decode the incoming cursor, load the matching set of data and build edges plus `pageInfo` from it. The most interesting trick lies in determining `hasNextPage`.\n\nA common beginner’s mistake is to derive `hasNextPage` from whether the result is smaller than `first`. That’s unreliable: if exactly `first` elements happen to be left, you wouldn’t know whether anything comes after them. The clean way is to load one element more than requested – `first + 1`. If this extra element exists, there is a next page. Afterwards, you trim the result back to `first`.\n\n```js\nfunction encodeCursor(id) {\n  return Buffer.from(`cursor:${id}`).toString(\"base64\");\n}\n\nfunction decodeCursor(cursor) {\n  const decoded = Buffer.from(cursor, \"base64\").toString(\"utf8\");\n  return Number(decoded.split(\":\")[1]);\n}\n\nasync function usersResolver(_parent, args, context) {\n  const { first = 20, after } = args;\n  const limit = Math.min(first, 100); // enforce an upper bound\n  const afterId = after ? decodeCursor(after) : 0;\n\n  // load one extra row to detect a following page\n  const rows = await context.db.query(\n    `SELECT id, name, created_at\n       FROM users\n      WHERE id > $1\n      ORDER BY id ASC\n      LIMIT $2`,\n    [afterId, limit + 1]\n  );\n\n  const hasNextPage = rows.length > limit;\n  const pageRows = hasNextPage ? rows.slice(0, limit) : rows;\n\n  const edges = pageRows.map((row) => ({\n    node: row,\n    cursor: encodeCursor(row.id),\n  }));\n\n  return {\n    edges,\n    pageInfo: {\n      hasNextPage,\n      hasPreviousPage: Boolean(after),\n      startCursor: edges.length ? edges[0].cursor : null,\n      endCursor: edges.length ? edges[edges.length - 1].cursor : null,\n    },\n  };\n}\n```\n\nTwo details are worth a second look. First, the upper bound: without a `Math.min`, a client could send `first: 1000000` and bring the database to its knees. An enforced upper bound is mandatory, not optional. Second, the cursor helpers `encodeCursor`/`decodeCursor` – they demonstrate that the opaque string here simply contains an ID, but that the client doesn’t need to know that.\n\nAs a dialog between client and server, the flow across several pages looks like this:\n\n```mermaid\nsequenceDiagram\n  participant C as Client\n  participant S as Server\n  C->>S: users(first: 2)\n  S-->>C: edges A, B<br/>pageInfo endCursor=B, hasNextPage=true\n  C->>S: users(first: 2, after: Cursor B)\n  S-->>C: edges C, D<br/>pageInfo endCursor=D, hasNextPage=true\n  C->>S: users(first: 2, after: Cursor D)\n  S-->>C: edges E<br/>pageInfo endCursor=E, hasNextPage=false\n  Note over C,S: Loop ends as soon as hasNextPage=false\n```\n\nSo the client pages in a simple loop: as long as `hasNextPage` is true, it sends the next request with the most recently received `endCursor` as `after`. No counting positions, no recalculating.\n\n## The price of sorting – and a database bonus\n\nOne place where cursor-based pagination silently fails is ambiguous sorting. The cursor needs a **deterministic, unique** order. If I sort only by `created_at`, for example, and two records carry the same timestamp, then it is undefined at this tie which one comes first – and exactly there, duplicates or omissions appear again. The solution is a tie-breaker: you additionally sort by a guaranteed unique column, usually the ID. `ORDER BY created_at` becomes `ORDER BY created_at, id`.\n\nThis yields a nice side effect. Cursor pagination can be expressed in SQL as so-called keyset pagination, and it scales much better than large offsets:\n\n```sql\nSELECT id, created_at, name\n  FROM users\n WHERE (created_at, id) > (:cursor_created_at, :cursor_id)\n ORDER BY created_at, id\n LIMIT :page_size;\n```\n\nThe reason: a large `OFFSET n` forces the database to read and discard `n` rows before it even starts returning anything – on deep pages, this becomes noticeably slow. The keyset variant with `WHERE (sort_key, id) > (...)`, by contrast, can jump straight to the right place via the index. So cursor pagination is not only more correct for changing lists, it is often faster for deep paging too.\n\n## When offset is still fine\n\nCursor pagination is not an end in itself. There are cases in which offset is perfectly sufficient:\n\n- The list is essentially stable, such as a historical archive or a closed report into which nothing gets inserted anymore.\n- The user should be able to jump straight to page 7 – numbered pages can’t easily be represented with pure cursors, because you don’t know an absolute position.\n- The data volumes are small and the pages shallow, so that neither consistency nor performance problems occur.\n\nSo this is not about dogma but about a deliberate choice. As soon as a list can change under the user *and* they potentially page deep into it – feeds, timelines, activity streams – cursor-based pagination with the connections pattern is the right answer. For a stable, manageable reference work, offset can happily stay.\n\n## Conclusion\n\nPagination seems trivial until you look at it in motion. Offset counts positions, and positions shift – the result is duplicates and gaps that never show up in the quiet demo and are hard to pin down in production. The cursor-based approach replaces the question “from which position” with “after which element” and thereby becomes robust against changes to the list.\n\nThe connections pattern pours this idea into a clean structure: edges carry the list-specific cursor, nodes remain plain records, and `pageInfo` with `hasNextPage` and `endCursor` provides exactly the two pieces of information a client needs to page on correctly. Then come the details that make the difference between demo and production – an extra element for `hasNextPage`, a tie-breaker in the sorting, an upper bound for the page size and the discipline to treat the cursor as truly opaque. If you take these four things to heart, you have pagination that is still correct when the list moves under the user’s fingers.\n\n## Further reading\n\n- Grounding repository: [introduction-graphql](https://github.com/mikebild/introduction-graphql) (`introduction-graphql/paging.md`)\n- [GraphQL Pagination – official learning resource](https://graphql.org/learn/pagination/)\n- [GraphQL Cursor Connections Specification](https://relay.dev/graphql/connections.htm)"},{"locale":"en","translation_key":"sveltekit-adapter-aws","slug":"sveltekit-adapter-aws-framework-meets-cloud","title":"SvelteKit Adapter AWS: Framework Meets Cloud","summary":"Why I built my own SvelteKit adapter for AWS and what the translation between the framework build and Lambda, S3 and CloudFront reveals about both sides.","tags":["Software","AWS","Cloud"],"published_at":"2022-01-12T10:00:00+00:00","updated_at":"2026-07-14T17:18:34.934208+00:00","url":"https://www.mikebild.dev/en/blog/sveltekit-adapter-aws-framework-meets-cloud/","audio_url":null,"audio_duration_secs":null,"text":"# SvelteKit Adapter AWS: Framework Meets Cloud\n\nWhen a framework’s deployment model and the target platform do not fit together, projects always produce the same by-product: a handwritten deploy script. It copies build output into an S3 bucket, zips up a Lambda handler somewhere, sets cache headers by hand and finally invalidates a CloudFront distribution. That works – until the framework changes the structure of its build output, until a header is forgotten or until the one person who can still explain the script leaves the project. After that, the team has a deployment nobody trusts anymore, and every release becomes a test of courage.\n\nThis is exactly where SvelteKit applications that are supposed to run on AWS stand at the beginning of 2022. SvelteKit itself is still in beta – version 1.0 has been announced but not released – and it brings a remarkably clear concept for this problem: adapters. There is `adapter-node` for your own server, `adapter-static` for purely static sites, `adapter-vercel` and `adapter-netlify` for the respective platforms. There is no official adapter for AWS. So I wrote one: [sveltekit-adapter-aws](https://github.com/MikeBild/sveltekit-adapter-aws), an open source project that rolls out a SvelteKit app to Lambda, S3 and CloudFront via the AWS CDK. While building it, I noticed a few things about both sides – about the framework and about the cloud. That is what this post is about.\n\n## Adapters are an architecture boundary\n\nAt its core, a SvelteKit adapter is a Node module with a single essential function: `adapt()`. After the actual build, SvelteKit calls this function and passes a `builder` object through which the adapter picks up the build output: the client code for the browser, the server code for rendering, the prerendered pages. What the adapter does with it is up to the adapter. `adapter-node` builds a startable HTTP server, `adapter-static` a directory structure for any web server, `adapter-vercel` exactly the format the Vercel platform expects.\n\nThis boundary is drawn deliberately. The framework knows how routes, components and endpoints become an application. It does not know – and does not want to know – where this application will run later. Everything platform-specific moves behind the adapter interface. For the user, the decision comes down to one line in `svelte.config.js`:\n\n```javascript\nimport { adapter } from 'sveltekit-adapter-aws';\nimport preprocess from 'svelte-preprocess';\n\nexport default {\n  preprocess: preprocess(),\n  kit: {\n    adapter: adapter({\n      autoDeploy: true,\n      FQDN: 'demo.example.com',\n      MEMORY_SIZE: 256,\n      LOG_RETENTION_DAYS: 7,\n    }),\n  },\n};\n```\n\nWith `autoDeploy: true`, the build step rolls out the application directly – `svelte-kit build` then ends not with a directory but with a running CloudFormation stack. That is convenient for prototypes and small projects; for everything else, you can plug in your own CDK app via `cdkProjectPath` that uses the adapter output as a building block.\n\n## Why there was no AWS adapter\n\nThe fact that Vercel and Netlify have their own adapters and AWS does not is neither a coincidence nor an oversight. Vercel and Netlify are platforms: they control both sides of the interface and can define exactly which artifact they expect. AWS is not a platform in this sense but a construction kit. There is no single service called “SvelteKit hosting,” but dozens of primitives from which you assemble one of many possible deployments.\n\nAn AWS adapter therefore has to do something the platform adapters do not: define an architecture. Which service answers SSR requests? Where do the static files live? Who distributes the traffic? These are decisions that an architect would otherwise make in a design document – here they live in an npm package. That is exactly what makes such an adapter an interesting piece of software: it is solidified architecture, versioned and reusable.\n\n## The architecture: three services, one application\n\nThe split I chose follows the character of the build output. A built SvelteKit app falls into two fundamentally different parts: static files (client bundles, assets, prerendered pages) that can be cached at will, and a server part that has to compute per request. Static content belongs in S3, dynamic content in a Lambda function, and in front of both sits CloudFront as the shared entry point that decides by path where a request goes.\n\n```mermaid\nflowchart LR\n  B[Browser] --> CF[CloudFront<br/>distribution]\n  CF -->|/_app/*, assets,<br/>prerendered pages| S3[S3 bucket<br/>static files]\n  CF -->|all other<br/>requests| GW[API Gateway<br/>HTTP API]\n  GW --> L[Lambda<br/>SvelteKit SSR]\n  R53[Route 53 + ACM<br/>custom domain] -.-> CF\n```\n\nThe whole thing is provisioned with the AWS CDK, specifically version 2, which only became generally available in December 2021 – so the project builds on a fairly fresh foundation. Above all, CDK v2 cleans up the package chaos of v1: one library, `aws-cdk-lib`, instead of dozens of individually versioned modules. For an adapter that travels into other people’s projects as an npm dependency, that is a noticeable difference, because version conflicts between CDK subpackages were a constant issue in v1. The core of the stack, slightly shortened:\n\n```typescript\nimport { Stack, StackProps, Duration } from 'aws-cdk-lib';\nimport * as lambda from 'aws-cdk-lib/aws-lambda';\nimport { RetentionDays } from 'aws-cdk-lib/aws-logs';\n\nexport class AWSAdapterStack extends Stack {\n  constructor(scope: Construct, id: string, props: StackProps) {\n    super(scope, id, props);\n\n    const serverHandler = new lambda.Function(this, 'ServerFunction', {\n      runtime: lambda.Runtime.NODEJS_14_X,\n      handler: 'index.handler',\n      code: lambda.Code.fromAsset(process.env.SERVER_PATH!),\n      memorySize: parseInt(process.env.MEMORY_SIZE ?? '128'),\n      timeout: Duration.seconds(15),\n      logRetention: RetentionDays.ONE_WEEK,\n    });\n    // ... HTTP API, S3 bucket, CloudFront distribution, Route 53 records\n  }\n}\n```\n\nA detail that is easy to miss: log retention is deliberately set to seven days. CloudWatch logs without a retention rule grow without limit, and with an SSR function that logs every page request, that adds up faster than you think. In my experience, such operational defaults belong in the adapter, not on a wiki page with recommendations.\n\n## From the Lambda event to the framework response\n\nThe actual translation work happens in two places. The first is the build: the server part of the SvelteKit output is bundled with esbuild into a single CommonJS file – format `cjs`, target Node 14, with the built-in Node modules kept external. Lambda thus gets an artifact without a `node_modules` directory, which has done package size and cold starts good. The second place is the runtime itself: a small handler shim receives the event from API Gateway, shapes it into the request structure the SvelteKit server expects and translates the response back:\n\n```javascript\n// index.js – bridges API Gateway events to the SvelteKit server\nimport { init, render } from './app.js';\n\ninit();\n\nexport async function handler(event) {\n  const { rawPath, rawQueryString, headers, requestContext } = event;\n\n  const response = await render({\n    method: requestContext.http.method,\n    path: rawPath,\n    query: new URLSearchParams(rawQueryString),\n    headers,\n    rawBody: event.body\n      ? Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8')\n      : undefined,\n  });\n\n  return {\n    statusCode: response.status,\n    headers: response.headers,\n    body: response.body,\n  };\n}\n```\n\nThis shim is unspectacular, but it is the place where the framework world and the cloud world actually meet. This is where it is decided whether binary data is passed through correctly, whether multiple `Set-Cookie` headers survive and whether query parameters with special characters arrive intact. I did not design any of these small things at my desk; I added each one after a concrete misbehavior. The entire flow from source code to stack looks like this:\n\n```mermaid\nflowchart LR\n  SRC[SvelteKit<br/>source code] --> BUILD[svelte-kit build<br/>via Vite]\n  BUILD --> ADAPT[adapter adapt&#40;&#41;<br/>sorts outputs]\n  ADAPT --> ESB[esbuild<br/>SSR bundle, cjs]\n  ADAPT --> STATIC[static files<br/>+ prerendered]\n  ESB --> CDK[AWS CDK v2<br/>synth + deploy]\n  STATIC --> CDK\n  CDK --> STACK[CloudFormation stack<br/>Lambda, S3, CloudFront]\n```\n\n## Building against a moving API\n\nThe most uncomfortable part of the project has nothing to do with AWS. SvelteKit is in beta, and the adapter interface is among the parts that move most often. Methods on the `builder` object were renamed, merged and changed in behavior; the structure of the server output has also shifted more than once. An adapter built against SvelteKit from October may still compile in December – and still produce a broken deployment.\n\nFor an open source project, this means: the issues do not come from your own bugs but from the drift between the user’s framework version and the version the adapter was developed against. A typical bug report starts with “doesn’t work for me” and, after some digging, ends at a SvelteKit version that is three weeks newer than my last update. Only unspectacular measures help against this: pin the tested SvelteKit version in the project, keep example repositories up to date, follow changes to the framework promptly. That is the real price of building against a beta – and I consider it reasonable. If you wait until an interface is stable, you leave the experience from the meantime to others. Along the way, an adapter forces you to really understand the framework: you do not work with the documented surface but with the build output and its assumptions.\n\nWhat the adapter concretely takes care of during the build is manageable and, precisely for that reason, easy to maintain:\n\n- sort client bundles, assets and prerendered pages into an artifact directory\n- bundle the server part with esbuild into a Lambda-ready file\n- place the handler shim for API Gateway next to it\n- synthesize a CDK stack and, if desired, roll it out directly\n- wire up domain, certificate and DNS records via Route 53 and ACM when an `FQDN` is set\n\n## What serverless does not take off your hands\n\nOn the other side of the boundary, the second disillusionment is waiting: even with a finished adapter, AWS is not a platform that takes operations off your hands. Serverless moves work; it does not eliminate it. A few points became clear to me while running my own SvelteKit deployments.\n\nCold starts are real but manageable. An SSR function bundled with esbuild starts fast enough for most pages at this scale – but if you pull heavy dependencies into the server part, you pay for it with every cold request. With Lambda, the memory size is also the CPU dial: the 128 MB default is often too tight for rendering, and more memory can improve response times so much that it pays off despite the higher price per millisecond. Measure instead of guessing.\n\nThen there is caching. CloudFront only relieves the function if the cache keys and headers are right – an SSR response with `Cache-Control` set to `private` hits the Lambda on every call. For small rewrites right at the edge, there have been CloudFront Functions since last year, which are much more lightweight than Lambda@Edge; for the actual rendering, both are the wrong place. And CloudFormation makes deployments traceable and reversible, but not fast: a change to the CloudFront distribution can take quite a few minutes. If you come from Vercel, you first have to get used to this pace.\n\nWhat remains is an honest division of labor. The adapter answers the question “how does the app get to AWS” – these questions stay with the team:\n\n- Observability: which logs, metrics and alarms show that rendering is suffering?\n- Costs: what do requests, data transfer and logs cost under real traffic?\n- Security: which permissions does the SSR function have, and which does it really need?\n- Lifecycle: who keeps up with framework and adapter updates, and how is a rollback rehearsed?\n\n## Bottom line\n\nThe project showed me two things that reach beyond SvelteKit and AWS. First: the adapter interface is a successful example of how a framework can draw a boundary without committing to a platform. Everything platform-specific – from the directory structure to the architecture decision – gets a clear place, and this place is versionable, testable and replaceable. The fact that a single person can provide a complete AWS foundation for a framework in a manageable repository speaks for the way this interface is cut.\n\nSecond: a deployment target is never just configuration. The path from `svelte-kit build` to a running CloudFront endpoint consists of nothing but small decisions – bundling, routing rules, cache behavior, memory sizes, log retention – and each of them has consequences in operations. A handwritten deploy script makes the same decisions, only invisibly and unversioned. An adapter makes them explicit and shares them with everyone who has the same problem. That is exactly why it is worth building something like this as open source, even when the framework is still in beta and the interface wobbles under your hands: the alternative is not “no adapter” but a hundred private scripts that all make the same mistakes again.\n\n## Further reading\n\n- Repository: https://github.com/MikeBild/sveltekit-adapter-aws\n- SvelteKit documentation on adapters: https://svelte.dev/docs/kit/adapters\n- AWS CDK v2 Developer Guide: https://docs.aws.amazon.com/cdk/v2/guide/home.html\n- Amazon CloudFront Functions: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-functions.html"},{"locale":"en","translation_key":"preview-umgebungen-pro-pull-request","slug":"preview-environments-per-pull-request","title":"Preview Environments per Pull Request","summary":"Ephemeral environments per pull request shorten feedback and make reviews concrete: you click through the change instead of imagining it from the diff.","tags":["Software","Delivery"],"published_at":"2021-11-24T10:00:00+00:00","updated_at":"2026-07-13T08:41:54.963229+00:00","url":"https://www.mikebild.dev/en/blog/preview-environments-per-pull-request/","audio_url":null,"audio_duration_secs":null,"text":"# Preview Environments per Pull Request\n\n“Is staging free?” – this question in the team chat is the real bottleneck. As long as one environment has to serve everyone, the order of the queue decides when someone even gets to see a change. If, instead, every pull request gets its own disposable instance, the relationship flips: the review doesn’t wait for the environment, the environment comes into being with it.\n\n## The problem behind the diff\n\nA review often ends right here: someone opens a pull request, a colleague reads the diff, imagines the behavior that goes with it and writes “LGTM”. That is a guessing game. A diff shows which lines changed – not how the application feels afterward. Whether the new checkout flow is usable on a smartphone, whether the loading state flickers, whether an edge case in the domain is right: none of that is in any `git diff`.\n\nThe classic answer was a shared staging environment. One team, one environment, one queue. If you want to test, you deploy your branch, overwrite the previous one and block everyone else. With two parallel features, that is a source of conflicts; with five, a permanent traffic jam. The actual goal – fast, concrete feedback – gets lost in the coordination.\n\nAnd the jam is only the visible side. The invisible one is that a shared staging environment never has a defined state: it always carries the leftovers of the last deploy, half-migrated schemas, test data from someone else’s feature. When a reviewer sees something odd there, nobody knows for sure whether it is the current PR or an artifact from yesterday. Exactly this “is it my change or the environment?” eats up time and trust. A freshly spun-up instance doesn’t have this problem – it starts from the same reproducible zero state on every run.\n\nThe thesis of this article is simple: every pull request gets its own disposable environment with its own URL. Reviewers click through the running change instead of imagining it. And because the environment is ephemeral, it disappears again on merge – without a cleanup ritual, without a growing bill.\n\n## The outcome, not the mechanics\n\nBefore we get to `app.json` and CI pipelines, it pays to look at the why. The benefit lies in the shorter feedback loop – and that pays directly into measurable delivery performance.\n\n*Accelerate* (Forsgren, Humble, Kim, 2018) backed this up with data: small batches, short lead time for changes and high deployment frequency are the drivers of high-performing software delivery. A preview environment per pull request pushes exactly there. It rewards small changes – a tiny PR can be deployed in seconds and reviewed in minutes. It lowers the threshold to integrate at all, because feedback doesn’t have to wait for the next staging slot. That fits seamlessly with Trunk-Based Development and with what Humble and Farley described back in 2010 in *Continuous Delivery*: short-lived branches, fast integration, the PR as the unit of integration.\n\nPerhaps the most underestimated effect is social. As soon as there is a clickable URL, people who don’t set up a development environment can review too: QA, product management, design. A designer who sees the real implementation in the browser gives feedback in five minutes that would otherwise take a meeting and three screenshots. That is the point where a technical feature turns into a delivery advantage.\n\nConceptually, this is closely related to the build-measure-learn loop from Ries’ *Lean Startup* (2011). A preview is a concrete artifact you can measure and learn from before anything goes to production. The smaller the batch, the faster the loop can become. Economically, though, an environment per PR only works if provisioning, data, runtime and teardown are under control. Otherwise, the preview merely shifts the friction from the review into operations.\n\n## The lifecycle of an ephemeral environment\n\nThe mechanics are the same across all established products – whether Heroku “Review Apps”, GitLab “Review Apps”, Netlify “Deploy Previews” or Vercel’s “Preview Deployments”. The PR is the trigger, the merge is the end.\n\n```mermaid\nsequenceDiagram\n    participant Dev as Developer\n    participant PR as Pull Request\n    participant CI as CI Pipeline\n    participant Env as Preview Environment\n    Dev->>PR: open / push commit\n    PR->>CI: trigger build (HEAD commit)\n    CI->>Env: deploy isolated instance (own URL + own DB)\n    Env-->>PR: post preview URL as commit status\n    Dev->>Env: reviewer clicks and tests\n    Dev->>PR: push new commit\n    PR->>CI: rebuild and redeploy\n    Dev->>PR: merge or close\n    PR->>Env: destroy environment\n```\n\nThe important word is *isolated*. Instead of one staging environment for everyone, n previews run in parallel – each with its own URL, ideally with its own data layer. The contrast with the old model is the whole point:\n\n```mermaid\ngraph LR\n    subgraph Classic[\"One staging for all\"]\n        A[PR 1] --> S[Shared Staging]\n        B[PR 2] --> S\n        C[PR 3] --> S\n        S --> Q[Queue and conflicts]\n    end\n    subgraph Ephemeral[\"Preview per PR\"]\n        D[PR 1] --> P1[preview-1.example.com]\n        E[PR 2] --> P2[preview-2.example.com]\n        F[PR 3] --> P3[preview-3.example.com]\n    end\n```\n\n## Declarative instead of a script graveyard\n\nThe most elegant approach describes the environment declaratively instead of assembling it from a chain of shell steps. Heroku shows how with an `app.json`: everything a review app needs – add-ons, migrations, feature flags – sits in one place, versioned in the repository.\n\n```json\n{\n  \"name\": \"my-app\",\n  \"environments\": {\n    \"review\": {\n      \"addons\": [\"heroku-postgresql:hobby-dev\"],\n      \"scripts\": {\n        \"postdeploy\": \"bundle exec rake db:migrate db:seed\"\n      },\n      \"env\": {\n        \"FEATURE_FLAGS\": \"preview\"\n      }\n    }\n  }\n}\n```\n\nThe appeal lies in the `postdeploy` hook: every preview gets a fresh database, migrates the schema and loads seed data. This makes the environment reproducible from nothing – and that is exactly what makes it disposable.\n\nIf you aren’t on a PaaS like Heroku or Netlify, you build the same pattern yourself with GitHub Actions. The three steps stay the same: build, deploy into an isolated instance, write the URL back into the PR. How the deploy script works internally – whether it talks to a container host, spins up an app on your own platform or ships a static bundle – is secondary for this skeleton; what matters is the clean contract of name, image and host.\n\n```yaml\nname: preview\non:\n  pull_request:\n    types: [opened, synchronize, reopened]\n\njobs:\n  deploy-preview:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n\n      - name: Build and push image\n        run: |\n          docker build -t registry.example.com/app:${{ github.sha }} .\n          docker push registry.example.com/app:${{ github.sha }}\n\n      - name: Deploy preview instance\n        run: |\n          ./scripts/deploy-preview.sh \\\n            --name \"pr-${{ github.event.number }}\" \\\n            --image \"registry.example.com/app:${{ github.sha }}\" \\\n            --host \"pr-${{ github.event.number }}.preview.example.com\"\n\n      - name: Comment preview URL\n        run: |\n          gh pr comment ${{ github.event.number }} \\\n            --body \"Preview ready: https://pr-${{ github.event.number }}.preview.example.com\"\n        env:\n          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n```\n\nTeardown is just as important as deployment. A preview that nobody cleans up is not a feature but a cost center. That is why a second workflow belongs with it, cleaning up when the PR is closed:\n\n```yaml\nname: preview-teardown\non:\n  pull_request:\n    types: [closed]\n\njobs:\n  destroy-preview:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Tear down environment\n        run: |\n          ./scripts/destroy-preview.sh --name \"pr-${{ github.event.number }}\"\n```\n\nWhether the deploy target is a Kubernetes namespace, a Heroku app or a static Netlify build doesn’t matter conceptually. The pattern is portable: PR opens, instance comes up, URL lands in the PR, merge cleans up.\n\n## Ephemeral environments as a test bench\n\nAn isolated, production-like instance is more than a click-through preview. It is a clean place to run automated checks against a real deployment – not just against mocks. Two examples that prove themselves in practice:\n\nContract tests with Pact check whether a service still meets the expectations of its consumers. Verified against a real, running PR instance, that is more meaningful than against a stub. And architectural fitness functions, as Ford, Parsons and Kua describe them in *Building Evolutionary Architecture* (2017), can be armed against the running preview: response times, dependency rules, bundle sizes. This turns the preview into a gate that answers not only “looks good” but “sticks to the rules”.\n\nFeature flags complete the picture. A preview with `FEATURE_FLAGS=preview` set shows the target state while the same change stays dark in production – review and rollout are decoupled. If you take the flag idea seriously, you can merge a change several times without enabling it and take it live later via a toggle. That reduces long feature branches and fits the trunk-based idea: integrate, make visible, roll out in a controlled way.\n\nThe line of thought behind this is the same as with blue-green or canary: you separate “deployed” from “visible to everyone”. In this sense, a preview is a canary for exactly one reviewer – the smallest conceivable rollout stage. Once you have internalized this separation, you no longer think of deployment and release as the same step, and that is one of the most effective reliefs for a team that wants to ship often and calmly.\n\n## Where it really hurts\n\nNone of this is frictionless. The hard part is never deploying the web process – it is everything underneath.\n\nThe data layer is the hardest. If all previews share one database, they contaminate each other: one PR migrates a schema, another trips over it. A database per PR solves this, but costs provisioning time and money – and every migration has to run cleanly from zero. That, by the way, is an underestimated side effect: if you take previews seriously, you also test your migration path on a greenfield with every PR. Migrations that only work on grown datasets show up immediately here instead of surprising you at the next fresh setup. External services make the picture even sharper: payments, email delivery, third-party APIs must never fire for real from a preview. That takes sandbox modes or stubs, and they have to be configured before the first reviewer clicks – otherwise the preview of a marketing feature accidentally sends real emails to real addresses.\n\nThe second perennial issue is the lifecycle. Forgotten environments cost money and drift away from the current state. The teardown on merge or close has to work reliably, supplemented by a TTL or an idle shutdown for PRs that stay open for weeks. A single close event that never fired – say, because a PR was deleted into the void – must not leave an orphaned instance behind, so in addition to event-driven teardown you need a regular cleanup job that sweeps by age or inactivity. And the feedback advantage flips when the build takes ten minutes: cold starts and long pipelines undermine exactly what you build the whole thing for. A fast, aggressively cached build is the precondition for the short loop to stay short at all.\n\nThird, secrets and access. Preview URLs are often public and guessable – `pr-42.preview.example.com` is not a security boundary. Unprotected, such previews leak unfinished features or real data. Secrets have to be injected securely, access belongs behind basic auth, SSO or password protection. Netlify offers password protection for deploy previews for exactly this reason.\n\nAnd finally, config skew. A preview is only useful if it is close to production. If it deviates too much, you get the worst of all outcomes: green review, red prod deploy. Then the environment has created trust it couldn’t back up. The countermeasures are unspectacular but effective: pass the same container image through from the preview all the way to production, control configuration consistently through environment variables instead of diverging build paths, and keep the few deliberate differences – sandbox endpoints, smaller resources, active feature flags – visible in one place. The closer the preview is to production, the more a green review is actually worth.\n\n## The common thread\n\nIn 2021, preview environments per pull request are common, productized practice – from Heroku through GitLab and Netlify to Vercel. The core is the same everywhere and told in a few sentences: the PR creates an isolated, disposable instance with its own URL, every new commit deploys again, the merge cleans up.\n\nThe gain is the shorter and more honest feedback loop. Reviewers judge running behavior instead of lines in the diff. Non-developers can have a say. Small batches are rewarded, the staging jam disappears. That is the *Accelerate* logic in its purest form: friction out, cycles shorter, quality visible earlier.\n\nGetting started is therefore unspectacular: start with the outcome, not with the platform. The hard questions are the database, the lifecycle and access protection – not deploying the web process. If you solve them cleanly, you get reviews you click through instead of imagining. And that is the difference between “LGTM” and “I’ve seen it”.\n\n## Further reading\n\n- [Heroku Review Apps](https://devcenter.heroku.com/articles/github-integration-review-apps)\n- [Netlify: Introducing Deploy Previews (2016)](https://www.netlify.com/blog/2016/07/20/introducing-deploy-previews-in-netlify/)\n- [GitLab Review Apps](https://docs.gitlab.com/ci/review_apps/)\n- [Vercel: Every push now receives a unique URL](https://vercel.com/changelog/every-push-now-receives-a-unique-url)\n- [Using the Four Keys to measure your DevOps performance (DORA)](https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance)\n- Forsgren, Humble, Kim: *Accelerate* (2018)\n- Humble, Farley: *Continuous Delivery* (2010)\n- Ford, Parsons, Kua: *Building Evolutionary Architecture* (2017)"},{"locale":"en","translation_key":"jamstack-architektur","slug":"jamstack-as-an-architecture-style","title":"Jamstack as an Architecture Style for Web Applications","summary":"Jamstack describes an architecture style with a pre-rendered frontend and decoupled services. This post puts the original building blocks JavaScript, APIs and Markup into context as of 2021.","tags":["Software","Architecture"],"published_at":"2021-11-15T10:00:00+00:00","updated_at":"2026-07-13T13:32:54.201633+00:00","url":"https://www.mikebild.dev/en/blog/jamstack-as-an-architecture-style/","audio_url":null,"audio_duration_secs":null,"text":"You can’t pull Jamstack into a project with `npm install`, and you can’t buy it anywhere either. It is an architecture style for web applications that emphasizes pre-rendering and decoupling the UI from services.\n\nThat is why the decision is also made one level above the choice of the next framework. That is exactly where Jamstack comes in.\n\nThe name was originally formed from **JavaScript, APIs and Markup**. Matt Biilmann and Chris Bach coined it at Netlify; Biilmann made it publicly known in 2015/2016. As early as 2021, Jamstack was used more broadly than the acronym. Two principles have remained: pre-rendering and decoupling. Instead of generating fresh HTML on the server for every request, markup is built in advance and delivered via a CDN; dynamic parts access APIs separately.\n\n## The paradigm shift: classic SSR versus Jamstack\n\nTo understand why this matters, it is worth looking at the classic model. With server-side rendering in the traditional sense, the same thing happens on every page view: the browser sends a request, an application server receives it, queries a database, assembles HTML from it and sends it back. Every single visitor triggers this chain again. That is proven, but it ties up server capacity per request and makes the app server both the bottleneck and the attack surface.\n\nJamstack reverses this order. The work no longer happens per request but once, at build time. A static site generator pulls content from data sources, renders finished HTML pages from it and stores them as static files. These files land on a CDN and are delivered from there globally, close to the user. Whatever has to be dynamic – a shopping cart, a login, a search – is loaded afterwards on the client side via APIs.\n\n```mermaid\nflowchart LR\n  subgraph Classic[\"Classic SSR\"]\n    B1[\"Browser\"] -->|\"Request\"| S1[\"App server\"]\n    S1 --> DB[(\"Database\")]\n    DB --> S1\n    S1 -->|\"HTML per request\"| B1\n  end\n  subgraph Jam[\"Jamstack\"]\n    B2[\"Browser\"] -->|\"static page\"| CDN[\"CDN<br/>(pre-rendered)\"]\n    B2 -->|\"dynamic parts at runtime\"| API[\"APIs /<br/>Serverless\"]\n  end\n```\n\nA clarification that regularly gets lost in discussions: Jamstack doesn’t forbid server-side rendering. It shifts the default case. Instead of “every page per request on the server”, it’s “every page once in the build” – and where it is really needed, I can still use server-side rendering selectively. That is exactly what the next section is about.\n\n## Static site generators and hybrid rendering\n\nThe engine of Jamstack is the static site generator. In the simplest case, it is a process that reads content and writes HTML from it. A deliberately reduced example makes the principle tangible – Markdown in, HTML out:\n\n```jsx\nimport { loadMarkdown, renderToHtml, writeFile } from \"./ssg\";\n\nfor (const post of loadMarkdown(\"content/**/*.md\")) {\n  const html = renderToHtml(post);\n  writeFile(`dist/${post.slug}/index.html`, html);\n}\n```\n\nIn practice, mature tools take care of this. Gatsby, for example, is a React-based generator with a GraphQL data layer and a large plugin ecosystem. Next.js – currently at version 12, released at the end of October 2021 with a new, much faster Rust compiler based on SWC – offers several rendering modes side by side. And SvelteKit, which has been in public beta since spring 2021, takes the same route with an adapter concept. SvelteKit should deliberately still be considered young; it is pre-1.0 and in beta, but the direction is already clearly visible.\n\nThe decisive point of modern generators is that I don’t set the rendering globally but decide per page or route. Next.js is a good example for sorting this out:\n\n- SSG (Static Site Generation) via `getStaticProps` and `getStaticPaths` renders the page in the build; afterwards it is pure markup from the CDN.\n- SSR (Server-Side Rendering) via `getServerSideProps` generates the page per request on the server, for truly dynamic content.\n- ISR (Incremental Static Regeneration), available since version 9.5 from 2020, rebuilds a static page in the background based on time or events.\n- CSR (Client-Side Rendering) via hooks and data libraries such as SWR loads the data only in the browser.\n\nA typical SSG pattern with a touch of ISR looks like this:\n\n```ts\nexport async function getStaticProps() {\n  const posts = await fetchFromCMS();\n\n  return {\n    props: { posts },\n    revalidate: 3600, // ISR: regenerate at most once per hour\n  };\n}\n```\n\nThe `revalidate` is the transition from purely static to hybrid: the page stays static and CDN-fast but doesn’t go stale, because it renews itself after the specified time. In my experience, this mix – static where possible, server-side or client-side where necessary – is the realistic normal case, not the pure doctrine.\n\n## CDN and performance\n\nWhy all the effort? Because pre-rendered assets from the CDN often reach the user faster. Instead of a computation chain of server and database, a nearby edge location delivers a finished file. That can improve time to first byte (TTFB) significantly. For interactivity, though, finished markup alone isn’t enough: a lot of JavaScript and expensive hydration can eat the advantage up again. That’s why I measure delivery and interactivity separately instead of crediting both to pre-rendering.\n\nThen there is the effect on SEO. With pre-rendered markup, search engines immediately see the complete content without depending on client-side loading. For content-driven sites – blogs, documentation, marketing – that is a real advantage I wouldn’t subordinate to pure loading speed.\n\nI want to clear up a common misunderstanding here: the CDN delivers the static assets, not the APIs. The dynamic data still comes via API requests – either directly from the frontend or via an upstream frontend API. So the CDN speeds up delivery of the skeleton, while the dynamic parts are served separately.\n\n## Decoupling and API orchestration\n\nThat brings us to the second big principle: decoupling. In Jamstack, delivering the frontend and dynamic data access are separate. The backend can still be one cohesive application or consist of several services; what matters is that the frontend accesses it via APIs during the build or at runtime. Authentication can be handled by an external service, content can come from a headless CMS, and your own business logic can live in serverless functions. These are common building blocks, not a definition of the architecture.\n\nThe exciting question then is where all these APIs come together. Two ways have become established. Either I orchestrate directly in the frontend, with the components querying the endpoints they need themselves:\n\n```jsx\nimport useSWR from \"swr\";\n\nconst fetcher = (url) => fetch(url).then((res) => res.json());\n\nfunction Cart() {\n  const { data, error } = useSWR(\"/api/cart\", fetcher);\n  if (error) return <p>Failed to load</p>;\n  if (!data) return <p>Loading…</p>;\n  return <CartView items={data.items} />;\n}\n```\n\nOr I put a frontend API in front – often via GraphQL, for example with AWS AppSync or the GraphQL endpoint of a headless CMS. The frontend then makes a single, consolidated request, and orchestrating the services behind it happens one layer deeper. For larger applications with many data sources, I prefer this route because it relieves the frontend of detailed knowledge about every single backend.\n\nThe serverless functions themselves are deliberately lean and stateless. A handler in Netlify or Lambda style typically looks like this:\n\n```js\nexports.handler = async (event, context) => {\n  const { name } = JSON.parse(event.body);\n\n  return {\n    statusCode: 200,\n    body: JSON.stringify({ message: `Hello ${name}` }),\n  };\n};\n```\n\nThe economic appeal behind this can be the billing model: pay-per-execution. Depending on the platform, base fee and load profile, you pay more for actual invocations and compute time than for permanently provisioned servers. The provider also largely takes care of scaling within its limits. Runtime limits, distributed failures, quotas and the cost of individual invocations still remain architecture questions.\n\n## Build and CI: the Git push as the trigger\n\nThe pre-rendering has to happen at some point, of course. Often a Git push starts a CI pipeline – for example via GitHub Actions – that runs the static site generator and puts the result on a CDN. Many specialized platforms publish these artifacts atomically and versioned, so that a new version becomes active as a whole and can be rolled back. That is a property of the chosen deployment system, not automatically of every Jamstack build.\n\n```mermaid\nflowchart LR\n  Dev[\"git push\"] --> CI[\"GitHub Actions<br/>(CI)\"]\n  CI --> SSG[\"Static Site Generator<br/>(Build)\"]\n  SSG --> Deploy[\"atomic deploy\"]\n  Deploy --> CDN[\"CDN<br/>(global edge)\"]\n  CDN --> User[\"User\"]\n  SSG -.->|\"large catalog\"| Shard[\"Sharding /<br/>parallel builds\"]\n  Shard --> Deploy\n```\n\nA simple workflow that does exactly this is quickly written down:\n\n```yaml\nname: build-and-deploy\non:\n  push:\n    branches: [main]\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v2\n        with:\n          node-version: \"16\"\n      - run: npm ci\n      - run: npm run build\n      - run: npx netlify deploy --prod --dir=dist\n```\n\nFor small sites, the build is done in seconds. For large catalogs with many thousands of pages, the build time itself becomes an issue – sharding helps here, splitting the build into parallel subprocesses. That is also a good transition to the limits I address further below.\n\n## Security and operational benefits\n\nA side effect of the architecture that is easily overlooked concerns security. If no application server is hit per request at runtime, the attack surface shrinks considerably. No monolithic server that runs database queries on every request and becomes vulnerable in the process. What gets delivered are static files, and the dynamic parts sit in clearly delimited APIs that can each be secured individually. All in all, this yields a handy list of benefits:\n\n- TTFB can drop because pre-rendered markup comes straight from the edge; interactivity additionally depends on the JavaScript delivered.\n- For static pages, there is no application server per read; the APIs remain an attack surface of their own.\n- CDN and platform can take over a large part of the scaling, each within their quotas and runtime limits.\n- Pay-per-execution can save costs with a fitting load profile, but it isn’t inherently cheaper.\n- The developer experience benefits from clear separation, Git-based deploys and fast rollbacks.\n\n## Three case studies from practice\n\nSo this doesn’t stay theoretical, here are three scenarios that I almost read as maturity levels in this order.\n\nThe first is the static blog or portfolio. This is where Jamstack plays to its strengths: content is rendered in the build, there is hardly any dynamic behavior, and the CDN can deliver it without an application server. For this class of projects, pure SSG is often already the complete answer.\n\nThe second scenario is B2C e-commerce. As soon as sessions, shopping carts and transactions come into play, purely static is no longer enough. Product pages can be pre-rendered statically very well and delivered via the CDN, while the cart, checkout and user account are served on the client side via APIs. That is the classic hybrid case, where ISR additionally helps keep product data up to date without rebuilding every page per request.\n\nThe third scenario is B2B, SaaS and IoT applications. Dashboards, personalized views and real-time data dominate here. A static skeleton can contribute to a fast initial delivery; protected areas can be rendered on the client, on the server or hybrid, depending on the product. A GraphQL frontend API can also make sense if several data sources really do have to be bundled for the UI.\n\n## Where Jamstack hits its limits\n\nAs convincing as the model is, I stay honest about the edges. Pure SSG doesn’t scale indefinitely. With a few thousand pages, build time slowly becomes relevant; with millions of pages, pre-rendering everything simply becomes impractical. This is exactly where the tools already mentioned come in: ISR only re-renders what really changes; hybrid rendering allows server-side generation for rarely visited or highly dynamic routes; and sharding spreads large builds across parallel processes.\n\nSobriety also pays off when choosing tools. SvelteKit is promising at the end of 2021 but still in beta. Azure Static Web Apps has only been generally available since May 2021 and is therefore also quite young, but it integrates Azure Functions directly as a backend. Fast build building blocks such as esbuild by Evan Wallace speed up the pipeline enormously but are themselves still pre-1.0. If you build here, you choose deliberately between established and up-and-coming.\n\n## Conclusion\n\nTo me, Jamstack is less a technology than a stance on architecture. It moves suitable work from the request into the build and separates delivering the frontend from dynamic data access. Whether an enterprise application, several services or serverless functions sit behind it is a separate decision. Fast delivery via the CDN, a smaller runtime surface and simple deployments can follow from it if the application and platform fit.\n\nWhat matters is that Jamstack stays open to technology. It doesn’t prescribe a framework but a way of thinking, within which I can use Next.js, Gatsby or SvelteKit just as well as Netlify, Vercel or Azure. And it isn’t dogma: pure SSG for the blog, hybrid for the shop, server-side plus API orchestration for the SaaS platform. With this gradation, the architecture decision is made where it belongs – one level above the framework.\n\n## Further reading\n\n- Mike Bild: “JAMstack-Architektur” – the detailed original article: https://www.developer-world.de/dwx-insights/architecture-patterns/jamstack-architektur\n- Official Jamstack resource: https://jamstack.org/\n- [Jamstack: definition and origin of the name](https://jamstack.org/what-is-jamstack/)\n- Next.js 12 (release from October 26, 2021): https://nextjs.org/blog/next-12\n- SvelteKit Public Beta: https://svelte.dev/blog/sveltekit-beta\n- Azure Static Web Apps GA (May 2021): https://www.infoq.com/news/2021/05/azure-static-web-apps-ga/"},{"locale":"en","translation_key":"ses-email-hook-serverless","slug":"serverless-transactional-email-with-ses-and-lambda","title":"Serverless Transactional Email: SES and Lambda","summary":"How SES becomes an event-driven email building block: outgoing confirmation emails from a Lambda Function and incoming Receipt Rules that turn an email into a handler call.","tags":["Software","AWS","Cloud"],"published_at":"2021-11-09T10:00:00+00:00","updated_at":"2026-07-13T08:41:19.011377+00:00","url":"https://www.mikebild.dev/en/blog/serverless-transactional-email-with-ses-and-lambda/","audio_url":null,"audio_duration_secs":null,"text":"A `SendEmail` call carries up to 50 recipients and 10 MB of message. An incoming SES event carries zero bytes of email text: it delivers headers and metadata, and the body sits in S3. These two numbers say more about the service than any feature list – the outgoing direction is done in half an hour, the incoming one has its own rules that you need to know.\n\nBehind this lies a decision that sounds like configuration to the team: “So how do we send out the confirmation email now?” Often there is already a signup flow, maybe with user management as in [Serverless Auth with Cognito User Pools](https://www.mikebild.dev/en/blog/serverless-auth-with-cognito-user-pools/), and the email looks like the last, trivial building block. That is exactly where the mistake lies. The real question is: Do I treat email as an external Side Effect that I stick onto the end of a flow, or as a full domain event – in and out – that deserves the same treatment as an API call or a queue message?\n\nThis choice decides whether the email part later fits cleanly into the architecture or causes friction as a foreign body. SES – the Simple Email Service – is instructive because it serves both directions with the same building blocks: Lambda on one side, Receipt Rules on the other. The leverage is not in the API fields but in this symmetry. Below I walk through both directions – first the outgoing confirmation email from a function, then the incoming email hook that turns a real email into, for example, a support ticket. The code is deliberately lean so that the common thread – event in, event out – stays visible.\n\n## SES as a building block in two directions\n\nBefore we write code, it pays to look at the mental model. SES sits at the system boundary between your application and the outside world of email. Outward: your app triggers an event – a new account, a paid order – and a Lambda Function calls `SendEmail`. Inward: someone sends an email to one of your addresses, and SES processes it further via so-called Receipt Rules, for example to S3, to SNS or directly to a Lambda Function.\n\nThis symmetry is the core. As soon as SES shows up in the design as an event-driven building block, it fits cleanly into the rest of the serverless architecture. If it stays a mere “email sender,” it ends up bolted on from the outside. The outgoing direction is the more common one and the easier place to start.\n\n- Outgoing: `SendEmail` or `SendTemplatedEmail`, a verified sender, sandbox and quota in view, triggered by an app event.\n- Incoming: a Receipt Rule Set with actions for S3, Lambda or SNS, available only in certain regions, triggered by an arriving email, body loaded afterward from S3.\n\nLet’s keep these two lines in mind – they structure the rest of the article.\n\n## Email as a domain event, not as SES configuration\n\nThe difference sounds academic, but it has real consequences. If you see SES as a configuration task, you stop at “sender verified, `SendEmail` works.” If you model email as a domain event, you keep asking: Which business event triggers this email, and which event does an arriving email create in my system? “I send a message” becomes “a signup happened,” and “someone emailed” becomes “a support case came in.” The email is then only the transport, not the event itself.\n\nThis perspective costs something and gives something. The price is extra care at the system boundary: verified identities, an active rule set, correct permissions, the knowledge that incoming bodies sit in S3. The return is connectability. An event can be passed on, orchestrated, logged and tested – a “sent email,” on the other hand, is a dead end.\n\nA few decision criteria help with the question of whether SES is the right building block:\n\n- Coupling and control: SES stays entirely within AWS and IAM, with no second provider and no additional contract. In return, you carry the regional restriction on receiving and the MIME parsing yourself.\n- Cost: SES bills per thousand emails and costs nothing when idle. A specialized transactional provider brings better deliverability tools and ready-made templates, but also its own bill and a second system that someone has to operate.\n- Impact: Only when the incoming email is a real event can you automate the follow-up – classification, assignment, draft reply. That is exactly what shortens the cycles that otherwise depend on manual triage.\n\nAs long as email is an event source and sink inside an AWS architecture, SES is the choice with the least friction. As soon as marketing deliverability, bounce analytics and campaign tooling come to the fore, a dedicated provider is the more honest choice. For the transactional core – confirmation out, ticket in – the event-driven SES building block wins.\n\n## The outgoing confirmation email\n\nLet’s start with the outgoing direction. A Lambda Function is triggered by an event – say, an API Gateway call after a successful registration – and is supposed to send a short confirmation email.\n\nThe following diagram shows the path of the event. The event comes in, the Lambda Function translates it into a `SendEmail` call, and SES accepts the message. That is not yet a delivery guarantee: bounces and complaints run through their own SES events. If the triggering event is repeated, the email can also be sent twice. For a production flow, I therefore need a stable event key and a stored sending status or an outbox.\n\n```mermaid\nflowchart LR\n  A[Event: Signup] --> B[Lambda: sendConfirmationEmail]\n  B --> C[ses:SendEmail]\n  C --> D[Recipient Inbox]\n```\n\nThe corresponding handler is manageable. Here I use the AWS SDK for JavaScript version 3, that is, the modular `@aws-sdk/client-ses` packages – the established version 2 with `new AWS.SES()` works just as well, but for new functions its import is simply too monolithic for my taste.\n\n```ts\nimport { SESClient, SendEmailCommand } from \"@aws-sdk/client-ses\";\n\nconst ses = new SESClient({ region: \"eu-west-1\" });\n\nexport async function sendConfirmationEmail(event: {\n  email: string;\n  name: string;\n}) {\n  const command = new SendEmailCommand({\n    Source: \"no-reply@example.com\",\n    Destination: {\n      ToAddresses: [event.email],\n    },\n    Message: {\n      Subject: {\n        Data: \"Willkommen bei uns\",\n        Charset: \"UTF-8\",\n      },\n      Body: {\n        Html: {\n          Data: `<p>Hallo ${event.name}, dein Konto ist aktiv.</p>`,\n          Charset: \"UTF-8\",\n        },\n      },\n    },\n  });\n\n  const result = await ses.send(command);\n  return { messageId: result.MessageId };\n}\n```\n\nThree things are mandatory here and therefore deserve a closer look. `Source` is the sender address and must be a 7-bit ASCII address of a verified identity. `Destination` groups the recipients into `ToAddresses`, `CcAddresses` and `BccAddresses`. `Message` carries `Subject` and `Body`, where the body can contain text and HTML, each as an object of `Data` and `Charset`. What comes back is a `MessageId` – the only receipt you get for a successful call. Optionally, you can add quite a bit more, such as `ReplyToAddresses` or a `ConfigurationSetName`, but for the confirmation email what is shown is enough.\n\n### Verified senders, sandbox and quota\n\nThe code is rarely the stumbling block. There are three organizational points you need to settle beforehand.\n\nFirst, the sender identity. SES only sends from verified senders. You can verify a single address or – much more sensible for production – an entire domain via DKIM and TXT records in DNS. If the sender is not verified, SES answers the call with “Email address not verified,” and the email does not go out.\n\nSecond, the sandbox. Every new SES account starts in the sandbox. That means you may only send to verified recipients or to the SES Mailbox Simulator, and the sending quota is reduced. The confirmation email to a real customer therefore fails in the sandbox as long as their address is not verified itself. For production use, you have to request production access via a support case.\n\nThird, the quota. Every recipient of a message counts against your sending allowance. A `SendEmail` call may address at most 50 recipients across `To`, `Cc` and `Bcc` combined, and the message may be up to 10 MB in size.\n\nFor demos and tests, the Mailbox Simulator is worth its weight in gold. A call to `success@simulator.amazonses.com` behaves like a successful delivery, without you running into sandbox limits or burdening real mailboxes.\n\n### Templates instead of string concatenation\n\nAs soon as more than one kind of email is involved, assembling HTML in code gets messy. SES offers server-side templates for this. You create a template once with `CreateTemplate` – with `SubjectPart`, `TextPart` and `HtmlPart`, containing placeholders in double curly braces – and then send with `SendTemplatedEmail`.\n\n```ts\nimport { SESClient, SendTemplatedEmailCommand } from \"@aws-sdk/client-ses\";\n\nconst ses = new SESClient({ region: \"eu-west-1\" });\n\nexport async function sendWelcome(email: string, name: string) {\n  const command = new SendTemplatedEmailCommand({\n    Source: \"no-reply@example.com\",\n    Destination: { ToAddresses: [email] },\n    Template: \"WelcomeTemplate\",\n    TemplateData: JSON.stringify({ name }),\n  });\n\n  return ses.send(command);\n}\n```\n\n`TemplateData` is a JSON string whose keys fill the placeholders in the template. The advantage: the text no longer lives in the deployment artifact but sits as a resource in SES and can be updated independently of the code. For many recipients at once, there is also `SendBulkTemplatedEmail` – in a transactional context, though, you rarely need it, because there one email usually goes to one person.\n\n## The incoming email hook\n\nNow we reverse the direction. The second, often overlooked capability of SES: it can receive arriving emails and turn them into an event in your architecture. This is the basis for patterns such as “an email to support@ automatically becomes a ticket.”\n\nThis is managed through a Receipt Rule Set. There can be several rule sets per account, but only one is ever active. Inside a rule set, you define individual Receipt Rules that match certain recipient addresses and work through a list of actions. Available actions include: storing in an S3 bucket, publishing to an SNS topic, invoking a Lambda Function, adding a header, a bounce or a stop.\n\nThe usual setup for a ticket flow combines two actions: first the raw email is written to S3, then a Lambda Function is triggered that takes care of the processing.\n\n```mermaid\nflowchart LR\n  A[Incoming Mail] --> B[SES Receipt Rule]\n  B --> C[S3: raw MIME]\n  B --> D[Lambda: handleInboundEmail]\n  D --> E[Ticket / DB]\n  B -.-> F[SNS Notification]\n```\n\n### The Receipt Rule as infrastructure\n\nThe Receipt Rule itself belongs in Infrastructure as Code, not in a console setup clicked together by hand – otherwise it is gone after the next account switch. As a sketch in CloudFormation-like form, a rule looks roughly like this:\n\n```yaml\nResources:\n  SupportRule:\n    Type: AWS::SES::ReceiptRule\n    Properties:\n      RuleSetName: default-rule-set\n      Rule:\n        Name: support-inbound\n        Enabled: true\n        Recipients:\n          - support@example.com\n        Actions:\n          - S3Action:\n              BucketName: inbound-mail-bucket\n          - LambdaAction:\n              FunctionArn: !GetAtt InboundFn.Arn\n              InvocationType: Event\n```\n\nTwo details matter here. The order of the actions counts: the email must first be in S3, then the Lambda Function that reads it from there is called. And `InvocationType: Event` means an asynchronous call – that is the recommended variant. The synchronous `RequestResponse` call also exists, but it has a hard timeout of 30 seconds and lets the Lambda Function control the rest of the rule flow through its return value, for example with `{ disposition: \"STOP_RULE\" }`. For a ticket handler that does not want to control the email flow anyway, `Event` is the right choice.\n\n### The handler and the most common mistake\n\nLet’s get to the handler – and to the pitfall that strikes most reliably in projects. The obvious assumption is that the Lambda event contains the email text. It does not. The event that SES passes to the Lambda Function carries only metadata and headers – sender, subject, message ID – but not the body. The complete MIME content lands in S3, and the handler has to load it from there.\n\nThe event is built around a `Records` array, with `eventSource: \"aws:ses\"` and the fields `ses.receipt` and `ses.mail`. The latter contains the processed headers under `commonHeaders` and, under `messageId`, the key under which the raw email sits in S3.\n\n```ts\nimport { S3Client, GetObjectCommand } from \"@aws-sdk/client-s3\";\nimport { Readable } from \"stream\";\n\nconst s3 = new S3Client({ region: \"eu-west-1\" });\n\nasync function streamToString(stream: Readable): Promise<string> {\n  const chunks: Buffer[] = [];\n  for await (const chunk of stream) {\n    chunks.push(Buffer.from(chunk));\n  }\n  return Buffer.concat(chunks).toString(\"utf-8\");\n}\n\nexport async function handleInboundEmail(event: any) {\n  const record = event.Records[0];\n  const mail = record.ses.mail;\n  const messageId = mail.messageId;\n\n  const raw = await s3.send(\n    new GetObjectCommand({\n      Bucket: \"inbound-mail-bucket\",\n      Key: messageId,\n    })\n  );\n\n  const mime = await streamToString(raw.Body as Readable);\n\n  // parse MIME, then create a support ticket\n  await createTicket({\n    from: mail.commonHeaders.from?.[0],\n    subject: mail.commonHeaders.subject,\n    body: mime,\n  });\n\n  return { status: \"processed\" };\n}\n```\n\nI deliberately left out the actual MIME parsing here – you use a library for that, because parsing multipart emails with attachments by hand is not a good idea. The point is the flow: headers from the event, body from S3, then the business action. The S3 object can be up to 40 MB in size.\n\n### Permissions and DNS, or nothing happens, silently\n\nThe second pitfall on the receiving side is unspectacular and therefore treacherous: without the right permissions, SES simply and silently does not process arriving email. SES needs a resource policy that allows it to write to the S3 bucket, publish to the SNS topic or invoke the Lambda Function. If one of these permissions is missing, there is no loud error message – the email just seeps away.\n\nThen there is DNS. For email to reach SES at all, the MX records of your domain must point to `inbound-smtp.<region>.amazonaws.com`. And there is a hard regional restriction: SES offers email receiving only in selected regions – as of today us-east-1, us-west-2 and eu-west-1. Lambda and SNS for the incoming flow must be in the same region as the SES endpoint. If you run the rest of your infrastructure in a different region, you have to move this part there deliberately.\n\n## Where SES fits into the larger architecture\n\nTogether, the two directions make a nice picture: Lambda is the shared compute core, SES the system boundary to the world of email. Outward, a function translates app events into emails; inward, SES translates arriving emails into function calls.\n\nIt gets interesting when the incoming hook is not the end but the beginning of a longer processing chain. A support email that gets parsed can kick off a chain of steps – classification, assignment, draft reply. This is exactly where orchestration is worth a look, as I described it in [Serverless Workflows with AWS Step Functions](https://www.mikebild.dev/en/blog/serverless-workflows-with-aws-step-functions/): the SES Lambda creates the ticket and hands over to a State Machine that coordinates the rest. That way the email hook stays small and does exactly one thing, while the domain logic gets its own traceable flow.\n\n## Conclusion\n\nThe aha moment with SES lies in the incoming direction: when it becomes clear that arriving email is not a special case but an entirely normal event trigger – just like an API call or a queue message. The outgoing side is quickly explained: verified sender, `SendEmail` or a template, keep sandbox and quota in mind. The incoming side needs more care: an active rule set, the right permissions, MX records and the knowledge that the body sits in S3 and not in the event.\n\nThe gain from this perspective is concrete. Shorter cycles, because an incoming email hook kicks off follow-up work instead of parking it in a mailbox. Less friction, because email follows the same event-driven rules as the rest of the architecture and does not stand beside it as a foreign body. Higher quality, because a modeled event is testable, loggable and orchestratable, where a loosely sent email remains a dead end. And clear limits: as soon as deliverability at scale, bounce analytics or campaigns come to the fore, a specialized provider is the more honest choice – SES shines in the transactional core. Once you have built these two patterns cleanly, you no longer think “how do I send an email” but “email is simply another event source and sink” – in and out.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-aws-serverless.en.html\n- Repository: `introduction-aws`, chapter `ses.md` and `examples/email-hook`\n- [SendEmail (SES API Reference)](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendEmail.html)\n- [SendTemplatedEmail (SES API Reference)](https://docs.aws.amazon.com/ses/latest/APIReference/API_SendTemplatedEmail.html)\n- [Creating verified identities](https://docs.aws.amazon.com/ses/latest/dg/creating-identities.html)\n- [Email receiving – concepts](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-concepts.html)\n- [Invoke Lambda action](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-action-lambda.html)\n- [Example of an incoming email event](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-action-lambda-event.html)\n- [Deliver to S3 action](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-action-s3.html)\n- [Permissions for email receiving](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-permissions.html)"},{"locale":"en","translation_key":"state-management-vergleich","slug":"state-management-in-react","title":"State Management in React: Redux Toolkit, Lightweight Stores, MobX","summary":"When state is truly app-wide, the tool question comes up – Redux Toolkit, a lightweight store such as Zustand or Jotai, or the reactive model of MobX. But why this choice only comes after the counter-check, and usually turns out smaller than expected.","tags":["Software","Frontend","React"],"published_at":"2021-10-26T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/state-management-in-react/","audio_url":null,"audio_duration_secs":null,"text":"# State Management in React: Redux Toolkit, Lightweight Stores, MobX\n\nA global store is not part of the basic equipment of a React application. It’s the exception you have to justify. That’s what the React overview said, where the question of ownership was the focus – where does a piece of state belong? What remained open there was what to use when a piece of state actually passes the justification, that is, when it really is app-wide. I had promised the comparison. Here it is.\n\n**Editorial note (July 2026):** The tools part is a snapshot from October 2021: Redux Toolkit 1.x, Zustand 3.x, Jotai 1.x and MobX 6. The more important separation is less transient: URL state, server cache and your own client state have different owners. Current versions can change the ergonomics, not these responsibilities.\n\nBefore we talk about tools, though, I have to hit the brakes. The question “Redux, Zustand or MobX?” is usually asked much too early – at a point when it isn’t even clear whether a store is needed at all. On closer inspection, the supposedly global state often turns out not to be global at all. That’s why the counter-check comes first, and only then the actual comparison.\n\nNot every kind of state needs the same storage. The choice starts with ownership, lifetime and the need for synchronization.\n\n::::comparison{title=\"Classifying state by responsibility\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Local UI state\"}\n- Owner · one component or a limited subtree\n- Lifetime · tied to the rendering\n- Examples · open dialog and input focus\n:::\n:::side{label=\"Shared client state\"}\n- Owner · several areas of the UI\n- Lifetime · within the application session\n- Examples · local selection and unsaved work in progress\n:::\n:::side{label=\"Server state\"}\n- Owner · backend or domain system\n- Lifetime · independent of the browser\n- Examples · records, permissions and approved revisions\n:::\n::::\n\nThe matrix doesn’t recommend a library. First of all, it keeps server data from being treated like local state, or short-lived UI details like global domain objects.\n\n## The counter-check first\n\nIn a project that “absolutely needed a global store,” we first wrote down everything that was supposed to go into it – and then started crossing things out. A surprisingly large part of it was really URL state: filter, page, selection or tab, insofar as they should be shareable, navigable or bookmarkable. Short-lived display details may stay local. A store that additionally holds navigable values, on the other hand, easily builds up a second truth next to the address.\n\nThe next big block is even trickier, because it looks like state and feels like state: loaded data. The list of invoices, the user profile, the search result. These are cache copies of something whose truth belongs to the backend. That calls for server cache semantics such as keys, freshness, invalidation and error states – whether a specialized library provides them or, say, RTK Query within the Redux store. The problem isn’t the physical storage location but a hand-managed slice that rebuilds these semantics.\n\nTake these two blocks out – navigable state into the address, server data into a cache – and often little is left. The real app-wide client state can be a small core: theme, language, a local draft or a shopping cart, insofar as its truth really lives in the client. Identity and permissions, on the other hand, usually come from the server; locally there is only their cache copy. For the remaining core, a store pays off, and because this core is small, the tool may be small too.\n\n```mermaid\nflowchart TB\n  Start[\"A value that looks like<br/>global state\"]\n  Start --> Global{\"Really app-wide,<br/>or only needed locally?\"}\n  Global -->|only one corner| Lokal[\"useState / useReducer<br/>in the component\"]\n  Global -->|app-wide| URL{\"Does it belong in the URL?<br/>filter, page, selection\"}\n  URL -->|yes| Adresse[\"Router / URL<br/>shareable, survives reload\"]\n  URL -->|no| Server{\"Does the truth belong<br/>to the backend?\"}\n  Server -->|yes| Cache[\"Server cache<br/>TanStack Query / SWR\"]\n  Server -->|no| Store[\"Real core: only<br/>now choose a store\"]\n```\n\nEverything depends on the order. If you start with the tool question, you fill the store with things that have no business being there and later wonder about synchronization bugs. If you start with the counter-check, you often get by with `useState` and the URL and don’t need a store at all. Only when a core remains after crossing things out is the rest of this post worth it.\n\n## Three families for the real core\n\nSuppose this core exists. Then there are roughly three schools of thought on how to hold app-wide state. I show each with a tiny example and say honestly what it costs – because none of them is free.\n\n### Redux Toolkit: the classic model, slimmed down\n\nRedux has a clear model: there is exactly one store, one central state tree. You never change it directly; you send actions – descriptive messages such as “increment” – and pure functions called reducers compute the new state from the old state plus the action. For years, this model earned Redux a reputation for being cumbersome: lots of ceremony, action types as constants, boilerplate for every little move.\n\nRedux Toolkit – RTK for short, today the officially recommended way to write Redux – takes exactly this ceremony away. A `createSlice` bundles state, actions and reducers in one piece. The reducer code is remarkable: it looks as if you were mutating the state directly, but it stays immutable internally, because RTK uses the Immer library, which turns the apparent mutations into a clean new copy.\n\n```js\nimport { configureStore, createSlice } from \"@reduxjs/toolkit\";\n\nconst cartSlice = createSlice({\n  name: \"cart\",\n  initialState: { items: [] },\n  reducers: {\n    addItem(state, action) {\n      // looks mutable, stays immutable via Immer\n      state.items.push(action.payload);\n    },\n    clear(state) {\n      state.items = [];\n    },\n  },\n});\n\nexport const { addItem, clear } = cartSlice.actions;\nexport const store = configureStore({ reducer: { cart: cartSlice.reducer } });\n```\n\n`configureStore` sets up the store with sensible defaults – the DevTools are already connected, common middleware is included. In TypeScript, you additionally create type-safe hooks once (`useAppSelector`, `useAppDispatch`) so that state and actions are typed throughout.\n\nRTK’s strength lies in traceability. Every state change is a named action that runs through a reducer – a loggable, reproducible transition. The DevTools show every action in order, allow time travel through the state history and turn “why is this value suddenly here?” into a question you can answer instead of guess. In large teams and with complex flows, that’s worth its weight in gold: the state flow is a convention everyone shares, not a matter of personal style. The price should be named just as honestly: more structure, more files, a central tree that everything runs through. For the small core of a medium-sized application, that is often more apparatus than the core deserves.\n\n### Lightweight Stores: Zustand and Jotai\n\nThe second family starts exactly there: minimal API, no forced provider, as little code as possible. Two representatives from the same ecosystem, but they think differently.\n\nZustand (yes, the library really is called that – a German word for “state” as its name) gives you a `create` function that returns a hook. From this hook you use a selector to read exactly the slice of state a component needs. The selector is the key: a component that only reads `count` doesn’t re-render when another field in the store changes. Re-renders stay granular without you having to nest context providers.\n\n```js\nimport { create } from \"zustand\";\n\nconst useCartStore = create((set) => ({\n  items: [],\n  addItem: (item) => set((state) => ({ items: [...state.items, item] })),\n  clear: () => set({ items: [] }),\n}));\n\n// in a component: read only what you need\nconst count = useCartStore((state) => state.items.length);\n```\n\nJotai approaches it from the other side. Instead of one store you read slices from, there are many small, atomic units of state – atoms – that you combine freely. An atom holds a value; derived atoms compute from other atoms. A component subscribes to exactly the atoms it reads, and nothing more.\n\n```js\nimport { atom, useAtom } from \"jotai\";\n\nconst itemsAtom = atom([]);\nconst countAtom = atom((get) => get(itemsAtom).length);\n\n// in a component\nconst [count] = useAtom(countAtom);\n```\n\nThe strength of both is obvious: very little code, fine-grained updates, a small bundle. You’re productive in minutes, and there are hardly any concepts to learn. The price is the other side of the same coin – less convention, less predefined structure. Redux forces you into a pattern; a lightweight store leaves you every freedom, including the freedom to build yourself a mess. The discipline to keep the store small and orderly, and not to dump server data into it after all, lies with the team. For the small core this is about, that is often exactly the right size.\n\n### MobX: the reactive approach\n\nThe third family thinks fundamentally differently. Redux and the lightweight stores are immutable at their core: changing state means producing a new state. MobX turns that around. You describe observable state, mutate it directly, and the library tracks on its own who reads what and updates exactly the places concerned.\n\nYou make an object observable with `makeAutoObservable`. You declare derived values as `computed` – here as getters – and they update by themselves as soon as their basis changes. Components you wrap in `observer` react specifically to exactly the observed values they read while rendering.\n\n```jsx\nimport { makeAutoObservable } from \"mobx\";\nimport { observer } from \"mobx-react-lite\";\n\nclass CartStore {\n  items = [];\n  constructor() {\n    makeAutoObservable(this);\n  }\n  addItem(item) {\n    this.items.push(item); // direct mutation is fine here\n  }\n  get count() {\n    return this.items.length; // derived, recomputes automatically\n  }\n}\n\nconst cart = new CartStore();\nconst CartBadge = observer(() => <span>{cart.count}</span>);\n```\n\nMobX shines when a lot of state is derived from other state. Where in Redux you would have to write and memoize selectors, in MobX the derived value comes about by itself and is only recomputed when its inputs change. Strikingly little code remains whose only job is to connect values. The price is implicitness: precisely because you don’t dispatch anything explicitly, the question “where does this change come from?” is harder to answer – the update happens in the background, triggered by a mutation somewhere in the code. And it’s a different mental model from the rest of the React ecosystem: targeted mutation instead of immutability. If you come from the Redux world, you have to rethink; if you think in objects, you feel at home immediately.\n\n## What to base the choice on\n\nThere’s no ranking that holds for everyone – the choice depends on a few properties of the project. The more people work on the same state, the more a fixed convention can help. For loggable transitions and rewinding the state history, the Redux DevTools are a strong but not exclusive solution. With a lot of derived state, MobX’s reactive model plays to its strengths. Add to that the bundle budget, existing tooling requirements and the team’s familiarity; hard judgments about size should be measured on the concrete build, not taken from a table.\n\nA few rules of thumb follow from this, without being laws. If the core really is small – a logged-in person, a theme, a shopping cart – [context with `useReducer`](https://www.mikebild.dev/en/blog/using-react-context-well/) or a lightweight store such as Zustand is enough, and more would be overkill. If a large team faces complex flows and wants auditable transitions, Redux Toolkit is the obvious choice, because it makes exactly this traceability a convention. If the application lives on a lot of derived state that should update in cascades, MobX is in its element. And if two options fit equally well, the team’s familiarity tips the balance.\n\n## The choice is secondary\n\nNo tool is “the best.” These comparisons are conducted with a seriousness the matter doesn’t deserve – as if the project’s success hinged on Redux versus MobX. It doesn’t. The choice of store is secondary to the question of ownership that comes before it. If you use the URL for what belongs in the URL and treat server data as a cache instead of as state, you keep the real client state so small that almost any of the three families is enough – and the decision between them shrinks to a matter of taste.\n\nThe mistake the tool debate hides is the more expensive one: building a big global store and filling it with URL state and server data that don’t belong there. No Redux Toolkit and no MobX will save you from the bugs that result. Conversely, with cleanly drawn boundaries and the simplest of the lightweight stores, you get surprisingly far. That’s why the counter-check is at the beginning of this post and not at the end: it decides more than the three-column table after it.\n\n## Further reading\n\n- Repository introduction-react (chapters react-hooks, state-management): https://github.com/mikebild/introduction-react\n- Redux Toolkit, official documentation: https://redux-toolkit.js.org/\n- Zustand: https://github.com/pmndrs/zustand\n- Jotai: https://jotai.org/\n- MobX: https://mobx.js.org/"},{"locale":"en","translation_key":"dynamodb-datenmodellierung-single-table","slug":"dynamodb-data-modeling-single-table-design","title":"DynamoDB Data Modeling: Single-Table Design","summary":"DynamoDB rewards a different way of thinking than a relational database: not starting from the data model but from the access patterns. Single-table design combines several entity types in one table through composite keys.","tags":["Software","AWS","Cloud"],"published_at":"2021-09-21T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/dynamodb-data-modeling-single-table-design/","audio_url":null,"audio_duration_secs":null,"text":"# DynamoDB Data Modeling: Single-Table Design\n\nWhen you define the partition key in DynamoDB, you have already decided which queries will be cheap later and which won’t work at all. There is no optimizer that rescues a clumsy choice after the fact, and no server-side join that connects two tables at runtime. The question “Where do I put the foreign keys?” simply has no answer – the relationship has to be in the key before the first item is written.\n\nThat turns the familiar order around. With a relational database, I first design a clean, normalized model and think about the queries later; the optimizer makes sure most queries work somehow. With DynamoDB, I first write down which questions the application will ask of the data and derive the key schema from that. The data model is the result of these patterns, not their starting point.\n\n## The three building blocks everything starts with\n\nSingle-table design stands or falls with three basic building blocks. Until they are in place, every description of the pattern hangs in the air.\n\nA DynamoDB table has a primary key in one of two forms. Either a simple primary key – just a partition key (PK, historically “hash key”). Or a composite primary key made of partition key plus sort key (SK, “range key”). In the composite variant, the combination of PK and SK must be unique per item; the PK alone may repeat. That is exactly the lever for everything else.\n\nThrough an internal hash, the partition key determines on which physical partition an item lands. The sort key orders the items within a partition and allows range conditions. All items with the same partition key form an item collection – and this item collection is the actual core of single-table design.\n\nThe `Query` API always reads exactly one item collection, that is, exactly one PK value. Optionally, a condition on the sort key narrows the result, with operators such as `=`, `<`, `<=`, `>`, `>=`, `BETWEEN` or `begins_with`. One call returns up to 1 MB; after that, you paginate via `LastEvaluatedKey`. The opposite is the `Scan`, which goes through the whole table – something I practically never want in production.\n\nSo the roles stay clear, here is the division of responsibilities at a glance:\n\n- The PK determines partition and distribution. Every query needs exactly one PK value – it decides which item collection gets read at all.\n- The SK orders and filters within the collection, through range conditions and `begins_with`. That is how I model one-to-many relationships and hierarchies.\n- A GSI (global secondary index) defines a new PK/SK combination for additional access patterns. It can be added at any time, is only eventually consistent and has its own throughput.\n\nThe LSI (local secondary index) is the contrasting case: the same PK as the base table, just an alternative SK. It supports strong consistency, but it must be defined when the table is created and binds the item collection per PK to a 10 GB limit. When in doubt, I take the GSI.\n\n## Why there is no join – and what happens instead\n\nDynamoDB has no server-side joins. That sounds like a shortcoming at first, but it is a deliberate decision for predictable latency. The trick: I don’t connect the data when reading but when writing. If different entity types carry the same partition key, they live in the same item collection and can be read together with a single query. That is pre-joining – the relationship is already built into the key schema before the first read happens.\n\nTake a small CMS with users, their posts and the comments on a post. The central access pattern is: “Get a user and all their posts in one call.” That is exactly what I derive the key design from, not from an ER diagram.\n\n```mermaid\nflowchart LR\n  A[\"Access pattern:<br/>Get user + their posts\"] --> B[\"Choose PK:<br/>USER#id\"]\n  B --> C[\"Choose SK prefix:<br/>USER# and POST#\"]\n  C --> D[\"Query on PK = USER#123<br/>returns one item collection\"]\n  D --> E[\"Result:<br/>user item + all post items\"]\n```\n\nThe direction of derivation matters: I start on the left with the pattern and work my way to the key. That is the mental move that irritates relational developers at first.\n\n## A single-table layout\n\nSingle-table design means: several entity types in a single table, held together by generic, composite keys. Instead of descriptive attribute names such as `UserId`, I deliberately use generic names such as `PK` and `SK`, because the same column carries different meanings depending on the entity type. For the CMS, a layout looks like this:\n\n```text\nPK              SK                    weitere Attribute\n--------------  --------------------  -----------------------------\nUSER#123        USER#123              name, email, createdAt\nUSER#123        POST#2021-09-01T...   title, body, status\nUSER#123        POST#2021-09-14T...   title, body, status\nPOST#987        COMMENT#2021-09-15..  author, text\nPOST#987        COMMENT#2021-09-16..  author, text\n```\n\nThe user and their posts share the partition key `USER#123` and thus form one item collection. The user item has an SK that repeats the PK (`USER#123`); the posts use the prefix `POST#` followed by a timestamp. As a bonus, the timestamp in the sort key sorts the posts chronologically – without any additional index.\n\nFor the pattern “Get all comments on a post”, the primary index isn’t enough, because comments are sensibly grouped under a different PK. This is where a GSI comes into play. I add the attributes `GSI1PK` and `GSI1SK` and project an index over them that makes post-to-comment readable in reverse. That is the idea of the inverted index: a GSI with swapped roles to read a relationship from the opposite direction.\n\nI define the table itself with generic keys and one GSI. An excerpt of the `CreateTable` parameters:\n\n```json\n{\n  \"TableName\": \"cms\",\n  \"BillingMode\": \"PAY_PER_REQUEST\",\n  \"AttributeDefinitions\": [\n    { \"AttributeName\": \"PK\", \"AttributeType\": \"S\" },\n    { \"AttributeName\": \"SK\", \"AttributeType\": \"S\" },\n    { \"AttributeName\": \"GSI1PK\", \"AttributeType\": \"S\" },\n    { \"AttributeName\": \"GSI1SK\", \"AttributeType\": \"S\" }\n  ],\n  \"KeySchema\": [\n    { \"AttributeName\": \"PK\", \"KeyType\": \"HASH\" },\n    { \"AttributeName\": \"SK\", \"KeyType\": \"RANGE\" }\n  ],\n  \"GlobalSecondaryIndexes\": [\n    {\n      \"IndexName\": \"GSI1\",\n      \"KeySchema\": [\n        { \"AttributeName\": \"GSI1PK\", \"KeyType\": \"HASH\" },\n        { \"AttributeName\": \"GSI1SK\", \"KeyType\": \"RANGE\" }\n      ],\n      \"Projection\": { \"ProjectionType\": \"ALL\" }\n    }\n  ]\n}\n```\n\n`BillingMode: PAY_PER_REQUEST` is the on-demand mode, available since the end of 2018. I like to use it for examples and fluctuating load because I don’t have to worry about reserving capacity in advance. For a GSI, I deliberately choose via `ProjectionType` which attributes come along – `KEYS_ONLY`, `INCLUDE` or `ALL`. `ALL` is convenient but costs more storage and write throughput.\n\n## The query over an item collection\n\nNow the part that justifies all the modeling. With SDK v3 and the `DynamoDBDocumentClient` from `@aws-sdk/lib-dynamodb`, I get all of a user’s posts with exactly one call:\n\n```ts\nimport { DynamoDBClient } from \"@aws-sdk/client-dynamodb\";\nimport { DynamoDBDocumentClient, QueryCommand } from \"@aws-sdk/lib-dynamodb\";\n\nconst client = DynamoDBDocumentClient.from(new DynamoDBClient({}));\n\nasync function getPostsByUser(userId: string) {\n  const result = await client.send(\n    new QueryCommand({\n      TableName: \"cms\",\n      KeyConditionExpression: \"PK = :pk AND begins_with(SK, :prefix)\",\n      ExpressionAttributeValues: {\n        \":pk\": `USER#${userId}`,\n        \":prefix\": \"POST#\",\n      },\n    })\n  );\n\n  return result.Items ?? [];\n}\n```\n\nThe `KeyConditionExpression` addresses exactly one item collection via `PK = :pk` and cuts out the posts with `begins_with(SK, :prefix)`. DynamoDB only reads the items that match `POST#` – the prefix acts directly on the sort key, not as an after-the-fact filter. If I want the user together with all posts, I drop the `begins_with` condition and get the complete collection in one go.\n\nFor the reverse pattern via the inverted index, little changes. I address the GSI and use its keys:\n\n```ts\nasync function getCommentsByPost(postId: string) {\n  const result = await client.send(\n    new QueryCommand({\n      TableName: \"cms\",\n      IndexName: \"GSI1\",\n      KeyConditionExpression: \"GSI1PK = :g AND begins_with(GSI1SK, :prefix)\",\n      ExpressionAttributeValues: {\n        \":g\": `POST#${postId}`,\n        \":prefix\": \"COMMENT#\",\n      },\n    })\n  );\n\n  return result.Items ?? [];\n}\n```\n\nAt its core, this is the same query mechanism, just on a different index. If you have understood the primary pattern, you can transfer it to the GSI without any adjustment.\n\n## The pitfall with FilterExpression\n\nThe `FilterExpression` looks like a cheap shortcut, but it isn’t one. Unlike the `KeyConditionExpression`, it only filters after the items have been read. That means I also pay the read capacity units for the items the filter then throws away. Worse still, combined with `Limit`, I can get empty pages back even though matching data exists – because the limit applies before the filter.\n\nThe consequence is clear: selectivity belongs in the key design, not in the filter. If I often filter by a criterion, that criterion should move into the sort key or into a GSI. I only use `FilterExpression` for rare, non-critical refinements at the edges.\n\n## When single-table pays off – and when it’s overkill\n\nAs elegant as the pattern is, it isn’t an end in itself. Single-table design also gets introduced where it mainly looked impressive in a conference talk – and then saddles the application with complexity that nobody pays back. That’s why an honest look at the motivation is worth it.\n\nSingle-table pays off when the access patterns are stable and known and when it matters to read a lot of related data with as few round trips as possible. The gain is performance and scaling with predictable latency, not storage savings. I deliberately accept data duplication and denormalization – that is a feature, not an accident.\n\nThe approach is overkill in several situations:\n\n- The access patterns are still unclear early in the project or change frequently. Single-table makes later changes to the patterns expensive, because the key schema is anchored deep in the data.\n- The application needs ad-hoc evaluations or analytics. Without SQL, the export and reporting story gets tedious, and a single-table layout with many entity types doesn’t make it easier.\n\nAlex DeBrie, whose writing on DynamoDB I like to pass on, names another case: GraphQL. A GraphQL server resolves fields individually via resolvers anyway, so the big advantage of loading everything with one query fizzles out. There, a multi-table approach often gives more flexibility. I described how GraphQL and DynamoDB work together concretely on AWS in [GraphQL APIs with AppSync and DynamoDB](https://www.mikebild.dev/en/blog/graphql-apis-with-appsync-and-dynamodb/).\n\nA technical detail that becomes a problem with many entity types in one table is DynamoDB Streams: AWS recommends running no more than two concurrent consumers per shard, otherwise throttling effects loom. When different entities need different processing logic, you quickly end up wanting more consumers than a stream can handle.\n\n## A word on the hard limits\n\nSo the modeling doesn’t fail because of physical limits, I keep a few numbers in mind that hold steady in 2021. An item may be at most 400 KB in size. A query returns at most 1 MB per call; after that, you paginate. `BatchGetItem` fetches up to 100 items or 16 MB. By default, up to 20 GSIs and a maximum of 5 LSIs are possible per table. These limits force deliberate design – for example, not letting very large or unboundedly growing item collections come into being in the first place.\n\n## Conclusion\n\nThe decisive rebuild happens in your head, not in the code. If you treat DynamoDB like a relational database, you fight against the system. If you start with the access patterns and derive the partition key, sort key and suitable GSIs from them, you work with it. Single-table design then follows from the wish to read related data with one query and without a join – and not from the appeal of the pattern itself.\n\nPragmatically, the way leads through three steps: first write down the access patterns, then design the key schema, then check whether a single primary index plus a few GSIs covers the patterns. If the patterns are still shaky or ad-hoc analyses are central, a simpler multi-table layout is the more honest choice. The goal is never the most elegant diagram, but the application that stays predictable under load.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-aws-serverless.en.html\n- Repository and accompanying article: [GraphQL APIs with AppSync and DynamoDB](https://www.mikebild.dev/en/blog/graphql-apis-with-appsync-and-dynamodb/)\n- AWS Docs, Core Components (tables, items, keys, item collections): https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html\n- AWS Docs, Query API: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html\n- AWS Docs, Global Secondary Indexes: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html\n- AWS Docs, Local Secondary Indexes: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LSI.html\n- AWS Docs, best practices and relational modeling: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-relational-modeling.html\n- Alex DeBrie, “The What, Why, and When of Single-Table Design”: https://www.alexdebrie.com/posts/dynamodb-single-table/\n- Alex DeBrie, “How to model one-to-many relationships”: https://www.alexdebrie.com/posts/dynamodb-one-to-many/\n- AWS Database Blog, “Single-table vs. multi-table design in Amazon DynamoDB”: https://aws.amazon.com/blogs/database/single-table-vs-multi-table-design-in-amazon-dynamodb/"},{"locale":"en","translation_key":"cdn-construct-infrastruktur-api","slug":"cdn-construct-a-small-infrastructure-api","title":"CDN Construct: A Small Infrastructure API","summary":"Why a custom CDK construct for static websites is more than saved lines: an opinionated interface over S3, CloudFront, certificates and DNS.","tags":["Software","AWS","Cloud"],"published_at":"2021-09-14T10:00:00+00:00","updated_at":"2026-07-14T17:16:42.516469+00:00","url":"https://www.mikebild.dev/en/blog/cdn-construct-a-small-infrastructure-api/","audio_url":null,"audio_duration_secs":null,"text":"# CDN Construct: A Small Infrastructure API\n\nAround 280 lines of CloudFormation, spread across two stacks in two regions – that was recently the price of rolling out a static website “properly” on AWS. Fourteen resources for a handful of HTML files: an S3 bucket, a bucket policy, an origin access identity, a CloudFront distribution with cache and error behavior, an ACM certificate including DNS validation – mandatory in us-east-1, hence the second stack – plus A and AAAA alias records in Route53. None of this is difficult on its own. But all of it together is wiring that comes up again with every new project and turns out a little bit different each time.\n\nIt was exactly this repetition that made me pack the whole chain into a small AWS CDK construct of my own: `cdk-cdn-construct`. Static content – a single-page application or a classic static website – lands in an S3 bucket and is delivered via CloudFront as a CDN. The call in your own stack shrinks to a few lines. That is the visible gain. The more interesting gain is a different one, and that is what this article is about: a good construct is an opinionated interface. It makes decisions explicit that were previously hidden in copy-and-paste templates, and it leaves free exactly the knobs that really vary from project to project.\n\n## What actually gets wired up\n\nBefore the abstraction holds, it is worth looking at what it encapsulates. A static website behind CloudFront consists of more parts than the sentence “S3 bucket with a CDN in front” suggests:\n\n- a private S3 bucket with Block Public Access fully enabled\n- an origin access identity (OAI) through which CloudFront – and only CloudFront – gets read access to the bucket\n- the matching bucket policy that allows exactly this identity `s3:GetObject`\n- a CloudFront distribution with enforced HTTPS, a default root object and sensible error behavior for client-side routing\n- an ACM certificate in us-east-1 including DNS validation\n- A and AAAA alias records in the Route53 zone that point to the distribution\n- the actual upload of the build output, including cache invalidation after the deployment\n\nAs a diagram, the wiring looks like this:\n\n```mermaid\nflowchart LR\n  Browser[Browser] -->|HTTPS| CF[CloudFront distribution]\n  CF -->|only via OAI| S3[S3 bucket<br/>private, Block Public Access]\n  ACM[ACM certificate<br/>us-east-1] -.->|TLS| CF\n  R53[Route53<br/>A/AAAA alias] -.->|resolves domain| CF\n  Build[Build output<br/>e.g. ./build] -->|Upload + invalidation| S3\n```\n\nEach of these edges is a decision. The bucket could also be public and offer website hosting directly – then no OAI would be needed, but the bucket would be reachable bypassing the CDN, and HTTPS on your own domain would be gone. The certificate could be imported instead of DNS-validated. The error pages could point to `404.html` instead of `index.html`. In handwritten templates, none of these decisions appear anywhere as a decision. They appear as 280 lines of YAML, and you can’t tell from them whether a deviation is intent or accident.\n\n## From template to API\n\nWith its construct levels, the AWS CDK offers a usable vocabulary for this. L1 constructs are generated one-to-one images of the CloudFormation resources. L2 constructs are handwritten classes with defaults and helper methods – `Bucket` instead of `CfnBucket`. And L3 constructs, also called patterns in the documentation, bundle several resources into a pattern with intent. Since last year, AWS itself has maintained a whole library of such patterns with the Solutions Constructs.\n\nMy construct is such an L3 building block, technically implemented as its own stack so it can be plugged into an existing CDK app as a whole. Using it looks like this:\n\n```typescript\n#!/usr/bin/env node\nimport { App } from '@aws-cdk/core';\nimport { CdkCdnConstructStack } from 'cdk-cdn-construct';\n\nconst app = new App();\n\n// ... your own stacks ...\n\nnew CdkCdnConstructStack(app, 'MyWebsite', {\n  namespace: 'my-app-namespace',\n  env: {\n    account: process.env.CDK_DEFAULT_ACCOUNT,\n    region: process.env.CDK_DEFAULT_REGION,\n  },\n});\n```\n\nWhat stays configurable from outside deliberately follows a plain convention via environment variables – name, build directory, domain:\n\n```\nCDK_DEFAULT_REGION=eu-central-1\nCDK_DEFAULT_ACCOUNT=default\nCDK_CDN_NAME=your-host-and-bucket-name\nCDK_CDN_PATH=./build\nCDK_CDN_DOMAIN=example.com\n```\n\nThat is the entire public surface. No switch for the distribution’s price class, none for TTLs, none for the question of whether the bucket should be public after all. That isn’t laziness but the heart of the matter. An opinionated interface says: these points are decided, and decided this way. If you need a different opinion, you shouldn’t thread it through a parameter but take a different construct – or write your own.\n\nTo be honest, the project is a work in progress, a building block from my own workshop and not a polished product. But that is exactly why it works as illustrative material: the question of which knobs an infrastructure API leaves free comes up with a small construct just as it does with a large platform – except that here, you can still discuss it during a coffee break.\n\n## A look inside\n\nInside, exactly what used to be in the template happens – just once, named and with defaults you can read in a code review. With the CDK v1 building blocks, the core can be sketched like this:\n\n```typescript\nconst originAccessIdentity = new cloudfront.OriginAccessIdentity(this, 'WebsiteOAI');\n\nconst websiteBucket = new s3.Bucket(this, 'WebsiteBucket', {\n  blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,\n});\nwebsiteBucket.grantRead(originAccessIdentity);\n\nconst certificate = new acm.DnsValidatedCertificate(this, 'WebsiteCertificate', {\n  domainName: props.domainName,\n  hostedZone: props.hostedZone,\n  region: 'us-east-1', // CloudFront accepts ACM certificates from us-east-1 only\n});\n\nconst distribution = new cloudfront.Distribution(this, 'WebsiteDistribution', {\n  defaultBehavior: {\n    origin: new origins.S3Origin(websiteBucket, { originAccessIdentity }),\n    viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,\n  },\n  domainNames: [props.domainName],\n  certificate,\n  defaultRootObject: 'index.html',\n});\n\nnew route53.ARecord(this, 'WebsiteAliasRecord', {\n  zone: props.hostedZone,\n  recordName: props.domainName,\n  target: route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)),\n});\n```\n\nI find three details remarkable here, because they show what an L2/L3 cut actually achieves compared to raw CloudFormation.\n\nFirst: `websiteBucket.grantRead(originAccessIdentity)` is one line. Behind it is the complete bucket policy with the OAI’s canonical principal – a piece of JSON that, back in template days, I regularly copied from the last project, including the opportunity to drag something along in the process. The method expresses the intent (“this identity may read”), not the mechanism.\n\nSecond: `DnsValidatedCertificate` with an explicit `region: 'us-east-1'`. CloudFront only accepts certificates from this one region, no matter where the rest of the stack lives. If you overlook this the first time, the deployment gives you an error message that points to the certificate but not to the cause – that happened to me back then with a certificate in eu-central-1, and the search cost half an afternoon. In the construct, this stumbling block is now a commented line. A colleague pointed at exactly that in a review and asked why the region is hardwired – and that very conversation is the point: the rule now lives in one place where you can discuss it, instead of being copied implicitly right or wrong in three projects.\n\nThird: the alias record is created in the same go as the distribution. In the template world, DNS entries were often the manual leftover, “we’ll do that later in the console” – and three months later, nobody knew why the staging environment pointed to a deleted distribution. When the record is part of the same building block, that leftover doesn’t exist.\n\n## Defaults are opinion, not magic\n\nThe usual objection to such building blocks is: abstraction hides what happens, and in the cloud, hidden quickly means expensive or insecure. The objection hits bad constructs, but it doesn’t hit the principle. The difference lies in whether the defaults are implicit or explicit.\n\nA copied template has defaults too – they just aren’t called that. They are whatever the author of the first template considered right two years ago, spread across 280 lines, without a name and without a reason. A construct, on the other hand, forces a decision: What is fixed? What is a parameter? What is deliberately not provided for? Answering these three questions cleanly once cost me more time when building the construct than the actual wiring – and it was the better-invested time.\n\nFor the CDN building block, the fixed opinions are, for example: the bucket is private, always. Delivery happens exclusively via CloudFront, always over HTTPS. The certificate is validated via DNS and lives where CloudFront demands it. What stays free are the domain, the namespace and the path to the build output – exactly the things that actually distinguish two projects. Opening up everything else would only shift the repetition: if you pass twenty parameters through, you end up with CloudFormation again, just with different brackets.\n\nThere is a limit here that I underestimated at first: a construct is an API, and infrastructure APIs have stricter compatibility rules than library APIs. If I rename a class in a library, builds break. If I change the structure in a construct, the logical IDs of the resources may change – and CloudFormation then replaces things instead of changing them. With an S3 bucket that has content, that isn’t a theoretical concern. Versioning a construct therefore doesn’t just mean assigning semantic version numbers, but keeping track of which changes trigger a replacement. That isn’t in any type system, and that is exactly why it belongs in the building block’s opinion.\n\n## When a custom construct pays off\n\nYou don’t have to build this wheel yourself. The AWS Solutions Constructs cover the “CloudFront to S3” pattern, and for many teams that is the right choice. In my view, a custom construct pays off when the opinion you want to encapsulate is more specific than that of a generic building block: your own naming conventions, a fixed deploy convention via environment variables, a specific error behavior for single-page applications, the in-house tagging requirement. In other words, whenever you notice that you readjust the generic building block in every project with the same five tweaks – then those five tweaks are the actual construct.\n\nThe process to get there follows a simple flow that you can also read as a cycle:\n\n```mermaid\nflowchart TD\n  A[Wiring in the project<br/>typed for the second time] --> B[Name decisions:<br/>fixed, parameter, excluded]\n  B --> C[Extract construct<br/>with minimal prop surface]\n  C --> D[Use it in two projects]\n  D --> E{Readjusted?}\n  E -->|yes, always the same| B\n  E -->|no| F[Opinion holds]\n```\n\nThe order matters: first experience the repetition, then extract. A construct created before the second project doesn’t encapsulate experience but a guess – and you recognize guesses with twenty parameters by the fact that they don’t dare to commit to anything.\n\nConversely: not every repetition deserves an abstraction. Two similar stacks are cheaper than a bad shared construct that grows a switch with every deviation. The honest question is whether the opinion is stable. For “static website behind CloudFront”, I’m sure of that by now – the pattern hasn’t moved across several projects; only the domains and build directories have changed. That is exactly the profile where the extraction pays for itself.\n\n## The bottom line\n\n280 lines in two regions become one import, one constructor call and five environment variables. That calculation is real, but it isn’t the actual return. The actual return is that the infrastructure decision now has an address. When someone asks why the bucket is private, why the certificate lives in us-east-1 or why there is no TTL switch, the answer points to a place in the code – with a name, a comment and Git history. Before, it pointed to a template that was copied somewhere at some point.\n\nFor a long time, I treated infrastructure as something you describe and application code as something you design. The CDK removes this separation, and a small construct of your own is the point where you really feel it: suddenly the familiar questions of API design – what is public, what is a default, what is excluded, what breaks with a change – apply to buckets and distributions just as they do to classes and modules. Building a small infrastructure API is therefore less a DevOps topic than an entirely normal design exercise. Except that here, a bad default doesn’t end in an exception but in a bill or a public bucket.\n\n## Further reading\n\n- Project repository: [github.com/MikeBild/cdk-cdn-construct](https://github.com/MikeBild/cdk-cdn-construct)\n- AWS CDK v1: [Construct Library](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-construct-library.html)\n- CloudFront: [Restricting access to S3 origins with an origin access identity](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html)\n- ACM: [Supported regions – certificates for CloudFront in us-east-1](https://docs.aws.amazon.com/acm/latest/userguide/acm-regions.html)\n- AWS Solutions Constructs: [github.com/awslabs/aws-solutions-constructs](https://github.com/awslabs/aws-solutions-constructs)"},{"locale":"en","translation_key":"outcome-vor-output","slug":"outcome-before-output","title":"Outcome Before Output: Why Velocity Is the Wrong Number","summary":"Completed tickets are output, but not yet evidence of impact. Why velocity misleads in management reporting and how to align teams with outcomes instead.","tags":["Software","Product"],"published_at":"2021-08-26T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/outcome-before-output/","audio_url":null,"audio_duration_secs":null,"text":"```typescript\n// Sprint-Report, wie er im Statusdeck landet\nconst sprint42 = {\n  storyPointsCommitted: 34,\n  storyPointsCompleted: 38,\n  ticketsDone: 17,\n  velocityTrend: \"up\",\n};\n```\n\nExactly one statement follows from this object: the team completed more points than it had committed to. Whether a user reaches their goal faster as a result, whether a system runs more reliably, whether revenue is generated anywhere – there is no field for that here, and you can’t compute one in after the fact. Still, exactly this curve travels into reports sprint after sprint, gets compared between two teams and occasionally ends up on a board slide next to revenue.\n\nThe question that actually counts isn’t “How many story points did the team complete?” but “What changed for the user, for the system, for the business as a result?” That’s the difference between output and outcome. And if you blur it, you systematically optimize a team for being busy instead of having an impact.\n\nThe dividing line runs between an observed activity and the demonstrable change that follows from it.\n\n::::comparison{title=\"Activity and impact answer different questions\" role=\"primary\" preferredPattern=\"split-comparison\"}\n:::side{label=\"Output\"}\n- Observation · What was built or completed?\n- Examples · Features, tickets and story points\n- Use · Planning and tracking the work\n- Limit · Doesn’t yet prove any change for the user\n:::\n:::side{label=\"Outcome\"}\n- Observation · What changed in behavior or results?\n- Examples · Activation, time to first value and error rate\n- Use · Checks whether a solution contributes to the goal\n- Limit · Needs context and a robust measurement\n:::\n::::\n\nThis keeps velocity useful as an internal planning measure without turning it into a statement about productivity or business value.\n\n## Velocity measures predictability, not productivity\n\nLet’s start at the source, because velocity has gotten a bad reputation it doesn’t deserve. Almost two decades ago, Martin Fowler described precisely what the number was meant for: a calibration tool for estimates. The principle is called “Yesterday’s Weather” – we assume that a team will get about as much done in the next sprint as in the last one. That keeps plans realistic without anyone making heroic commitments.\n\nStory points are a team-specific baseline. They mean something different for team A than for team B, because they are estimated relative to each context. That’s exactly why comparing two teams by their velocity isn’t just imprecise but simply meaningless – you compare two different units of measurement and pretend they are the same.\n\nAnd then the predictable happens. As soon as velocity becomes a management target, it gets gamed. Teams estimate more generously, split tickets more finely, declare minor things a story. The curve rises, delivery stays the same. That isn’t malice, it’s Goodhart’s Law in its purest form: “When a measure becomes a target, it ceases to be a good measure.” Any number you elevate to a measure of success stops being honest at that very moment.\n\nSo I don’t want to demonize velocity at all. Internally, as an aid for planning and forecasting, it’s completely legitimate and useful. The mistake isn’t in the number but in promoting it to a measure of success. That’s an important distinction that tends to get lost in the heat of the “velocity is evil” debates.\n\n## True output is impact – and you can’t measure it directly\n\nFowler’s truly radical point comes next: “True output is business value.” A team’s real yield isn’t the number of features but the value created. His example sums it up: a team that delivers fewer features but generates ten million in profit is more productive than one with more features and five million in value.\n\nThe catch is sobering. Business value lags behind the investment, often by years. What a team builds today pays off – if at all – only later, intertwined with the market, sales, timing and a dozen other factors. An immediate, clean measurement of productivity is therefore simply impossible. Fowler’s honest conclusion: “We have to admit our ignorance.” We can’t measure productivity directly. Period.\n\nThat sounds discouraging, but it’s liberating. Because if the perfect number doesn’t exist, we stop looking for it and turn to what we can actually influence and observe: the impact of our work on users and the system.\n\n## Outcome instead of output: the core of modern product work\n\nThis is exactly where the product side comes in. In her work on continuous discovery, Teresa Torres draws a clean distinction: outputs are what we build – features, screens, endpoints. Outcome is the change in user behavior that creates value for the customer and the business. If you declare outputs the goal, you produce a “disconnect” between the team’s activity and the value delivered. The team is fully utilized, the board is full, and still nothing moves for the user.\n\nMarty Cagan puts the same observation even more sharply: “Empowered teams get outcomes, feature teams get output.” A feature team is handed a roadmap and works through it – output. An “empowered” team gets a problem and an outcome goal and is allowed to figure out for itself how to get there. The difference isn’t cosmetic. It decides whether people think along or just work through a list.\n\nThe tool I have had the best experience with here is the Opportunity Solution Tree. At the root sits exactly one outcome, for example “increase the activation rate by X percent.” Below it branch out opportunities – concrete user problems or needs that contribute to this outcome. Below those come solutions, and at the very bottom the experiments we use to check whether a solution actually works. The tree forces the question the velocity curve never asks: Does what we are building right now contribute to the root at all?\n\n```mermaid\ngraph TD\n    subgraph output[\"Output view (vanity)\"]\n        B[Backlog] --> S[Sprint]\n        S --> V[\"Velocity chart<br/>many completed tickets\"]\n        V --> U[\"up and to the right\"]\n    end\n    subgraph outcome[\"Outcome view\"]\n        O[\"Outcome<br/>activation rate +X%\"] --> OP1[Opportunity A]\n        O --> OP2[Opportunity B]\n        OP1 --> SOL[Solution]\n        SOL --> EXP[Experiment]\n    end\n    V -. \"does the output move<br/>the root?\" .-> O\n```\n\nThe diagram shows the two worlds side by side. On the left, the output pipeline that reliably points upward. On the right, the tree that makes impact traceable. The dashed arrow in between is the real management question – and exactly this arrow is missing almost entirely from the reports I get to see.\n\n## Vanity metrics: the engineering version of self-deception\n\nEric Ries coined the term vanity metrics for this kind of number in the Lean Startup context. Sign-ups, page views, downloads – numbers that go “up and to the right” and feel good without proving real progress. Velocity and completed tickets are the engineering version of exactly this pattern. They rise reliably, they create a good feeling, and they say nothing about whether we have gotten closer to the goal.\n\nOn the other side are actionable metrics: numbers that show a cause-and-effect relationship and lead to a decision. For Ries, the unit of progress isn’t “feature shipped” but “validated learning” – confirmed learning about what actually works for the user. The framework for this is called innovation accounting, the cycle Build-Measure-Learn.\n\nIn practice, this means: you don’t instrument what you built, you instrument what the user does in response. An event that tracks an outcome looks different from one that counts output.\n\n```typescript\n// Actionable: measures what actually moves the user\ntrack(\"activation_completed\", {\n  userId,\n  cohort,\n  timeToValueSeconds, // how fast does the user reach first value?\n});\n\n// Vanity: feels like progress, says nothing about impact\n// track(\"features_shipped\", { count });\n// track(\"story_points_done\", { total });\n```\n\nThe decisive step comes next: you roll out the feature behind a flag and compare the outcome delta between two cohorts. Does the new solution measurably increase the activation rate, or not? That’s Build-Measure-Learn in one line of infrastructure – and it shifts the question of success from “did we build it?” to “did it work?”\n\n## Better proxies: DORA and fitness functions\n\nAt this point, someone usually chimes in: But there’s DORA. The four key metrics from the Accelerate research by Forsgren, Humble and Kim – Deployment Frequency, Lead Time for Changes, Change Failure Rate and Time to Restore Service – are a big step forward. They deliberately measure team outcomes instead of individual outputs. Explicitly no lines of code, no story points, no utilization, because those are siloed activity numbers. And they balance speed against stability, so you can’t optimize one number at the expense of the whole system.\n\nDORA helps, with one caveat: these metrics are proxies too, not real outcomes. Deployment frequency isn’t user impact. A team can deploy fifty times a day and still miss what’s needed. DORA measures the ability to deliver quickly and stably – an excellent indicator of delivery health, but not the goal itself. If you confuse the two, you have just replaced one vanity number with four.\n\nAt the architecture level, there is an instrument that is particularly close to my heart, because it makes outcome executable: fitness functions from Evolutionary Architecture by Ford, Parsons and Kua. A fitness function is an objective, automated assessment of an architectural property. Instead of checking off “performance improved” in a ticket, you write a test that checks the system’s effect itself:\n\n```python\ndef test_checkout_latency_stays_within_budget():\n    \"\"\"Architectural fitness function: checkout stays fast under load.\"\"\"\n    result = load_test(endpoint=\"/checkout\", concurrent_users=200)\n\n    assert result.p99_ms < 500       # latency budget, not a story point\n    assert result.error_rate < 0.01  # reliability is the real outcome\n```\n\nThe beauty of it: success is no longer a status update here but a measurable system property that is either maintained or not. The test is green because the system delivers the promised effect – not because someone moved a story to “done.” Consumer-Driven Contracts work in a similar way, for example with Pact: a test fails when a service breaks a promise to its consumer. That, too, is a test close to the outcome – it checks the actual effect at the interface instead of the mere existence of code.\n\n## How to really align teams with outcomes\n\nWhen I set this up in an organization, I follow a simple process. It’s deliberately lean, because the whole point of the exercise is to replace process overhead with clarity, not to create new ceremonies.\n\n```mermaid\nflowchart LR\n    A[\"Define the outcome<br/>one goal, measurable\"] --> B[\"Opportunities<br/>map user problems\"]\n    B --> C[\"Experiments<br/>behind feature flags\"]\n    C --> D[\"Measure impact<br/>cohort delta\"]\n    D -->|\"works\"| E[\"scale\"]\n    D -->|\"does not work\"| B\n```\n\nIt starts with exactly one outcome, phrased as a measurable change in behavior – not “ship the checkout redesign” but “reduce the checkout abandonment rate.” The idea of a North Star Metric fits here and, at the goal level, OKRs: the objective describes the direction, and the key results are the outcome signals by which we recognize progress.\n\nThe second step collects the opportunities: Where do users actually drop off, where does friction arise? Only then come solutions, and they aren’t rolled out and checked off but tested as an experiment behind a flag. If the cohort delta shows an effect, we scale. If it doesn’t, we go back to the opportunities – without a guilty conscience, because a disproven experiment is validated learning and therefore a result in itself.\n\nAn important caveat belongs here, otherwise you walk into the next trap. Goodhart applies to outcome KPIs too. An activation rate can be gamed as well, and the time lag from Fowler’s observation remains: impact takes time, and attribution is rarely clear-cut. If you set an outcome goal, you have to factor in this fuzziness instead of defining it away – otherwise you construct false causalities and are no further along than with the velocity chart.\n\n## Conclusion\n\nThe common thread through all of this is simple: output is necessary, but impact is the goal. Completed tickets, story points and velocity describe work and planning – not whether anything improved for users or the business. As an internal planning aid, they are legitimate; as a measure of success for management, they steer in the wrong direction, because a target number gets optimized and being busy doesn’t yet prove impact.\n\nThe way out isn’t a better single number but an attitude. We align teams with a measurable outcome, make impact visible through actionable metrics, fitness functions and experiments, and treat DORA as what it is – a good proxy for delivery capability, not the goal. In my experience, the result isn’t a heavier process but a lighter one: shorter cycles, because we abandon wrong paths early; less friction, because teams are allowed to decide for themselves; and higher quality, because success depends on impact and not on the status color of a ticket.\n\nFowler’s sober admission remains the best starting point: we can’t measure productivity directly. But we can stop celebrating the wrong number and start asking the right question – does what we build move the root at all?\n\n## Further reading\n\n- Martin Fowler: [CannotMeasureProductivity](https://martinfowler.com/bliki/CannotMeasureProductivity.html) and [XpVelocity](https://martinfowler.com/bliki/XpVelocity.html)\n- Teresa Torres: [Continuous Discovery Habits](https://www.goodreads.com/book/show/58046715-continuous-discovery-habits) (2021)\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate* (2018); [Four Keys to measure DevOps performance](https://cloud.google.com/blog/products/devops-sre/using-the-four-keys-to-measure-your-devops-performance)\n- Eric Ries: [The Lean Startup – Principles](https://theleanstartup.com/principles) (2011)\n- Neal Ford, Rebecca Parsons, Patrick Kua: [Building Evolutionary Architectures – Fitness Functions](https://www.oreilly.com/library/view/building-evolutionary-architectures/9781491986356/ch02.html) (2017)"},{"locale":"en","translation_key":"datenanalyse-mit-pandas","slug":"data-analysis-with-numpy-pandas-and-matplotlib","title":"Data Analysis with NumPy, Pandas, and Matplotlib","summary":"From raw data to insight: how NumPy, pandas, and Matplotlib work together – vectorized computation, groupby aggregation, and a quick plot in a small pipeline.","tags":["Software","Python","Data"],"published_at":"2021-08-24T10:00:00+00:00","updated_at":"2026-07-13T10:03:09.962873+00:00","url":"https://www.mikebild.dev/en/blog/data-analysis-with-numpy-pandas-and-matplotlib/","audio_url":null,"audio_duration_secs":null,"text":"A `DataFrame` is not a spreadsheet and not a database table. It is a collection of typed columns in memory, each of them a NumPy array, all tied together by a shared index. This origin explains almost everything that surprises you later: why looping over individual rows is so expensive, why a selection sometimes returns a view of the original data and sometimes a copy, and why a `groupby` does in a single expression what would otherwise take a loop plus a cache.\n\nStill, the first reflex when you face a CSV file with a few hundred thousand rows is the Python loop. Open it, walk through it line by line, sum up the values, print the result. That works – for a hundred rows. With a million rows, you end up waiting and wondering why it takes so long.\n\nThe loop question is actually the smaller one. The bigger one is decided further up: an analysis is rarely an end in itself. In the end, a decision depends on it. A price gets adjusted, a budget gets shifted, a region gets expanded or scaled back. So the value of an analysis is not measured by how elegantly it computes but by how reliably its result supports a decision. And that is where the real risk lies: not in the runtime, but in whether the final number is right and whether I can produce the same number again tomorrow.\n\nThe toolkit of NumPy, pandas, and Matplotlib is the answer to this requirement, not just to the speed problem. Together, the three libraries form a path from raw data to the finished chart, and each takes on a clearly defined job. What matters is that this path becomes repeatable: the same code, the same raw data, the same result, no matter who runs it. In this article, I walk the whole path once: first fast computation with NumPy, then structured tables with pandas, and finally visualization with Matplotlib. At the end, there is a small pipeline that loads, cleans, groups, and plots. I focus less on individual function calls and more on the places where an analysis gains or loses its reliability. If you are still wondering how the data gets into your program in the first place, [Reading Data in Python](https://www.mikebild.dev/en/blog/reading-data-in-python/) covers the basics.\n\n## Why not a Python loop? NumPy and the ndarray\n\nAt the core of NumPy is a single data type: the `ndarray`. At first glance, it looks like a list, but the difference lies in memory. A Python list holds references to arbitrary objects scattered somewhere in memory. An `ndarray` is homogeneously typed and stored contiguously – all elements have the same data type and sit right next to each other.\n\nThis layout is the prerequisite for what makes NumPy fast: vectorized operations. Instead of iterating over individual elements in Python, the whole computation is handed off to compiled C code. An example makes the difference clear.\n\n```python\nimport numpy as np\n\nvalues = np.arange(1_000_000)   # 0, 1, 2, ... 999999\nresult = values * 2 + 1         # vectorized, no Python loop\ntotal = result.mean()\n\nprint(result.shape)             # (1000000,)\nprint(result.dtype)             # int64\nprint(total)                    # 1000000.0\n```\n\nThe line `values * 2 + 1` computes on all million elements without a single Python `for` loop running. The expression is not only faster, it is also shorter and reads closer to the mathematical intent. That is the real gain: you describe *what* should be computed, not *how* to iterate over the elements.\n\nBesides arithmetic operations, two tools show up in virtually every analysis. One is reductions such as `.sum()`, `.mean()`, `.std()`, or `.min()` and `.max()`, which turn an array into a single metric. The other is Boolean masks.\n\n```python\nimport numpy as np\n\ndata = np.array([-3, 7, -1, 4, 9, -8])\n\nmask = data > 0                 # array of True/False\npositives = data[mask]          # keep only positive values\nclipped = np.where(data < 0, 0, data)   # replace negatives with 0\n\nprint(positives)                # [7 4 9]\nprint(clipped)                  # [0 7 0 4 9 0]\n```\n\n`data > 0` does not produce a single `True` or `False` but a whole array of truth values. You can then use it to filter (`data[mask]`) or to replace values case by case with `np.where`. Again, no loop and no condition in Python code – the logic lives entirely in the vectorized operation.\n\nClosely related to vectorization is broadcasting. It lets you combine arrays of different shapes as long as their dimensions are compatible. Conceptually, a scalar is stretched across the entire shape of the array – that is why `values * 2 + 1` works without you having to inflate the `2` and the `1` to a million elements yourself. The same rule applies to two-dimensional data: a row vector with a matching number of columns can be applied to every row of a matrix, for example to subtract the mean from each column. Broadcasting saves you many explicit loops and keeps the code close to mathematical notation. The only important thing is to keep the shapes in your head: if the dimensions don’t fit, NumPy responds with a `ValueError` instead of silently computing something wrong.\n\n## Pandas: tables with labels\n\nNumPy is good at computing with numbers, but real data has structure. Columns have names, rows have meaning, and numbers are often mixed with text and dates. This is where pandas comes in, and pandas builds directly on NumPy. Underneath pandas tables are NumPy arrays.\n\nThe two central structures are `Series` and `DataFrame`. A `Series` is a one-dimensional column with an index. A `DataFrame` is a two-dimensional table with labeled rows and columns – essentially a collection of `Series` that share the same index.\n\n```python\nimport pandas as pd\n\ndf = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"north\", \"west\", \"south\"],\n    \"amount\": [120.0, 80.0, 45.0, 200.0, 95.0],\n    \"channel\": [\"online\", \"store\", \"online\", \"store\", \"online\"],\n})\n\nprint(df.shape)                 # (5, 3)\nprint(df[\"amount\"].mean())      # 108.0\n```\n\nReading from a file usually goes through `pd.read_csv`, which turns a CSV file into a `DataFrame`. From then on, you keep working with the same table, no matter where it came from.\n\n### Selecting with loc and iloc – the classic stumbling block\n\nAs soon as you want to pick out specific rows and columns, two access methods show up that beginners reliably mix up: `.loc` and `.iloc`. The difference is actually simple, but you have to learn it consciously once.\n\n`.loc` is label-based. You access rows and columns by their labels, and – this is the quirk – the endpoint of a range is **inclusive**. `.iloc` is position-based. You access by integer position, and the endpoint is **exclusive**, just like regular Python slicing.\n\n```python\nimport pandas as pd\n\ndf = pd.DataFrame(\n    {\"amount\": [120, 80, 45, 200, 95]},\n    index=[\"a\", \"b\", \"c\", \"d\", \"e\"],\n)\n\n# label-based, endpoint INCLUDED -> rows a, b, c\nprint(df.loc[\"a\":\"c\", \"amount\"])\n\n# position-based, endpoint EXCLUDED -> rows a, b, c (positions 0, 1, 2)\nprint(df.iloc[0:3, 0])\n```\n\nBoth expressions return the same three rows here, but for different reasons: once because `\"c\"` is included as a label, once because position `3` is just barely left out. If you mix them up, you get either an off-by-one error or a `KeyError`. So: labels always via `.loc`, positions always via `.iloc`, and never mix the two in one expression.\n\nFor filtering, you use Boolean masks – just like in NumPy, except that the condition refers to a column.\n\n```python\nimport pandas as pd\n\ndf = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"north\", \"west\"],\n    \"amount\": [120, 80, 45, 200],\n})\n\nbig = df[df[\"amount\"] > 100]              # keep rows above 100\nbig_regions = df.loc[df[\"amount\"] > 100, \"region\"]   # filter + pick column\n```\n\n## The most common mistake: chained indexing\n\nNow to a pitfall that comes up regularly in code reviews and leads to one of the most searched warnings in the pandas world: the `SettingWithCopyWarning`. It is caused by chained indexing – two consecutive accesses in one expression.\n\n```python\n# problematic: chained indexing\ndf[df[\"amount\"] > 100][\"tier\"] = \"high\"     # may write into a copy!\n```\n\nThe tricky part: depending on the situation, `df[df[\"amount\"] > 100]` returns either a view of the original data or a copy of it – and you cannot reliably predict which. If you then write into the result, the assignment may land in a copy that is immediately thrown away. The original stays unchanged, and that is exactly what pandas warns you about. The correct form uses a single `.loc` access that addresses the row selection and the column in one step:\n\n```python\n# correct: single .loc access\ndf.loc[df[\"amount\"] > 100, \"tier\"] = \"high\"\n```\n\nAnd if you deliberately want to keep working with an independent copy, say so explicitly with `df.copy()`. Then it is clear that changes should not touch the original. In my experience, this one rule – selection and assignment in a single `.loc` – saves you most of these warnings.\n\nThe second mistake in the same category is iterating over rows. If you come from classic programming, you instinctively reach for `df.iterrows()` and go row by row. That is slow and memory-hungry, because pandas has to build a new object for every row, and the whole speed advantage of the vectorized NumPy foundation is lost. Almost always, you can express the same intent with a column operation, with `groupby`, or with `np.where` – and it then runs orders of magnitude faster.\n\n## Grouping and aggregating with groupby\n\nPerhaps the most important operation for analysis is `groupby`. It follows a pattern known as split-apply-combine: the data is split into groups by a key (split), an aggregate function is applied to each group (apply), and the partial results are combined into a new table (combine).\n\n```python\nimport pandas as pd\n\ndf = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"north\", \"west\", \"south\"],\n    \"amount\": [120.0, 80.0, 45.0, 200.0, 95.0],\n})\n\nsummary = (df.groupby(\"region\")\n             .agg(total=(\"amount\", \"sum\"),\n                  avg=(\"amount\", \"mean\"))\n             .reset_index())\n\nprint(summary)\n#   region  total    avg\n# 0  north  165.0   82.5\n# 1  south  175.0   87.5\n# 2   west  200.0  200.0\n```\n\nNamed aggregation, `total=(\"amount\", \"sum\")`, is my preferred notation: in a single line, it says which column is aggregated with which function and what the result column should be called. The result is a compact table that you can process further right away. The `.reset_index()` at the end moves the grouping key from the index back into a regular column – handy if you want to plot right afterward.\n\nOften the data does not live in a single table but is spread out. Sales figures here, region information there. To bring them together, you use `merge`, which works like database joins:\n\n```python\nimport pandas as pd\n\nsales = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"west\"],\n    \"amount\": [165, 175, 200],\n})\nmanagers = pd.DataFrame({\n    \"region\": [\"north\", \"south\", \"east\"],\n    \"manager\": [\"Ada\", \"Ben\", \"Cleo\"],\n})\n\njoined = sales.merge(managers, how=\"inner\", on=\"region\")\nprint(joined)\n#   region  amount manager\n# 0  north     165     Ada\n# 1  south     175     Ben\n```\n\nIt pays to keep a close eye on the `how` parameter here. With `how=\"inner\"`, only regions that appear in both tables remain – “west” and “east” drop out. A `how=\"outer\"` would keep all regions and fill the missing values with `NaN`. If you pick the wrong mode, you either silently lose rows or end up with unexpected gaps. It is worth checking `.shape` before and after a `merge` to see whether the row count matches your expectations.\n\n## The pipeline: load, clean, group, plot\n\nLet’s put the pieces together. A typical analysis always passes through the same stations, and it helps to have this flow in front of you as a picture.\n\n```mermaid\nflowchart LR\n    A[Rohdaten<br/>CSV-Datei] --> B[Laden<br/>pandas.read_csv]\n    B --> C[Bereinigen<br/>dropna / fillna]\n    C --> D[Transformieren<br/>groupby / agg]\n    D --> E[Plotten<br/>matplotlib]\n```\n\nGrouping is usually preceded by cleaning. Real data has gaps, and `groupby` or computations on top of it are sensitive to missing values. Two tools cover most cases: `dropna` throws away rows with missing values, `fillna` replaces them with a default value. Which one is right depends on the question – sometimes a gap is a genuine nothing, sometimes a disguised zero.\n\n```python\nimport pandas as pd\n\ndf = pd.read_csv(\"sales.csv\")\n\n# clean: drop rows without an amount\ndf = df.dropna(subset=[\"amount\"])\n\n# transform: aggregate per region\nsummary = (df.groupby(\"region\")\n             .agg(total=(\"amount\", \"sum\"))\n             .reset_index())\n```\n\n## Data quality and reproducibility as a decision risk\n\nThe step `df.dropna(subset=[\"amount\"])` looks like a formality. It isn’t. The moment I throw away missing values instead of filling them, I decide which number ends up in front of the decision-maker. `dropna` shrinks the population and can make a region disappear that was simply poorly recorded. `fillna(0)` turns an “unknown” into a hard zero and drags every average down with it. Both are sometimes right and sometimes wrong, but never neutral. The question is always the same: is the gap a genuine nothing or a disguised zero? This decision belongs in the documentation, not made silently.\n\nThe second, more expensive risk factor is silent data loss. A `merge` with the wrong `how` drops rows without warning, a cleanup step quietly halves the population, and the bar chart still looks plausible. That is exactly the danger: a wrong analysis looks deceptively like a correct one. That is why I build checks directly into the pipeline instead of trusting what I see.\n\n```python\nbefore = len(df)\ndf = df.dropna(subset=[\"amount\"])\nassert len(df) >= before * 0.9, \"dropped more than 10% of rows\"\nassert df[\"amount\"].between(0, 10_000).all(), \"amount out of expected range\"\n```\n\nAssertions like these cost minutes during development. A decision based on a population that shrank by ten percent costs considerably more, and the error is often noticed only after it has already had its effect. That is the real trade-off: a little friction while writing in exchange for a reliable number when deciding.\n\nThe third point is reproducibility. An analysis that I click together in a spreadsheet can no longer be traced after two weeks. Nobody knows which cells were touched by hand. An analysis as code is the opposite: the same code on the same raw data delivers the same result, at any time, for everyone on the team. The raw data stays untouched, every transformation is visible in the script, and the result can be traced back to its source. This turns a one-off number into a process that I can check, version, and defend. That is exactly what lifts an analysis from a nice chart to a basis for decisions.\n\n## Matplotlib: turning numbers into a picture\n\nAt the end of the pipeline comes visualization. Matplotlib is the established library for it, and I recommend the object-oriented style from the start: first create a figure and an axis with `plt.subplots()`, then build everything on that axis. It is a bit more typing than the quick `plt.plot()` one-liner, but it stays clear as soon as a chart contains more than one line.\n\n```python\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.bar(summary[\"region\"], summary[\"total\"])\nax.set_xlabel(\"Region\")\nax.set_ylabel(\"Total sales\")\nax.set_title(\"Sales by region\")\nplt.show()\n```\n\nFor the three most common chart types, there is a matching function on the axis. A bar chart with `ax.bar(x, height)` compares categories – ideal for the `groupby` result from before. A line chart with `ax.plot(x, y)` shows trends, such as a metric over several months. And a scatter plot with `ax.scatter(x, y)` shows the relationship between two variables. For me, labels via `set_xlabel`, `set_ylabel`, and `set_title` are always part of it; a chart without axis labels is only half a statement.\n\n## Who does what? The division of roles at a glance\n\nThe division of work in the toolkit is clearly cut, and if you know it, you won’t reach for the wrong library for a problem:\n\n- NumPy forms the numerical foundation: homogeneous arrays, vectorized computation, mathematical operations. Everything above builds on it.\n- pandas takes care of structured, labeled tabular data: reading, cleaning, selecting, filtering, grouping, merging – the entire handling of real, messy data.\n- Matplotlib handles visualization: the fully prepared numbers become a chart that carries a message.\n\nThis order is no accident. It describes exactly the path the data takes: from raw numbers through a structured table to a picture.\n\n## The common thread\n\nThe real shift in thinking for data analysis with Python is saying goodbye to the loop. No longer going element by element, but treating whole columns and whole tables as a unit. NumPy does this with vectorized operations on the `ndarray`, pandas lifts the same idea to labeled tables, and `groupby` aggregates whole groups at once following the split-apply-combine pattern. But the gain is not just speed. If you know the two beginner traps, chained indexing and iterating over rows, you avoid the most common friction points and write code that stays just as calm at a million rows as at a hundred.\n\nThis toolkit has its impact where analysis meets decision. A pipeline made of code shortens the cycle from question to answer: if the raw data changes, the same script runs again, and the new number is ready in minutes instead of half a day of manual work. It reduces friction in the team, because everyone can reproduce the same result instead of deciphering someone else’s spreadsheet. And it raises quality, because checks and documented cleanup decisions make sure a wrong number gets noticed before it supports a decision. The limit is just as clear: these tools work well where the data fits in memory and a batch analysis is enough. With data volumes beyond a single machine or with continuous data streams, a different set of tools begins, and the art is recognizing this limit in time instead of forcing pandas beyond its scope.\n\nThe rest is practice: load, clean, group, plot, and go through this cycle until it becomes second nature. The tool only becomes useful when the steps stay reproducible and a second person gets the same number.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-python.en.html\n- Repository `introduction-python` with runnable examples for NumPy, pandas, and Matplotlib\n- NumPy – “the absolute basics for beginners”: https://numpy.org/doc/stable/user/absolute_beginners.html\n- pandas – Indexing and Selecting Data (loc/iloc, chained indexing): https://pandas.pydata.org/docs/user_guide/indexing.html\n- pandas – Group by: split-apply-combine: https://pandas.pydata.org/docs/user_guide/groupby.html\n- pandas – Merge, join, concatenate: https://pandas.pydata.org/docs/user_guide/merging.html\n- Matplotlib – pyplot API: https://matplotlib.org/stable/api/pyplot_summary.html"},{"locale":"en","translation_key":"wann-cqrs-und-event-sourcing-zu-viel-ist","slug":"when-cqrs-and-event-sourcing-are-too-much","title":"When CQRS and Event Sourcing Are Too Much","summary":"For most systems, CRUD is enough. CQRS and Event Sourcing only pay off under clear conditions – this article offers an honest decision guide instead of patterns for their own sake.","tags":["Software","Architecture"],"published_at":"2021-07-13T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/when-cqrs-and-event-sourcing-are-too-much/","audio_url":null,"audio_duration_secs":null,"text":"# When CQRS and Event Sourcing Are Too Much\n\nChanging an email address takes three lines in a CRUD handler: load, set the field, save. With CQRS and Event Sourcing, it takes five parts – a command, an event, an aggregate with a replay path, an append to the event store and a projection that updates the read model. On top of that comes a time window in which a query still returns the old address. Five moving parts and a consistency problem that didn’t exist before.\n\nYou can pay this price, and under certain conditions it pays off. I like both patterns and have defended them in other articles. For the majority of systems, they’re still too much.\n\nThis isn’t a bold claim. Martin Fowler puts it almost identically: “For most systems CQRS adds risky complexity.” And unusually clearly for him: in the majority of cases he came across, CQRS wasn’t a good choice but carried a considerable risk of getting the system into serious difficulties. When the author who made a pattern well known warns like that, an honest decision guide is worth it.\n\n## The baseline is CRUD\n\nBefore I talk about alternatives, I want to state what the standard solution actually achieves. CRUD means: a single data model for reading and writing, direct persistence of the current state, usually against a table through an ORM. Create, Read, Update, Delete. Fowler puts it soberly: “Many systems do fit a CRUD mental model, and so should be done in that style.”\n\nThe key point is that CRUD isn’t the primitive preliminary stage you later replace with something better. For a form that gets saved and displayed again, CRUD isn’t the compromise but the right answer. An illustrative handler for it is unspectacular – and that’s exactly its strength:\n\n```ts\nasync function updateCustomerEmail(id: string, email: string): Promise<void> {\n  const customer = await repo.findById(id);\n  customer.email = email;\n  await repo.save(customer); // read and write share the same model\n}\n```\n\nOne model, one access, no latency between writing and reading. If you optimize this value away without having a problem, you trade simplicity for complexity and get nothing back for it.\n\n## What CQRS and Event Sourcing really are\n\nTo make the decision clean, I separate the two terms that are often mentioned in one breath. CQRS – Command Query Responsibility Segregation – means you use a different model for changing data than for reading it. The write side accepts commands, checks invariants and returns nothing. The read side answers queries, returns data and changes nothing. That’s more than Bertrand Meyer’s Command Query Separation principle: CQS separates methods on an object, CQRS separates entire models.\n\nEvent Sourcing is something else. Here, every state change is recorded as an event, and the current state comes from replaying the events. The event store is the authoritative source of truth; the state is purely derived. Fowler’s analogy for this is version control: the commit log corresponds to the event store, the working tree to the current system state. I developed this idea in more detail in [Event Sourcing: The Event Store as a Logbook](https://www.mikebild.dev/en/blog/event-sourcing-the-event-store-as-a-logbook/).\n\nImportant for today’s article: the two patterns are independent of each other. Greg Young makes this clear several times – CQRS isn’t Event Sourcing, doesn’t need a message bus and isn’t necessarily tied to DDD either. You can run CQRS without Event Sourcing, that is, with a separate read database but classic state persistence. And you can run Event Sourcing with only one model. So if you introduce both together, you’re choosing two cost blocks, not one.\n\n## The costs you rarely plan for\n\nSeparate models effectively force eventual consistency. As soon as the write side produces an event and the read side only then builds a projection from it, there’s a time window in which a query doesn’t yet see the value that was just written. Fowler says so openly: separate models increase the likelihood of having to use eventual consistency. That isn’t a feature but a cost item.\n\nAn illustrative contrast to the CRUD handler above shows the additional moving parts. First the messages:\n\n```ts\ninterface ChangeEmail {\n  type: \"ChangeEmail\";\n  id: string;\n  email: string;\n}\n\ninterface EmailChanged {\n  type: \"EmailChanged\";\n  id: string;\n  email: string;\n  version: number;\n}\n```\n\nThen the write model, which is rehydrated from its events and checks an invariant when changing instead of simply overwriting a field:\n\n```ts\nclass Customer {\n  private constructor(\n    private readonly id: string,\n    private email: string,\n    private version: number,\n  ) {}\n\n  static empty(): Customer {\n    return new Customer(\"\", \"\", 0);\n  }\n\n  static from(events: EmailChanged[]): Customer {\n    // fold the event stream into current state (replay)\n    return events.reduce(\n      (state, event) => state.apply(event),\n      Customer.empty(),\n    );\n  }\n\n  private apply(event: EmailChanged): Customer {\n    return new Customer(event.id, event.email, event.version);\n  }\n\n  changeEmail(email: string): EmailChanged[] {\n    if (email === this.email) return []; // no change, no event\n    return [{ type: \"EmailChanged\", id: this.id, email, version: this.version + 1 }];\n  }\n}\n```\n\nAnd finally the handler, which loads, decides, appends – and updates the projection separately:\n\n```ts\nasync function handle(command: ChangeEmail): Promise<void> {\n  const events = await store.load(command.id);\n  const customer = Customer.from(events);\n  const newEvents = customer.changeEmail(command.email);\n  await store.append(command.id, newEvents); // source of truth\n  // read model is updated asynchronously by a projection\n}\n```\n\nThe read side is its own, deliberately dumb read model built from the same events:\n\n```ts\nclass CustomerListView {\n  private rows = new Map<string, { id: string; email: string }>();\n\n  on(event: EmailChanged): void {\n    this.rows.set(event.id, { id: event.id, email: event.email });\n  }\n\n  // a query right after append may still return the previous email (stale read)\n  find(id: string) {\n    return this.rows.get(id);\n  }\n}\n```\n\nBetween the first CRUD example and this variant lies not progress but a trade-off. I’ve exchanged more types, more indirection, a replay path, a projection and a consistency window – for a benefit that only arises under certain conditions in the first place.\n\nBeyond that, Event Sourcing brings its own, often underestimated costs. Old events have to remain readable practically forever, which makes event versioning and schema evolution a permanent task. Projections and read models have to be buildable and rebuildable. External side effects during replay need careful handling, otherwise a rebuild accidentally sends real emails. And a simple ad hoc query on the current state no longer comes for free. These points come on top of the CQRS costs.\n\n## A decision flow\n\nI base the decision on a few questions, in this order. Important: this applies per bounded context, not globally. Greg Young is unambiguous here – CQRS isn’t a top-level pattern; it’s applied within a component, not slapped over the entire system.\n\n```mermaid\nflowchart TD\n  Start([New context]) --> Inv{Real domain model<br/>with colliding invariants?}\n  Inv -->|no| Crud[CRUD is enough]\n  Inv -->|yes| Asym{Strong read/write asymmetry<br/>OR audit/time-travel requirement?}\n  Asym -->|no| Lite[Stay with CRUD<br/>or CQRS-lite]\n  Asym -->|yes| Team{Can the team handle eventual consistency<br/>and event versioning?}\n  Team -->|no| Kompromiss[CRUD or compromise]\n  Team -->|yes| Cqrs[CQRS – plus Event Sourcing<br/>if audit or temporal]\n```\n\nThe benefit of CQRS is closely tied to two conditions. First, a complex domain in which a shared model for reading and writing actually becomes too complicated. Second, a pronounced read/write asymmetry – many reads, few writes – so that scaling the read and write sides independently pays off. If both are missing, Fowler’s observation leads straight into the trap: CQRS on a domain that doesn’t fit increases complexity, lowers productivity and raises risk. The pattern doesn’t simplify on its own, only where real model or invariant complexity already exists.\n\n## Signals for and against\n\nIn a concrete project, the answer hinges on a few signals that you usually see earlier than you take them seriously.\n\nIn favor:\n\n- a task-based UI with many people working concurrently whose actions can collide in the domain\n- hard audit, compliance or time-travel requirements that demand a complete history – this is where Event Sourcing in particular pulls its weight\n- a pronounced read/write asymmetry with separate scaling goals\n- a rich domain with real, competing invariants and clearly different read and write shapes\n\nAgainst:\n\n- a classic CRUD or form application without real invariant complexity\n- a small team that has no experience with eventual consistency yet\n- no audit or history requirement that justifies the effort\n- the wish for a global one-size-fits-all architecture – or simply “because everyone does it”\n\nThe last point leads to the actual pitfall.\n\n## The pitfall: the pattern for its own sake\n\nThe biggest risk isn’t the wrong technology but the wrong motivation. Greg Young describes the core precisely: teams want to implement CQRS and Event Sourcing everywhere, as a cookie-cutter architecture – and that’s exactly a massive risk. A pattern gets introduced because it shines, not because a concrete problem calls for it. Fowler advises caution because the pattern is hard to use well.\n\nThree symptoms give away the cargo cult. There are events, but nobody can name a domain invariant they protect. There’s a projection, but the read shape is identical to the write shape. And there’s an event store, but no requirement for audit or history. When these three things come together, the pattern is decorative, not load-bearing.\n\nThen there are the usual confusions. CQRS isn’t Event Sourcing – the two are orthogonal and can be used separately. CQRS isn’t an architecture or a top-level pattern but a decision within a bounded context. CQRS isn’t CQS, because it separates models, not methods. CQRS needs neither a message bus nor DDD. And Event Sourcing isn’t the same as event-driven integration via pub/sub – it’s an internal persistence and source-of-truth mechanism, not a communication style between systems. Fowler deliberately separates these meanings of “event-driven,” because otherwise four different things blur under one word.\n\n## More moving parts, made visible\n\nA direct contrast of the paths makes the trade-off tangible. The CRUD path is short; the CQRS path with Event Sourcing has more stations – and each station is a place where something can go wrong.\n\n```mermaid\nflowchart LR\n  subgraph CRUD\n    C1[Client] --> H1[Handler] --> DB[(Database)]\n  end\n  subgraph CQRS_ES\n    Cmd[Command] --> Agg[Aggregate] --> ES[(Event Store)]\n    ES --> Proj[Projection] --> RM[(Read Model)]\n    RM --> Q[Query]\n  end\n```\n\nThis diagram isn’t selling anything. It just makes honest that the lower variant means more components, more contracts and more failure paths. If you know this price and pay it anyway because the domain is worth it, you’re making a good decision. If you pay it without getting the value in return, you’re building complexity in advance.\n\n## Conclusion\n\nCQRS and Event Sourcing aren’t better default architectures but targeted tools for targeted problems. The honest starting point is CRUD, and for the majority of systems it remains the right answer. The two patterns pay off when a domain has real, colliding invariants, when read and write load diverge strongly or when audit and time-travel requirements demand a complete history – and when the team is ready to carry eventual consistency and event versioning. They become overhead in simple CRUD apps, in small teams, without real invariant complexity and whenever the pattern is chosen out of fashion rather than need.\n\nThe best way to handle this is a conscious, context-local decision. Not globally, not as a cookie cutter, but per bounded context, with a clear “what for.” I described why CQRS needs this domain boundary and isn’t a framework in [CQRS Is a Domain Boundary](https://www.mikebild.dev/en/blog/cqrs-is-a-domain-boundary-not-a-framework/). The most mature architectural quality often shows not in using a demanding pattern – but in deliberately, and for good reason, not using it.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html\n- Martin Fowler, CQRS: https://martinfowler.com/bliki/CQRS.html\n- Martin Fowler, Event Sourcing: https://martinfowler.com/eaaDev/EventSourcing.html\n- Martin Fowler, Command Query Separation: https://martinfowler.com/bliki/CommandQuerySeparation.html\n- Martin Fowler, What do you mean by Event-Driven?: https://martinfowler.com/articles/201701-event-driven.html\n- Greg Young, CQRS is not an Architecture (2012): https://gregfyoung.wordpress.com/2012/09/09/cqrs-is-not-an-architecture/\n- Greg Young, CQRS (2012): https://gregfyoung.wordpress.com/2012/03/02/cqrs/\n- Vaughn Vernon, Implementing Domain-Driven Design (sample): https://ptgmedia.pearsoncmg.com/images/9780321834577/samplepages/0321834577.pdf\n- My own talk material “CQRS + Event Sourcing” (SlideShare)\n\nThe sources anchor the terms against established standards. The actual message remains the context-local decision to use the pattern only where the domain deserves it."},{"locale":"en","translation_key":"graphql-konzepte-schema-resolver-ausfuehrung","slug":"graphql-concepts-schema-resolvers-execution","title":"GraphQL Concepts: Schema, Resolvers, Execution","summary":"The ideas behind GraphQL that last, no matter which server is in fashion right now – the schema as a typed contract, the query as a shape, the resolver model and the order of execution. A conceptual deep dive with diagrams.","tags":["Software","API","GraphQL"],"published_at":"2021-06-24T10:00:00+00:00","updated_at":"2026-07-13T13:20:27.930931+00:00","url":"https://www.mikebild.dev/en/blog/graphql-concepts-schema-resolvers-execution/","audio_url":null,"audio_duration_secs":null,"text":"# GraphQL Concepts: Schema, Resolvers, Execution\n\nGraphQL isn’t a query language for databases, and a resolver isn’t a controller. Both comparisons hold up to a point and then break – at the latest with the query that looks harmless and triggers thirty individual database calls in the server. The explanation isn’t in the manual of whichever server you use but in the specification. Once you have properly understood its execution rules, you read different GraphQL servers with the same mental model.\n\nThe GraphQL overview laid out the topic in breadth, from the schema to federated architecture. Here we go one level deeper, to the ideas behind the tools: what a schema really is, why a query looks like its response, and how execution walks through the tree field by field. That sounds like basics, but it’s exactly on these basics that it’s decided whether you master GraphQL or merely use it.\n\n## The schema is a typed graph\n\nOn first reading, a schema looks like a collection of data types. It is that, but the decisive property lies in the relationships between the types. Let’s take a blog again:\n\n```graphql\ntype Author {\n  id: ID!\n  name: String!\n  posts: [Post!]!\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  author: Author!\n}\n```\n\n`Author` points to `Post`, and `Post` points back to `Author`. So the schema doesn’t describe a flat catalog but a graph: the types are nodes, and the fields that point to other types are edges. The name is meant literally. A query is then nothing more than a path through this graph that the client chooses itself.\n\nThe modifiers are part of the contract, not decoration. `String!` means: this field is guaranteed to be present. `[Post!]!` means: guaranteed to be a list, guaranteed to have no gaps in it. A client can rely on this and doesn’t have to check defensively for `null` where the schema rules `null` out. Conversely, a non-nullable field that does return `null` forces an error – so the guarantee is enforced, not merely promised.\n\nAnd then there are the three root types: `Query`, `Mutation` and `Subscription`. They are the only doors into the graph. Everything a client can do starts at a field of one of these three types. Whatever isn’t there doesn’t exist for the client. That makes the schema a complete, binding contract – and one of the few API descriptions that are documentation, validation rule and type definition at the same time.\n\n## A query is a shape\n\nThe second idea is simple and still the one that surprises people switching over the longest: a GraphQL query has the same shape as its response.\n\n```graphql\nquery {\n  author(id: \"1\") {\n    name\n    posts {\n      title\n    }\n  }\n}\n```\n\nThe response to it has the same structure – an `author` with a `name` and a list of `posts`, in which every entry has a `title`. You don’t describe how data is fetched but which shape you want to have in the end. That’s the same declarative attitude that shows up elsewhere in the modern frontend world: you name the goal, not the path.\n\nFrom this follows the well-known promise of reducing over-fetching and under-fetching at the interface. The client only receives the selected fields and can request related data in one document. That guarantees neither a single network round trip under every transport architecture nor efficient access behind the resolvers. But the server gets a precise description of what is needed – a good basis for planning execution accordingly.\n\n## The resolver model\n\nNow to execution. For every field in the query, the server calls a function, the resolver. A resolver always receives the same four arguments, in this order:\n\n```js\nfunction resolver(source, args, context, info) {\n  // source  – the parent object (the return value of the field above)\n  // args    – this field's arguments in the query\n  // context – a per-request object (e.g. the logged-in user, data access)\n  // info    – information about execution state (which field, which path)\n}\n```\n\nThe first argument is the key to understanding the chain. The return value of a resolver becomes the `source` for the resolvers of the fields below it. If the resolver for `author` resolves an author, the resolver for that author’s `posts` gets exactly this author as `source` and can use it to load the posts.\n\n```js\nconst resolvers = {\n  Query: {\n    author: (source, { id }, context) => context.db.loadAuthor(id),\n  },\n  Author: {\n    // source here is the author from the resolver above\n    posts: (author, args, context) => context.db.loadPostsForAuthor(author.id),\n  },\n  Post: {\n    // source here is a single post\n    author: (post, args, context) => context.db.loadAuthor(post.authorId),\n  },\n};\n```\n\nFor most fields, you don’t write a resolver at all. If a field is called `name` and the parent object has a `name` property, the default resolver kicks in: it reads the property of the same name from the `source`. So you only write resolvers explicitly where something needs to be done – where data is loaded, computed or transformed. That keeps most schemas surprisingly lean.\n\nThe `context` deserves a sentence of its own, because a lot depends on it. It’s built once per request and passed to every resolver. That’s where the identity of whoever makes the request ends up, and that’s where access to the data sources lives. Because every resolver sees the same context, it’s the natural place for authentication and for shared resources – without having to thread them through every function signature.\n\n## The order of execution\n\nHow exactly does execution walk through the tree? It follows the selection recursively from the root fields to their subfields. A subfield can only be resolved once the value of its parent field is available; independent sibling fields, on the other hand, may be evaluated in parallel. So it isn’t a strictly clocked breadth-first traversal, level by level.\n\n```mermaid\nflowchart TB\n  Q[\"Query\"] --> A[\"author resolver<br/>returns author\"]\n  A --> N[\"name<br/>(default resolver)\"]\n  A --> P[\"posts resolver<br/>returns list\"]\n  P --> T1[\"title of post 1\"]\n  P --> T2[\"title of post 2\"]\n```\n\nTwo subtleties matter, because they have consequences in everyday work. First: the server resolves sibling fields on the same level concurrently, not strictly one after the other. If a resolver returns a promise, the server waits for it, but it doesn’t block the siblings. That’s why resolvers must not make assumptions about their execution order relative to neighboring fields – they should work independently of one another.\n\nSecond, and this is the one deliberate exception: at the top level of a mutation, execution runs serially. If a mutation names several write fields, the server executes them one after the other in document order. That replaces neither transactions nor isolation. For queries, freedom from side effects is an important convention, not a guarantee enforced by the execution model; that’s why the server may evaluate independent root fields in parallel.\n\n## N+1 and why batching belongs to it\n\nAn almost inevitable problem follows from the resolver model, one that every GraphQL developer runs into sooner or later. If someone queries a list of authors and the posts for each, the `posts` resolver runs once per author. With ten authors, that’s ten calls – and if each makes its own database query, you have ten queries plus the one for the author list. That’s the N+1 problem: one query for the list, N more for the children.\n\nThe way out is batching. Instead of running off immediately, you collect all requests that arise within one execution tick and answer them with a single query. The usual implementation is the DataLoader library: you no longer ask the database directly but a loader for an ID; the loader waits until the end of the current tick, bundles all collected IDs and resolves them in one go. Along the way, it remembers within the request what it has already loaded, so the same ID isn’t fetched twice.\n\n```mermaid\nflowchart LR\n  R1[\"posts of author 1\"] --> L[\"DataLoader<br/>collects IDs in the tick\"]\n  R2[\"posts of author 2\"] --> L\n  R3[\"posts of author 3\"] --> L\n  L -->|one batched query| DB[(\"Database\")]\n```\n\nBatching doesn’t paper over a design flaw. It’s the consistent answer to the nature of the resolver model: field-by-field resolution is the reason for GraphQL’s flexibility – and batching is both its price and the clean solution for it. A loader belongs in the `context`, so that it’s fresh for each request and its cache doesn’t persist across request boundaries.\n\n## Why these concepts last\n\nYou can build GraphQL with Apollo Server, with GraphQL Yoga, with a library in C#, Go or Python. The server changes, the ecosystem shifts, the specification gets new versions. But the schema remains a typed graph, the query remains a shape, the resolvers remain a chain with the same four arguments, and execution remains a top-down traversal with serial mutations and concurrent siblings.\n\nThat’s exactly why it pays to understand this level and not just the API of a particular server. If you know what a resolver receives and how execution runs through the tree, you can narrow down N+1 problems in a more targeted way, design [schemas that grow with you](https://www.mikebild.dev/en/blog/a-graphql-schema-that-grows/), and find your way around a different server faster. The tools are interchangeable. The concepts aren’t.\n\n## Further reading\n\n- Repository introduction-graphql (chapters resolver, schema, subscriptions): https://github.com/mikebild/introduction-graphql\n- Slide overview for this topic area: https://slides.mikebild.dev/introduction-graphql.en.html\n- GraphQL, execution: https://graphql.org/learn/execution/\n- GraphQL, Schema and types: https://graphql.org/learn/schema/\n- GraphQL specification, execution: https://spec.graphql.org/\n- DataLoader (batching and caching per request): https://github.com/graphql/dataloader"},{"locale":"en","translation_key":"appsync-dynamodb-graphql-api","slug":"graphql-apis-with-appsync-and-dynamodb","title":"GraphQL APIs with AppSync and DynamoDB","summary":"AWS AppSync moves the GraphQL server out of your own operational responsibility and into a managed service. Using a DynamoDB backend, I show when this build-vs-buy decision holds up and when managed becomes a dead end, including the VTL mapping templates that are the price for it in 2021.","tags":["Software","AWS","Cloud"],"published_at":"2021-06-15T10:00:00+00:00","updated_at":"2026-07-13T10:02:55.07027+00:00","url":"https://www.mikebild.dev/en/blog/graphql-apis-with-appsync-and-dynamodb/","audio_url":null,"audio_duration_secs":null,"text":"If you publish a GraphQL schema, you have taken on running a server – even if the project plan only says “schema and clients”. The resolvers have to run somewhere, the connections have to end somewhere, the load has to be absorbed somewhere. That bill doesn’t arrive on deployment day; it arrives every month after.\n\nThe popular GraphQL introductions stop before this bill. Defining types, writing queries, fetching data with Apollo or urql: all well explained. The server with the resolvers, the database underneath, scaling, the real-time connections – they say nothing about those. Still, you can’t define this layer away. Someone builds it, deploys it and keeps it running.\n\nThat leaves the question of who this someone is: your own team or a managed service. I tie the answer to a concrete setup – AWS AppSync on DynamoDB, as it actually looks in mid-2021, including the VTL mapping templates that take some getting used to at first. The code isn’t the core here. The core is what this decision gains you and what it costs.\n\n**Editorial note (July 2026):** Besides VTL, AppSync today supports the JavaScript-based resolver runtime `APPSYNC_JS`. VTL remains valid, but it is no longer the only direct mapping to DynamoDB. Managed takes running the GraphQL server off the team’s hands; schema, resolvers, permissions, data model, deployment and observability remain your own work.\n\n## What AppSync actually is\n\nAppSync is a fully managed GraphQL layer. The crucial point: you don’t run your own GraphQL server. There is no Node process with Apollo Server, no container, no hosting, no scaling logic you would have to take care of. Instead, you upload a schema in the GraphQL Schema Definition Language (SDL) and attach a resolver to each field that points to a data source. AWS handles the rest.\n\nThis shift is the real value. In a classic setup, the GraphQL server is the centerpiece that you write, deploy and run yourself. With AppSync, running that server lies with AWS, while the team describes the mapping between schema field and data source as well as its infrastructure. This is the familiar serverless trade: less operations of your own in exchange for tighter coupling to the service.\n\nA resolver always connects exactly one schema field to a data source. And in 2021 there is a manageable but well-covered selection of those:\n\n- DynamoDB tables as a key-value and document store\n- AWS Lambda for any custom logic\n- HTTP endpoints to connect existing REST APIs\n- Amazon Elasticsearch Service for full-text search\n- relational databases via RDS or Aurora Serverless, plus “None” local resolvers without an external source\n\nIn this post I focus on DynamoDB, because it is the most common combination in serverless projects and because it shows the VTL mechanics best.\n\n## The request flow\n\nBefore we look at code, it helps to look at the path a request takes. A client sends a GraphQL query or mutation to AppSync. AppSync validates it against the schema and calls the matching resolver for the requested field. The resolver has two parts: a request template that translates the GraphQL request into a DynamoDB call, and a response template that turns the DynamoDB result back into GraphQL form.\n\n```mermaid\nflowchart LR\n  Client[GraphQL Client] -->|Query / Mutation| AppSync[AppSync<br/>Schema + VTL Resolver]\n  AppSync -->|Request Template| DDB[(DynamoDB Table)]\n  DDB -->|Response Template| AppSync\n  AppSync -->|JSON Result| Client\n  AppSync -.->|other data sources| Lambda[AWS Lambda]\n  AppSync -.->|other data sources| HTTP[HTTP Endpoint]\n```\n\nThese two templates are the centerpiece and, at the same time, the part where opinions split in 2021. That’s because they are not written in JavaScript but in the Apache Velocity Template Language, VTL for short.\n\n## VTL: the language in between\n\nVTL is a template language, not a full programming language. It can insert values and express simple conditions and loops, but it is deliberately kept narrow. For translating between GraphQL arguments and DynamoDB calls, that is enough in most cases, and AWS ships a set of helper functions that take care of the typical tasks.\n\nLet’s take a small CMS as an example. We want to create blog posts, fetch them individually and be notified in real time about new posts. The schema looks like this:\n\n```graphql\ntype Post {\n  id: ID!\n  title: String!\n  body: String!\n}\n\ntype Query {\n  getPost(id: ID!): Post\n}\n\ntype Mutation {\n  createPost(title: String!, body: String!): Post\n}\n\ntype Subscription {\n  onCreatePost: Post @aws_subscribe(mutations: [\"createPost\"])\n}\n```\n\nThis is plain SDL, as you know it from any GraphQL introduction. The only AppSync-specific addition is the `@aws_subscribe` directive on the subscription field, more on that later. First, the resolvers for `createPost` and `getPost`.\n\n### A PutItem resolver\n\nWhen a client calls `createPost`, a new item should land in the DynamoDB table. The request template describes exactly this `PutItem` call:\n\n```vtl\n{\n  \"version\": \"2017-02-28\",\n  \"operation\": \"PutItem\",\n  \"key\": {\n    \"id\": $util.dynamodb.toDynamoDBJson($util.autoId())\n  },\n  \"attributeValues\": $util.dynamodb.toMapValues($ctx.args)\n}\n```\n\nA lot happens in a small space here. The version string `\"2017-02-28\"` sets the template format. In 2021 that’s the default value you don’t change without a specific reason. The `operation` field tells DynamoDB what to do. The key is created via `$util.autoId()`, a helper function that generates a UUID so that each post gets a unique primary key.\n\nThe most important point hides in `$util.dynamodb.toDynamoDBJson(...)` and `$util.dynamodb.toMapValues(...)`. DynamoDB doesn’t expect values as bare strings or numbers but in a typed attribute format: a string becomes `{\"S\": \"...\"}`, a number `{\"N\": \"...\"}`. These helper functions handle the conversion automatically. If you forget them and insert the raw values directly, you write an item in the wrong format – the mistake almost everyone stumbles over once when getting started with AppSync.\n\nThe response template, by contrast, is unspectacular. It simply returns the written item as JSON:\n\n```\n$util.toJson($ctx.result)\n```\n\n`$ctx`, also available as `$context`, is the object that gives you access to everything relevant: `$ctx.args` for the arguments of the GraphQL operation, `$ctx.identity` for information about the calling user, `$ctx.result` for the result of the data source. The response template uses `$ctx.result` to send the item that was just written back to the client.\n\nBesides the plain result, AppSync also provides `$ctx.error` in the response template in case the data source returns an error, such as a rejected condition on a `PutItem`. If you ignore it, you silently return `null` on failure instead of giving the client a meaningful message. With `$util.error(...)` or `$util.appendError(...)` you can pass the error through to the GraphQL response in a controlled way, so that it ends up in the `errors` block of the response. For the two simple resolvers here, you can still do without it, but as soon as real conditions come into play, this check belongs in the template.\n\n### A GetItem resolver\n\nFor `getPost`, things are even simpler. The request template describes a `GetItem` call with the `id` argument as the key:\n\n```vtl\n{\n  \"version\": \"2017-02-28\",\n  \"operation\": \"GetItem\",\n  \"key\": {\n    \"id\": $util.dynamodb.toDynamoDBJson($ctx.args.id)\n  }\n}\n```\n\nHere, too, the value from `$ctx.args.id` goes through `toDynamoDBJson` so that it arrives at DynamoDB in the right format. The response template is identical to the previous one:\n\n```\n$util.toJson($ctx.result)\n```\n\nWhen you put these two resolvers side by side, the principle becomes tangible: a resolver is always a pair of request and response template that connects a schema field to a concrete DynamoDB operation. There is no more magic behind it.\n\nThe available operations cover the usual DynamoDB repertoire. Besides `GetItem` and `PutItem`, there are `UpdateItem` and `DeleteItem`, plus `Query` and `Scan` for multiple results as well as the batch and transaction variants such as `BatchGetItem` or `TransactWriteItems`. The four single-item operations are enough to get started, and you grow into the more complex variants along with the data model. The nice thing is that the pattern always stays the same. You change the `operation` field, adjust key and values, and the structure of the template barely changes. This uniformity is what makes VTL manageable in daily work despite its clunkiness.\n\n## Subscriptions with no effort of your own\n\nThe part that surprises people most at first contact is the real-time subscriptions. In a self-built GraphQL server, this is the most laborious part of all: managing WebSocket connections, running a pub/sub system, keeping state in sync across several server instances. With AppSync, you have to do none of that.\n\nLet’s recall the directive from the schema:\n\n```graphql\ntype Subscription {\n  onCreatePost: Post @aws_subscribe(mutations: [\"createPost\"])\n}\n```\n\nThis one line is enough. `@aws_subscribe(mutations: [\"createPost\"])` binds the subscription field `onCreatePost` to the `createPost` mutation. Whenever this mutation completes successfully, AppSync pushes the result over a WebSocket connection to all clients that have subscribed to `onCreatePost`. No polling, no server of your own, no connection management.\n\n```mermaid\nsequenceDiagram\n  participant A as Client A\n  participant AS as AppSync\n  participant D as DynamoDB\n  participant B as Client B (subscribed)\n  A->>AS: mutation createPost\n  AS->>D: PutItem\n  D-->>AS: written item\n  AS-->>A: created Post\n  AS-->>B: onCreatePost (WebSocket push)\n```\n\nThe connection runs over WebSockets, which AppSync provides out of the box. The client only has to subscribe to `onCreatePost` once and then automatically receives every new post. For a live feed, a chat feature or a dashboard, this is a huge simplification, because the entire real-time part disappears from your own operational responsibility.\n\nOne detail you must not overlook: without the `@aws_subscribe` directive, simply nothing happens. More than once I have seen someone define a subscription, connect the client and then wonder why no events arrive. The answer was the same every time: the directive was missing or pointed to the wrong mutation. The subscription field has to be coupled explicitly to the mutation that triggers it.\n\n## Where VTL reaches its limits\n\nAs elegant as the approach is, its edges are just as clear. VTL is deliberately not a programming language, and you notice that as soon as the logic gets more complex. Nested conditions, multi-step transformations, merging several sources: you can express all of this in VTL somehow, but the templates quickly become unreadable and hard to maintain.\n\nThe limit lies where a template does more than reorder arguments and pour them into a DynamoDB call. As of 2021, more complex logic belonged in a Lambda resolver. Today you should first check whether an `APPSYNC_JS` resolver expresses the mapping more readably; for free-form runtime logic and external libraries, Lambda remains the further-reaching option. VTL is still well suited for lean, direct mappings to DynamoDB.\n\nThe second edge doesn’t concern AppSync but DynamoDB itself. Whether an access becomes a `Query` or a `Scan` is decided by the table design. A `Query` uses partition and sort key or a global secondary index and is fast and cheap. A `Scan` reads the whole table if in doubt and becomes expensive and slow as the data grows. You have to think through these access patterns before the first write, because DynamoDB rarely forgives a poorly planned key design after the fact. The nice AppSync frontend doesn’t change the fact that underneath sits a DynamoDB table with its own rules.\n\n## Managed or self-hosted: the real decision\n\nSo far it has been about mechanics. The reason I bring up AppSync in projects at all lies one level higher. A GraphQL server is not a feature you write once and then forget. It is a permanent operational commitment. It has to run, scale, be updated and be monitored, and with real-time connections, all the state across several instances comes on top. These costs don’t arise once during the build but every month in operation.\n\nAt this point, build vs. buy means concretely: running it yourself means a Node process with Apollo Server, hosting, a scaling strategy, a pub/sub system for subscriptions and the willingness to fix all of it at night when things go wrong. Managed means that I declare schema, resolvers and data sources and hand the rest over to AWS. I then no longer pay in operating hours but in usage and in a piece of control that I give away.\n\nWhen does managed hold up? Whenever the GraphQL server is not a differentiator for the product but a necessity. A CRUD backend with a real-time feed is rarely the part with which a team stands out from the competition. Exactly such standard layers are better bought in, because every self-operated hour is missing where the team actually creates value. Small teams without their own platform team, projects with fluctuating load, prototypes that have to go live quickly: in all these cases, dropping the operations is worth more than the control you give up.\n\nWhen does managed become a dead end? As soon as the mapping the service offers no longer fits your own problem. For AppSync in 2021, VTL is this mapping. As long as I pour arguments into DynamoDB calls, it’s a good trade. As soon as I squeeze nested logic, multi-step transformations or merging several sources into templates, I pay back the managed convenience with maintainability. The second dead-end marker is lock-in. Schema and clients stay portable; the VTL resolvers and the DynamoDB key design don’t. If you expect to switch providers later, you should keep this boundary layer deliberately thin.\n\nThis boils the decision down to a few criteria. Is the layer standard or differentiation? How expensive are operations relative to team size? How well does the offered mapping fit your own problem, today and in two years? And how deep does the lock-in go if the answer no longer fits one day? Managed is not a matter of faith but a calculation you redo for each layer. For AppSync, it clearly comes out in favor of buy for a large share of serverless projects, but not for all of them.\n\n## What remains in the end\n\nI’ll come back to the beginning, to the question of running the server. The popular GraphQL content covers schema design and the client side. That is important and stays important, no matter which backend sits underneath. AppSync with DynamoDB is the other half, the managed backend, where the self-written server melts down into a configuration of schema, resolvers and data sources.\n\nThe effect of this decision is concrete: the team still deploys schema, resolvers and infrastructure, but doesn’t run its own GraphQL process or its own WebSocket layer. This leaves more time for the data model and domain logic. Whether the calculation works out depends on how well the resolver runtimes and data sources fit the problem.\n\nThe price for this is the VTL templates and a degree of lock-in to AWS. Both are manageable as long as you know the limits: lean mappings in VTL, complex logic in Lambda, a key design that anticipates the access patterns. Where these limits hold, the trade is excellent. Where they break, the layer should be built yourself. Drawing this line cleanly is the real architecture work, not writing the templates.\n\nAppSync doesn’t stand on its own. It meshes with Lambda, DynamoDB and the other managed services, and it unfolds its value precisely in this interplay.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-aws-serverless.en.html\n- Repository with the schema and resolver examples from my serverless workshops\n- [DynamoDB resolver reference (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html)\n- [`APPSYNC_JS` resolver reference (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-js-version.html)\n- [Tutorial: Simple Post Application with DynamoDB resolvers (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-resolvers.html)\n- [Resolver mapping template overview (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-overview.html)\n- [$util utility reference (AWS)](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-util-reference.html)\n- [AppSync FAQs on data sources and subscriptions (AWS)](https://aws.amazon.com/appsync/faqs/)"},{"locale":"en","translation_key":"context-richtig-einsetzen","slug":"using-react-context-well","title":"Using Context Well: A Distribution Path, Not Secret Global State","summary":"Context solves distributing data through the tree – but not the question of who owns the state. If you confuse the two, you build a global store through the back door and cause unnecessary renders when provider values change carelessly.","tags":["Software","Frontend","React"],"published_at":"2021-05-26T10:00:00+00:00","updated_at":"2026-07-13T07:56:47.211196+00:00","url":"https://www.mikebild.dev/en/blog/using-react-context-well/","audio_url":null,"audio_duration_secs":null,"text":"# Using Context Well: A Distribution Path, Not Secret Global State\n\n```jsx\nconst AppContext = createContext(null);\n\nfunction AppProvider({ children }) {\n  const [user, setUser] = useState(null);\n  const [filter, setFilter] = useState(\"\");\n  const [items, setItems] = useState([]);\n\n  return (\n    <AppContext.Provider value={{ user, setUser, filter, setFilter, items, setItems }}>\n      {children}\n    </AppContext.Provider>\n  );\n}\n```\n\nThree pieces of state hang off a single provider, and the object behind `value` is created anew on every render. One character in the filter field is enough, and everything that reads this Context re-renders along with it – including the header, which only shows the name of the signed-in person. A shortcut through the component tree has turned into a store without anyone consciously making that decision.\n\nContext can do exactly one thing: provide a value at the top and make it readable further down, without the layers in between passing it along. Everything else – where the value comes from, who updates it, how often it changes – remains manual work and has to be decided beforehand. Let us start with the problem Context was built for.\n\n## The problem: prop drilling\n\nIn React, data flows from top to bottom. A component passes values to its children through props, they pass them on to their children, and so on. As long as the path is short, that is exactly right – the data flow is visible, and you can read from the props what a component needs.\n\nIt gets unpleasant when a value is created far up and needed far down, but nothing in between needs it at all. Take the signed-in person: they are determined once at the very top, and needed in the header, in a comment form deep in the tree and in a menu somewhere else entirely. All components along the way have to accept the value and pass it on, even though they only funnel it through.\n\n```jsx\nfunction Page({ user }) {\n  return <Layout user={user} />;\n}\n\nfunction Layout({ user }) {\n  return <Sidebar user={user} />;\n}\n\nfunction Sidebar({ user }) {\n  return <Profile user={user} />;\n}\n\nfunction Profile({ user }) {\n  return <span>{user.name}</span>;\n}\n```\n\n`Layout` and `Sidebar` do not care about `user`. They only carry the prop along because someone further down needs it. That is exactly what is called prop drilling – you drill a value through a layer of components that have nothing to do with it. It makes intermediate components harder to reuse, because they are coupled to data they only pass through, and every new intermediate layer has to take the prop along by hand.\n\n```mermaid\nflowchart TB\n  subgraph drilling[\"prop drilling\"]\n    P1[\"Page (user)\"] --> L1[\"Layout<br/>only passes user on\"]\n    L1 --> S1[\"Sidebar<br/>only passes user on\"]\n    S1 --> Pr1[\"Profile<br/>needs user\"]\n  end\n  subgraph context[\"Context\"]\n    P2[\"Provider (user)\"] -.-> Pr2[\"Profile<br/>reads via useContext\"]\n  end\n```\n\n## How Context works\n\nContext reverses this passing along. Instead of handing a value down layer by layer, you provide it once at the top and read it directly at the bottom – without bothering the layers in between. Three parts belong to it: `createContext` creates the object, a `Provider` provides the value for a subtree, and `useContext` reads it where it is needed.\n\n```jsx\nimport { createContext, useContext } from \"react\";\n\nconst CurrentUserContext = createContext(null);\n\nfunction Page({ user }) {\n  return (\n    <CurrentUserContext.Provider value={user}>\n      <Layout />\n    </CurrentUserContext.Provider>\n  );\n}\n\nfunction Profile() {\n  const user = useContext(CurrentUserContext);\n  return <span>{user.name}</span>;\n}\n```\n\n`Layout` and `Sidebar` are out of the picture – they no longer know about `user` and do not have to pass anything on. `Profile` takes the value directly from the nearest provider above it. That is exactly the job of Context, and for this job it is the right tool: it is a distribution path, a shortcut through the tree.\n\nWhat matters is what does not happen here. The provider does not create the value. It receives it from above and makes it available. Where `user` comes from, who changes it, where it lives – all of that is still completely open at this point. And this is exactly where the problems start if you are not careful.\n\n## The central trap: Context as a substitute for state ownership\n\nBecause Context makes values so conveniently available everywhere, a temptation is close at hand: you simply put everything in it that several components need. The loaded list, the current filter, half-opened dialogs, the entire application state – Context becomes the storage place for everything shared. That feels great at first and reliably takes its revenge later.\n\nTwo consequences come back to bite you. The first is rendering. React compares the old and new provider value with `Object.is`. If they differ, the components that read this Context re-render; plain descendants without `useContext` are not automatically affected. With a large object as the Context value, however, a changed reference also affects consumers that only use a different field from it. A small update can turn into a wave of renders this way.\n\n```mermaid\nflowchart TB\n  Change[\"Context value changes\"] --> P[\"Provider\"]\n  P --> C1[\"Consumer A<br/>shows the value\"]\n  P --> C2[\"Consumer B<br/>reads another field –<br/>re-renders anyway\"]\n  P --> C3[\"Consumer C<br/>reads another field –<br/>re-renders anyway\"]\n```\n\nIn one project, the value of a search field happened to sit in the same Context as the theme. With every keystroke in the search field, half the UI flickered – components that had nothing to do with the search re-rendered along with it, just because they were attached to the same Context. The value had ended up in the wrong container.\n\nThe second consequence is coupling. Everything that reads from a Context is bound to that provider. You can no longer use, test or reuse such a component in isolation without building the matching provider around it. The more a Context holds, the more components depend on it, and the more sluggish the application becomes. Context makes the origin of a value invisible – that is an advantage for distribution and a problem for ownership, because you no longer see who is actually responsible for a value.\n\nThe core of the misunderstanding is this: Context answers the question “how does the data get to where it is needed.” It does not answer the question “who owns the data and who may change it.” You still have to answer the second question – state ownership – yourself, with `useState` or `useReducer` in a clearly named component. Context does not replace this decision; it only transports its result.\n\n## Rules for clean use\n\nThree rules follow from this separation, and they keep Context exactly what it is meant to be – a means of transport.\n\nFirst: ownership lives at the top, Context only passes it through. The state belongs in a clearly named component – let us call it `CurrentUserProvider` – that holds it with `useState` or `useReducer`. This component is the one place where the value lives and is changed. Context transports it from there downward, nothing more. If you open the provider and look for `useState`, you find the owner right away; if you do not find it, you have probably built hidden global state.\n\nSecond: keep the value stable. This is where the most common concrete mistake lies. If you write a fresh object directly into `value`, every render of the provider component creates a new reference – and because the reference changes, all consumers re-render, even if nothing has changed in content:\n\n```jsx\nfunction CurrentUserProvider({ children }) {\n  const [user, setUser] = useState(null);\n\n  // new object on every render → all consumers re-render\n  return (\n    <CurrentUserContext.Provider value={{ user, setUser }}>\n      {children}\n    </CurrentUserContext.Provider>\n  );\n}\n```\n\nThe fix is to memoize the value so that the reference only changes when something has actually changed:\n\n```jsx\nfunction CurrentUserProvider({ children }) {\n  const [user, setUser] = useState(null);\n  const value = useMemo(() => ({ user, setUser }), [user]);\n\n  return (\n    <CurrentUserContext.Provider value={value}>\n      {children}\n    </CurrentUserContext.Provider>\n  );\n}\n```\n\nWith state from `useReducer`, a second step is often worth it: put state and dispatch into two separate Contexts. Dispatch is stable; it never changes. If you split it off, components that only trigger actions and do not display the state at all no longer re-render on a state change – they only depend on the immutable dispatch Context.\n\n```jsx\nconst StateContext = createContext(null);\nconst DispatchContext = createContext(null);\n\nfunction StoreProvider({ children }) {\n  const [state, dispatch] = useReducer(reducer, initialState);\n\n  return (\n    <StateContext.Provider value={state}>\n      <DispatchContext.Provider value={dispatch}>\n        {children}\n      </DispatchContext.Provider>\n    </StateContext.Provider>\n  );\n}\n```\n\nThird: do not put every changing value into it. Some things you reflexively put into a Context belong elsewhere. Server data – loaded lists, detail data, search results – is not application state but a cache, and it belongs in a data fetching library, not in Context. I covered this boundary in detail in “Client State vs. Server Cache.” And the current selection, the filter, the page in a list belong in the URL – shareable, bookmarkable, and they survive a reload. Subtract these two categories and surprisingly little is left for Context, and exactly that remainder is its real home.\n\n## What Context is really good for\n\nContext plays to its strength with rarely changing, app-wide things – with what describes the environment of an application rather than its actual data. The active theme, the selected language, the signed-in person, an app-wide service or dispatch function: such values change rarely but are needed in many places. That is exactly what a distribution path that skips the layers in between is meant for.\n\nThe common denominator of these good cases is that they are “environment” and not “application data.” They do not change every second, so the wave of renders hardly matters. And they really are app-wide, so the coupling to a provider does not get in the way – you only want to use these components inside the application anyway. Before every new Context, a test question is therefore worth asking: does the value describe the environment a component runs in, or the data it displays? Only the former belongs in it.\n\n## Context and reducer as a small global core\n\nFor a manageable global core, Context and `useReducer` can be combined into a lightweight pattern. The reducer holds the state and the logic in one place, two separate Contexts distribute state and dispatch, and consumers access them through small hooks:\n\n```jsx\nfunction useStore() {\n  return useContext(StateContext);\n}\n\nfunction useDispatch() {\n  return useContext(DispatchContext);\n}\n```\n\nThat goes surprisingly far – for a shopping cart, a few app-wide settings, a small set of actions. Ownership is clear (in the `StoreProvider`), transport is clean (two Contexts), and separating state and dispatch keeps renders in check.\n\nBut you should know the limit of this pattern and name it openly: Context is not state management, it is transport. The reducer next to it is the actual logic, and Context only passes its result through. As long as the core stays small, the pattern holds. When the logic grows – many interdependent pieces of state, selectively reading individual fields without waves of renders, middleware, persistence, time travel while debugging – the combination reaches its limits. Then you need a real store that is built for exactly these jobs. That is not a defeat for Context, but the right division of labor: Context never claimed to be a store.\n\n## What should stick\n\nContext answers a single question very well: how the data gets to where it is needed. It does not answer the other, more important question: who owns it and who changes it. You have to answer that second question yourself, in a clearly named component with `useState` or `useReducer`, before you touch Context at all.\n\nIf you keep these two questions cleanly apart, you use Context for what it is – a distribution path for a few rarely changing, app-wide values, with a stable `value` and, where needed, separate state and dispatch Contexts. If you mix them up, you build global state through the back door, complete with waves of renders and coupling. The difference costs one single deliberate decision while writing and saves a lot of debugging afterwards.\n\n## Further reading\n\n- Repository introduction-react: https://github.com/mikebild/introduction-react\n- react.dev, “Passing Data Deeply with Context”: https://react.dev/learn/passing-data-deeply-with-context\n- react.dev, “Scaling Up with Reducer and Context”: https://react.dev/learn/scaling-up-with-reducer-and-context\n- [react.dev: `useContext`, value comparison and re-rendering](https://react.dev/reference/react/useContext)"},{"locale":"en","translation_key":"python-daten-einlesen","slug":"reading-data-in-python","title":"Reading Data in Python: CSV, JSON, Excel and Databases","summary":"A toolkit for every data source: when the standard library is enough, when pandas pays off, and how to keep encoding, memory and SQL injection from becoming your downfall.","tags":["Software","Python","Data"],"published_at":"2021-04-27T10:00:00+00:00","updated_at":"2026-07-13T10:32:52.212694+00:00","url":"https://www.mikebild.dev/en/blog/reading-data-in-python/","audio_url":null,"audio_duration_secs":null,"text":"A reader is not a transport function. `csv.DictReader`, `json.load`, `pandas.read_excel` – they all turn foreign bytes into Python objects, and in that transition it is decided whether an `ä` stays an `ä`, whether a required column is filled and whether an input will later wipe out an entire table. And the sources are rarely as tidy as you’d like: a CSV file someone pulled from an export. A JSON response from an API. An Excel workbook with three sheets and a header that only starts in row four. Or an SQLite file sitting quietly in the project folder, waiting to be queried.\n\nWhich reader I pick for this is the smaller decision. The bigger one is where trust is established: Is the encoding right, are required fields filled, do the types match? A wrongly decoded umlaut or an unchecked input rarely costs anything at read time – the bill comes later, in the report to the customer, in the database, in the model trained on garbage. Reading data is therefore the boundary where data quality is decided.\n\nThe step is unspectacular, and yet a surprising number of projects get stuck on it. It isn’t hard, just confusing: Python has its own way for every format, and it’s easy to lose track of which one is right when. This article puts together a small toolkit for it: the standard library for direct, row-by-row access, pandas for tabular analysis work, and a parameterized database query that never leads into the most common security trap in the first place. The tools are quickly explained – more interesting is the attitude behind them: treating data as a domain whose quality you actively own.\n\n## Data is a domain, not a sideshow\n\nBefore we get to readers, it’s worth taking a step back. If reading data is seen as transport – bytes in, objects out, move on – that is an expensive view, because it puts trust in the wrong place. If I only check late – in the report, in the analysis, in the production endpoint – then I’m checking data that has long since traveled through half my system. The error is then no longer a line in a file but an incident with a name: wrong revenue for the customer, a record that skews an analysis, an input that wipes a table.\n\nThat’s why I treat reading data as its own small domain with a clear job: turn unknown bytes into trustworthy, typed objects – and reject everything that doesn’t meet that bar. Three questions decide the product risk here, and all three arise at the system boundary. Encoding: Is a character really the intended character? An `Ã¤` instead of `ä` is not a cosmetic flaw. It is silent data damage that propagates through every later search, every comparison, every export. Trust: Who owns the source? I treat my own export differently from user input or a third-party API – for anything coming from outside, the assumption is that it may be hostile. Validation: Are the fields there, and do they have the expected shape?\n\nThe trade-off lies in validation, because checking takes time. The further the data travels and the more people depend on it in the end, the earlier and stricter I check. A throwaway script for a one-off analysis can be lenient. A reader that feeds a customer database or a recurring report checks at the boundary and visibly rejects faulty data instead of passing it on without complaint. The gain is concrete: a problem shows up where it originates, with file and line – instead of three layers later as mysterious misbehavior that you have to trace backwards through half a system.\n\n## The two camps: standard library or pandas\n\nBefore we write code, a rough classification helps. Python already ships everything you need for the most common formats – `csv`, `json`, `xml.etree` and `sqlite3` are part of the standard library, with nothing to install. These modules work close to the raw data: you get lists, dictionaries, individual rows. That’s ideal when you want to process a file row by row, have little memory available or simply don’t want to pull an external dependency into your project.\n\npandas belongs to the other camp. It’s an additional library, and it pays off whenever your data is tabular and you want to analyze, filter or aggregate it. Instead of maintaining a separate mental model for each format, in pandas you always end up in the same `DataFrame` – no matter whether the source was a CSV, an Excel workbook, a JSON document or an SQL query. `read_csv`, `read_excel`, `read_json`, `read_sql`: one reader per format, one common target. On top of that come type inference and a rich set of operations.\n\nThe following overview shows the path from source to target structure:\n\n```mermaid\nflowchart LR\n  CSV[CSV] --> STD[Standard library<br/>csv, json, etree, sqlite3]\n  JSON[JSON] --> STD\n  XML[XML] --> STD\n  DB[(SQLite/DB)] --> STD\n  CSV --> PD[pandas<br/>read_csv, read_excel, read_sql]\n  XLSX[Excel .xlsx] --> PD\n  DB --> PD\n  STD --> DICTS[dicts / lists]\n  PD --> DF[DataFrame]\n```\n\nThe classification I decide by is short: row by row, small, no extra dependency – standard library. Tabular, analytical, with filters and aggregates – pandas. And you can only sensibly read Excel in the modern `.xlsx` format through pandas anyway (with a helper library), because the standard library can’t do it. What matters is not the most convenient API but the data volume and the work that is supposed to happen with the data afterwards.\n\n## CSV with the standard library: the classic\n\nCSV is the format you’ll run into most often, and at the same time the one with the most little pitfalls. The standard library offers two ways: `csv.reader` returns a list per row, `csv.DictReader` returns a dictionary per row and automatically uses the header row as keys. In practice I almost always reach for `DictReader`, because access through meaningful column names makes the code more readable.\n\n```python\nimport csv\n\nwith open(\"customers.csv\", newline=\"\", encoding=\"utf-8\") as f:\n    reader = csv.DictReader(f)          # header row becomes dict keys\n    rows = [row for row in reader]      # each row is a dict\n\nfor row in rows[:3]:\n    print(row[\"name\"], row[\"email\"])\n```\n\nTwo details on this `open` line are more important than they look. First, `newline=\"\"`: the `csv` module handles line breaks inside fields itself, and if you don’t open the file with an empty `newline`, rows can get torn apart under certain conditions. The documentation says so, and it’s one of those rules you learn once and never forget – usually after the first broken record.\n\nSecond, `encoding=\"utf-8\"`. More on that in a moment, because this is where the pitfall lies that causes the most confusion in projects – hardly any data error shows up as reliably.\n\nA nice side effect of `DictReader`: because it iterates over the file, you can also use it for large files without loading everything into memory at once. Instead of materializing the list with a comprehension, you then process row by row in the loop and keep only what you really need.\n\n## JSON: from file to Python object\n\nJSON is pleasantly straightforward in Python, because the structure maps almost one to one onto dictionaries and lists. `json.load` reads from an open file object, `json.loads` from a string. The result is a perfectly normal Python object you can work with right away.\n\n```python\nimport json\n\nwith open(\"config.json\", encoding=\"utf-8\") as f:\n    data = json.load(f)         # dict or list, depending on the document\n\nprint(data[\"version\"])\nfor item in data[\"items\"]:\n    print(item[\"id\"], item[\"title\"])\n```\n\nFor writing back, there are the counterparts `json.dump` and `json.dumps`. When writing, `ensure_ascii=False` is usually worth it so umlauts end up in the file as real characters rather than `\\u` escapes, along with `indent=2` for readable formatting. When reading, you don’t need these options – JSON is refreshingly undemanding there.\n\n## Excel: here the path leads through pandas\n\nAs soon as real tables come into play – several sheets, number formats, header rows – pandas becomes the tool of choice. `read_excel` reads an `.xlsx` into a DataFrame, and you can pick a specific sheet with `sheet_name`.\n\n```python\nimport pandas as pd\n\ndf = pd.read_excel(\"report.xlsx\", sheet_name=\"Sales\")  # openpyxl engine by default\nprint(df.head())\nprint(df[\"revenue\"].sum())\n```\n\nOne point many people stumble over the first time: for `.xlsx`, `read_excel` needs an additional library called `openpyxl`. Since pandas 1.2.0 (end of 2020), `openpyxl` has been the default engine for this format – the older `xlrd` library no longer supports modern `.xlsx` files and is only responsible for the old `.xls` files. So if you get an error message about a missing engine, the fix is almost always `pip install openpyxl`.\n\nIf you pass `sheet_name=None`, pandas returns a dictionary of all sheets as DataFrames – handy when you want to read a whole workbook. And if your header isn’t in the first row, the `header` parameter helps you set the right row as column names.\n\n## Databases: sqlite3 and the most important security note\n\nSQLite is my default tool for database access in small projects and prototypes, because it needs no server and the `sqlite3` module is already part of the standard library. The flow is always the same: open a connection, get a cursor, run a query, fetch the result, close the connection.\n\n```python\nimport sqlite3\n\nconn = sqlite3.connect(\"shop.db\")\ncur = conn.cursor()\n\ncategory = \"books\"\ncur.execute(\n    \"SELECT name, price FROM products WHERE category = ?\",\n    (category,),\n)\nresult = cur.fetchall()\n\nfor name, price in result:\n    print(name, price)\n\nconn.close()\n```\n\nThe crucial part is in the `execute` line: the question mark as a placeholder and the value as a separate tuple in the second argument. This is not a matter of style but a matter of security. If you build the value directly into the SQL string instead – via concatenation or an f-string – you open the door to SQL injection. A manipulated input field can then rewrite the query, read data or delete entire tables.\n\nThe comparison makes the difference clear:\n\n```python\n# unsafe: never do this\ncur.execute(f\"SELECT name, price FROM products WHERE category = '{category}'\")\n\n# safe: the driver handles quoting and escaping\ncur.execute(\n    \"SELECT name, price FROM products WHERE category = ?\",\n    (category,),\n)\n```\n\nBesides security, the parameterized way has a second advantage: the database driver handles quoting and escaping for you. You don’t have to worry about quotation marks in the value. One important detail: the placeholder `?` appears **without** surrounding quotation marks in the SQL text – the driver does the quoting, not you.\n\nIf you want more convenience or want to switch between different databases, SQLAlchemy comes into play. With `create_engine(\"sqlite:///shop.db\")` you set up a connection, and `pandas.read_sql(query, con)` reads the result directly into a DataFrame. That closes the loop between database and analysis: the query comes from SQL, and the result lands straight in the familiar pandas model.\n\n## And XML? Don’t forget it, but you’ll rarely need it\n\nYou’ll run into XML less often than you used to, but it still shows up in configurations, exports and older interfaces. The standard library covers it with `xml.etree.ElementTree`. You parse the source into a tree, get the root and navigate with `find`, `findall` and `iter` to the elements you care about.\n\n```python\nimport xml.etree.ElementTree as ET\n\ntree = ET.parse(\"catalog.xml\")\nroot = tree.getroot()\n\nfor product in root.findall(\"product\"):\n    name = product.find(\"name\").text\n    price = product.get(\"price\")        # read an attribute\n    print(name, price)\n```\n\nFor simple structures, that’s entirely sufficient. With more complex XML documents with namespaces or deep nesting, it quickly gets fiddly – then I like to reach for specialized libraries. For everyday work, though, `ElementTree` covers most cases.\n\n## Which reader for which format?\n\nTo help you keep track, here is the mapping as a compact list:\n\n- For CSV, use `csv.DictReader` from the standard library for row-by-row reading and `pandas.read_csv` as soon as it gets analytical.\n- For JSON, `json.load` and `json.loads` from the standard library are enough; `pandas.read_json` helps when the JSON is tabular.\n- For Excel in the `.xlsx` format, the path leads through `pandas.read_excel` with `openpyxl` installed – the standard library can’t handle this format.\n- For databases, `sqlite3` covers direct, parameterized access; `pandas.read_sql` or SQLAlchemy come in when analysis or portability is needed.\n- For XML, `xml.etree.ElementTree` from the standard library is enough for manageable documents.\n\n## Three pitfalls that strike again and again\n\nIn practice, it’s rarely the readers themselves that cause problems, but three recurring topics around reading data.\n\n### Encoding\n\nWhy encoding is a product risk was covered above – here is the practical part. The default character set when opening a file depends on the platform, on Windows often `cp1252` instead of UTF-8. If umlauts appear as `Ã¤` or `Ã¶`, or a `UnicodeDecodeError` shows up, the encoding is almost always to blame, and the fix is to specify it explicitly: `encoding=\"utf-8\"`. For files exported from Excel, you often need `encoding=\"utf-8-sig\"`, because Excel puts a so-called byte order mark at the beginning, which plain `utf-8` misreads as a special character.\n\n### Loading large files entirely into memory\n\nIt’s tempting to simply load a CSV in full with `pandas.read_csv(\"big.csv\")` – until the file is several gigabytes and memory overflows. pandas offers `chunksize` for this: instead of a DataFrame, you then get an iterator that lets you work through the file in blocks.\n\n```python\nimport pandas as pd\n\ntotal = 0\nfor chunk in pd.read_csv(\"big.csv\", chunksize=100_000):\n    total += chunk[\"amount\"].sum()     # process one block at a time\n\nprint(total)\n```\n\nIn the standard library you achieve the same by iterating row by row with `DictReader` instead of materializing everything into a list. One more note: `read_excel` has no native chunking – for very large tables it’s worth converting the data to CSV or into a database beforehand.\n\n### SQL injection\n\nImportant enough to repeat: never build user input into an SQL query via string concatenation or an f-string. Always use placeholders and pass the values separately. It doesn’t cost an extra line of code and saves you from an entire class of security vulnerabilities.\n\nThe following decision tree sums up how I choose the path in practice:\n\n```mermaid\nflowchart TD\n  A{Tabular<br/>analysis needed?} -->|yes| B[pandas]\n  A -->|no| C{Row by row,<br/>small, no dependency?}\n  C -->|yes| D[Standard library]\n  C -->|no| B\n  B --> E{Very large file?}\n  E -->|yes| F[chunksize / streaming]\n  E -->|no| G[read directly]\n```\n\n## Conclusion\n\nThe choice of tool is quickly made: for row-by-row, direct access without an extra dependency, the standard library with `csv`, `json`, `xml.etree` and `sqlite3` is enough; as soon as things get tabular and analytical, or Excel is involved, pandas pays off with its uniform DataFrame model. The difference between a script that runs and one you trust doesn’t come from the readers but from the attitude: encoding, trust and validation belong at the system boundary.\n\nIf you draw this boundary deliberately, you change the economics of the project. Errors show up early and with a name instead of late and mysteriously – that shortens debugging cycles and takes friction out of further work. The data that gets through is the data you can trust, which raises the quality of every later step. And the three reflexes that go with it cost almost nothing: always set the encoding explicitly so umlauts don’t fall apart. With large files, think early about `chunksize` or row-by-row streaming instead of filling up memory. Database queries always with placeholders, never with assembled SQL. The clear upper limit matters too: not every script needs full schema validation, and where effort and risk don’t match, leniency is the right choice. If you decide this instead of leaving it to chance, you reach your goal quickly and safely – and can turn to what’s actually interesting: what’s in the data.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-python.en.html\n- Repository `introduction-python` – data access examples from my training courses (`csv`, `json`, `sqlite3`, pandas).\n- csv – Python documentation: https://docs.python.org/3/library/csv.html\n- json – Python documentation: https://docs.python.org/3/library/json.html\n- sqlite3 – Python documentation: https://docs.python.org/3/library/sqlite3.html\n- xml.etree.ElementTree – Python documentation: https://docs.python.org/3/library/xml.etree.elementtree.html\n- pandas IO guide: https://pandas.pydata.org/docs/user_guide/io.html\n- pandas 1.2.0 – openpyxl as the default engine: https://pandas.pydata.org/docs/whatsnew/v1.2.0.html\n- SQLAlchemy documentation: https://docs.sqlalchemy.org/en/14/"},{"locale":"en","translation_key":"adr-entscheidungen-die-man-versteht","slug":"adrs-decisions-you-still-understand","title":"Architecture Decision Records: Decisions You Will Still Understand in Two Years","summary":"Why did we choose PostgreSQL back then and decide against the message bus? ADRs make the why durable as a versioned Markdown artifact – instead of letting it seep away in hallway talk.","tags":["Software","Architecture"],"published_at":"2021-03-26T10:00:00+00:00","updated_at":"2026-07-13T08:40:51.197927+00:00","url":"https://www.mikebild.dev/en/blog/adrs-decisions-you-still-understand/","audio_url":null,"audio_duration_secs":null,"text":"Five sections are enough to make an architecture decision durable: Title, Status, Context, Decision, Consequences. Michael Nygard described this format in 2011 in his blog post “Documenting Architecture Decisions” and called it an Architecture Decision Record, ADR for short – a small, versioned text artifact that records exactly one decision together with its forces. One page of Markdown, nothing more.\n\nNygard states the motivation right in the first sentence: “One of the hardest things to track during the life of a project is the motivation behind certain decisions.” The *what* is in the code. The *why* is nowhere – or it’s buried in a Slack thread, a Confluence page nobody can find anymore, or in the head of someone who happens to be on vacation. The most expensive question in a project is therefore rarely “How do we build this?” but “Why did we actually build it this way back then?” A team takes over a system, runs into a strange decision – an unusual database, a homegrown cache, skipping the obvious message bus – and nobody can say whether it was intentional or an accident. The people who knew are long gone to the next project or the next company. What remains is code that executes a decision whose rationale has evaporated.\n\n## The outcome first: less archaeology, faster handovers\n\nBefore I talk about format and tooling, I want to say what ADRs bring in practice – because that’s what this is about, not another documentation ritual. In the projects where I introduced ADRs, one thing in particular gets dramatically shorter: the time it takes a new team member to go from “I understand the code but not the logic behind it” to “I can take part in decisions here.” Onboarding turns from digging into reading up.\n\nThe second effect is subtler but more valuable. When a decision *has to* be written down, it also gets made more deliberately. While writing, you notice whether you really weighed alternatives or just took the first path that came along. The artifact doesn’t force more bureaucracy – it forces clarity. And clarity at the moment of decision is cheaper than any later reconstruction.\n\nWhat matters to me here is the distinction Nygard makes himself: agile methods are not against documentation, they are against *valueless* documentation. The 80-page architecture handbook that’s outdated by the first commit is valueless. A one-page ADR that sits next to the code and travels with it through the Git history is not. ADRs are the lightweight compromise between “write nothing down” and “document everything to death.”\n\n## The format: five sections, one decision\n\nNygard describes ADRs as “a format similar to an Alexandrian pattern” – a short text that describes a set of forces and records *one* decision in response to them. The format is deliberately minimal, and the brevity is not a shortcoming but the feature: small documents are more likely to be kept up to date than large ones.\n\nThis is what an ADR typically looks like for me. It lives as Markdown in the same repository as the code, under `docs/adr/`:\n\n```markdown\n# 7. Use PostgreSQL as primary datastore\n\nDate: 2021-03-12\n\n## Status\n\nAccepted   <!-- proposed | accepted | superseded by ADR-0012 -->\n\n## Context\n\nThe core service needs a transactional store. Expected load is\nmoderate (low thousands of writes per minute at peak). The team\nhas deep operational experience with PostgreSQL and none with\ndistributed NewSQL stores. Strong consistency is a hard requirement\nfor the billing path.\n\n## Decision\n\nWe will use PostgreSQL as the primary datastore for the core service.\n\n## Consequences\n\nPositive: strong consistency, mature tooling, no learning curve for the team.\nNegative: single-primary HA needs operational care; revisit this decision\nif sustained write throughput exceeds ~5k writes/second.\n```\n\nThe Context section is where the real value lies. It describes what Nygard calls the “balancing of forces” – the forces acting on the decision: expected load, team skills, consistency guarantees, cost. If you read this ADR two years from now, you don’t just see *that* PostgreSQL was chosen but under which assumptions. And – this is crucial – the Consequences section even names the condition under which the decision should be reevaluated. That’s not dogma; it’s a state of thinking, preserved.\n\nOne point here is often overlooked: the Context has to describe the world *at the time of the decision*, not the world of today. An ADR is a snapshot, not a living document. That leads directly to the most important principle.\n\n## Immutability: ADRs are never overwritten\n\nThe most common mistake I see when teams try ADRs for the first time: they treat an ADR like a wiki page and update it when the decision changes. That destroys the whole point. An ADR is a log entry, not a state object.\n\nThe rule is: once an ADR has been accepted, its content is never changed again. If the decision changes, you write a *new* ADR that replaces the old one. The old one gets the status `superseded` and a reference to its successor. The numbering is sequential and never reused – 0001, 0002, 0003, even if 0002 is long outdated. What you get is a decision *log*: a complete history that shows which decision applied when and what replaced it.\n\n```\ndocs/adr/          # sequential, zero-padded, never renumbered\n  0001-record-architecture-decisions.md\n  0002-use-markdown-for-adrs.md\n  0007-use-postgres-as-primary-datastore.md   # Status: superseded by 0012\n  0012-switch-to-cockroachdb.md               # Status: accepted\n```\n\nYou can think of this lifecycle as a state diagram. An ADR moves from `proposed` to `accepted` – and at some point, maybe, to `superseded`, with the pointer referring to the following ADR:\n\n```mermaid\nstateDiagram-v2\n    [*] --> proposed\n    proposed --> accepted: PR merged\n    proposed --> rejected: not adopted\n    accepted --> superseded: replaced by newer ADR\n    superseded --> [*]: points to successor ADR\n    rejected --> [*]\n```\n\nThe charm of this is that the Git history and the ADR history run in parallel. Both live in the same repo, both travel through the same commits. When I check out an old commit, I see the ADRs that belonged to that state. The why travels through time with the code.\n\n## Hallway talk versus artifact\n\nTo show what ADRs actually change, a simple contrast helps. On one side is the normal state of many teams: decisions are made in meetings, in chat threads, in passing at the coffee machine. They are real, they shape the architecture – but they can’t be found anywhere. On the other side is the versioned Markdown artifact that lives in the repo and is reviewed via the pull request.\n\n```mermaid\nflowchart LR\n    subgraph Flurfunk\n        A[Slack thread] --> X[lost knowledge]\n        B[whiteboard photo] --> X\n        C[hallway talk] --> X\n        D[someone's memory] --> X\n    end\n    subgraph Artefakt\n        E[ADR in docs/adr/] --> G[reviewed via PR]\n        G --> H[versioned with the code]\n        H --> I[readable in two years]\n    end\n```\n\nThe difference is not that no decisions are made on the left. The same decisions are made. The difference is whether the rationale becomes an artifact or evaporates. And in the end, that’s a question of friction: as long as writing things down costs more than forgetting them, things get forgotten. ADRs work because they make writing down so cheap – one Markdown file, one commit, done – that it’s worth it.\n\n## Tooling: just enough not to get in the way\n\nYou don’t need a tool for ADRs. A text file and Git are enough. Still, a bit of convention helps keep the numbering and the template consistent. Nat Pryce built `adr-tools` for this, a lean CLI you install via Homebrew:\n\n```bash\n# create a new, auto-numbered ADR from the standard template\n$ adr new \"Use PostgreSQL as primary datastore\"\n# -> docs/adr/0007-use-postgres-as-primary-datastore.md\n\n# create an ADR that supersedes an earlier one\n$ adr new -s 7 \"Switch to CockroachDB\"\n# -> docs/adr/0012-switch-to-cockroachdb.md\n#    and sets ADR-0007 status to \"superseded by 0012\"\n```\n\nIf you prefer a richer template, MADR – “Markdown Any Decision Records” – offers a more structured one that explicitly leaves room for the options that were weighed. To get started, though, I almost always recommend the bare five Nygard sections. You can refine later; it’s hard to introduce discipline after the fact.\n\nThe most effective lever isn’t a tool anyway but a process habit: an architecture-relevant change in a pull request only gets merged if the corresponding ADR is in the same PR. That makes the ADR part of the review. The decision isn’t just recorded but read by at least one other person at the same moment. The lonely “I just built something” becomes a deliberate, shared step.\n\nBy the way, that the format holds up is not a lone opinion. The ThoughtWorks Technology Radar placed “Lightweight Architecture Decision Records” in *Adopt* – the highest recommendation level – as early as November 2017. That’s no longer a novelty; it’s established practice.\n\n## Where ADRs tip over – the honest chapter\n\nADRs don’t run themselves. They fail, and in three predictable ways.\n\nThe first failure mode: ADRs go stale anyway. If you don’t write them with discipline for every relevant decision, you get a history full of gaps. And a history full of gaps is more dangerous than none at all, because it pretends to be complete. If someone reads “these are our decisions” and the crucial one is missing, they draw wrong conclusions. They rely on a log that lies – not by saying something false, but by leaving something out. Discipline beats tooling, always. No CLI and no template replaces the simple habit of pausing briefly at the moment of decision and recording it.\n\nThe second failure mode: too big, too late. As soon as ADRs swell into design documents, the update rate drops, and Nygard’s whole point – brevity – is lost. Post-hoc ADRs are especially treacherous, that is, rationales you hand in weeks after the decision. They only rationalize instead of capturing the real forces. You then no longer write down *why* you decided but why the decision looks good in hindsight. That’s self-deception in Markdown – and it’s hard to spot, because a cleanly worded ADR looks convincing regardless of whether it captures the real forces or just builds a pretty facade in front of them.\n\nThe third failure mode: the wrong granularity. Without a defined trigger, one of two things happens. Either every trifle becomes an ADR, and the signal drowns in noise. Or nobody knows what “architecture-relevant” means, and nothing gets written at all. A rough threshold, agreed on early in the team, helps: an ADR is written when a decision is hard to reverse, affects several teams or deliberately rejects an obvious alternative. Everything else is a comment in the code, not an ADR. This threshold may stay fuzzy; more important than the exact line is that the team shares any common idea of it at all.\n\nOne more thought that lifts ADRs beyond pure documentation: if you take the condition in the Consequences section seriously – “revisit if write throughput exceeds 5k/s” – you can make it verifiable. In *Building Evolutionary Architecture*, Ford, Parsons and Kua call these *fitness functions*: automated checks that measure an architectural property. An ADR documents the decision; a Fitness Function watches over whether its assumption still holds. Together, they turn a dead document into a living guardian.\n\n## Conclusion\n\nADRs don’t solve a technical problem. They solve a memory problem – and in the long run, memory problems are more expensive than technical ones because they accrue interest. Every undocumented decision turns into a small debt over time: at some point, someone has to laboriously reconstruct what could have been written down in five minutes.\n\nThe core is unspectacular and precisely for that reason durable: in my convention, an accepted text stays unchanged; a new decision replaces it with a reference to the old ADR. That way, context, decision and consequences stay versioned next to the code and reviewable via the pull request. This doesn’t need a new system, just the discipline to record the why while it’s still fresh.\n\nThe easiest start is the first ADR itself – the one that records that from now on, ADRs will be written. `0001-record-architecture-decisions.md`. Everything else follows once the habit is in place. And in two years, someone will read it whom nobody on the team knows today.\n\n## Further reading\n\n- Michael Nygard, “Documenting Architecture Decisions” (Cognitect, 2011): https://cognitect.com/blog/2011/11/15/documenting-architecture-decisions.html\n- Martin Fowler, bliki “Architecture Decision Record”: https://martinfowler.com/bliki/ArchitectureDecisionRecord.html\n- ThoughtWorks Technology Radar, “Lightweight Architecture Decision Records” (Adopt, Nov 2017): https://www.thoughtworks.com/radar/techniques/lightweight-architecture-decision-records\n- adr.github.io – community collection on ADRs and tooling: https://adr.github.io/"},{"locale":"en","translation_key":"graphql-schema-das-mitwaechst","slug":"a-graphql-schema-that-grows","title":"A GraphQL Schema That Grows: Evolution Without Breakage","summary":"How to evolve a GraphQL schema additively instead of versioning it – safe changes, real breaking changes, @deprecated as a tool and a field migration step by step.","tags":["Software","API","GraphQL"],"published_at":"2021-03-24T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/a-graphql-schema-that-grows/","audio_url":null,"audio_duration_secs":null,"text":"# A GraphQL Schema That Grows: Evolution Without Breakage\n\nA schema doesn’t break because it grows, but because it takes something back. One more field doesn’t bother any running client; one field less, a renamed argument, a withdrawn guarantee shuts it down. All of schema evolution rests on this one distinction – adding or taking back. In everyday work, it’s just less clear-cut than it sounds: some things look like a takeback and are completely harmless, some look purely additive and break anyway.\n\nThe typed contract between server and client that I described in the GraphQL overview and in the GraphQL concepts is simple at the moment it is written down. It gets hard in ongoing operation: a new field has to go in, an old one has become superfluous, a signature no longer fits. Meanwhile, clients are running out there, some of which you don’t even know – web, mobile, a partner backend, an app version from eighteen months ago that is still in the field. Almost anyone can design a GraphQL schema. Maintaining it for years without breaking existing clients is the actual discipline.\n\n## Not /v2, but one schema\n\nIf you come from REST, you have a reflex: for a bigger change, you build `/v2`. The old URL stays, the new one runs alongside it, and at some point you switch off `/v1`. That works, but it costs – every version is code that someone builds, tests, operates and documents, often in parallel for years.\n\nGraphQL takes a different path. There is no version number in the URL, just exactly one schema that evolves additively. The reason lies in a property I already described in the concepts: a client gets only what it names in its query. It asks for `name` and `title`, so it gets `name` and `title` – and nothing else. If a `subtitle` field is added to the schema tomorrow, this client won’t even notice. It never named it, so it doesn’t show up in its response, and its response keeps exactly the same shape as yesterday.\n\nThat’s the lever. Because the client determines the shape of its response itself, additional fields in the schema fundamentally don’t bother it. So you can let the schema grow without every addition being an event. The official docs put it in a nutshell: GraphQL takes a strong opinion on avoiding versioning and instead provides tools for the continuous evolution of a schema.\n\n## Safe changes: what you can simply add\n\nA whole class of changes is harmless by nature, because they only add and never take away anything a client relies on. A new field on an existing type goes unnoticed by anyone who doesn’t query it. A new type or a new query or mutation entry point is purely an offer, not an obligation. A new optional argument on an existing field keeps everyone who omits it on the old behavior – provided the default matches what applied before. And a new enum value is also additive, though with a caveat I’ll come back to shortly, because there’s a trap lurking here.\n\nThe common denominator: existing queries return the same result after the change as before. That is the actual definition of “non-breaking” – not that nothing changes, but that no valid query from yesterday suddenly becomes invalid today or returns a different shape.\n\n## Breaking changes: what really tears clients apart\n\nOn the other side are the changes that break a query that was valid yesterday. The most important ones, with concrete examples:\n\nThe most obvious is removing or renaming a field. If a client asks for `user { fullName }` and I rename `fullName` to `displayName`, the query is invalid immediately. From the schema’s point of view, renaming is nothing but deleting plus adding – the old name disappears, and every query that names it runs into a validation error.\n\nMore subtle, and reliably good for a surprise, is nullability in the wrong direction. Tightening a nullable field to non-null is *not* breaking: anyone who has so far reckoned with a possible `null` can also cope with a value always coming now. The other way around, however – making a non-null field nullable – *is* breaking. A client that relied on the `String!` guarantee and never checked for `null` suddenly gets a `null` it doesn’t expect. The same logic applies to arguments, just mirrored: making a required argument optional is harmless, making an optional one required breaks everyone who has omitted it so far.\n\nA changed argument type or a new required argument also breaks. If a `String` argument becomes an `Int`, existing queries no longer fit. And a new *non-optional* argument makes every query invalid that doesn’t supply it yet – hence the emphasis on *optional* above.\n\nAnd removing an enum value breaks just the same: if a value disappears that a client sends as an argument or expects in a response, the interaction breaks.\n\n```mermaid\nflowchart LR\n  subgraph Additiv[\"Safe – additive\"]\n    A1[\"add a field\"]\n    A2[\"add a type\"]\n    A3[\"optional argument\"]\n    A4[\"nullable → non-null\"]\n  end\n  subgraph Breaking[\"Breaks clients\"]\n    B1[\"remove/rename a field\"]\n    B2[\"non-null → nullable\"]\n    B3[\"add a required argument\"]\n    B4[\"remove an enum value\"]\n  end\n```\n\nThe trick when reading this list: it’s never about “more” or “less” but always about the same question – can a query that was valid yesterday still run validly after the change and return the same shape? If yes, the change is additive. If no, it is breaking, no matter how small it looks.\n\n## @deprecated: deprecate instead of remove\n\nBecause removing breaks, you need a way to get rid of a field *without* removing it right away. GraphQL has a built-in directive for exactly that: `@deprecated`.\n\n```graphql\ntype User {\n  id: ID!\n  fullName: String @deprecated(reason: \"Use `displayName` instead. Removal planned for a future release.\")\n  displayName: String!\n}\n```\n\nThe field stays fully functional – every query that names `fullName` still gets a response. But the schema now carries a visible marker. Through introspection, this hint lands in all tooling: the GraphiQL explorer strikes the field through, editor plugins warn while you type, codegen and linters report usage. The `reason` text is the actual message to the team on the other end – ideally with a successor *and* a deadline. Client teams see the hint, migrate to `displayName`, and only much later, when nobody queries `fullName` anymore, do I remove it.\n\nBy the way, you can deprecate not only fields but also individual enum values and arguments. The pattern is the same everywhere: mark first, give time, then remove. That makes deprecation the most important tool of schema evolution, period.\n\n## Nullability is a design decision, not a reflex\n\nOne point deserves more than a line, because it is often decided wrongly during design and can hardly be corrected later: the question of whether a field should be non-null.\n\n`String!` feels clean. It says: a value always comes here. But non-null is a guarantee, and you can’t take guarantees back in a running contract – the way from non-null back to nullable is, as we saw, a breaking change. So you commit, and permanently.\n\nWhat weighs more is what happens at runtime when the guarantee doesn’t hold for once. If the resolver of a non-null field fails – the database hiccups, an upstream service returns nothing – then GraphQL *must* prevent a `null` where `null` is forbidden. It can’t just let the value through. So it lets the `null` propagate upward: the error bubbles up to the nearest nullable parent field and makes everything there `null`. A single failed non-null resolver can drag an entire response path down with it, all the way up to a point that tolerates `null`. A local problem turns into a large-scale outage in the response.\n\nSo when in doubt, start nullable. Non-null only where the guarantee really holds – for an `id`, for a field that structurally can never be missing. For everything that depends on an external system, an optional relation or a computation that may fail, nullable is the more honest and more robust choice. You can always tighten from nullable to non-null later, once the guarantee has proven stable. You don’t have the way back.\n\n## Input types: cutting mutations to be future-proof\n\nAdditive evolution already starts at design time, and nowhere more clearly than with mutations. If you build a mutation with a handful of individual arguments, you block your own future:\n\n```graphql\ntype Mutation {\n  createPost(title: String!, body: String!, authorId: ID!): Post!\n}\n```\n\nIf a field is added later – a category, a publication date – the argument list grows, and every addition that isn’t optional breaks existing callers. The signature is rigid.\n\nThat’s why you encapsulate the input in its own `input` type:\n\n```graphql\ninput CreatePostInput {\n  title: String!\n  body: String!\n  authorId: ID!\n}\n\ntype Mutation {\n  createPost(input: CreatePostInput!): Post!\n}\n```\n\nThe mutation now takes exactly one argument, `input`. You add new input fields additively in the `input` type – as *optional* fields, so that existing callers who don’t set them stay valid. The signature of the mutation itself never moves again. The same principle applies on the output side: a dedicated payload type instead of a bare `Post!` leaves room to add, say, an error or metadata field later without rebuilding the return value. A little more structure at the start, in exchange for years of additive freedom of movement.\n\n## Extending enums carefully\n\nBack to the trap I left open in the safe changes. *Adding* an enum value is additive on the server side – the schema just gets richer. The breakage happens elsewhere, namely in client code.\n\nMany clients handle enum values in a `switch` or an `if` chain and cover exactly the values that existed when they were built. If a new value comes over the wire, such a client falls into no branch – at best it shows nothing, at worse it throws an error. A cleanly additive schema change thus becomes a real breakage for the user.\n\nThe solution isn’t in the schema but in client discipline: every consumer of an enum should have a default or fallback branch for unknown values. The GraphQL best practices point this out explicitly – clients should behave so that a future enum value, unknown today, doesn’t crash anything. If you plan for this from the start, you can extend enums later without hesitation.\n\n## A field migration step by step\n\nLet’s bring it all together with the example already hinted at above: `fullName` is to make way for `displayName`. This is how the migration runs cleanly, without any client breaking at any point.\n\n```mermaid\nflowchart TB\n  S1[\"1 – add displayName<br/>additively\"] --> S2[\"2 – mark fullName with<br/>@deprecated\"]\n  S2 --> S3[\"3 – migrate clients<br/>(deadline running)\"]\n  S3 --> S4[\"4 – remove fullName<br/>once nobody asks anymore\"]\n```\n\nStep one, add: I create `displayName` as a new field. Purely additive, nobody is affected. Existing clients keep asking for `fullName`, new ones can use `displayName` right away.\n\nStep two, deprecate: I mark `fullName` with `@deprecated` and a `reason` that points to `displayName` and the planned deadline. From now on, all client teams see through their tooling that the old field is being phased out – but it keeps working.\n\nThe transition period is what matters: the resolver returns *both* fields correctly.\n\n```js\nconst resolvers = {\n  User: {\n    // legacy field – kept working until the deprecation window closes\n    fullName: (user) => user.displayName,\n    displayName: (user) => user.displayName,\n  },\n};\n```\n\nStep three, migrate: the client teams switch to `displayName` at their own pace. How long that takes depends on the slowest relevant client – for a mobile app often months, because old versions stay in the field. A schema registry or traffic analysis shows whether `fullName` is still being queried at all.\n\nStep four, remove: only when the deadline has passed *and* there is demonstrably no more traffic on `fullName` do I remove the field and the resolver. Now, and not a moment earlier, the breaking change becomes a non-event, because nobody is left who could break.\n\n## A safety net in CI\n\nKeeping all these rules in your head is one thing. Reliably following them on every merge while several people work on the schema is another. That’s why the check doesn’t belong in your head but in the pipeline.\n\nA tool like graphql-inspector compares the schema of a pull request with the currently published one and classifies every difference – additive, dangerous or breaking. If it finds a breaking change, it can turn the build red before anything is merged. A removed field, an argument that became non-null, a vanished enum value is caught in review this way, not only when a client breaks out there. If you also keep the schema in a registry, you can even run the check against actually observed traffic: a “breaking change” to a field that nobody has queried for months isn’t one after all – and the migration above can be tied exactly to this data.\n\n## Maintained, not recut\n\nA GraphQL schema evolves differently from a REST API. You don’t put a `/v2` next to it every few years and migrate everything at once; you maintain a single contract over its entire lifetime. Growth is additive: new fields, new types, new optional arguments keep coming without anyone noticing. And where something does have to go, disciplined deprecation replaces the hard cut – mark, set a deadline, let clients migrate, then remove.\n\nThat is less spectacular than a big version jump, and that’s exactly the point. To its clients, a good schema feels like something that has simply always been there and never hurt. This calm is no accident – it is the result of a few rules, applied consistently, and a CI check that watches over them.\n\n## Further reading\n\n- Repository introduction-graphql (chapters schema, resolver): https://github.com/mikebild/introduction-graphql\n- GraphQL, schemas and types: https://graphql.org/learn/schema/\n- GraphQL best practices (versioning, nullability, deprecation): https://graphql.org/learn/best-practices/\n- graphql-inspector (schema checks in CI): https://github.com/kamilkisiela/graphql-inspector"},{"locale":"en","translation_key":"step-functions-serverless-workflows","slug":"serverless-workflows-with-aws-step-functions","title":"Serverless Workflows with AWS Step Functions","summary":"Step Functions turn nested Lambda handlers into a declarative state machine: a visible flow, explicit retry and catch paths, Standard or Express.","tags":["Software","AWS","Cloud"],"published_at":"2021-03-23T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/serverless-workflows-with-aws-step-functions/","audio_url":null,"audio_duration_secs":null,"text":"The first function validates and calls the second, which calculates and calls the third, which sends a notification. On the whiteboard, that makes a clean chain. At runtime, all that remains is a sequence of calls that nobody can pause, inspect or resume from the outside. If you chain Lambda functions together inside their handlers, you have taken the flow away from operations: when an order gets stuck, the search through the logs begins.\n\nAWS Step Functions turns this relationship around. Instead of hiding the flow in nested handlers, you describe it declaratively as a state machine – and the state becomes visible instead of disappearing into call chains.\n\nA state machine makes the flow visible as a series of named states and explicitly handled results.\n\n:::process{title=\"An explicit workflow\" role=\"primary\" preferredPattern=\"connected-process\"}\n1. Input · take over the business request and the context it needs\n2. Task · run exactly one bounded capability\n3. Choice · pick the next permitted path based on a result\n4. Parallel · start independent branches only when there is real concurrency\n5. Catch · route expected errors into a named handling path\n6. Completion · record success or failure as an unambiguous end state\n:::\n\nThe diagram doesn’t pretend there is a linear happy path. Branching and error handling stay part of the model instead of disappearing into scattered function calls.\n\n## The problem: orchestration in code\n\nLet’s first look at what the reflex solution typically looks like. A Lambda function that processes an order might orchestrate internally like this:\n\n```js\nexports.handler = async (event) => {\n  const order = await validateOrder(event);\n  if (!order.valid) {\n    await notifyFailure(order);\n    return { status: \"rejected\" };\n  }\n\n  if (order.amount > 1000) {\n    await requestManualReview(order);\n  } else {\n    await autoApprove(order);\n  }\n\n  const [inventory, payment] = await Promise.all([\n    reserveInventory(order),\n    chargePayment(order),\n  ]);\n\n  return finalize(order, inventory, payment);\n};\n```\n\nAt first glance, this is readable. But every one of these calls can fail, and as soon as you want robustness, the code grows. What happens if `chargePayment` throws a transient error? Then you need a retry with backoff. What if `reserveInventory` succeeds but `chargePayment` fails for good? Then the reservation has to be rolled back. Bit by bit, the handler fills up with try/catch blocks, counters and timeout logic. The actual business flow – validate, decide, run in parallel, finish – disappears under the error handling.\n\nAnd the most unpleasant part comes in operations. When an order gets stuck, there is no place where you can read its state. You have CloudWatch logs and have to reconstruct how far the process got. With a single function, that’s still manageable. With five functions calling each other, it turns into detective work. Coordinating several functions is one of the limits you quickly run into with plain code.\n\n## The idea: the flow as a state machine\n\nStep Functions moves orchestration out of the code into a declarative description. This description is written in the **Amazon States Language** (ASL), a JSON format. You define states, their transitions and the error paths – the individual Lambda functions stay small and each do exactly one thing.\n\nThe key gain: the flow no longer lives in a handler but exists as a standalone artifact that the console renders graphically. For every execution, you can see which state it is in, which transition was taken and where something failed.\n\nAn ASL definition has only a few required fields at the top level. `StartAt` names the entry state, `States` holds the states as an object. Every state has a `Type` and either points to the next state with `Next` or marks itself as terminal with `\"End\": true`.\n\nBefore we get into a concrete definition, here are the eight state types available in 2021 – that’s the complete toolkit:\n\n- `Task` does work, typically a Lambda function.\n- `Choice` branches based on conditions, the if/else of the state machine.\n- `Parallel` runs several branches at the same time and collects their results.\n- `Map` applies a flow to every element of a list, in 2021 only as the inline variant.\n- `Pass` passes input through or injects fixed data, useful for testing.\n- `Wait` pauses for a duration or until a point in time.\n- `Succeed` ends the execution successfully.\n- `Fail` ends the execution with an error.\n\nWith these eight building blocks, you can model a surprising number of processes without writing a single line of orchestration code.\n\n## A task with retry and catch\n\nLet’s start with the core: a task state that calls a Lambda function and handles errors declaratively. This is the part that costs the most code in the handler approach – and shrinks to a few fields in ASL.\n\n```json\n{\n  \"Comment\": \"Order processing workflow\",\n  \"StartAt\": \"ValidateOrder\",\n  \"States\": {\n    \"ValidateOrder\": {\n      \"Type\": \"Task\",\n      \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:ValidateOrder\",\n      \"Retry\": [\n        {\n          \"ErrorEquals\": [\"Lambda.ServiceException\", \"Lambda.SdkClientException\"],\n          \"IntervalSeconds\": 2,\n          \"MaxAttempts\": 3,\n          \"BackoffRate\": 2.0\n        }\n      ],\n      \"Catch\": [\n        {\n          \"ErrorEquals\": [\"States.ALL\"],\n          \"Next\": \"NotifyFailure\"\n        }\n      ],\n      \"Next\": \"CheckAmount\"\n    },\n    \"NotifyFailure\": {\n      \"Type\": \"Task\",\n      \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:NotifyFailure\",\n      \"End\": true\n    }\n  }\n}\n```\n\nThere is a lot in here, so let’s go step by step. The `Retry` block is an array of retrier objects. `ErrorEquals` names the errors this retrier responds to – here two transient Lambda service errors that you shouldn’t blame on the business code. `IntervalSeconds` sets the first wait time, `BackoffRate` multiplies it with every further attempt (default 2.0), `MaxAttempts` caps the retries (default 3). Without explicit values, AWS would use these defaults.\n\nThe `Catch` block kicks in when the retries are exhausted or when an error occurs that no retrier covers. Every catcher needs `ErrorEquals` and a `Next` that describes the transition. `States.ALL` is the catch-all error that matches everything – and that is exactly why there are two rules you need to know: `States.ALL` has to stand alone in its `ErrorEquals` and has to come last. If another retrier or catcher follows it, the definition is invalid.\n\nAn important detail about the order: the matching retriers are processed first, and only when none of them applies anymore is the catcher transition taken. Retry before catch, always in this order. That is exactly the behavior you would painstakingly rebuild by hand in code – here it is a convention of the language.\n\nOne point that regularly causes discussion: not every `States.` error is caught by everything. `States.TaskFailed`, for example, matches pretty much everything except `States.Timeout` – so if you only retry on `States.TaskFailed` and expect a timeout, you’ll be surprised. And `States.DataLimitExceeded`, which occurs when the payload limit is exceeded (in 2021 that is 256 KB between states), is not caught by `States.ALL`. You have to deliberately avoid errors like these, not catch them.\n\n## Branching with Choice\n\nAfter validation, the process should make a decision. Small orders are approved automatically, large ones go to manual review. In the handler this was an `if`; in ASL it is a choice state.\n\n```json\n{\n  \"CheckAmount\": {\n    \"Type\": \"Choice\",\n    \"Choices\": [\n      {\n        \"Variable\": \"$.amount\",\n        \"NumericGreaterThan\": 1000,\n        \"Next\": \"ManualReview\"\n      }\n    ],\n    \"Default\": \"FanOut\"\n  },\n  \"ManualReview\": {\n    \"Type\": \"Task\",\n    \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:RequestManualReview\",\n    \"Next\": \"FanOut\"\n  }\n}\n```\n\nThe choice state contains a `Choices` array. Each rule consists of a `Variable` (a path into the current input, here `$.amount`), a comparison operator such as `NumericGreaterThan`, `StringEquals` or `BooleanEquals`, and a `Next`. You can also nest conditions with `And`, `Or` and `Not`. If no rule matches, `Default` applies.\n\nThis very `Default` is a common pitfall. Choice has no `End` and no implicit exit. Without `Default` and without a matching rule, the execution runs into a `States.NoChoiceMatched` error. That’s why I recommend always setting `Default`, even if you believe you have covered all cases in theory.\n\n## Parallel: several branches at once\n\nFor reservation and payment, which run independently of each other, there is the parallel state. It runs several `Branches` at the same time – each branch is itself a small state machine with its own `StartAt` and `States`.\n\n```json\n{\n  \"FanOut\": {\n    \"Type\": \"Parallel\",\n    \"Branches\": [\n      {\n        \"StartAt\": \"ReserveInventory\",\n        \"States\": {\n          \"ReserveInventory\": {\n            \"Type\": \"Task\",\n            \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:ReserveInventory\",\n            \"End\": true\n          }\n        }\n      },\n      {\n        \"StartAt\": \"ChargePayment\",\n        \"States\": {\n          \"ChargePayment\": {\n            \"Type\": \"Task\",\n            \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:ChargePayment\",\n            \"End\": true\n          }\n        }\n      }\n    ],\n    \"Next\": \"Finalize\"\n  },\n  \"Finalize\": {\n    \"Type\": \"Task\",\n    \"Resource\": \"arn:aws:lambda:eu-central-1:123456789012:function:Finalize\",\n    \"End\": true\n  }\n}\n```\n\nThe output of a parallel state is an ordered array – one entry per branch, in the order of the definition. So `Finalize` receives both results bundled together. Parallel also supports `Retry` and `Catch` at the state level, and so does the map state when you process a list iteratively.\n\n## How data flows between states\n\nThe first time you work seriously with ASL, you stumble over a question that never comes up in handler code: what exactly does the next state receive as input? In a JavaScript function, you simply pass values on as arguments. In a state machine, passing data on follows rules, and you need to know them, or data gets lost without anyone noticing.\n\nEvery state receives a JSON object as input and returns a JSON object as output. Four fields control this flow. `InputPath` filters which part of the input reaches the state at all. `Parameters` builds the object the Lambda function actually receives from it. `ResultPath` determines where in the input the result is inserted. Finally, `OutputPath` filters what gets passed on to the next state.\n\nThe most common pitfall is in `ResultPath`. Without a value, the default is `$`, which means the task’s result replaces the entire input. If you still want to access `$.amount` in the choice state after `ValidateOrder`, you have to put the result under its own key with `\"ResultPath\": \"$.validation\"`; otherwise the original order is gone. This very default is the reason a choice state then reaches into nothing: the key the condition expects no longer exists after the task. Errors like this look like a wrong condition but are really a data flow problem.\n\n## The flow as a picture\n\nThe real argument for Step Functions is visibility. What I described above in JSON, the console renders as a graph. And exactly this structure can be traced as a diagram:\n\n```mermaid\nflowchart TD\n    Start([Start]) --> Validate[ValidateOrder<br/>Task]\n    Validate --> Check{CheckAmount<br/>Choice}\n    Check -->|amount > 1000| Review[ManualReview<br/>Task]\n    Check -->|else| FanOut[FanOut<br/>Parallel]\n    Review --> FanOut\n    FanOut --> Reserve[ReserveInventory]\n    FanOut --> Charge[ChargePayment]\n    Reserve --> Finalize[Finalize<br/>Task]\n    Charge --> Finalize\n    Finalize --> Done([Succeed])\n    Validate -. \"Catch States.ALL\" .-> Notify[NotifyFailure<br/>Task]\n```\n\nThe dashed edge is the error path described by the catcher. For a running execution, the console colors the states it has passed through, so you can see at a glance where the process stands or where it got stuck. I never get this view with the handler approach – and that’s the difference between “we have to search the logs” and “just look at the execution.”\n\n## Standard or Express\n\nWhen you create a state machine, you have to choose a type, and that choice is fixed afterward. If you get it wrong, you build a new state machine. That’s why it pays to understand the two types early.\n\n**Standard** is the type for long-running, auditable processes. An execution may last up to a year, execution is exactly-once, and the complete history is available through the API for up to 90 days. Billing is per state transition. Important for the cost calculation: every retry attempt is its own transition and counts too. Visual debugging in the console is only available for Standard.\n\n**Express** is meant for high-frequency, short flows. An execution may run for five minutes at most. Run asynchronously, the guarantee is at-least-once; run synchronously via `StartSyncExecution` (available since November 2020), it is at-most-once. Billing is based on the number of executions plus duration and memory. There is no execution history in the console – you depend on CloudWatch Logs, and for that, logging has to be enabled.\n\nThe dividing line follows the domain: order processes, approval workflows, anything with human involvement or audit requirements belongs to Standard. High-throughput event processing, short transformations, IoT ingestion – that’s Express territory. The idempotent nature of short Express flows fits at-least-once semantics, while for a payment you want the exactly-once guarantee of Standard.\n\n## When to use Step Functions – and when not\n\nI don’t recommend turning every sequence of two functions into a state machine. If one function calls another and that’s it, a direct call or an event is perfectly fine. The effort of Step Functions pays off from the point where there is real flow logic: branches, parallelism, retries with different strategies, compensation for partial failures, or when operations needs to see the state.\n\nA second criterion is error handling. As soon as you notice that the orchestrating handler contains more try/catch than domain logic, that’s a strong signal. Moving this handling out declaratively makes the code of the individual functions small and readable again – each function focuses on its one job, and the coordination lives in the state machine.\n\nAnd Step Functions doesn’t replace the other serverless building blocks; it coordinates them. The Lambda functions stay, the database stays, authentication – for example with [Cognito User Pools](https://www.mikebild.dev/en/blog/serverless-auth-with-cognito-user-pools/) – stays where it is. Step Functions is the layer on top that describes the flow.\n\n## Conclusion\n\nMoving from nested handlers to a state machine is above all a change of perspective. Instead of hiding the flow in code, you make it an artifact: `StartAt`, a few states, `Next` transitions, and the error paths as `Retry` and `Catch` right on the state. The individual functions get smaller because they no longer have to carry the coordination, and operations get calmer because the state of every execution is visible.\n\nThe eight state types are quickly learned, and with Task, Choice and Parallel you already cover most real-world flows. With the order of retry and catch in mind, a `Default` set on every choice and a deliberate choice between Standard and Express, you have the foundation in place. In the projects I was involved in, what really won people over was the colored execution in the console anyway. From then on, the flow is no longer buried in logs but is a picture everyone can look at.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-aws-serverless.en.html\n- Repository for the serverless training with the ASL examples from this article\n- [AWS Step Functions – States (States)](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-states.html)\n- [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html)\n- [Standard vs. Express Workflows](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-standard-vs-express.html)\n- [Error handling: Retry and Catch](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-error-handling.html)\n- [Task state](https://docs.aws.amazon.com/step-functions/latest/dg/state-task.html)\n- [Choice state](https://docs.aws.amazon.com/step-functions/latest/dg/state-choice.html)\n- [Tutorial: State machine with Lambda](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-creating-lambda-state-machine.html)"},{"locale":"en","translation_key":"event-sourcing-der-event-store-als-logbuch","slug":"event-sourcing-the-event-store-as-a-logbook","title":"Event Sourcing: The Event Store as a Logbook","summary":"Event Sourcing doesn’t store the current state but the sequence of events as the source of truth: the event store as a logbook, the state as the result of a fold. Benefits, honest costs and how it differs from CQRS.","tags":["Software","Architecture"],"published_at":"2021-02-23T10:00:00+00:00","updated_at":"2026-07-13T08:40:37.248914+00:00","url":"https://www.mikebild.dev/en/blog/event-sourcing-the-event-store-as-a-logbook/","audio_url":null,"audio_duration_secs":null,"text":"```sql\nUPDATE accounts SET balance = 300 WHERE id = 42;\n```\n\nAfter this statement, the database says that the account holds 300 euros. The previous value is overwritten, and with it the answer to the question of how the 300 came about: one deposit of 300, or two of 200 plus a withdrawal of 100? The row no longer knows. Every booking eats its predecessor, and the `balance` field keeps only the result.\n\nEvent Sourcing reverses this order. The truth isn’t the current state but the sequence of events that produced it. The event store is a logbook – an append-only log that only ever gets appended to and in which nothing is changed or deleted. The current state is then no longer a stored fact but a derived artifact: you fold the events and get the state out.\n\nEvent Sourcing is almost always mentioned in the same breath as CQRS, and that’s exactly where the most stubborn misunderstandings arise. So first the core, then the boundaries – drawn deliberately sharp.\n\n## State is a left fold\n\nMartin Fowler describes Event Sourcing as “Capture all changes to an application state as a sequence of events.” Every state change is recorded as an event, which makes the application state fully derivable from the event log. You can throw away the cached state completely and reconstruct it by replaying all events onto an empty initial state.\n\nGreg Young coined the most didactically elegant formula for this: “Current state is a left fold of previous behaviours.” The state isn’t a table but the result of a fold over the event sequence. In code anyone can read right away:\n\n```ts\ntype Event =\n  | { type: \"AccountOpened\"; owner: string }\n  | { type: \"MoneyDeposited\"; amount: number }\n  | { type: \"MoneyWithdrawn\"; amount: number };\n\ntype Account = { owner: string; balance: number };\n\nconst apply = (state: Account, event: Event): Account => {\n  switch (event.type) {\n    case \"AccountOpened\":\n      return { owner: event.owner, balance: 0 };\n    case \"MoneyDeposited\":\n      return { ...state, balance: state.balance + event.amount };\n    case \"MoneyWithdrawn\":\n      return { ...state, balance: state.balance - event.amount };\n  }\n};\n\nconst fold = (events: Event[]): Account =>\n  events.reduce(apply, { owner: \"\", balance: 0 });\n```\n\nThat’s the whole trick, and it’s deliberately little. `apply` takes a state and an event and returns the next state. `fold` runs over the stream with `reduce` and is nothing other than a `left fold` with `apply` as the folding function. The code here is illustrative – not a runnable repository, but the idea reduced to its essentials.\n\nA few properties are already in these lines. The events are named in the past tense – `AccountOpened`, `MoneyDeposited`. They’re facts that have already happened, and therefore immutable: an event is never changed and never deleted; only a new one is added. And `apply` has no side effects; it’s a pure function from the old to the new state. That’s no accident but the precondition for replay to work reliably at all.\n\nThis all comes down to the same dividing line as in [Cleanly Separating Commands, Events and Queries](https://www.mikebild.dev/en/blog/separating-commands-events-and-queries/): a command is an intention that may fail; an event is what actually came of it and can no longer fail. Event Sourcing consistently stores the second kind.\n\n## The logbook as the source of truth\n\nIf you look at the flow, a simple picture emerges. A command arrives, the aggregate decides and produces one or more events from it, which are appended to the log. The state then comes from folding.\n\n```mermaid\nflowchart LR\n  C[Command] --> A[Aggregate decides]\n  A --> E[New Event]\n  E --> L[(Event Store<br/>append-only)]\n  L --> F[fold / apply]\n  F --> S[Current State]\n```\n\nWhat matters in this picture is the direction. The command produces an event, the log only grows at the end, and the state hangs at the end of the chain. If the state is lost – cache gone, new service, changed calculation – it can be restored from the log at any time. The log is authoritative; the state is derivable.\n\nThis leads to three benefits that make Event Sourcing attractive, and they all hinge on the same property: the log is preserved in full.\n\n- A complete audit trail comes for free. Not as an after-the-fact protocol, but because the event log is the state. It doesn’t just describe what happened – it *is* what happened.\n- Temporal queries become possible. Because every earlier state is an intermediate result of the fold, I can ask: what did the account look like on January 3? I simply fold up to the event that was written on that day.\n- Projections can be rebuilt. A read model I don’t have today I can introduce tomorrow by running through the existing events again. History that would long have been overwritten with state-based storage is fully available here.\n\nThe third point weighs the most in practice: when writing, nobody has to foresee which views will be needed later.\n\n## Projections: read models from the stream\n\nIf the state is derived anyway, then so are any number of views on the same stream. That’s exactly what projections are, and they’re the natural transition to [read models as projections](https://www.mikebild.dev/en/blog/read-models-from-events-projections/): derived models optimized for reading, disposable and rebuildable at any time.\n\n```ts\ntype BalanceView = Record<string, number>;\n\nconst project = (events: Event[]): BalanceView =>\n  events.reduce((view, event) => {\n    switch (event.type) {\n      case \"AccountOpened\":\n        return { ...view, [event.owner]: 0 };\n      case \"MoneyDeposited\":\n        // update the read model per event\n        return view;\n      case \"MoneyWithdrawn\":\n        return view;\n    }\n  }, {} as BalanceView);\n```\n\n`project` is also a fold, just with a different target model. One fold produces the aggregate for decisions, the other a flat overview for the read side. From the same log you can derive an account overview, a monthly revenue report and fraud detection – three projections, three folds, one stream.\n\n```mermaid\nflowchart LR\n  L[(Event Store<br/>append-only)] -->|project| A[Read Model A<br/>balances]\n  L -->|project| B[Read Model B<br/>monthly report]\n  L -->|project| C[Read Model C<br/>fraud signals]\n```\n\nTwo things have to be named honestly here. First, these read models are only eventually consistent – they lag behind the write log because the projection runs after the append. If you need immediate consistency between writing and reading, you don’t get it for free here. Second, projections must not trigger any external side effects, and that leads directly to the first serious pitfall.\n\n## Replay is not innocent\n\nFowler points out a detail that never stands out in demos and gets expensive in production: external systems don’t distinguish between real processing and replay. If I rebuild a read model and run through the events again, a gateway that sent an email or triggered a payment the first time sees no difference. It would send the email again.\n\nThat’s why the rule is: `apply` and `project` are pure folds without side effects. Everything that has an effect on the outside – emails, payments, notifications – doesn’t belong in the fold but behind gateways that know a replay mode and suppress their effects in it. If you don’t separate this, you build yourself a disaster at the first rebuild.\n\n## Snapshots: the memoized fold\n\nThat leaves the question of performance. An account with twenty bookings folds in microseconds. An aggregate with two hundred thousand events no longer does on every access. The answer is called a snapshot, and Greg Young put it so precisely that his wording can hardly be improved: “A snapshot is a memoization of your left fold.”\n\nA snapshot is a stored capture of the fold result at event N. You then keep folding from the snapshot instead of starting at event 0.\n\n```ts\ntype Snapshot = { version: number; state: Account };\n\nconst rebuild = (snapshot: Snapshot, newerEvents: Event[]): Account =>\n  newerEvents.reduce(apply, snapshot.state);\n// snapshot = memorized left fold at version N\n```\n\nThe crucial point: a snapshot is purely a performance optimization, not a new source of truth. Because the events are immutable, a snapshot can never become invalid – the past it was folded from doesn’t change, after all. If a snapshot is lost or the folding logic changes, you throw it away and fold again from the start. The log remains authoritative; the snapshot is only a cache of the fold.\n\n## The distinction: Event Sourcing is not CQRS\n\nEvent Sourcing and CQRS are almost always mentioned together, and many people think they’re the same thing. They aren’t.\n\n[CQRS is a domain boundary](https://www.mikebild.dev/en/blog/cqrs-is-a-domain-boundary-not-a-framework/) – the separation of write model and read model. Event Sourcing is a persistence strategy – events instead of state as what gets stored. These are two different decisions on two different axes. You can run CQRS without Event Sourcing: separate write and read sides, both classically with state tables. And you can run Event Sourcing without strict CQRS, even though the read model projections then suggest the separation almost by themselves.\n\nThey’re often combined because Event Sourcing produces read model projections very naturally and CQRS offers exactly the right frame for them. But neither forces the other. If you keep them apart, you make both decisions consciously instead of one in the wake of the other.\n\nAnd one more distinction that becomes important in distributed systems: Event Sourcing isn’t Event-Driven Architecture. Event Sourcing is storage and source of truth within an aggregate. Pub/sub messaging between services is integration. A domain event that travels over a bus as an integration message isn’t automatically a stored Event Sourcing event. Where the two levels blur, you get systems nobody can see through after a year.\n\n## The honest costs\n\nAs attractive as the logbook sounds – Event Sourcing is expensive. The benefit comes with a real price, and both sides belong on the table next to each other.\n\nThe benefits are a complete audit trail, temporal queries, projections you can introduce after the fact and good domain semantics through intentional events. The costs are event schema versioning over the entire lifetime, replay performance including snapshot management, the eventual consistency of the read models and higher operational complexity overall.\n\nThe biggest cost block is versioning. Events live forever, and a replay still has to be able to read the old event versions from three years ago. If the schema changes – a field is added, a meaning shifts – I need a strategy for upcasting: converting old events to the current form when reading. If you underestimate this, you’ll notice at the first big rebuild that your log contains events in five generations that all still need to be read. You either plan for this effort from the start or you plan for it painfully afterward.\n\nOn top of that comes eventual consistency – a permanent companion no ticket can debug away. And snapshots aren’t a free tool: additional infrastructure you have to manage, invalidate and regenerate when the folding logic changes.\n\n## Two anti-patterns that destroy the benefit\n\nI see two mistakes so often that they deserve their own section.\n\nThe first is “CRUD in disguise.” If the events are called `EntityUpdated` or generic `FieldChanged`, you’ve built in Event Sourcing mechanically but thrown away the actual intent. A `MoneyWithdrawn` tells you what happened in the domain; a `BalanceFieldSetTo` only tells you that some setter ran. All the value – intent, audit, semantics – lies in the domain naming. Generic setter events are CRUD with more ceremony and less benefit.\n\nThe second is “Event Sourcing everywhere.” It isn’t a default persistence. It pays off where history, audit and temporal questions have real domain value – accounting, trading, anything with regulatory traceability. For a master data CRUD service that only needs the latest state, it’s expensive overhead. The art lies in drawing the line where the context really justifies the logbook, and not pushing it across the whole system out of enthusiasm.\n\n## Conclusion\n\nEvent Sourcing shifts a single assumption: the truth isn’t the state but the sequence of events that produced it. The event store becomes a logbook – append-only, immutable, authoritative – and the state falls out as a left fold over this stream. Audit trail, temporal queries and any number of rebuildable projections grow out of it almost by themselves.\n\nThe price for this is real: event versioning over years, replay performance with snapshots as a memoized fold, eventual consistency and the discipline to keep side effects out of the folds. And the most important conceptual separation: Event Sourcing is a persistence strategy, CQRS a domain boundary – often together, never forced by each other.\n\nIf you weigh this up soberly, you use Event Sourcing where the history pays back the effort, and otherwise keep storing good old state. Exactly this decision – conscious, not driven by fashion – is the real gain.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html\n- Martin Fowler, *Event Sourcing*: https://martinfowler.com/eaaDev/EventSourcing.html\n- Martin Fowler, *Retroactive Event* (on corrections through new events): https://martinfowler.com/eaaDev/RetroactiveEvent.html\n- Greg Young, talk *CQRS and Event Sourcing*, Code on the Beach 2014 (left fold, snapshots as a “memorized fold”)\n- Greg Young, *Functional Domain Models and Event Sourcing* (2012)\n- Vaughn Vernon, *Implementing Domain-Driven Design* (2013) – chapters on Event Sourcing and CQRS\n- Mike Bild, talk material *CQRS + Event Sourcing* (SlideShare) – the author’s material this article draws on"},{"locale":"en","translation_key":"flask-apps-testen","slug":"testing-flask-apps","title":"Testing Flask Apps: The Test Client and Reliable Endpoints","summary":"How I test Flask endpoints: with app.test_client() without a running server, pytest fixtures and verified JSON responses.","tags":["Software","Python","Backend"],"published_at":"2021-02-16T10:00:00+00:00","updated_at":"2026-07-13T13:19:37.617788+00:00","url":"https://www.mikebild.dev/en/blog/testing-flask-apps/","audio_url":null,"audio_duration_secs":null,"text":"`app.test_client()` is not an HTTP client. It doesn’t open a socket, doesn’t occupy a port and doesn’t need `app.run()`. It calls the WSGI application directly in the same process and returns what the view function produced – a Python object, not a network response.\n\nThat removes the argument that endpoints are laborious to secure with tests. A `curl` in the terminal shows that a route does the right thing at this one moment; after the next refactoring, it no longer tells you anything. This article builds on [Web APIs with Flask](https://www.mikebild.dev/en/blog/web-apis-with-flask/) and flips the perspective: not building the endpoints but securing them. The tool for this is lean – Flask ships the test client, and pytest provides the structure around it.\n\n## A test without a server\n\nThe obvious approach would be to start the app for a test and then fire at it with an HTTP library. That works, but it is slow, error-prone and needs a free port. Flask offers a much better way. `app.test_client()` returns a client that calls the WSGI application directly in the same process. There is no socket, no `app.run()`, no real network connection – the request is passed to the app as a Python call, and the response comes back as an object.\n\nThat is the crucial point: the test talks to your application, but not over the network. As a result, the tests run fast and also work in a CI environment without open ports. Leaving out the network and server path removes some sources of variation; but the test only becomes deterministic once data, time and external dependencies are under control too.\n\n```mermaid\nflowchart LR\n    A[Test] -->|client.get / post| B[test_client]\n    B -->|WSGI in-process<br/>no socket, no server| C[Flask app]\n    C --> D[View function]\n    D -->|Response<br/>status_code + body| B\n    B -->|Response object| A\n    A -->|assert| E[Status &amp; body checked]\n```\n\nThe client behaves like a small browser without a UI. I call `client.get(\"/\")` or `client.post(\"/json\", json={...})` and get back a response object that I can examine. The most important attributes are quickly listed: `response.status_code` as an integer, `response.data` as the raw body in bytes and `response.get_json()` for already deserialized JSON responses.\n\n## From unittest style to pytest fixtures\n\nMany older Flask examples – including the one I used to work with in my `introduction-python` repository – use `unittest`. The structure then typically looks like this:\n\n```python\nimport unittest\nfrom examples.app import app\n\n\nclass HelloTestCase(unittest.TestCase):\n    def setUp(self):\n        app.testing = True\n        self.client = app.test_client()\n\n    def test_index(self):\n        result = self.client.get(\"/\")\n        self.assertEqual(result.status_code, 202)\n        self.assertEqual(result.data, b\"Hello World!\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n```\n\nThat works and is a good starting point. The endpoint in my example deliberately returns the unusual status `202` – which is exactly why it is well suited for testing, because a wrong status stands out immediately. Still, I now modernize this to pytest, for two reasons: the tests become shorter and more readable, and fixtures make the setup reusable without me repeating it in every test class.\n\nThe second, subtler reason lies in a detail of the code above. The app is imported as a module-global object, and the client shares this one instance. As long as the app is stateless, that works fine. As soon as it holds data, it gets tricky – more on that later.\n\n## Fixtures in conftest.py\n\nWith pytest, I put the setup into a file `tests/conftest.py`. pytest finds this file automatically, and the fixtures defined there are available to all tests in the directory. I define two fixtures: one for the configured app and one for the client.\n\n```python\nimport pytest\nfrom examples.app import app as flask_app\n\n\n@pytest.fixture\ndef app():\n    flask_app.config.update({\"TESTING\": True})\n    yield flask_app\n\n\n@pytest.fixture\ndef client(app):\n    return app.test_client()\n```\n\nTwo things matter here. First, the `TESTING = True` configuration. It turns on error propagation: if a view raises an exception, Flask passes it through in test mode instead of wrapping it in a generic `500` response. Without this flag you are debugging blind, because you only see the status `500` and not the actual stack trace. In one project I spent half an hour in a test run searching for a cause that would have been in the traceback from the start with `TESTING=True`.\n\nSecond, the `client` fixture, which depends on the `app` fixture. pytest resolves this dependency automatically: it builds the app first, then the client. Every test that declares `client` as an argument gets a fresh, cleanly configured instance. Exactly this freshness is the key to isolated tests.\n\n## The AAA structure\n\nWhen I write tests, I stick to the AAA pattern: Arrange, Act, Assert. First prepare the state, then perform the one action, then check. In Flask tests, most of the Arrange falls into the fixtures, the Act is the request and the Assert is checking the response.\n\n```mermaid\nflowchart TD\n    A[\"Arrange<br/>Fixtures: App + Client<br/>TESTING = True\"] --> B[\"Act<br/>client.get / client.post\"]\n    B --> C[\"Assert<br/>check status_code<br/>check get_json / data\"]\n```\n\nA first, simple test for the index endpoint then looks like this:\n\n```python\ndef test_index_returns_hello(client):\n    # Act\n    response = client.get(\"/\")\n\n    # Assert\n    assert response.status_code == 202\n    assert response.data == b\"Hello World!\"\n```\n\nNo `setUp`, no class, no `self`. The fixture takes care of the Arrange, and the test stays with the actual statement: this endpoint responds with status `202` and the body `Hello World!`.\n\n## Bytes are not a string\n\nI have stumbled over this spot often enough myself. The obvious comparison\n\n```python\nassert response.data == \"Hello World!\"   # fails\n```\n\nfails. `response.data` returns bytes, not a `str`. The comparison between `b\"Hello World!\"` and `\"Hello World!\"` is always `False` in Python. There are two clean ways: either I compare against a byte literal `b\"Hello World!\"`, or I fetch the body as text.\n\n```python\ndef test_index_body_as_text(client):\n    response = client.get(\"/\")\n    assert response.get_data(as_text=True) == \"Hello World!\"\n```\n\n`get_data(as_text=True)` decodes the body into a string. Both variants are correct – I choose depending on whether I want to check raw bytes or readable text. What I deliberately don’t use in this context is `response.text`; this string property only came with a later tooling version and isn’t available yet in Flask 1.1.\n\n## Checking JSON responses\n\nMost real endpoints don’t return `Hello World!` but JSON. This is where the second big advantage of the test client shows. Instead of parsing the raw body yourself, you call `response.get_json()` and get a ready-made Python structure – a `dict` or a `list`. This cleanly separates two levels of checking: the body as bytes for the exact raw comparison and the deserialized structure for checking the content.\n\nLet’s take an endpoint that accepts a JSON object, adds fields to it and returns it – similar to the `/json` example from my repository:\n\n```python\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n\n@app.route(\"/json\", methods=[\"POST\"])\ndef json_endpoint():\n    payload = request.json\n    result = {\"username\": \"John Doe\", \"role\": payload.get(\"role\")}\n    return jsonify(result)\n```\n\nThe corresponding test sends JSON and checks the deserialized response:\n\n```python\ndef test_json_endpoint(client):\n    # Act\n    response = client.post(\"/json\", json={\"role\": \"admin\"})\n\n    # Assert\n    assert response.status_code == 200\n    data = response.get_json()\n    assert data[\"username\"] == \"John Doe\"\n    assert data[\"role\"] == \"admin\"\n```\n\nOne detail is worth mentioning: the client’s `json=` parameter automatically sets the content type to `application/json` and serializes the dictionary. So you neither have to set headers by hand nor call `json.dumps` yourself. On the response side, `get_json()` takes the parsing off your hands. This keeps the test close to the actual statement about the endpoint’s behavior.\n\n## Error cases are part of it\n\nA common mistake I come across in code reviews is testing only the happy path. An endpoint that works with correct input but silently does the wrong thing with wrong input is not reliable. That’s why every serious test suite includes at least one error case. The simplest one is the unknown route:\n\n```python\ndef test_unknown_route_returns_404(client):\n    response = client.get(\"/does-not-exist\")\n    assert response.status_code == 404\n```\n\nWhat I cover at a minimum fits into a short list:\n\n- The status code – do I expect `200`, `202`, `201` or a deliberate error code?\n- The response body or the JSON structure – are the fields and values right?\n- The error cases – such as `404` for unknown routes and `400` for invalid input.\n\nThese three levels aren’t much work, but they fundamentally change how meaningful a test suite is. A test that only checks the status misses wrong content. A test that only checks the body misses a wrong status. Together they give a solid picture.\n\n## The pitfall: shared state\n\nNow we come to the problem I hinted at above, which in practice causes most of the hard-to-find test failures: shared state between tests. As long as an app is stateless, all tests share the same instance without danger. But as soon as the app holds data – a list in memory, a global dictionary, a database – the order of the tests suddenly becomes relevant.\n\nImagine an endpoint that collects entries in a module-global list. One test creates an entry, another counts the entries. If the counting test runs after the creating test, it sees one entry more than expected. If it runs before, it sees zero. Such tests are sometimes green, sometimes red, depending on the order – and nothing is more frustrating than a test that turns out one way or the other without any code change.\n\nThe solution lies in the fixtures. Instead of importing a global app, I build it fresh for each test. pytest fixtures have the scope `function` by default, which means they are executed anew for every test call. If the fixture returns an app with empty state on every call, no test can influence the next one.\n\n## Isolating databases cleanly\n\nThe same problem one size bigger is the non-isolated database. If tests write to the same database without cleaning up, they get in each other’s way just like with the global list. One test creates a user, the next one finds it there and doesn’t expect it.\n\nThe clean answer is setup and teardown around the fixture’s `yield`. Everything before the `yield` sets up the state, everything after it cleans up. In practice, I like to use a fresh temporary SQLite database per test or a transaction rollback at the end. Schematically, the pattern looks like this:\n\n```python\nimport pytest\nfrom myapp import create_app, db\n\n\n@pytest.fixture\ndef app():\n    app = create_app({\"TESTING\": True, \"DATABASE\": \":memory:\"})\n\n    with app.app_context():\n        db.create_all()      # Setup: fresh schema\n        yield app\n        db.drop_all()        # Teardown: clean up\n\n\n@pytest.fixture\ndef client(app):\n    return app.test_client()\n```\n\nThe core is the `yield` in the middle. Before it comes creating the schema, after it the cleanup. This way, every test gets an empty database, works in it and leaves no traces for the next one. That is a bit more effort than a shared database, but it’s the difference between tests I trust and tests I first eye suspiciously on every red run.\n\n## What counts in the end\n\nFlask’s test client turns securing endpoints into a matter of diligence rather than an infrastructure topic. It takes no running server and no network library, just `app.test_client()`, a few fixtures and the discipline to check status, body and error cases together.\n\nThe three ideas that have proven themselves for me are simple. First: test in-process, without a server – then the tests are fast and independent of port and network. Second: use pytest fixtures so that every test gets a fresh, configured app – the best defense against shared state. Third: for anything that holds data, think about setup and teardown, otherwise the result depends on the test order. This lets you reliably check the WSGI application against its HTTP semantics. This test level deliberately doesn’t cover the real path through WSGI server, reverse proxy, TLS and network.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-python.en.html\n- Repository `introduction-python`, `web/4-testing.md` and the examples `examples/5-testing.py`, `examples/app.py` and `examples/3-json.py`\n- Flask, Testing Flask Applications: https://flask.palletsprojects.com/en/1.1.x/testing/\n- Flask, API reference for `Flask.test_client` and the `TESTING` config: https://flask.palletsprojects.com/en/1.1.x/api/\n- Werkzeug, test utilities and response object (`get_json`, `data`): https://werkzeug.palletsprojects.com/en/stable/test/\n- pytest, fixtures: https://docs.pytest.org/en/6.2.x/fixture.html\n- Flask tutorial, Test Coverage: https://flask.palletsprojects.com/en/1.1.x/tutorial/tests/"},{"locale":"en","translation_key":"react-zustand-erhalten-und-zuruecksetzen","slug":"preserving-and-resetting-state-in-react","title":"Preserving and Resetting State: React and the Position in the Tree","summary":"React does not store state in the component but at its position in the render tree – once you understand that, you control preservation and reset on purpose instead of by accident.","tags":["Software","Frontend","React"],"published_at":"2021-01-26T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/preserving-and-resetting-state-in-react/","audio_url":null,"audio_duration_secs":null,"text":"# Preserving and Resetting State: React and the Position in the Tree\n\nTwo facts decide whether a component’s state survives an update: the position in the render tree and the component type that sits at this position. If both stay the same, React passes on the remembered state. If either of them changes, the state is discarded. There are no other criteria – and no exception for “but it’s the same component.”\n\nThis only becomes puzzling because a different picture pushes itself forward: the state lives in the component, the way a variable lives in an object. According to this picture, `useState` would have to hold its value where the function stands. React does not do that. When updating, it compares two trees – the old one and the new one – and derives from the differences what needs to happen in the DOM ([How React renders the tree](https://www.mikebild.dev/en/blog/how-react-renders-and-updates-the-tree/)). It is exactly this comparison that also decides about the state. Two kinds of bugs grow out of the wrong picture: sometimes a state is lost that you wanted to keep, sometimes one sticks around that you wanted to get rid of.\n\n## State hangs on the position, not on the component\n\nThe right picture is this: React does not store the state in the component but at its position in the render tree. Every spot in the tree – first child of a container, second child, the element behind this condition – is an address. At this address, React remembers which component last stood there and what state it had. If the same component stands at the same address again on the next update, React hands it the remembered state once more. If something else stands there – or nothing at all anymore – React throws away the state of this address.\n\nThat gives you the whole rule in one sentence: the same component at the same position keeps its state. If the type changes at a position, or if the position disappears, the state there is discarded. Everything else in this post is just this one rule, applied to cases that otherwise seem puzzling.\n\n## Example A: two counters, two positions\n\nLet’s take two identical components side by side. Both are the same `Counter`, written from the same function:\n\n```jsx\nfunction Counter({ label }) {\n  const [count, setCount] = useState(0);\n  return (\n    <button onClick={() => setCount(count + 1)}>\n      {label}: {count}\n    </button>\n  );\n}\n\nfunction App() {\n  return (\n    <div>\n      <Counter label=\"left\" />\n      <Counter label=\"right\" />\n    </div>\n  );\n}\n```\n\nIf you click the left one up, the right one stays put. That is irritating at first, because it is the same component – shouldn’t they share the same state? No, and the position rule immediately explains why. The left `Counter` sits at the address “first child of the `div`,” the right one at “second child.” Those are two addresses, so two separate states. That both come from the same function does not matter – the function is only the template; the state hangs on the position.\n\nNow the case that really sharpens the point. We conditionally hide the right counter and show it again:\n\n```jsx\nfunction App() {\n  const [showRight, setShowRight] = useState(true);\n  return (\n    <div>\n      <Counter label=\"left\" />\n      {showRight && <Counter label=\"right\" />}\n      <button onClick={() => setShowRight(!showRight)}>toggle right</button>\n    </div>\n  );\n}\n```\n\nYou count the right one up to 7, switch it off, switch it back on – and it is at 0. The state is gone, irretrievably. As long as `showRight` is false, nothing stands at the second position. React sees a position that has disappeared and clears away its state. When the `Counter` comes back, from React’s point of view it is a freshly occupied address, not a reunion. The state was never “in the counter” – it was bound to a position that did not exist in the meantime.\n\n## Example B: the same position, a different type\n\nThe opposite case shows the same rule from the other side. As long as the same component type stands at a position, the state survives every change of props. You can give a `Counter` a different `label` on every update, change its color, switch it from active to inactive – the count stays, because the same type still stands at the position. Props reshape the component; they do not reset it.\n\nIf, on the other hand, the type flips at the same spot, the state is gone. This is exactly where the type rule of reconciliation applies, which I described in [How React renders the tree](https://www.mikebild.dev/en/blog/how-react-renders-and-updates-the-tree/): if React encounters a different element type at a position than before, it tears down the old subtree and builds the new one from scratch – including state. A common trigger looks harmless:\n\n```jsx\nfunction Panel({ editing }) {\n  if (editing) {\n    return <input defaultValue=\"draft\" />;\n  }\n  return <p>draft</p>;\n}\n```\n\nAt this position, the type switches between `<input>` and `<p>`. Every switch throws away the old node – the `<input>` loses its typed text, because on the next toggle a `<p>` stands there and after that a brand-new `<input>`. The same happens when one component is rendered at a spot sometimes and a different one at other times: different types at one address mean different things to React, and different things do not share state.\n\n```mermaid\nflowchart TB\n  subgraph erhalten[\"gleiche Position, gleicher Typ\"]\n    A1[\"Counter an Position 2<br/>count = 7\"] --> A2[\"neue Props<br/>Typ bleibt Counter\"]\n    A2 --> A3[\"count = 7<br/>bleibt erhalten\"]\n  end\n  subgraph reset[\"gleiche Position, anderer Typ\"]\n    B1[\"p an Position 2\"] --> B2[\"jetzt input<br/>an Position 2\"]\n    B2 --> B3[\"alter Teilbaum weg,<br/>Zustand verworfen\"]\n  end\n```\n\n## Resetting state on purpose\n\nSo far this sounds like a trap. But you can turn the rule around and make it a tool. Sometimes you explicitly want a reset – and then the position rule tells you exactly how to order one.\n\nThe crude way: render the component at a different position. Two branches of an `if` that seemingly show the same `Counter` are two different positions from React’s point of view if they hang at different spots in the tree; if you toggle between them, you get a fresh state every time. That works, but it is heavy-handed and easy to trigger by accident.\n\nThe elegant way goes through the `key`. A `key` tells React explicitly: “This is a specific element; distinguish it from its neighbors.” From [JSX, precisely](https://www.mikebild.dev/en/blog/jsx-precisely-the-rules-behind-the-markup/), you know keys as the thing that makes lists stable so that React recognizes the elements when reordering. But exactly the same capability also works outside of lists for a targeted reset. If an element’s `key` changes, React treats it as a new element at this position – the old subtree is torn down, the state created fresh.\n\nThe classic example is a form that should start fresh for each selected record:\n\n```jsx\nfunction ContactEditor({ selectedId }) {\n  return <Form key={selectedId} contactId={selectedId} />;\n}\n```\n\nWithout the `key`, `Form` would stay at the same position; if `selectedId` changed, the form would only get new props, and the half-typed text of the previous contact would remain in the field. With `key={selectedId}`, the key changes with every new selection, React sees a new element, and the form starts empty – without you resetting a single field by hand. The `key` does exactly the work you would otherwise rebuild with an effect and lots of `setState`.\n\n```mermaid\nflowchart LR\n  S1[\"selectedId = 1\"] --> F1[\"Form key=1<br/>frischer Zustand\"]\n  S2[\"selectedId = 2\"] --> F2[\"Form key=2<br/>neues Element,<br/>Formular leer\"]\n  S3[\"selectedId = 2<br/>Feld getippt\"] --> F3[\"Form key=2<br/>Zustand bleibt\"]\n```\n\n## Preserving state even though the structure changes\n\nThe counterpart is the case in which you want to keep the state but the surroundings change. Here the point is to keep position and type stable, even if things are being rebuilt around them. If you write a component into one branch or the other depending on a condition, you move it to a different position – and then wonder about the reset. Often you can avoid this by rendering the component at a fixed spot and only switching its props instead of letting it wander through the tree.\n\nAnd if a state has to survive a real restructuring, it usually does not belong where it currently is. Then you lift it up to a common parent that stays untouched by the restructuring. The state then hangs on a position that is stable, and the children below it may come and go without dragging it along. This is the same move as the classic lifting of state. The reason here is a different one: it is about surviving a structural change, not about sharing between siblings.\n\n## The nastiest bug: a component inside a component\n\nI save the most unpleasant case for the end, because it puts the position rule to the test and because it hides in real codebases surprisingly often. It looks like this:\n\n```jsx\nfunction Page() {\n  function Sidebar() {\n    const [open, setOpen] = useState(true);\n    return <button onClick={() => setOpen(!open)}>{open ? \"hide\" : \"show\"}</button>;\n  }\n\n  return (\n    <div>\n      <Sidebar />\n    </div>\n  );\n}\n```\n\n`Sidebar` is defined inside `Page`. That looks tidy – after all, the component stands where it is needed. The effect is devastating nonetheless. On every render of `Page`, the line `function Sidebar()` runs again and creates a new function. On every pass, it is literally a different function with a different identity. For React, however, the identity of the function is the type. A different type at a position means: old subtree gone, new one built, state discarded.\n\nIn practice, this looks eerie. Every update of `Page`, however small, resets `open`, the input field inside loses its text, and if you are typing in a field, you lose focus mid-word because the DOM element under you was replaced. You search for the bug everywhere – in the effect, in the event handler, in the state management – except at the spot where the component is defined. And yet that is exactly it: a function identity reborn on every render that forces React to throw away the whole subtree.\n\nThe solution is unspectacular and therefore easy to overlook: components belong at the module level, not in the body of another component. Then `Sidebar` exists exactly once, keeps the same identity across all updates, stands as the same type at the same position – and its state stays. If the inner component needs data from outside, you pass it in as props, not via the nested definition.\n\n## Place and time in the tree\n\nState in React is bound to place and time: to a position in the render tree and to the duration for which this position stays occupied by the same type. Almost everything that seems puzzling about the behavior of state clears up as soon as you stop asking “which component is this in?” and instead ask “at which position in the tree, and does the same type still stand there?”\n\nOnce you have internalized this, you have both directions in hand. You order a reset with a `key` or a new position instead of resetting fields one by one. You secure preservation by keeping position and type stable and, if necessary, lifting the state up. And you avoid the nastiest bug before it arises by keeping components where they belong – at the module level. That turns something that felt like magic into a decision you make on purpose instead of suffering it by accident.\n\n## Further reading\n\n- Repository introduction-react: https://github.com/mikebild/introduction-react\n- React, “Preserving and Resetting State”: https://react.dev/learn/preserving-and-resetting-state\n- React, “State as a Snapshot”: https://react.dev/learn/state-as-a-snapshot\n- React, “Render and Commit”: https://react.dev/learn/render-and-commit"},{"locale":"en","translation_key":"cognito-userpool-auth-serverless","slug":"serverless-auth-with-cognito-user-pools","title":"Serverless Auth with Cognito User Pools","summary":"Cognito User Pools as a managed identity backend: sign-up, confirm and sign-in without your own auth server, the three tokens properly understood, and an API Gateway endpoint secured by a Cognito authorizer.","tags":["Software","AWS","Cloud"],"published_at":"2021-01-19T10:00:00+00:00","updated_at":"2026-07-13T10:01:52.666784+00:00","url":"https://www.mikebild.dev/en/blog/serverless-auth-with-cognito-user-pools/","audio_url":null,"audio_duration_secs":null,"text":"Cognito takes password handling off your hands – it doesn’t take the decision about who owns your users’ identities off your hands. These two things get lumped together all the time. The `signUp()` call is integrated in an afternoon; the `sub` that Cognito assigns along the way then travels as a foreign key through every table and stays for years. The integration is cheap, owning the identities is expensive.\n\nStoring passwords, sending confirmation emails, signing and rotating tokens – solved problems, and rarely what sets a product apart from the competition. A homegrown auth server isn’t differentiation but a surface that has to be maintained and secured for good. AWS has a managed building block for this responsibility: Cognito User Pools. What’s interesting about it is less the API call than the trade-off behind it: Which operational responsibility do I hand over, and what price do I pay if I switch later? That is exactly what I take apart here – with one continuous example that shows the path from registration to the secured endpoint.\n\nTo me, serverless mainly means handing over operational responsibility where it creates no competitive advantage. Your own auth server rarely is one – it is an attack surface you have to maintain.\n\n## What a user pool actually is\n\nA Cognito User Pool is a managed directory for your end users plus all the machinery around it: registration, email or SMS verification, sign-in, password reset and issuing tokens. Your application no longer stores passwords – it only talks to Cognito. That is the decisive change of perspective: it isn’t your app that decides whether a password is correct, it’s the user pool. In the end, your app just gets a signed token and has to be able to trust that token.\n\nYou need to keep two objects apart. The **user pool** itself is the directory including its policies – password rules, which attributes are required, which get verified automatically. The **app client** is the application that authenticates against the pool; it defines which auth flows are allowed and how long a refresh token stays valid. A pool can have several app clients – for example one for the web and one for the native app.\n\nThis is what it looks like minimally in CDK. I deliberately stick with the L1 constructs (`Cfn...`) because they map one to one to the CloudFormation resources, so you see exactly what gets created:\n\n```js\nconst {\n  CfnUserPool,\n  CfnUserPoolClient,\n  CfnUserPoolGroup,\n} = require('@aws-cdk/aws-cognito');\n\nconst userPool = new CfnUserPool(this, 'UserPool', {\n  userPoolName: 'UserPool',\n  adminCreateUserConfig: {\n    allowAdminCreateUserOnly: false,\n  },\n  policies: {\n    passwordPolicy: {\n      minimumLength: 6,\n    },\n  },\n  schema: [\n    {\n      attributeDataType: 'String',\n      name: 'email',\n      required: true,\n    },\n  ],\n  autoVerifiedAttributes: ['email'],\n});\n\nconst userPoolClient = new CfnUserPoolClient(this, 'UserPoolClient', {\n  clientName: 'UserPoolClient',\n  explicitAuthFlows: ['ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],\n  refreshTokenValidity: 30,\n  userPoolId: userPool.ref,\n});\n```\n\n`autoVerifiedAttributes: ['email']` makes Cognito automatically send a confirmation code by email after registration. `refreshTokenValidity: 30` sets the lifetime of the refresh token to 30 days – more on that in a moment. If you prefer building with the higher-level L2 constructs (`UserPool`, `UserPoolClient`), you get more convenient defaults; for getting started, I find the explicit L1 variant more instructive. If you are wondering why I describe infrastructure in a programming language at all instead of YAML: I explained that in [CDK: Infrastructure in a Programming Language](https://www.mikebild.dev/en/blog/cdk-early-days-infrastructure-in-a-programming-language/).\n\n## Sign-up, confirm, sign-in\n\nA user’s lifecycle has three stations. On the client – or, as in my example, in a thin Node backend – I use `amazon-cognito-identity-js`, the official JavaScript SDK for user pools. Registration, confirmation, sign-in:\n\n```ts\nimport {\n  CognitoUserPool,\n  CognitoUser,\n  AuthenticationDetails,\n  CognitoUserAttribute,\n} from 'amazon-cognito-identity-js';\n\nconst userPool = new CognitoUserPool({\n  UserPoolId: process.env.USER_POOL_ID,\n  ClientId: process.env.USER_POOL_CLIENT_ID,\n});\n\n// 1) sign-up: create the user, Cognito emails a confirmation code\nuserPool.signUp(\n  username,\n  password,\n  [new CognitoUserAttribute({ Name: 'email', Value: username })],\n  [],\n  (err, result) => {\n    /* result.user is created but not yet confirmed */\n  }\n);\n\n// 2) confirm: user submits the code from the email\nconst cognitoUser = new CognitoUser({ Username: username, Pool: userPool });\ncognitoUser.confirmRegistration(code, true, (err, result) => {\n  /* result === 'SUCCESS' */\n});\n\n// 3) sign-in: authenticate and receive tokens\ncognitoUser.authenticateUser(\n  new AuthenticationDetails({ Username: username, Password: password }),\n  {\n    onSuccess(session) {\n      const idToken = session.getIdToken().getJwtToken();\n      const accessToken = session.getAccessToken().getJwtToken();\n      // refresh token is available too, but opaque\n    },\n    onFailure(err) {\n      /* wrong password, unconfirmed user, ... */\n    },\n  }\n);\n```\n\nThe important point: the confirm step sits between steps one and three. A freshly registered user is `UNCONFIRMED` at first and can’t sign in until they confirm the code delivered by email. Cognito sends that email itself.\n\n## The three tokens – and why “three JWTs” is wrong\n\nAfter a successful sign-in, Cognito returns exactly three tokens. That sounds trivial, but a stubborn misconception lives here: people often say you get “three JWTs”. That isn’t true. Two of them are JWTs, one explicitly is not.\n\nThe ID token is a JWT and carries the user’s identity – claims such as `sub`, `email` and `cognito:username`. It answers the question “who is this user?” and is the standard token for the classic API Gateway Cognito authorizer. The access token is also a JWT, but it carries OAuth scopes and answers “what is this client allowed to do?”; it comes into play as soon as you use scope-based authorization with resource servers. Finally, the refresh token is not a JWT but an encrypted string that only Cognito can read. It is long-lived – 30 days in my configuration – and serves only to exchange it for fresh ID and access tokens without entering the password again.\n\nWhy is this more than hair-splitting? Because you can verify a JWT locally – check the signature, check the expiry, done – but not an opaque token. And if the frontend sends the wrong token to the API, you get a `401` without understanding why. For the REST Cognito authorizer without configured scopes, the ID token goes into the header. Only when you configure `authorizationScopes` does the gateway expect the access token. This exact mix-up is one of the most common sources of errors.\n\nA decoded ID token essentially looks like this – you can see the issuer, the audience and the intended use:\n\n```json\n{\n  \"sub\": \"a1b2c3d4-....\",\n  \"email\": \"user@example.com\",\n  \"cognito:username\": \"user@example.com\",\n  \"aud\": \"the-app-client-id\",\n  \"iss\": \"https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_ABC123\",\n  \"token_use\": \"id\",\n  \"exp\": 1611060000\n}\n```\n\n## Securing the endpoint – without your own verification code\n\nNow comes the part where managed auth really pays off. I could check the token myself in every Lambda: load the pool’s JWKS document, find the matching key via the `kid` from the token header, convert it to a PEM and verify the signature. I built exactly that in a classic Express backend, and it is instructive to have seen it done by hand once:\n\n```ts\nexport async function validateToken({ token, region, userPoolId }) {\n  const response = await fetch(\n    `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`\n  );\n  const { keys } = await response.json();\n\n  const decoded = jwt.decode(token, { complete: true });\n  if (!decoded) throw new Error('Invalid JWT');\n\n  const key = keys.find((k) => k.kid === decoded.header.kid);\n  if (!key) throw new Error('Invalid JWT');\n\n  const pem = jwkToPem({ kty: key.kty, n: key.n, e: key.e });\n  return new Promise((resolve, reject) => {\n    jwt.verify(token, pem, (err, payload) =>\n      err ? reject(new Error('Invalid JWT')) : resolve(payload)\n    );\n  });\n}\n```\n\nThat works – but it is code I have to write, test and maintain, and it shows up again in every secured route. The **API Gateway Cognito authorizer** takes exactly this work off your hands. You point the gateway at the user pool, and it handles the entire check as a managed service: signature against the pool JWKS, `exp`, `aud`, `iss`. If a valid token arrives, the Lambda gets invoked; if an invalid or expired one arrives, the gateway answers with `401` before your function even starts. No verification code of your own.\n\nIn CDK, you connect this to a REST API route via a `CognitoUserPoolsAuthorizer`:\n\n```ts\nimport {\n  RestApi,\n  CognitoUserPoolsAuthorizer,\n  AuthorizationType,\n  LambdaIntegration,\n} from '@aws-cdk/aws-apigateway';\n\nconst authorizer = new CognitoUserPoolsAuthorizer(this, 'Authorizer', {\n  cognitoUserPools: [userPool],\n});\n\nconst api = new RestApi(this, 'Api');\nconst items = api.root.addResource('items');\n\nitems.addMethod('GET', new LambdaIntegration(getItemsFn), {\n  authorizer,\n  authorizationType: AuthorizationType.COGNITO,\n});\n```\n\nIf you work directly at the API Gateway level – in an OpenAPI definition, for example – you’ll recognize the same configuration in its raw form. The authorizer is of type `cognito_user_pools`, references the pool by ARN and reads the token from the `Authorization` header:\n\n```json\n{\n  \"type\": \"apiKey\",\n  \"name\": \"Authorization\",\n  \"in\": \"header\",\n  \"x-amazon-apigateway-authtype\": \"cognito_user_pools\",\n  \"x-amazon-apigateway-authorizer\": {\n    \"type\": \"cognito_user_pools\",\n    \"providerARNs\": [\n      \"arn:aws:cognito-idp:eu-central-1:123456789012:userpool/eu-central-1_ABC123\"\n    ],\n    \"identitySource\": \"method.request.header.Authorization\"\n  }\n}\n```\n\nSo the client simply sends its ID token in the `Authorization` header – in practice usually as `Bearer <idToken>` – and doesn’t have to take care of anything else. The whole flow looks like this:\n\n```mermaid\nsequenceDiagram\n  participant C as Client\n  participant Cog as Cognito User Pool\n  participant GW as API Gateway\n  participant L as Lambda\n  C->>Cog: sign-in (username / password)\n  Cog-->>C: ID + Access + Refresh tokens\n  C->>GW: GET /items<br/>Authorization: Bearer idToken\n  GW->>Cog: verify JWT via JWKS (signature, exp, aud, iss)\n  GW->>L: invoke (token valid)\n  L-->>C: 200 OK\n```\n\n## Lambda triggers: hooking your own logic into the flow\n\nSometimes the standard flow isn’t enough. For example, you want to allow only email addresses from a specific company domain, or write additional data to a table of your own during registration. For this, the user pool offers **Lambda triggers** – entry points at defined places in the lifecycle. Available in 2021 are, among others, `PreSignUp`, `PostConfirmation`, `PreAuthentication`, `PostAuthentication`, `PreTokenGeneration` and `CustomMessage`.\n\nA `PreSignUp` trigger runs before Cognito creates a new user. This is where I check the email domain, for example:\n\n```js\nexports.handler = async (event) => {\n  const email = event.request.userAttributes.email || '';\n  if (!email.endsWith('@example.com')) {\n    throw new Error('Only example.com addresses are allowed');\n  }\n  // do NOT auto-confirm: keep the email verification step intact\n  event.response.autoConfirmUser = false;\n  return event;\n};\n```\n\nTwo things are crucial here, and both are classic pitfalls. First: the trigger must **return** the `event` object at the end, unchanged except for the intended response fields. If you forget the `return event`, the flow aborts. Second: `autoConfirmUser` and the related auto-verify fields are powerful. If you accidentally set them to `true`, a user bypasses the email confirmation step completely – and later you wonder about unconfirmed addresses in the pool.\n\nThe small component picture for this:\n\n```mermaid\nflowchart LR\n  Pool[User Pool + App Client] -->|JWKS| GW[API Gateway<br/>Cognito Authorizer]\n  GW --> Fn[Lambda]\n  Trigger[PreSignUp trigger] -.-> Pool\n```\n\n## The real trade-off: managed identity versus vendor lock-in\n\nEverything shown so far is the credit side: no password handling, no homegrown token issuing, no verification logic in every route. This responsibility, including the attack surface, moves to AWS – usually the heavier item. Still, I won’t hide the debit side: lock-in to the vendor.\n\nThis lock-in is more concrete than it seems at first. Your tokens are signed against this pool’s JWKS, your client talks through the Cognito SDK, your triggers are tailored to Cognito’s event structure – and weighing heaviest: every user’s `sub` is a UUID assigned by Cognito that travels as a foreign key across your databases. It isn’t the login code that sticks, it’s these identities.\n\nTwo edge cases make this tangible. Cognito doesn’t hand out password hashes: if you move away, you can’t quietly take your users with you – either everyone resets their password, or you migrate them lazily on their next login through a `UserMigration` trigger on the target system. And everything beyond the standard – custom attributes, SRP assumptions in the client, MFA configuration – is Cognito vocabulary that another provider doesn’t speak one to one. So the migration risk doesn’t sit in the auth flow, which you can rebuild in days, but in the identities and their references, which have grown over years.\n\nThis turns into a clear decision grid. For standard sign-in with email and password, small to medium teams without dedicated security staff and without a multi-cloud requirement, managed identity almost always wins – the operations you save clearly outweigh the lock-in risk. I would reconsider as soon as an existing identity provider is in place in-house, real vendor portability is required, or data residency dictates where identities may live at all. The trade-off doesn’t go away – but you make it deliberately instead of by reflex, and you make it at the start, when it is still cheap.\n\n## An important distinction: infrastructure auth is not resolver auth\n\nFinally, the distinction that blurs fastest in practice. What the Cognito authorizer does at the API Gateway is **infrastructure or edge auth**. It answers a single, coarse question: “Is the caller authenticated at all?” If the token is valid, the request gets through – if it isn’t, it gets thrown out with `401` before any of your own code runs. That is a bouncer, not a case worker.\n\nWhat the authorizer doesn’t do: decide whether *this specific user* may see or change *this specific object*. May user A delete user B’s comment? May someone only query their own orders? That is fine-grained authorization, and it belongs in your application logic – in a GraphQL API, for example, in the resolver context, where you check the identity from the token against the actual data objects. The authorizer gives you the reliable identity; which permissions you enforce with it remains your job. Keeping these two levels cleanly apart saves a lot of confusion – and prevents the fallacy that with an authorizer, “authorization is done”.\n\nFor the setup shown here – user pool, standard login and a secured API endpoint – Cognito takes a lot of infrastructure off your hands. You can build a first end-to-end path with it at a manageable effort; it only becomes production-ready with settled recovery flows, MFA, monitoring and fine-grained authorization. The authorizer provides the reliable identity; the permissions on concrete domain objects deliberately stay in your application logic. You pay the price, the vendor lock-in, with your eyes open – and you make the decision where it belongs: at the architecture level, not in passing with the first API call.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-aws-serverless.en.html\n- Repository with the complete example: `introduction-aws/examples/userpool` (CDK stack, sign-up/confirm/login and the manual token check as a contrast to the authorizer)\n- [Amazon Cognito – Using Tokens with User Pools](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html)\n- [Using the ID Token](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-id-token.html) · [Using the Access Token](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html) · [Using the Refresh Token](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html)\n- [Control access to a REST API using Amazon Cognito user pools](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) · [Setting up the authorizer (ID vs. access token/scopes)](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html)\n- [Decoding and verifying a JWT (JWKS)](https://repost.aws/knowledge-center/decode-verify-cognito-json-token)\n- [Customizing user pool workflows with Lambda triggers](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html)"},{"locale":"en","translation_key":"trunk-based-development-und-feature-flags","slug":"trunk-based-development-instead-of-a-branch-graveyard","title":"Trunk-Based Development Instead of a Branch Graveyard","summary":"Short integration cycles with feature flags beat long-lived branches: daily integration without merge hell and a release that becomes a decision instead of a deploy event.","tags":["Software","Delivery"],"published_at":"2020-11-24T10:00:00+00:00","updated_at":"2026-07-13T08:39:51.028726+00:00","url":"https://www.mikebild.dev/en/blog/trunk-based-development-instead-of-a-branch-graveyard/","audio_url":null,"audio_duration_secs":null,"text":"If you postpone integration, you haven’t avoided the conflict – you’ve just let it accrue interest. A branch called `feature/redesign` that runs alongside `master` for six weeks picks up a few changes every day that nobody checks against the current state anymore. The merge at the end is then no longer a work step but an excavation – and nobody can say beforehand how long it will take. Repositories in which half a dozen such branches slowly age away are what I call the branch graveyard in reviews.\n\nThe way out isn’t the next branching model but less distance: integrate into a shared state daily, keep it shippable at all times and separate switching on a feature from rolling out the code. That sounds like Git cosmetics, but it affects lead times and fixing bugs. Deploy and release are two different things – everything else hinges on this separation. It isn’t free, though: every flag creates additional states, testing effort and a cleanup task.\n\n## The actual idea: keep the integration distance small\n\nLet’s start with the core idea, not the tool. Trunk-Based Development – as Paul Hammant describes it on trunkbaseddevelopment.com – essentially means: all developers integrate their work into a single shared branch at least once a day. Let’s call it `main` or `trunk`. This branch stays releasable at all times. Branches, if they exist at all, are short-lived – well under a day.\n\nThe key concept behind this is integration distance. Every day a branch lives away from the trunk increases the distance between what I’m working on and what the rest of the team sees. This distance isn’t linear. It grows disproportionately, because changes pile up on both sides and can conflict with each other. A merge after six weeks isn’t six times as expensive as one after a week but many times that – and above all, it’s unpredictable.\n\nMartin Fowler gets to the heart of this with his notion of Continuous Integration, and more literally than many read it. “Continuous Integration” really means integrating continuously. A long-lived feature branch is by definition the opposite: deferred integration. You can’t practice Continuous Integration and sit on your own branches for days at the same time. One rules out the other. In his Patterns for Managing Source Code Branches, Fowler provides the matching taxonomy: integration frequency, the notion of the “healthy branch,” the mainline. Once you have internalized this vocabulary, you spot the branch graveyard immediately.\n\n## What the data says – carefully phrased\n\nI’m skeptical of methodology promises that rest only on gut feeling. That’s why I value the work of Nicole Forsgren, Jez Humble and Gene Kim in *Accelerate* and the State of DevOps Reports. There, Trunk-Based Development isn’t treated as an opinion but as a statistically identified capability.\n\nI phrase this deliberately carefully, because the temptation to exaggerate here is great. The data shows: higher software delivery performance correlates with few active branches in the repository – on the order of three or fewer – and with merges into the trunk at least once a day. Trunk-Based Development is one of the practices that statistically predict Continuous Delivery. Not “guaranteed to cause” but predicts and correlates. This difference is too important to blur when quoting. But the direction is clear, and it matches what I observe in teams: if you keep the integration distance small, you deliver faster, break things less often and with less drama.\n\n## The flawed thinking: deploy isn’t release\n\nNow comes the part where many discussions tip over. “If everyone merges to the trunk all the time – how is anything half-finished ever supposed to stay out of production?” This question is fair, and its answer is the real lever of this whole approach.\n\nDeploy and release are two different events. Deploy means: the code is on the production environment. Release means: the behavior is active for users. Feature toggles – described by Fowler in the bliki and systematized in detail by Pete Hodgson in *Feature Toggles (aka Feature Flags)* – decouple exactly these two things. The code is rolled out, but the feature is switched off. Activation becomes a configuration and business decision, not a technical deploy event with a night shift and a rollback plan.\n\n```mermaid\nflowchart LR\n    subgraph friedhof[\"Branch graveyard\"]\n        direction TB\n        M0[\"main\"] --> M1[\"main\"]\n        M0 --> B1[\"feature branch<br/>day 1\"]\n        B1 --> B2[\"... day 20 ...\"]\n        B2 --> B3[\"diverges far\"]\n        M1 --> MG((\"big<br/>merge conflict\"))\n        B3 --> MG\n    end\n    subgraph tbd[\"Trunk-Based\"]\n        direction TB\n        T0[\"trunk\"] --> T1[\"+ commit\"]\n        T1 --> T2[\"+ commit\"]\n        T2 --> T3[\"+ commit\"]\n        T3 --> T4[\"trunk stays green\"]\n        T4 -. \"toggle on<br/>= release\" .-> R((\"Release<br/>as a switch\"))\n    end\n```\n\nThe diagram shows the core: on the left, a branch diverges over twenty days and ends in a painful merge. On the right, a continuous trunk flows with many small commits, and activation happens on a separate axis – decoupled in time from the merge and the deploy. Release becomes a switch.\n\nHodgson distinguishes four categories of toggles, and this distinction is valuable in practice because each has a different lifecycle. Release toggles hide unfinished work and are meant to be short-lived. Ops toggles control operational behavior, for example to switch off an expensive function under load. Experiment toggles drive A/B tests and fit well with the Build-Measure-Learn idea from Eric Ries’ *Lean Startup*. Permission toggles unlock behavior for specific user groups. If you don’t keep these four apart, you end up treating every flag the same – and that comes back to bite you.\n\n## How unfinished work lives safely on the trunk\n\nA release toggle in its simplest form looks like this. What matters is that the flag isn’t scattered as a loose `if` in the domain code but sits behind a clean abstraction:\n\n```typescript\n// The domain code does not know about flag plumbing.\n// It asks a small, well-named abstraction.\nif (features.isEnabled(\"new-checkout-flow\")) {\n    return newCheckoutService.process(cart);\n}\nreturn legacyCheckoutService.process(cart);\n```\n\nThe configuration side decides whether a deploy is also a release. A disabled flag means: the code is there, but nobody sees it. That’s deploy without release:\n\n```yaml\nfeatures:\n  new-checkout-flow:\n    enabled: false        # deploy != release\n    strategy: canary      # gradual rollout instead of big-bang\n    percentage: 5         # start with 5% of traffic\n```\n\nFor large rebuilds, though, a single `if` isn’t enough. When I replace a central module, the Branch by Abstraction pattern helps – described by Fowler and attributed to Paul Hammant. The idea: I introduce a shared interface under which the old and the new implementation live in the trunk at the same time. Switching happens through a factory or a toggle. Instead of a weeks-long branch, I integrate a large refactoring in small steps that are integrated daily:\n\n```java\npublic interface PaymentGateway {\n    PaymentResult charge(Order order);\n}\n\n// Both live in the trunk at the same time.\nfinal class LegacyPaymentGateway implements PaymentGateway { /* ... */ }\nfinal class NewPaymentGateway    implements PaymentGateway { /* ... */ }\n\n// A factory selects the implementation behind a toggle.\nPaymentGateway gateway = features.isEnabled(\"new-payment-gateway\")\n        ? new NewPaymentGateway()\n        : new LegacyPaymentGateway();\n```\n\nIn addition, there are dark launching and the keystone interface: you build a large feature piece by piece but put the visible element – the keystone – in place only at the very end. Until then, the new code may already be running along, collecting data or being tested against production load, without any user noticing. Canary releases and blue-green deployments play into this too: rolling out and activating become gradual, controllable processes instead of a big bang.\n\n## The contrast: GitFlow and the reflex toward the long branch\n\nI want to be fair. GitFlow, which Vincent Driessen introduced in 2010 in “A successful Git branching model,” was a well-thought-out answer to a real problem – for a particular kind of software. In 2020, Driessen himself added a note that his model wasn’t intended for continuously delivered web apps. That’s exactly the point. If you build a product with versioned releases and long support cycles, you can live well with a branching model like GitFlow. If you run a continuously delivered application, you get the branch graveyard delivered right to your door.\n\nAs a lighter alternative, GitHub Flow has existed since 2011: a short-lived branch, a pull request, a quick merge back into the mainline. That’s already much closer to Trunk-Based Development. The real difference isn’t in the tooling but in the question of how long a team is willing to postpone integration. The longer the answer, the more expensive the bill.\n\n## Honest about the pitfalls\n\nThe approach doesn’t solve everything, and it brings its own problems. There are three edges where teams reliably cut themselves.\n\nFirst: toggle debt, the toggle graveyard. The irony is bitter. You introduce feature flags to avoid the branch graveyard and in the process produce a new graveyard of flags that were never removed. Every release toggle that stays in the code after the release is technical debt. It doubles paths, confuses readers and rots quietly. Hodgson is clear here: release toggles need an expiration date and must be actively removed. In the teams where this worked, removing the flag was a fixed part of the definition of a finished feature – it was only done once its release toggle had disappeared from the code again.\n\n```mermaid\nflowchart LR\n    A[\"create toggle\"] --> B[\"deploy dark\"]\n    B --> C[\"gradual release\"]\n    C --> D[\"fully on\"]\n    D --> E[\"remove toggle\"]\n    E --> F[\"trunk stays clean\"]\n```\n\nSecond: Trunk-Based Development without robust test automation and a CI gate is dangerous. The whole approach stands or falls with the trunk staying green and releasable. If builds and tests are slow or unreliable, you import instability directly into the mainline instead of isolating it in branches. In poorly tested codebases, the long branch is sometimes a rational form of self-protection. The right order is therefore: first fast, reliable tests and a gate, then daily integration. Not the other way around. If you also fear integration risks between services with frequent merges, consumer-driven contract testing – for example with Pact – gives you an effective safety net.\n\nThird: the test matrix explosion. Every flag combinatorially doubles the possible paths through the code. Two flags result in four states, three in eight. Untested flag combinations are a real risk space, not a theoretical one. The discipline against this is unspectacular but effective: few toggles active at the same time, clear ownership for each one, and a deliberate eye on the combinations that can actually occur together.\n\n## Why the effort pays off\n\nWhen I pull all of this together, I don’t end up with a tool recommendation but with an attitude toward delivery. Small integration distance, a trunk that is releasable at any time and the clean separation of deploy and release together produce something that shows up in business numbers.\n\nCycles get shorter, because nobody loses days in merge conflicts anymore. Friction in the team drops, because everyone works against the same current state and conflicts are small and frequent instead of big and rare. Quality rises, because a feature is rolled out gradually and reversibly instead of in a single risky leap. And the release loses its terror: it’s no longer a nightly deploy event but a decision that someone makes with a switch – reversible, measurable, calm.\n\nIn the end, that’s the appeal of the approach. It replaces process overhead with something simple and elegant. Instead of an elaborate branching model that manages the merge pain, you avoid the pain by never letting it arise. The branch graveyard isn’t a law of nature. It’s a consequence of postponed integration – and that can be abolished.\n\n## Further reading\n\n- Paul Hammant et al.: [trunkbaseddevelopment.com](https://trunkbaseddevelopment.com/)\n- Martin Fowler & Pete Hodgson: [Feature Toggles (aka Feature Flags)](https://martinfowler.com/articles/feature-toggles.html)\n- Martin Fowler: [Patterns for Managing Source Code Branches](https://martinfowler.com/articles/branching-patterns.html)\n- Martin Fowler: [Branch by Abstraction](https://martinfowler.com/bliki/BranchByAbstraction.html)\n- Forsgren, Humble & Kim: *Accelerate* (2018) and the State of DevOps Reports\n- Humble & Farley: *Continuous Delivery* (2010)\n- Vincent Driessen: [A successful Git branching model](https://nvie.com/posts/a-successful-git-branching-model/) (for contrast)"},{"locale":"en","translation_key":"wie-react-den-baum-rendert-und-aktualisiert","slug":"how-react-renders-and-updates-the-tree","title":"How React Renders and Updates the Tree","summary":"From the JSX element to the visible pixel – what exactly happens between a state change and the redrawn screen. Render and commit as separate phases, the comparison of two trees and why React almost always touches only a tiny part of the DOM.","tags":["Software","Frontend","React"],"published_at":"2020-10-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/how-react-renders-and-updates-the-tree/","audio_url":null,"audio_duration_secs":null,"text":"# How React Renders and Updates the Tree\n\n```js\nsetCount(count + 1);\n```\n\nAfter this line, nothing at all happens in the browser at first. No node is replaced, no pixel redrawn. React initially just calls JavaScript functions – the components – and collects what they return. Whether a DOM node has to be touched at all is only decided afterward, in a separate step. That a component function runs and that the browser gets something to do are two different processes – and most misunderstandings about React performance dissolve at this separation.\n\nThe article [JSX Precisely: The Rules Behind the Markup](https://www.mikebild.dev/en/blog/jsx-precisely-the-rules-behind-the-markup/) was about the fact that a JSX element is ultimately just an object – a description of what should be on the screen. Here the path continues: how does this description become a real DOM, and what happens to it when the state changes? Rendering is a computation in JavaScript, changing the DOM a write operation in the browser. React deliberately keeps the two apart.\n\nBetween a state change and a visible DOM change lie several clearly separated stages.\n\n:::process{title=\"From update to DOM\" role=\"primary\" preferredPattern=\"vertical-journey\"}\n1. Trigger · state, props or context make work necessary\n2. Render · React calls components and produces the next element structure\n3. Reconcile · old and new structure are compared by type and key\n4. Commit · necessary changes are applied to the DOM and effects\n:::\n\nThe separation explains why calling a component again doesn’t automatically mean a complete rebuild of the DOM.\n\n## Three steps: trigger, render, commit\n\nReact displays a UI in three steps. You can picture them like an order in a restaurant kitchen: someone places the order, the kitchen cooks, the waiter brings the dish to the table.\n\n```mermaid\nflowchart LR\n  Trigger[\"1. Trigger<br/>initial or setState\"] --> Render[\"2. Render<br/>call components\"]\n  Render --> Commit[\"3. Commit<br/>minimal DOM change\"]\n  Commit --> Paint[\"Browser repaints\"]\n```\n\nThe first step is the trigger. There are exactly two occasions. At application startup, it happens once, when you create the root and pass in the top-level component. After that, a re-render is only triggered by a state change – always through the setter function from `useState` or a corresponding mechanism. Without a state change, React re-renders nothing. That’s important: a click alone does nothing; only when the click changes the state does the machine get going.\n\n```jsx\nimport { createRoot } from \"react-dom/client\";\n\nconst root = createRoot(document.getElementById(\"root\"));\nroot.render(<App />);\n```\n\n## Rendering means: React calls your functions\n\nThe second step, rendering, is the one that is misunderstood the most. In React, rendering doesn’t mean painting something on the screen. Rendering means: React calls your component functions to find out what should be displayed. The first time, it calls the root component. On a re-render, it calls the component whose state has changed.\n\nAnd this call is recursive. If a component returns other components, React calls those too, and their children as well, until there are no more nested components. At the end of this pass there’s no DOM but a new tree of React elements – the same description objects from the JSX article, just the whole tree of them.\n\n```mermaid\nflowchart TB\n  App[\"App()\"] --> Liste[\"InvoiceList()\"]\n  App --> Kopf[\"Header()\"]\n  Liste --> Z1[\"Row() #1\"]\n  Liste --> Z2[\"Row() #2\"]\n  Z1 --> Betrag1[\"Amount()\"]\n  Z2 --> Betrag2[\"Amount()\"]\n```\n\nFor this pass to be reliable, React requires a property I already emphasized in earlier articles: rendering has to be a pure computation. The same props and the same state must produce the same description, and nothing that already existed may be changed during rendering. Only under this condition can React safely repeat rendering, defer it or discard it in favor of a later result – all things the modern, concurrent version of React actually does.\n\n## Reconciliation: comparing two trees\n\nNow comes the core that explains why the whole thing is fast. After a re-render, React has two trees: the new one, just computed, and the previous one from the last pass. Before anything is written to the DOM, React compares the two. This comparison is called reconciliation, and it follows a few simple rules.\n\nAt the same position in the tree, the type of the element decides. If the type is the same – a `<div>` before, a `<div>` again now, or the same component before and now – React keeps the existing node and only updates the properties that have changed. If the type is different – a `<p>` before, a `<div>` now – there’s no detailed comparison: React tears down the old subtree, throws away its state and builds the new one from scratch.\n\n```mermaid\nflowchart LR\n  subgraph Vorher[\"Before\"]\n    A1[\"div\"] --> A2[\"span: 'Hello'\"]\n  end\n  subgraph Nachher[\"After\"]\n    B1[\"div\"] --> B2[\"span: 'World'\"]\n  end\n  A1 -. \"same type:<br/>node stays\" .-> B1\n  A2 -. \"only text content<br/>changes\" .-> B2\n```\n\nThis rule has a practical consequence that beginners often stumble over. Because a type change discards the whole subtree, you also lose its state: an input field that used to sit in a `<div>` and now sits in a `<section>` is treated as a new element and is empty again. If you want state to be preserved, you have to make sure the same type is at the same position.\n\n## Lists are the special case – and this is where keys come in\n\nFor children in a list, the position isn’t enough, because lists change their order. That’s exactly what the key is for, which I already talked about in the article [JSX Precisely](https://www.mikebild.dev/en/blog/jsx-precisely-the-rules-behind-the-markup/) – and here it becomes clear why it matters so much. When reconciling a list, React doesn’t compare position with position but key with key. An element with the same key counts as the same element as before, no matter where it is now. React then moves the existing DOM node instead of throwing it away and rebuilding it.\n\nThat’s why the array index as a key is so treacherous. If you insert an element at the front, every index shifts by one. To React it then looks as if the content of every row had changed – and the state that actually belonged to the third invoice suddenly sticks to the fourth. With a stable domain ID as the key, React recognizes the identity correctly: the inserted element is new, all the others are the same as before and simply move one position further.\n\n## Commit: React only touches what has changed\n\nOnly after reconciliation comes the third step, the commit. Now React writes to the real DOM – but only what reconciliation identified as a difference. On the very first render, everything has to be created, and React attaches the created nodes to the page with the usual DOM calls. Every time after that, the decisive sentence from the documentation applies: React only changes a DOM node if there’s a difference between two render passes.\n\nThat sounds obvious, but it has visible consequences. When a parent component re-renders but an input field deep inside it stays unchanged, React doesn’t touch that node – and the text you just typed stays put, even though the whole branch was recomputed. That’s exactly the proof that rendering and DOM changes are separate: the component was re-rendered (the function ran), but the DOM wasn’t touched (there was no difference).\n\n```mermaid\nsequenceDiagram\n  participant N as User\n  participant R as React\n  participant D as DOM\n  N->>R: setState (state changes)\n  R->>R: call components again (render)\n  R->>R: compare new tree against old one\n  R->>D: write only the differences\n  D->>N: Browser paints the result\n```\n\nAfter the commit, React is done. What happens next belongs to the browser: it repaints the changed part of the page. This repainting is a separate step, independent of React – another reason why the minimal DOM change is worth so much, because the less changes in the DOM, the less the browser has to repaint.\n\n## Why a re-render doesn’t have to be expensive\n\nWith this picture, a widespread misunderstanding dissolves. Many people believe a re-render is automatically slow and optimize wildly against it. But rendering at first only means that a JavaScript function runs again and creates a few objects. That’s rarely the problem. What gets expensive is writing to the DOM and the subsequent repaint – and that’s exactly what React keeps small through reconciliation.\n\nThat doesn’t mean rendering is free. If a component high up in the tree re-renders, React calls the whole subtree below it again, even if hardly any DOM changes come out of it in the end. For the vast majority of applications, that’s not an issue. Where it does become measurable, you can memoize a subtree by hand, for example with `React.memo`: React then skips re-rendering as long as its props haven’t changed. But the order stays the same: measure first, then check whether rendering really is the problem – and most of the time it isn’t.\n\n## What to take away\n\nThe whole mechanism boils down to one sentence: on every state change, React computes a new description of the UI, compares it with the old one and writes only the differences to the DOM. The description is cheap, the comparison is clever, and the expensive DOM work stays minimal. The key isn’t a detail here but the information the comparison uses to tell identity from position – and the reason a good choice of key decides whether state is preserved correctly.\n\nWith that in mind, you make better decisions in everyday work: you no longer flinch at a re-render, you know why an input field keeps or loses its text, and you understand when a type change or a changing key throws away an entire subtree. For the deeper behavior of state across render boundaries – why state is bound to a position in the tree and when it gets reset – there’s the follow-up article on preserving and resetting state.\n\n## Further reading\n\n- Repository introduction-react (examples to follow along): https://github.com/mikebild/introduction-react\n- React, Render and Commit: https://react.dev/learn/render-and-commit\n- React, State as a Snapshot: https://react.dev/learn/state-as-a-snapshot\n- React, Preserving and Resetting State: https://react.dev/learn/preserving-and-resetting-state\n- React, Rendering Lists (keys): https://react.dev/learn/rendering-lists"},{"locale":"en","translation_key":"team-automatisierung-github-actions","slug":"team-automation-with-github-actions","title":"Team Automation with GitHub Actions","summary":"Why I run selected, recurring checks as workflows – and how you can tell whether the automation actually takes load off the team.","tags":["Software","Architecture"],"published_at":"2020-10-12T10:00:00+00:00","updated_at":"2026-07-13T08:39:36.579783+00:00","url":"https://www.mikebild.dev/en/blog/team-automation-with-github-actions/","audio_url":null,"audio_duration_secs":null,"text":"# Team Automation with GitHub Actions\n\nA file under `.github/workflows` is not a build script and not a better Makefile. It is a rule with teeth: something that applies on every push and every pull request without anyone having to remind people. The difference sounds academic, but it decides what such a file can actually do in a team’s everyday work.\n\nIt becomes visible in the questions that end up there. Is code merged before the tests are green? Is the code formatted? Does the change have a changelog entry? Who may trigger a release? As long as the answers live in the head of an experienced person, in a wiki or in a PR comment you have already written three times, they hold – but only as long as everyone is awake and present. They break on the day someone new joins, someone is on vacation or it is simply late.\n\nIn the repository, on the other hand, the rule sits next to the code, in the same history, and is applied instead of negotiated. That is exactly where its value lies, and exactly where the interesting architecture questions begin.\n\n## Automation as an executable agreement\n\nThe first mistake is to sell automation as a time saver. It does save time, but that is the smaller effect. The bigger one is that a decision stops being negotiable. If “we only merge with green tests” is a convention, it holds until the pressure rises. If the same rule is a required check on the branch, it holds even when nobody is looking. The rule moves from the social space to the technical space, and there it is robust against fatigue and hierarchy.\n\nThis shifts my design question. I do not ask “which steps can I automate” but “which decision do I want to make reliable.” That is an architecture decision, not a scripting exercise. A good workflow encodes an intent: this class of errors should never reach the main branch. Nobody should do this follow-up work by hand anymore. This step should be traceable, even in half a year.\n\n## Where the line runs\n\nBefore I write a line of YAML, I draw a line that many pipelines do not draw cleanly: the one between checking and changing. A gate only reads. It says yes or no and touches nothing – lint, tests, typecheck, format check. A changing step intervenes: it publishes an artifact, tags a release, deploys, comments, labels. These two classes have completely different requirements for permissions, repeatability and failure behavior, and if you mix them in the same job, the harmless test step suddenly inherits the permissions of the dangerous deploy step.\n\nCheck steps therefore run on every pull request, including those from forks, and get no secrets. Changing steps run only on trusted triggers – a merge to the main branch, a tag, a deliberately triggered run. This separation carries the security architecture of the entire repository. GitHub takes care of part of it: for a pull request from a fork, the `GITHUB_TOKEN` is read-only and secrets are not visible. That is the answer to a real attack scenario, and I build my workflows so that they respect this boundary instead of working around it.\n\n## A concrete gate\n\nThis is what a pull request gate looks like that I set up in this form again and again. It checks and changes nothing:\n\n```yaml\nname: pr-gate\n\non:\n  pull_request:\n    branches: [main]\n\njobs:\n  verify:\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        node-version: [12.x, 14.x]\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v1\n        with:\n          node-version: ${{ matrix.node-version }}\n      - run: npm ci\n      - run: npm run lint\n      - run: npm run typecheck\n      - run: npm test -- --ci\n```\n\nA few decisions in it are deliberate and carry more meaning than they appear to. `npm ci` instead of `npm install`, because I want reproducible installs from the lockfile and no creeping drift of dependencies. The matrix over two Node versions, because “works on my machine” is the most common lie in teams and I would rather move compatibility from the laptop into the pipeline. `fail-fast: false`, because on a red run I want to see both versions, not just the first one that aborts – an aborted report costs a whole round of feedback.\n\nBut the real lever is not the YAML. It is the branch protection rule that makes this check mandatory. Only that turns a friendly recommendation into a boundary that the main branch defends. The workflow provides the signal; the protection rule gives it teeth.\n\n## The expensive mistake is the happy path\n\nThe happy path is quickly built: everything green, artifact built, release out. It gets interesting exactly where things do not go well, and that is where it is decided whether the automation is a tool or a new source of errors.\n\nThe first stumbling block is idempotency. A changing step must be built so that a second run does no harm. Runs get repeated – after a network error, via the re-run button, because someone sets the same tag again. If my publish step creates a duplicate artifact the second time or aborts with a hard error, I have not abolished the manual follow-up work, only moved it. That is why I build such steps so that they check whether the version already exists and then cleanly do nothing.\n\nThe second stumbling block is the fork. A pull request from outside should be checked, but not rewarded with trust. There is `pull_request_target`, which runs with the permissions of the target repository and has access to secrets – intended for harmless tasks such as labeling or commenting on a PR. If you use it to check out and run foreign code from the fork, you open the door to exactly the secrets you wanted to protect. That is why, in my setups, `pull_request_target` only runs code from the target branch and never the content of the PR. This puts the separation of checking and trust exactly where it really hurts.\n\nThe third stumbling block is the flaky test. A check that turns red at random is worse than no check, because it teaches the team to ignore the red cross. The moment “just run it again” becomes a habit, the value of the gate is gone. For me, an unstable test is not a side issue but a defect in the boundary itself – it should be fixed or isolated, not tolerated.\n\n## The path from checking to changing\n\nThe picture behind it is simple, and I deliberately draw it as a flow, because the direction carries the whole message:\n\n```mermaid\nflowchart LR\n  PR[Pull Request] --> Gate{Gate<br/>lint, test, types}\n  Gate -- red --> Stop[Merge blocked]\n  Gate -- green --> Merge[Merge to main]\n  Merge --> Trusted[Trusted run]\n  Release --> Audit[Traceable in the history]\n  Trusted --> Release[Tag, Publish, Deploy]\n```\n\nOn the left, things are only read; on the right, changes happen only after the merge. Between the two lies the trust boundary. Almost all of the security and operations questions that come up in real projects can be traced back to whether a step sits on the right side of this line.\n\n## The deliberate trigger\n\nNot every changing step should fire automatically. For a release, I often want a human involved, but without someone typing commands locally that nobody else sees. That is exactly what I use `workflow_dispatch` for – a trigger that you deliberately press a button for, with a small input form:\n\n```yaml\nname: release\n\non:\n  workflow_dispatch:\n    inputs:\n      level:\n        description: \"semver bump level\"\n        required: true\n        default: patch\n\njobs:\n  publish:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v1\n        with:\n          node-version: 14.x\n      - run: npm ci\n      - run: npm run build\n      - run: node ./scripts/release.js --level \"${{ github.event.inputs.level }}\"\n        env:\n          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}\n```\n\nThis is the manual decision as a form instead of a verbal agreement. The actual logic deliberately lives in `release.js`, a tested script that the workflow merely calls – the secret is limited to this one trusted path and never shows up in the check gate. The gain lies in traceability: every release appears with its trigger, time and person in the same history as the code. A process that used to vanish into a terminal becomes an entry you can still read half a year later.\n\n## What it measurably delivers\n\nI do not like automation that only feels good. The benefit should show in three places; otherwise I have traded effort for a gut feeling.\n\nThe first is the lead time of a pull request. If the gate already answers the usual review questions – is it formatted, do the tests pass, is the typecheck clean – before a human looks at it, the time from “PR open” to “merged” shrinks noticeably. The review can focus on what a machine cannot see: whether the solution is the right one.\n\nThe second is the friction in the review itself. Discussions about formatting and style are expensive, not because they take long, but because they poison the tone. A machine that decides formatting questions takes them out of the interpersonal level. Nobody argues with a linter anymore.\n\nThe third is the time until a new person’s first meaningful contribution. If the team’s rules are in the repository and become visible with the first PR, nobody has to pass them on verbally. Onboarding turns from an obligation of experienced colleagues into a property of the project. For me, this is the most underrated effect: automation is also a form of documentation that never goes stale, because it is executed.\n\n## When I deliberately do not do it\n\nA tool is not an architecture, and GitHub Actions is no exception. There are cases where I advise against it. If an automation would be real orchestration across many systems with state, restart points and long run times, a workflow runner is the wrong home – that belongs in a proper job runner or a platform built for it, not in a CI file. And if a rule is still in flux because the team itself does not know whether it is right, I do not cement it in a required check. Automation is good at enforcing settled decisions and bad at replacing unsettled ones.\n\nThe most expensive mistake is letting the runner grow into a secret deployment platform until critical processes live in a YAML file nobody understands anymore. A workflow that fills a page is a win. A workflow that fills three screens and catches special cases with `if` conditions is usually a program in the wrong place – then the logic belongs in a tested script or a small CLI that the workflow merely calls.\n\n## How I get started\n\nIn practice, I do not turn this into a big initiative. I start with exactly one gate that removes a real, recurring friction – usually tests plus a format check on every PR – and make it mandatory via branch protection. Then I wait two weeks and see whether it takes load off the team or just annoys it. Only when it holds does the next step come along, and the first changing step deliberately comes later than the first checking one.\n\nThe yardstick stays the same as for any architecture: a decision is only good once I can describe its failure path. What happens on a re-run? What if the PR comes from a fork? What if a test becomes flaky? Who notices when the gate fails silently? When I can answer these questions, convenience has turned into a piece of reliable team infrastructure. That a machine takes work off your hands along the way is the pleasant Side Effect. The point is the decision that finally holds."},{"locale":"en","translation_key":"web-apis-mit-flask","slug":"web-apis-with-flask","title":"Web APIs with Flask: From the App to a JSON API","summary":"From Hello World to a JSON API: how routing, request handling and jsonify work together in Flask 1.1 – and why SSR and APIs are the same mechanism.","tags":["Software","Python","Backend"],"published_at":"2020-09-22T10:00:00+00:00","updated_at":"2026-07-13T10:01:21.588381+00:00","url":"https://www.mikebild.dev/en/blog/web-apis-with-flask/","audio_url":null,"audio_duration_secs":null,"text":"Three terms are enough to describe everything Flask does: route, request, response. A decorator binds a URL path to a Python function, the `request` object describes the incoming request, and the function’s return value becomes the response. Templates, blueprints, JSON – everything else hangs off these three points.\n\nThat makes Flask a good starting point when a Python script is supposed to become an interface another program can talk to over HTTP. It’s a micro-framework: routing, request object and template engine are included, almost everything else is left open. There’s hardly any magic you’d first have to take apart to understand what actually happens between the HTTP request and your own function. Throughout, this text refers to Flask 1.1 – the stable series at the time of writing (1.1.2 came out in April 2020). If you’ve worked with Python objects, decorators and dictionaries before, you’ll find your way quickly.\n\n**Editorial note (July 2026):** In today’s Flask 3.1, `request.json` calls `get_json()` internally and responds with 415 by default if the `Content-Type` isn’t suitable. Only `request.get_json(silent=True)` returns `None` in that case. This change affects error handling, not the routing model of this article.\n\n## Hello World, and what’s behind it\n\nThe smallest meaningful Flask server fits into six lines. You can read the entire model from it.\n\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n    return 'Hello World!'\n\nif __name__ == '__main__':\n    app.run(debug=True, port=8080)\n```\n\n`Flask(__name__)` creates the application. Flask later uses the module name as a starting point, for example to find templates and static files relative to the project. The decorator `@app.route('/')` links a URL path to a function. When the server is called at `/`, Flask calls `hello_world()` and sends the return value back as the response. `app.run()` starts the built-in development server.\n\nThe central idea: a function that returns a string becomes an HTTP response with `Content-Type: text/html`. Flask takes care of the entire translation between HTTP and the Python function for me. And this translation is more flexible than the first impression suggests. A view may return not only a string but also a tuple of body and status code:\n\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n    return 'Hello World!', 202\n```\n\nHere the client gets the same text, but with status 202 instead of the default 200. The tuple can even have three elements – body, status and a dictionary with additional headers. These return conventions are the core of Flask, and they explain why the same route sometimes behaves as an HTML page and sometimes as a JSON API.\n\n## Routing, request, response\n\nBefore we get to the actual API, the three terms deserve a closer look, because they come up again and again:\n\n- Route: The decorator `@app.route(pfad, methods=[...])` binds a URL path to a function. Path parameters like `<int:item_id>` pass parts of the URL directly to the function, and `methods` defines which HTTP verbs the route serves.\n- Request: The imported `request` object describes the incoming request – `request.args` reads the query string, `request.form` the form fields, `request.json` the JSON body, `request.method` the verb used.\n- Response: The function’s return value. A string becomes HTML, `jsonify(...)` becomes JSON, a tuple `(rumpf, status)` controls the status code.\n\nThese three axes are enough to build a surprising amount. A path with a parameter looks something like this:\n\n```python\n@app.route('/user/<username>')\ndef profile(username):\n    return f'Profile page of {username}'\n```\n\nThe placeholder `<username>` is passed to the function as an argument. If you need a numeric value, the converter `<int:item_id>` requires an integer and delivers it already as an `int` – if the path doesn’t match this pattern, Flask responds with 404 on its own, before my function even runs.\n\nThe request lifecycle can be summarized in a simple diagram. Between the incoming request and the finished response there are only a few clearly named steps.\n\n```mermaid\ngraph LR\n    A[HTTP Request] --> B[\"@app.route<br/>Matching\"]\n    B --> C[View Handler]\n    C --> D[\"jsonify()\"]\n    D --> E[JSON Response]\n```\n\nThe request arrives, Flask looks for the matching route, calls the associated function, which builds a response with `jsonify`, and that goes back to the client. None of these steps is hidden – you can put a `print` anywhere and watch.\n\n## From page to interface\n\nNow to the actual goal: a small, REST-style interface. For this I build a single path that serves two verbs – a `GET` returns the list of all entries, a `POST` creates a new one. That one URL can serve several methods is exactly the point where REST thinking becomes visible: the resource is the same, only the action on it differs.\n\n```python\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\nitems = []  # demo-only in-memory store\n\n@app.route('/items', methods=['GET', 'POST'])\ndef items_collection():\n    if request.method == 'POST':\n        payload = request.get_json()\n        item = {'id': len(items) + 1, 'name': payload['name']}\n        items.append(item)\n        return jsonify(item), 201\n    return jsonify(items)  # GET\n\n@app.route('/items/<int:item_id>')\ndef item_detail(item_id):\n    match = next((i for i in items if i['id'] == item_id), None)\n    return (jsonify(match), 200) if match else ('Not found', 404)\n```\n\nA few things here are deliberate. For `POST`, I read the JSON body with `request.get_json()` and respond with status 201, the code for “created.” For `GET`, I return the entire list. And the second route shows the path parameter in action: `/items/3` looks up the entry with this ID and returns either it or a 404 response.\n\n`jsonify` is more than a prettier `json.dumps`. It serializes the dictionary or list, sets the `Content-Type` correctly to `application/json` and builds a finished response object. The handmade way – turning `json.dumps(...)` into a string and setting the header manually – works, but it’s more error-prone and duplicates exactly the work Flask does cleanly anyway.\n\n## The historical twist: returning a dict directly\n\nA note is worth making here, because it causes confusion in older examples. Since Flask 1.1, a view may return a `dict` directly – Flask then automatically calls `jsonify()` on it internally:\n\n```python\n@app.route('/status')\ndef status():\n    return {'ok': True, 'items': len(items)}  # Flask >= 1.1 -> JSON\n```\n\nThat’s convenient, but it’s a relatively recent convenience. In Flask 1.0 and earlier, exactly this line was an error: a dictionary wasn’t a valid return type, and you got a `TypeError`. If you wanted to deliver JSON back then, you had to write `return jsonify({...})` explicitly. Tutorials and Stack Overflow answers show both variants side by side without stating the version – which makes it easy to mix up version and behavior. As long as I’m not sure which Flask version is running, I write `jsonify` explicitly. It works in every version and makes the intent clear.\n\n## SSR and APIs are the same mechanism\n\nServer-side rendering (SSR) and a JSON API are often seen as two different worlds. In Flask they aren’t: the same routing mechanism, the same function, just a different return type. Instead of `jsonify`, I use `render_template`, which fills an HTML file from the `templates/` folder with Jinja2.\n\n```python\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n    return render_template('index.html', items=items)\n\n@app.route('/forms', methods=['POST'])\ndef forms():\n    return 'You said: ' + request.form['text']\n```\n\nThe corresponding template is ordinary HTML with placeholders. The context passed in – here `items` – is available in the template as a variable:\n\n```html\n<form action=\"/forms\" method=\"POST\">\n  <input name=\"text\">\n  <input type=\"submit\" value=\"Submit\">\n</form>\n\n<ul>\n  {% for item in items %}\n    <li>{{ item.name }}</li>\n  {% endfor %}\n</ul>\n```\n\nThe difference between the API and the rendered page is purely the representation: once JSON for machines, once HTML for the browser. The framework underneath stays the same. As a diagram, the branching is quickly told.\n\n```mermaid\ngraph LR\n    A[View Handler] --> B{Representation?}\n    B -->|render_template| C[HTML]\n    B -->|jsonify| D[JSON]\n```\n\nWith that, “API framework” and “web framework” dissolve as separate categories. It’s a decision per route, not an architectural break.\n\n## Structure with blueprints\n\nAs soon as more than a handful of routes come together, the one big `app.py` gets cluttered. Flask offers blueprints for this – a way to group routes by topic and attach them to the app with a shared prefix.\n\n```python\nfrom flask import Blueprint, jsonify\n\napi = Blueprint('api', __name__, url_prefix='/api')\n\n@api.route('/items')\ndef list_items():\n    return jsonify(items)\n\n# in the main app:\n# app.register_blueprint(api)\n```\n\nAll routes of this blueprint then live under `/api` – so the route above is reachable at `/api/items`. Important to understand: a blueprint is purely a structural tool. It doesn’t change anything about runtime behavior and brings no magic of its own; it only helps cut the code into understandable units. I like to use it to separate the JSON API from the rendered pages – two blueprints, one project.\n\n## Three pitfalls\n\nFinally, the places where things regularly get stuck in practice. None of these points is a bug in Flask – they’re peculiarities you need to know.\n\nThe first concerns `request.json`. In the Flask 1.1 used here, the value was simply `None` without `Content-Type: application/json`, and a direct access like `payload['name']` ran into an error. Current Flask versions respond to this access with 415 by default. If you deliberately want to handle it yourself, use `request.get_json(silent=True)` and check for a possible `None`.\n\n```python\n@app.route('/echo', methods=['POST'])\ndef echo():\n    data = request.get_json(silent=True)\n    if not data:\n        return jsonify({'error': 'expected JSON body'}), 400\n    return jsonify(data)\n```\n\nThe second is `debug=True`. In the development server, debug mode is handy – it reloads on changes and shows an interactive traceback on errors. But exactly this interactive traceback is an executable console in the browser. In a publicly reachable environment, that’s an open door for executing arbitrary code. `debug=True` belongs exclusively in local development. And `app.run()` itself is only the development server anyway – for production, you put a WSGI server like gunicorn or uWSGI in front of it.\n\nThe third concerns global state. My `items = []` list is a demo shortcut and not a database. It lives in the process’s memory, is lost on every restart and behaves unreliably as soon as several workers run in parallel – then each worker sees its own list. For an example like this, that’s perfectly fine; for real data you need persistence, such as a database behind the route.\n\n## Conclusion\n\nThe path from a Python script to a web interface is shorter with Flask than many expect, and – more importantly – it’s easy to follow. A function is bound to a path through a decorator, the `request` object describes the request, the return value becomes the response. Whether that becomes an HTML page via `render_template` or a JSON API via `jsonify` is a decision per route, not a change of system. Blueprints give the whole thing structure as it grows, without introducing new concepts.\n\nMore important to me than the list of features is that you can say at any time what happens between the HTTP request and your own function. Flask keeps this chain visible. Once you’ve walked through it, you’ll also read more comfortable frameworks more calmly – underneath, they all have the same model of route, request and response.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-python.en.html\n- Repository `introduction-python`, directory `web/examples/` – the runnable Flask examples (`1-app.py`, `2-html.py`, `3-json.py`, `app.py`) this article builds on.\n- Flask 1.1 Quickstart – routing, methods and path parameters: https://flask.palletsprojects.com/en/1.1.x/quickstart/\n- Flask 1.1 API reference – request object and `jsonify`: https://flask.palletsprojects.com/en/1.1.x/api/\n- Flask 1.1 Blueprints: https://flask.palletsprojects.com/en/1.1.x/blueprints/\n- Flask 1.1 Deployment – why the development server doesn’t belong in production: https://flask.palletsprojects.com/en/1.1.x/deploying/\n- [Flask 3.1: incoming request data and `get_json()`](https://flask.palletsprojects.com/en/stable/api/#flask.Request.get_json)"},{"locale":"en","translation_key":"read-models-sind-projektionen","slug":"read-models-from-events-projections","title":"Read Models from Events: Projections Instead of Accidental Caches","summary":"A read model built from events is a deliberately maintained projection for concrete queries. Origin and rebuild set it apart from an accidentally grown cache, even if the technical view can look cache-like.","tags":["Software","Architecture"],"published_at":"2020-09-15T10:00:00+00:00","updated_at":"2026-07-13T07:56:13.215191+00:00","url":"https://www.mikebild.dev/en/blog/read-models-from-events-projections/","audio_url":null,"audio_duration_secs":null,"text":"# Read Models from Events: Projections Instead of Accidental Caches\n\nThis post looks at the event sourcing case: behind the read view there is an event stream from which it can be derived again. That makes the read model the view intended for queries, not an accidental acceleration layer. Technically it may still look cache-like, for example as a denormalized table with fast replacement. What matters is origin and rebuild, not the storage product.\n\nThe comparison with a cache is still tempting: a denormalized, fast view that sits next to the actual database simply looks like one. It gets expensive the moment the first schema on the read side has to change. A read side that was built as a cache can then no longer be restored cleanly. One that was built as a projection has the rebuild in its design from the start – and this difference runs through operations, migration and troubleshooting.\n\n## Where the cache reflex comes from\n\nThe reflex has a grain of truth. On the surface, a read model and a cache solve the same problem: queries should be fast without asking the expensive write model every time something is displayed. Both are denormalized, both sit closer to the user than the source of truth, both are potentially stale.\n\nThe break lies one level deeper, in the question: who is the source of truth, and how does the fast view emerge from it? A cache has an authoritative database *behind* it. If the cache entry drops out, you pull the record from that source again and store it again. Invalidation is a side effect of TTL or eviction, and a cold start is an operational detail. A read model, on the other hand, has no “actual” read database behind it from which you reload it when needed. It *is* the authoritative read view. What lies behind it is the event store or the write model – and the read model is not “reloaded” from it but *computed*.\n\nThat computation is the projection. And it is the reason I insist on the distinction.\n\n## What makes a projection\n\nThree terms come before the code. Martin Fowler describes CQRS as a deliberate separation: you use a different model to update information than the model you use to read information. The read model is not a view through the domain model, but a separate model that serves queries exclusively. Greg Young and Vaughn Vernon provide the link: the projection – the process that derives and updates the read model from the changes on the write side, specifically from the domain events.\n\nThe decisive property of the projection discussed here is its origin in an immutable event stream. If events, order, projection code and other inputs are fixed, replaying produces the same read model. The second property follows from that: you can throw the view away and recompute it entirely from the events. The rebuild is not an emergency plan but a regular tool.\n\nThis is exactly where the projection parts ways with the cache. You can refill a cache too, but that rebuild is a cold-start side effect whose result depends on the source at the *current* moment. Rebuilding a projection is deterministic and independent of time, because it rests on history, not on a momentary state.\n\nA caveat belongs here: this free rebuild assumes that the events are available permanently and completely – that is, a write path with event sourcing in which the event store is the source of truth. CQRS and event sourcing are two separate decisions that are often made together but do not have to be; Fowler explicitly describes CQRS independently of the form of persistence. If you run CQRS without a persistent event history and only update the read side from transient notifications, you have a projection in operation, but not the deterministic rebuild from history. The examples here assume the event store – and with it the property that separates the read model from the cache.\n\n## The projection as a fold\n\nIt becomes clearest in code. At its core, a projection is a fold – a `reduce` over the events that starts with an empty state and applies each event to the state so far. As an illustration, in TypeScript:\n\n```ts\ntype OrderPlaced = { type: \"OrderPlaced\"; orderId: string; total: number }\ntype OrderShipped = { type: \"OrderShipped\"; orderId: string }\ntype OrderCancelled = { type: \"OrderCancelled\"; orderId: string }\n\ntype OrderEvent = OrderPlaced | OrderShipped | OrderCancelled\n\ntype OrderSummary = {\n  orderId: string\n  total: number\n  status: \"placed\" | \"shipped\" | \"cancelled\"\n}\n\n// pure reducer: (state, event) => state\nfunction apply(state: OrderSummary, event: OrderEvent): OrderSummary {\n  switch (event.type) {\n    case \"OrderPlaced\":\n      return { orderId: event.orderId, total: event.total, status: \"placed\" }\n    case \"OrderShipped\":\n      return { ...state, status: \"shipped\" }\n    case \"OrderCancelled\":\n      return { ...state, status: \"cancelled\" }\n  }\n}\n\n// the projection is a fold over the event stream\nfunction project(events: OrderEvent[]): OrderSummary {\n  return events.reduce(apply, {} as OrderSummary)\n}\n```\n\n`apply` is a pure function `(state, event) => state`. No access to the clock, no network, no randomness. That is not a stylistic preference. Without this purity, the rebuild does not stay deterministic. As soon as a `Date.now()` or an external lookup sneaks into `apply`, the nice property “same events, same read model” is lost – and you have unknowingly built yourself a cache whose rebuild depends on the point in time.\n\n## One read model per view\n\nThe second key point: there is no *single* read model. There is one per query, each denormalized and tailored exactly to the view it serves. Vernon points out that read models are especially useful where the displayed data cuts across several aggregates. The read model pulls this data together in advance, so the query stays flat and cheap.\n\nA view for an order list pulls different fields than a detail view. Instead of joining and computing at runtime, the projection stores the finished values:\n\n```ts\ntype CustomerOrderListItem = {\n  orderId: string\n  customerName: string   // denormalized from the customer aggregate\n  itemCount: number      // precomputed, no join at read time\n  totalAmount: number\n  statusLabel: string    // display-ready, e.g. \"Versandt\"\n}\n\n// this projection cuts across order and customer to build one flat view\nfunction toListItem(\n  order: OrderSummary,\n  customerName: string,\n  itemCount: number,\n): CustomerOrderListItem {\n  return {\n    orderId: order.orderId,\n    customerName,\n    itemCount,\n    totalAmount: order.total,\n    statusLabel: order.status === \"shipped\" ? \"Versandt\" : \"Offen\",\n  }\n}\n```\n\nThe direction of thinking is what matters: the read model is built for the query, not the query for the read model. That is exactly what I mean in [CQRS is a domain boundary](https://www.mikebild.dev/en/blog/cqrs-is-a-domain-boundary-not-a-framework/) when I say that separating reads and writes is a statement about responsibility, not about two databases. The read side may have its own shape because it has its own job.\n\n## The rebuild is part of the design\n\nBecause the projection emerges deterministically from the events, the rebuild is trivial to express – you clear the read side and replay the events:\n\n```ts\ninterface ReadStore {\n  clear(): void\n  save(view: OrderSummary): void\n}\n\ninterface EventStore {\n  allEvents(): Iterable<OrderEvent>\n}\n\nfunction rebuild(events: EventStore, read: ReadStore): void {\n  read.clear()\n  const views = new Map<string, OrderSummary>()\n  for (const event of events.allEvents()) {\n    const current = views.get(event.orderId) ?? ({} as OrderSummary)\n    views.set(event.orderId, apply(current, event))\n  }\n  for (const view of views.values()) read.save(view)\n}\n```\n\nThis `rebuild` is the practical litmus test. If you can write it cleanly, you have a projection. If you *cannot* write it cleanly – because state flows in from outside, because events were discarded, because `apply` is not pure – then you have a cache and should stop calling it a read model.\n\nThe rebuild is also the answer to a question that comes up in projects sooner or later: what happens with a schema change on the read side? With a cache, that is a migration problem with data transfer. With a projection, it is a new projector that you run over the existing events. The new view emerges from the same source as the old one. This is the moment when the initial discipline pays off.\n\n## The data flow in a picture\n\nOne source, several view-specific projections – this is what the flow looks like:\n\n```mermaid\nflowchart LR\n  C[Command] --> W[Write Model /<br/>Event Store]\n  W -->|Events| P[Projector]\n  P -->|async · eventual| A[Read Model A<br/>List]\n  P -->|async · eventual| B[Read Model B<br/>Detail]\n  P -->|async · eventual| R[Read Model C<br/>Report]\n```\n\nThe command runs against the write model and produces events. The projector subscribes to these events and uses them to update as many read models as there are views. The edges to the read models are deliberately labeled “async · eventual,” because this is where the third key point lies: consistency.\n\n## Eventual consistency is a deliberate trade\n\nThe projection runs asynchronously after the write has succeeded. Fowler states the consequence soberly: you cannot guarantee exactly *when* the read model is consistent. Shortly after the write, it is potentially stale. That is not a bug, not data loss and not corruption – it is a bounded, known delay that you accept in order to decouple the read side from the write side.\n\nThe delay itself rarely causes trouble. How you deal with it does. If you expect synchronous read-after-write consistency, you build the UI so that it reads from the read model immediately after the command and are surprised that the new record is “missing.” It is not gone; the projection just has not caught up yet. That belongs in the design of the UI, not in a bug report.\n\nThe second variant is more dangerous: checking command-side invariants from the read model. Greg Young is clear here – the read model must not carry a business decision that has to rely on current, consistent state. Because it can be stale, you would be deciding on stale data. Checking whether an account has sufficient funds or whether an order may still be canceled belongs on the write side, against the aggregate, not against the read view. I wrote up this division of labor in more detail in [Cleanly Separating Commands, Events and Queries](https://www.mikebild.dev/en/blog/separating-commands-events-and-queries/): a query asks a question and changes nothing; that is why it must not force a decision either.\n\n## Projection or cache – the distinction in five points\n\nWhether a concrete read side is a projection or a cache becomes clear from five questions:\n\n- Who is the source of truth? With a projection, the event store is the source, and the read model is the authoritative read view. With a cache, the authoritative source is the database behind it.\n- How is it invalidated? The projection is updated event-driven, the cache through TTL or eviction.\n- How does the rebuild work? The projection can, by design, be recomputed deterministically from history; the cache rebuild is a cold-start side effect that depends on the current state of the source.\n- What shape does the view have? The projection is denormalized per view and pulled together across aggregates, the cache is usually a copy of the source record.\n- What about consistency? The projection is deliberately eventually consistent with a bounded delay, the cache best effort.\n\nYou can argue about one or two of these points. But if the answers mostly land in the cache column, you should call the thing what it is and not hang the expectations of a read model on it.\n\n## The three pitfalls, concretely\n\nFinally, the patterns that cause the trouble, each named in one sentence along with the countermeasure.\n\nThe first is cache thinking itself: treating the read model as an optional accelerator that you pull again from the “actual” database on a miss. That actual database does not exist. Updates are event-driven, and the rebuild comes from the events. If you take this seriously, you stop looking for the source *behind* the read model.\n\nThe second is the read model as the source of truth: deciding on command invariants from a potentially stale read view. The consequence is decisions based on old state. The countermeasure is discipline across the boundary between the sides – decisions go on the write side, against the aggregate.\n\nThe third is the forgotten rebuild: building a projection that cannot be replayed because `apply` is not pure or events were discarded. Then the first schema migration becomes a dead end. The countermeasure is in the code above – keep the projector a pure fold over the events, and write the `rebuild` early, not only when things are on fire.\n\n## Conclusion\n\nA read model deserves a better name than “cache,” because the name sets the expectations. If you call it a cache, you build an optional accelerator with a supposed source behind it, TTL invalidation and a rebuild that remains a side effect. If you call it a projection, you build a pure fold over an immutable event stream, tailored per view, updated event-driven and deterministically recomputable at any time. The three properties I use to pin this down are always the same: deterministically derived, rebuildable at any time, deliberately eventually consistent. If you build these three into the design, you have a read side that you can operate and migrate without breaking a sweat at every change.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html\n- Martin Fowler, [CQRS](https://martinfowler.com/bliki/CQRS.html) – the conceptual model split and the warning to use it only locally within a context.\n- Martin Fowler, [Reporting Database](https://martinfowler.com/bliki/ReportingDatabase.html) – the related but narrower idea of a separate read database.\n- Martin Fowler, [Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html) – the form of persistence that makes projections so natural.\n- Greg Young, [CQRS Documents (2010, PDF)](https://cqrs.files.wordpress.com/2010/11/cqrs_documents.pdf) – the foundations of read models, eventual consistency and rebuild.\n- Vaughn Vernon, *Implementing Domain-Driven Design* (2013), chapters on architecture and CQRS; sample code in the [IDDD Samples](https://github.com/VaughnVernon/IDDD_Samples).\n- My own talk material “CQRS + Event Sourcing” on SlideShare – the slides from which I derive the core in trainings: reading and writing are different responsibilities."},{"locale":"en","translation_key":"cloud-guardrails","slug":"cloud-guardrails","title":"Cloud Guardrails Instead of Cloud Gatekeeping","summary":"Why central approval processes in the cloud breed shadow infrastructure and how technically enforced guardrails – SCPs, Permission Boundaries, Config Rules, budgets – give teams their freedom of movement back.","tags":["Software","Architecture"],"published_at":"2020-09-12T10:00:00+00:00","updated_at":"2026-07-14T17:13:13.975247+00:00","url":"https://www.mikebild.dev/en/blog/cloud-guardrails/","audio_url":null,"audio_duration_secs":null,"text":"# Cloud Guardrails Instead of Cloud Gatekeeping\n\nAn approval process with a three-day wait doesn’t create control. It creates shadow infrastructure. The team waiting for approval of a DynamoDB table isn’t really waiting – it finds a way around: a colleague’s private AWS account, the project lead’s credit card, the “temporary” bucket in the sandbox account that still holds production data two years later. The process that was supposed to prevent risks shifts them exactly to where nobody looks anymore: no review, no central logging, no cost control, no backups.\n\nOn a project last year, I saw this up close. A central cloud team, a Jira board, every new resource a ticket. Official lead time: three days. Actual lead time with follow-up questions: a week or more. The cloud team was neither malicious nor lazy – it was simply too small for twelve product teams, and every ticket needed context that only the requesting team had. What struck me was that the actual discussion was never “allow or forbid.” It was almost always: “In which region? With which tagging? Who pays for it?” In other words, questions that can be phrased as a rule. And whatever can be phrased as a rule, a machine can enforce – without any waiting time.\n\n## What the ticket process actually protects\n\nBefore you abolish the process, it’s worth looking at which legitimate concerns it carries. On that project, there were four at the core:\n\n- Cost: nobody should accidentally start an expensive cluster with an exotic instance size.\n- Data sovereignty: data stays in European regions, period.\n- Security baselines: no public S3 bucket, no disabled CloudTrail, no wide-open security groups.\n- Privilege escalation: anyone who may create roles could otherwise grant themselves arbitrarily far-reaching permissions.\n\nAll four concerns are real. But none of them needs a person who reads a ticket three days later. They need boundaries that apply at the moment of the API call – not at the moment of approval. The ticket process checks a declaration of intent; it never again checks what actually happens afterward. The guardrail checks every single action, every time.\n\nAWS itself now has a name for this way of thinking: Control Tower, generally available since summer 2019, literally calls its preconfigured rules “guardrails.” So the term isn’t a buzzword from conference slides; it comes from the platform’s product practice. More interesting than the name is the distinction Control Tower makes: preventive guardrails prevent an action, detective guardrails detect a deviation. This distinction carries the entire architecture.\n\n```mermaid\nflowchart LR\n  A[Team changes<br/>infrastructure] --> B{Preventive:<br/>SCP / Boundary}\n  B -->|violates| C[API call rejected<br/>immediately]\n  B -->|allowed| D[Resource<br/>is created]\n  D --> E{Detective:<br/>AWS Config}\n  E -->|compliant| F[Nothing happens]\n  E -->|deviation| G[Alarm or<br/>auto-correction]\n```\n\n## Hard limits: Service Control Policies\n\nThe outermost guardrail is Service Control Policies in AWS Organizations. An SCP applies to entire accounts or organizational units and overrides every IAM policy in the account – not even the account administrator gets past it. That’s exactly why only the rules that are truly non-negotiable belong here. On that project, there were two: allowed regions and a short list of forbidden services.\n\n```json\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"DenyOutsideAllowedRegions\",\n      \"Effect\": \"Deny\",\n      \"NotAction\": [\n        \"iam:*\",\n        \"organizations:*\",\n        \"route53:*\",\n        \"cloudfront:*\",\n        \"support:*\"\n      ],\n      \"Resource\": \"*\",\n      \"Condition\": {\n        \"StringNotEquals\": {\n          \"aws:RequestedRegion\": [\"eu-central-1\", \"eu-west-1\"]\n        }\n      }\n    },\n    {\n      \"Sid\": \"DenyUnapprovedServices\",\n      \"Effect\": \"Deny\",\n      \"Action\": [\"gamelift:*\", \"robomaker:*\", \"chime:*\"],\n      \"Resource\": \"*\"\n    }\n  ]\n}\n```\n\nTwo details matter to me here. First, the `NotAction` exceptions: IAM, CloudFront and Route 53 are global services, and their API calls technically run through us-east-1 – if you forget them in the region lock, you lock yourself out. We learned that the hard way, luckily in a test account. Second, the nature of the list of forbidden services: it’s short and justified, not an allowlist of a hundred entries. An SCP that forbids everything except what someone once requested is just the old gatekeeping in JSON form. The guardrail marks the edge of the road, not the only permitted lane.\n\nImportant for understanding: an SCP grants no permissions itself. It defines the upper limit of what IAM policies in the account can effectively allow at all. Within this limit, the teams move freely – and that’s exactly the point.\n\n## Self-service for IAM: Permission Boundaries\n\nThe most uncomfortable question on the project came from the security officer: “If developers may create their own IAM roles, can’t they give themselves any permissions they want?” Without a countermeasure: yes. Anyone with `iam:CreateRole` and `iam:AttachRolePolicy` can build a role with administrator permissions and assume it. That’s why IAM was historically the last territory of the central team – and the most common reason for waiting, because every Lambda function and every pipeline needs a role.\n\nSince 2018, there have been Permission Boundaries for this: a managed policy attached to a role as an upper limit. The effective permissions are the intersection of the boundary and the attached policies. The trick lies in self-reinforcement – the boundary only allows creating new roles if the new role carries the same boundary again:\n\n```json\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"AllowWorkloadServices\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\n        \"s3:*\", \"dynamodb:*\", \"lambda:*\", \"sqs:*\",\n        \"logs:*\", \"cloudwatch:*\", \"apigateway:*\"\n      ],\n      \"Resource\": \"*\"\n    },\n    {\n      \"Sid\": \"DenyCreateWithoutBoundary\",\n      \"Effect\": \"Deny\",\n      \"Action\": [\"iam:CreateRole\", \"iam:CreateUser\"],\n      \"Resource\": \"*\",\n      \"Condition\": {\n        \"StringNotEquals\": {\n          \"iam:PermissionsBoundary\": \"arn:aws:iam::111122223333:policy/workload-boundary\"\n        }\n      }\n    },\n    {\n      \"Sid\": \"DenyBoundaryTampering\",\n      \"Effect\": \"Deny\",\n      \"Action\": [\n        \"iam:DeleteRolePermissionsBoundary\",\n        \"iam:DeletePolicy\",\n        \"iam:CreatePolicyVersion\"\n      ],\n      \"Resource\": \"arn:aws:iam::111122223333:policy/workload-boundary\"\n    }\n  ]\n}\n```\n\nWith this, the teams could create roles for their services without anyone having to approve them – but no role could ever allow more than the `workload-boundary`. In the CDK, which we used to describe the infrastructure anyway, that’s one line per role:\n\n```ts\nimport * as iam from '@aws-cdk/aws-iam';\n\nconst boundary = iam.ManagedPolicy.fromManagedPolicyName(\n  this,\n  'WorkloadBoundary',\n  'workload-boundary'\n);\n\nconst serviceRole = new iam.Role(this, 'OrderServiceRole', {\n  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),\n  permissionsBoundary: boundary,\n});\n```\n\nThat got rid of the three-day wait for “please create a role for the order service.” Not because someone approved faster, but because there was nothing left to approve: the boundary was already drawn before the request came up.\n\n## Detect, don’t just prevent: AWS Config\n\nPreventive rules have a gap: they can only forbid what can be expressed as an IAM condition. “No S3 bucket without encryption” or “no security group with 0.0.0.0/0 on port 22” are properties of a resource, not API actions – for these, you need the second kind of guardrail. AWS Config records the state of all resources and continuously checks it against rules. On deviation: an alarm and, where it can be done safely, automatic correction.\n\n```ts\nimport * as config from '@aws-cdk/aws-config';\nimport * as budgets from '@aws-cdk/aws-budgets';\n\nnew config.ManagedRule(this, 'BucketsNotPublic', {\n  identifier: 'S3_BUCKET_PUBLIC_READ_PROHIBITED',\n});\n\nnew config.ManagedRule(this, 'VolumesEncrypted', {\n  identifier: 'ENCRYPTED_VOLUMES',\n});\n\nnew budgets.CfnBudget(this, 'TeamMonthlyBudget', {\n  budget: {\n    budgetType: 'COST',\n    timeUnit: 'MONTHLY',\n    budgetLimit: { amount: 500, unit: 'USD' },\n  },\n  notificationsWithSubscribers: [\n    {\n      notification: {\n        notificationType: 'ACTUAL',\n        comparisonOperator: 'GREATER_THAN',\n        threshold: 80,\n      },\n      subscribers: [\n        { subscriptionType: 'EMAIL', address: 'team-orders@example.com' },\n      ],\n    },\n  ],\n});\n```\n\nFor me, the budget belongs in the same category, even though it’s technically a different service. Fear of costs was the emotional core of the old approval process – and a budget alarm at 80 percent answers it better than any ticket, because it reacts to actual spending instead of estimated spending. On that project, each team got its own budget with its own notification. The discussions about costs didn’t become fewer, but they took place with numbers instead of guesses, and they took place within the team – not between the team and a gatekeeper.\n\nThe second benefit of Config is less conspicuous: the history. If a security group looks different today than yesterday, Config shows when what changed – that saved us hours in more than one debugging session, quite apart from the rules. An approval process only knows what was requested; Config knows what actually happened.\n\nI have become more cautious with automatic correction. A rule that immediately removes a public bucket policy is a security gain. A rule that deletes resources at night whose tags are wrong once cost us a morning of debugging, because a legitimate prototype had disappeared. Detecting and reporting is almost always right; intervene automatically only where the correction is guaranteed not to destroy anything.\n\n## Guardrails are code, not click configuration\n\nThe point where such setups tip over, in my experience, isn’t the technology but the maintenance. An SCP that someone clicked together in the console a year ago is just as opaque as the old approval process – except that now nobody knows why port 22 is blocked and who may change that. Guardrails are infrastructure, and for infrastructure, what I already described [when reviewing infrastructure code](https://www.mikebild.dev/en/blog/infrastructure-as-code-needs-code-reviews/) applies: it should be versioned, reviewed and changed traceably.\n\nFor us, that specifically means: SCPs, boundary policies and Config Rules live as code in the repository, changes go through a pull request, and the review includes someone from a product team alongside the platform team. The pull request replaces the ticket – with one crucial difference: what gets discussed is a permanent rule for everyone, not a one-off approval for one team. So the discussion is worth it, and its result keeps having an effect. I described how such rules can also be checked when synthesizing your own stacks in [Policy as Code for CDK](https://www.mikebild.dev/en/blog/policy-as-code-for-cdk/) – together, the two give you two checkpoints: one early in the build, one at the account boundary that can’t be bypassed.\n\nBy the way, the pattern isn’t AWS-specific. The same thing is happening right now in the Kubernetes world with Open Policy Agent and Gatekeeper – rules as code, enforced at the admission controller instead of in a meeting. If you run both worlds, you’ll recognize the line of thinking immediately.\n\n```mermaid\nflowchart TD\n  Root[Organization Root] --> Sec[OU Security<br/>Logging, Audit]\n  Root --> Work[OU Workloads]\n  Root --> Sand[OU Sandbox]\n  Work --> A1[Account Team Orders]\n  Work --> A2[Account Team Billing]\n  SCP1[SCP: EU regions,<br/>service blocklist] -.applies to.-> Work\n  SCP2[SCP: additionally<br/>tight cost limits] -.applies to.-> Sand\n```\n\nThe organizational structure itself is part of the guardrails: a sandbox OU with tight limits and a cleanup rule takes the risk out of experimenting, and a workload OU carries the binding rules. If you start with a multi-account structure today, Control Tower gives you exactly this scaffolding preconfigured – the guardrails behind it are the same SCPs and Config Rules, just already wired up.\n\n## What’s different in the end\n\nAfter half a year with this setup, the cloud team’s Jira board was almost empty – not because less was happening, but because most things no longer needed an approval. The tickets that remained were the interesting ones: requests to change a guardrail. That’s exactly where human attention belongs. And the platform team suddenly had time for the work that had been left lying around before: better templates, sharper rules, a new account in an hour instead of a week.\n\nI take away a few observations. The approval process and the guardrail answer the same question – “what may happen here?” – but at different times: the process once, beforehand, based on a description; the guardrail at every action, based on reality. That makes guardrails not only faster but more honest. Second: the split into preventive and detective isn’t a subtlety but the central design decision. Everything that is strictly forbidden belongs in SCPs and boundaries; everything that concerns properties of resources belongs in Config Rules with an alarm. If you try to enforce everything preventively, you rebuild the gatekeeping in JSON. And third: shadow infrastructure isn’t a discipline problem of the teams but a symptom. It doesn’t disappear through stricter processes, but through an official path that is faster than the detour.\n\n## Further reading\n\n- [Service Control Policies – AWS Organizations User Guide](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html)\n- [Permissions Boundaries for IAM Entities – AWS IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)\n- [What Is AWS Config? – AWS Config Developer Guide](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)\n- [AWS Control Tower – Set up & Govern a Multi-Account AWS Environment (AWS News Blog, 2019)](https://aws.amazon.com/blogs/aws/aws-control-tower-set-up-govern-a-multi-account-aws-environment/)"},{"locale":"en","translation_key":"cdk-constructs-abstraktion-mit-haftung","slug":"cdk-constructs-abstraction-with-liability","title":"CDK Constructs: Abstraction with Liability","summary":"If you publish a CDK construct, you’re not shipping a helper function but operational decisions – about defaults, upgrade paths and what ends up in the consumer’s CloudFormation template.","tags":["Software","AWS","Cloud"],"published_at":"2020-08-12T10:00:00+00:00","updated_at":"2026-07-14T17:10:58.285909+00:00","url":"https://www.mikebild.dev/en/blog/cdk-constructs-abstraction-with-liability/","audio_url":null,"audio_duration_secs":null,"text":"# CDK Constructs: Abstraction with Liability\n\nAn abstraction you import is responsibility you hand off – that is the unspoken assumption when a team pulls its first ready-made CDK construct into its project. Three lines of code, one `cdk deploy`, and the S3 bucket, CloudFront distribution and bucket policy are in place. After all, someone else has thought through the details.\n\nI think exactly this assumption is wrong, and in both directions. If you use a construct, you don’t hand off responsibility – you import someone else’s decisions into your own CloudFormation template, onto your own AWS bill and into your own attack surface. And if you publish a construct, you haven’t simply shared code – from now on you are liable for defaults, for upgrade paths and for everything that ends up in other people’s production. A construct is abstraction with liability. That sets it apart from almost everything else I get from npm.\n\n## Three levels, three different promises\n\nThe CDK sorts its building blocks into three levels, and the liability question arises differently on each. L1 constructs (`CfnBucket`, `CfnDistribution`) are generated one-to-one mappings of the CloudFormation resources. They promise nothing except completeness: every property, no default, no opinion. L2 constructs (`s3.Bucket`, `lambda.Function`) are handwritten wrappers with an opinion – sensible defaults, convenience methods like `grantRead`, automatically wired IAM policies. Finally, L3 constructs, also called patterns in CDK parlance, wire several services together into a domain building block: “static website with a CDN”, “API with Lambda and DynamoDB”.\n\nThe higher the level, the bigger the promise – and the bigger the liability. An L1 construct can hardly surprise me, because it decides nothing. An L3 construct decides almost everything, and I can’t tell from the code. That is exactly why L3 constructs are so tempting: they read like domain concepts (“a website”, “an API”) and hide the fact that underneath lies a bundle of very concrete operational decisions. What really happens only shows up in synthesis:\n\n```mermaid\nflowchart LR\n  L3[L3: StaticSite<br/>own pattern] --> L2[L2: s3.Bucket<br/>CloudFrontWebDistribution]\n  L2 --> L1[L1: CfnBucket<br/>CfnDistribution]\n  L1 --> SYNTH[cdk synth]\n  SYNTH --> TPL[CloudFormation template<br/>several hundred lines]\n  TPL --> DEPLOY[cdk deploy]\n  DEPLOY --> RES[real resources:<br/>cost, permissions, attack surface]\n```\n\nThe arrow on the far right is where a construct differs from a library function. A function from lodash produces an array at runtime. A construct produces a CloudFront distribution that costs money, a bucket that may or may not be public, and IAM statements that allow someone to do something. If `map` has a bug, a test fails. If a construct has a bug, a bucket lies open on the internet or a removal policy deletes production data when the stack is torn down. That’s no reason to do without abstraction – but it is a reason to treat it differently.\n\n## A construct of my own and its uncomfortable decisions\n\nThis really became clear to me when I built a small construct myself: a static website in S3, delivered via CloudFront. It was the third or fourth handwritten stack of this kind around me, always the same sixty lines, so extracting it was the obvious move. The first draft was done quickly. Things got interesting with the questions the first draft left open.\n\n```typescript\nimport { Construct, RemovalPolicy } from '@aws-cdk/core';\nimport * as s3 from '@aws-cdk/aws-s3';\nimport * as cloudfront from '@aws-cdk/aws-cloudfront';\nimport * as deployment from '@aws-cdk/aws-s3-deployment';\n\nexport interface StaticSiteProps {\n  readonly sourcePath: string;\n  readonly retainBucket?: boolean;\n}\n\nexport class StaticSite extends Construct {\n  public readonly siteBucket: s3.Bucket;\n  public readonly distribution: cloudfront.CloudFrontWebDistribution;\n\n  constructor(scope: Construct, id: string, props: StaticSiteProps) {\n    super(scope, id);\n\n    const originAccessIdentity = new cloudfront.OriginAccessIdentity(\n      this,\n      'OriginAccessIdentity'\n    );\n\n    this.siteBucket = new s3.Bucket(this, 'SiteBucket', {\n      encryption: s3.BucketEncryption.S3_MANAGED,\n      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,\n      removalPolicy: props.retainBucket\n        ? RemovalPolicy.RETAIN\n        : RemovalPolicy.DESTROY,\n    });\n    this.siteBucket.grantRead(originAccessIdentity);\n\n    this.distribution = new cloudfront.CloudFrontWebDistribution(this, 'Distribution', {\n      originConfigs: [\n        {\n          s3OriginSource: {\n            s3BucketSource: this.siteBucket,\n            originAccessIdentity,\n          },\n          behaviors: [{ isDefaultBehavior: true }],\n        },\n      ],\n    });\n\n    new deployment.BucketDeployment(this, 'DeploySite', {\n      sources: [deployment.Source.asset(props.sourcePath)],\n      destinationBucket: this.siteBucket,\n      distribution: this.distribution,\n    });\n  }\n}\n```\n\nEach of these lines is an operational decision I make for all future users. The bucket is not public but only reachable through the Origin Access Identity – that is the right decision, but it isn’t a given: the bare `s3.Bucket` from the CDK still sets no public access block to this day if you don’t specify one. Encryption is turned on, even though the content of a public website strictly speaking doesn’t need it – because nobody should have to discuss later why this particular bucket is unencrypted. And the removal policy defaults to `DESTROY`.\n\nI thought longest about this last default. The CDK itself retains buckets when a stack is torn down (`RETAIN`), because a bucket with content can’t simply be deleted and because data loss is the most expensive of all errors. For a website construct whose bucket content is regenerated from the build on every deployment, however, `RETAIN` is the wrong protection: it leaves an orphaned bucket behind for every test stack torn down, and after three months nobody knows which of them can go. So `DESTROY` as the default and `retainBucket` as the way out for cases where the bucket does contain more than build artifacts. Maybe that’s the wrong trade-off – but it now sits in one line of interface definition and can therefore be discussed. Before, it was hidden, unspoken, in sixty lines of copied stack code.\n\nThe two `public readonly` fields are just as deliberate. A construct that hides its inner resources forces its users to fork at the first special case. If you need to get at the `CfnDistribution`, you can reach it via `this.distribution.node.defaultChild` and use `addPropertyOverride` to override anything my abstraction didn’t anticipate:\n\n```typescript\nconst cfnDistribution = site.distribution.node\n  .defaultChild as cloudfront.CfnDistribution;\n\ncfnDistribution.addPropertyOverride(\n  'DistributionConfig.ViewerCertificate.MinimumProtocolVersion',\n  'TLSv1.2_2019'\n);\n```\n\nThese escape hatches are not a blemish on the abstraction but part of the contract. In infrastructure, an abstraction without a way out is a dead end, and you only ever notice dead ends once you’re already standing in one.\n\n## cdk synth is the test of truth\n\nFor the other side of liability – the consumer’s – there is a tool I consider more important than any documentation: synthesis. `cdk synth` writes out the CloudFormation template that results from the whole construct tree. The template doesn’t lie. It contains every resource, every policy, every default that any construct has set anywhere.\n\n```bash\nnpm install @aws-cdk/aws-s3@1.57.0 @aws-cdk/aws-cloudfront@1.57.0\n\ncdk synth StaticSiteStack > synthesized.yaml\n\n# what did the abstraction actually decide for me?\ngrep -A 6 'PublicAccessBlockConfiguration' synthesized.yaml\ngrep -B 2 'DeletionPolicy' synthesized.yaml\n\n# and before every deployment: what changes against reality?\ncdk diff StaticSiteStack\n```\n\nBefore I use someone else’s construct, I build a minimal example, synthesize and read. Not the whole template line by line – but specifically the places where other people’s defaults become expensive or dangerous. That takes half an hour and has paid off every time so far: once I found a CloudFront price class this way that delivered worldwide where Europe would have been enough; another time a log configuration that was simply missing, which would only have been noticed at the first incident. A pattern with three lines of application code easily produces several hundred lines of template, and somewhere in there are the answers to the questions the README doesn’t answer:\n\n- Which IAM statements are created, and do they contain wildcards I didn’t order?\n- Which resources cost money continuously, even when nobody uses the system?\n- What is publicly reachable, what is encrypted, what has which `DeletionPolicy`?\n- Which properties can I change through the interface – and for which do I need the escape hatch on day one?\n\nThis spring, AWS launched its own library of such patterns with the Solutions Constructs: vetted two-service combinations such as CloudFront in front of API Gateway in front of Lambda, with defaults along the Well-Architected Framework. I have read some of them, used a few, and find the source code especially instructive – there you see how many lines of default logic it takes for “CloudFront plus S3” to be wired really sensibly, including the details that are regularly missing from handwritten stacks. That is exactly the value of someone else’s L3 abstraction: not that I no longer need to know anything, but that someone has already made and written down the decisions I can hold my own up against. I already looked at how such checks can be automated instead of depending on discipline in [Policy as Code for CDK](https://www.mikebild.dev/en/blog/policy-as-code-for-cdk/) – for me, synthesis and rule checking now belong together.\n\n## What the author owes\n\nThat leaves the question of what you take on when you publish yourself. After half a year with my own construct and quite a few others I’ve read, I have a provisional list, and it is longer than I realized when I extracted the first sixty lines.\n\nFirst there are the defaults, about which everything has already been said above – with the addition that a published default is practically impossible to change. If you tighten it, you break existing deployments; if you loosen it, you make existing users less secure without them noticing. A default is a promise with a very long term.\n\nThen the upgrade paths. The CDK currently ships a new version almost weekly, we’re at 1.5x, and modules like CloudFront still carry the experimental stamp, so they may change in minor releases. A construct I publish spans this movement: my users raise their CDK version and expect my construct to come along. Peer dependencies on the right `@aws-cdk` packages, prompt releases after upstream changes, a changelog that mentions template changes – that is not a bonus, that is half the work. And because the CDK also generates Python, Java and .NET bindings via jsii, the shape of the API alone (no TypeScript specialties that jsii can’t represent) decides whom I can reach as users at all.\n\nThen there are tests, and on the right level. Unit tests against your own TypeScript logic check only half the truth; what I’m liable for is the template. With `@aws-cdk/assert`, you can pin down both – individual assertions (`expect(stack).to(haveResource('AWS::S3::Bucket', { PublicAccessBlockConfiguration: … }))`) for the decisions that must never flip, and a snapshot of the entire synthesized template so that every change in the output becomes visible in review rather than at the user’s end. Since I started doing this, I’ve caught two upstream changes before they reached a release – both would have changed the template without a single line of my code changing.\n\nAnd finally the template output itself. Logical IDs in the template are derived from the construct path; if you rename or move children while refactoring your construct, you change the IDs – and CloudFormation then replaces resources instead of updating them. For a CloudFront distribution that means half an hour of waiting; for a bucket with data, an incident. That’s why for me `cdk diff` against a deployed example stack comes before every release of the construct, for the same reason it comes before every deployment. Since July, CDK Pipelines (Developer Preview) has offered a building block that pulls such checks into a self-mutating deployment pipeline – still fresh, but the direction is right: delivering a construct is infrastructure too and wants to be treated as such.\n\n## Bottom line\n\nA little over a year ago, I [wrote about what changes when infrastructure becomes a programming language](https://www.mikebild.dev/en/blog/cdk-early-days-infrastructure-in-a-programming-language/). Constructs are the continuation of that: if infrastructure is code, it also takes on the properties of code – reuse, packaging, versioning. Only the cost of errors remains that of infrastructure.\n\nThat’s why I think both comfortable attitudes are wrong. “I write everything myself, then I know what’s in it” doesn’t scale and reproduces the same forgotten details in every stack. “I take the ready-made pattern, then I don’t have to understand it” mistakes abstraction for absolution. What works for me lies in between: L3 abstractions, yes, including your own – but read before use, synthesized before trust, and, when publishing, with the awareness that from now on you share in decisions about other people’s production environments. A construct is not a snippet. It is a contract about defaults, ways out and upgrade paths, and `cdk synth` is the document in which this contract is written in black and white.\n\n## Further reading\n\n- AWS Solutions Constructs on GitHub: https://github.com/awslabs/aws-solutions-constructs\n- AWS CDK on GitHub: https://github.com/aws/aws-cdk\n- Constructs in the CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n- Announcement of the AWS Solutions Constructs (AWS blog): https://aws.amazon.com/blogs/aws/aws-solutions-constructs-a-library-of-architecture-patterns-for-the-aws-cdk/\n- CDK Pipelines Developer Preview (AWS blog): https://aws.amazon.com/blogs/developer/cdk-pipelines-continuous-delivery-for-aws-cdk-applications/"},{"locale":"en","translation_key":"bounded-contexts-grenze-vor-microservice","slug":"bounded-contexts-before-the-service-split","title":"Bounded Contexts Before the Service Split","summary":"Before I split services, I clarify domain boundaries. A bounded context is a language boundary and a possible, but not mandatory, service split.","tags":["Software","Architecture"],"published_at":"2020-07-24T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/bounded-contexts-before-the-service-split/","audio_url":null,"audio_duration_secs":null,"text":"# Bounded Contexts Before the Service Split\n\nIf you fix the number of services before the domain boundaries are settled, you do not remove coupling – you distribute it over the network. The split then separates code, but not responsibilities: a change to a single term still runs through three systems, only now with HTTP in between and three teams that have to coordinate.\n\nThe boundary that is missing beforehand is not a technical one. It runs where a word stops meaning the same thing.\n\nThe architecture emerges at the language boundaries and at the translations between them.\n\n:::relationship{title=\"Domain boundaries before technical splits\" role=\"primary\" preferredPattern=\"architecture-map\"}\n- Subdomain · describes a domain problem space\n- Bounded context · gives terms and rules an unambiguous scope\n- Model · implements the language within this boundary\n- Context map · names dependencies and influence between contexts\n- Anti-Corruption Layer · translates a foreign model into your own language\n- Service · can run a boundary, but does not automatically define it\n:::\n\nThis keeps boxes from becoming an end in themselves. What matters is where meaning changes and who is responsible for that translation.\n\n## Why the order decides the outcome\n\nThe question monolith migrations usually start with is: “How many microservices do we break the monolith into?” It is already the wrong question. The number is a result, not a target. What needs clarifying is where the domain boundaries lie – and whether you can name a separate, internally consistent language for each boundary. How many services that turns into becomes clear afterwards.\n\nThe reason is economic. A service split is cheap to draw and expensive to correct once teams, deployments and databases depend on it. A domain boundary, on the other hand, can be moved on the whiteboard as long as it is still a model and not infrastructure. That is why I invest the first week of such a project in language and not yet in infrastructure and deployment diagrams. The business result is measurable: shorter change cycles, because a change stays within one context; less friction between teams, because nobody trips over shared tables; higher quality, because the model reflects the domain instead of an accidental technical structure.\n\n## The bounded context is a language boundary\n\nEric Evans coined the term in 2003 in *Domain-Driven Design*, and Martin Fowler summed it up in his bliki: a bounded context is the area in which exactly one model and exactly one ubiquitous language apply. Within this boundary, every word means exactly one thing. Across the boundary, the same word may mean something else – that is where the real gain lies.\n\nAn example from retail: the word “Product.” In sales, a Product is a thing with a price, a description and availability. In the warehouse, the same Product is an SKU with stock, a storage location and a reorder point. In accounting, it is a line item with a tax rate and a revenue account. Three contexts, three legitimate meanings. The classic mistake is to try to build a single canonical `Product` object out of this that does justice to all three. The result is a class with forty fields, of which each context ignores ten – and every change affects all three teams.\n\nFowler names not technology but “human culture” – language and organization – as the dominant factor in drawing these boundaries. This is where Conway’s Law comes in: context boundaries and team boundaries influence each other. If I draw a clean boundary but two teams have to work on it together, I am drawing it in the wrong place.\n\nIn practice, I test a suspected boundary with two questions. First: can I say a sentence in this context that a domain expert from the neighboring context no longer understands unambiguously without translation? If so, these are two languages and therefore two contexts. Second: is there a rule that applies exactly here and not next door – for example “a Product without stock is still visible in sales, but does not exist in the warehouse”? Such rule breaks are the most reliable boundary markers I know. They come up in conversations with domain experts, not in the class diagram, and that is exactly why I only find them if I listen first instead of modeling.\n\n## Sort subdomains, implement bounded contexts\n\nBefore I draw boundaries, I sort the problem space. Strategic DDD separates problem space and solution space. The subdomains live in the problem space, and I categorize them into three classes:\n\nThe core domain is what a company does better than its competitors – that is where the best team and most of the modeling work belong. Supporting subdomains are necessary, but not a differentiator; solid standard work is enough here. Generic subdomains are solved problems such as authentication, accounting or notifications; I buy or standardize them instead of building them myself.\n\nThis classification is a business decision, not a technical one. It answers the question of where effort pays off. Bounded contexts are then the answer in the solution space: ideally, one subdomain corresponds to exactly one bounded context. In reality, they rarely match – a system that grew historically often cuts across. But the core/supporting/generic classification tells me at which boundary I need precision and where pragmatism is enough.\n\n## The edges are the architecture, not the boxes\n\nIsolated models are not a system yet. The system emerges from the relationships between the contexts, and naming these relationships is the core of the work – context mapping. Without a context map, you get exactly what Evans calls a “distributed Big Ball of Mud”: many services that all depend on each other, without anyone controlling the translation.\n\nI draw a context map as boxes with edges. The boxes are the contexts, each with its own language. The edges are what is interesting: who is upstream (determines the model), who is downstream (has to adapt)? Who translates, who publishes?\n\n```mermaid\ngraph LR\n  subgraph U[\"Upstream\"]\n    INV[\"Inventory<br/>Product = SKU + stock\"]\n  end\n  subgraph D[\"Downstream\"]\n    SAL[\"Sales<br/>Product = price + description\"]\n    BIL[\"Billing<br/>Product = tax + revenue account\"]\n  end\n  INV -->|\"OHS / PL\"| SAL\n  SAL -->|\"ACL\"| BIL\n  INV -.->|\"SK shared kernel\"| SAL\n```\n\nThe labels carry the statement. An Open Host Service with a Published Language (OHS/PL) on the upstream side means: Inventory offers a stable, documented interface that many can connect to. An Anti-Corruption Layer (ACL) on the downstream side means: Billing actively protects its model from foreign terms. A Shared Kernel (SK) means: two contexts deliberately share a small common model – and with it, coupling.\n\nThe decisive point: the later service split is laid *on top of* this context map. First it exists, then I decide which context becomes one service, which becomes two, and which stay deployed together. The bounded context is the model boundary, the service the deployment unit. Vladik Khononov put it aptly in 2018: bounded contexts are not microservices. A service can be part of a context, and a context can span several services.\n\n## The pattern that saves the most friction: the Anti-Corruption Layer\n\nOf all context mapping patterns, the Anti-Corruption Layer is the one whose absence I most often see paid for dearly. As soon as a cleanly modeled context borders on a legacy or third-party system, it needs a translation layer. Without it, the foreign model – often a bad one – seeps into my core. What starts as “we’ll adapt briefly” (Conformist) silently becomes the permanent solution.\n\nConcretely: my Sales context knows a clean `Product`. The Inventory system speaks in `LegacyInventoryResponse` with `sku` and `price_cents`. I never let these foreign DTOs into my domain model. An adapter translates in exactly one place:\n\n```java\n// Downstream context: Sales\ninterface CatalogPort {\n    Product findById(ProductId id);\n}\n\n// ACL: isolates the upstream \"Inventory\" model.\n// Only this class knows the foreign DTOs; the domain never does.\nclass InventoryAntiCorruptionLayer implements CatalogPort {\n\n    private final LegacyInventoryClient legacyClient;\n\n    @Override\n    public Product findById(ProductId id) {\n        LegacyInventoryResponse raw = legacyClient.get(id.value());\n        return new Product(\n            new ProductId(raw.sku),\n            Money.of(raw.price_cents) // translate cents into the domain type\n        );\n    }\n}\n```\n\nThe gain is not cosmetic. When the Inventory team changes its format, exactly one class changes. My core stays stable, my tests stay green, and the translation is documented instead of scattered across the code. That is the difference between a boundary that holds and one that leaks.\n\nThe flip side applies to the Shared Kernel: I only use it when two teams work in a real partnership and deliberately want the coupling. A shared model means shared change – every adjustment forces both teams to coordinate. Misused as the default, the Shared Kernel becomes a brake. When in doubt, I give each context its own model and connect them through a Published Language.\n\nBetween Conformist and ACL there is a cost trade-off, and it should be spelled out. Conformist means: we take over the foreign model one to one and save ourselves the translation. That is legitimate when the upstream is stable and its model fits your own – for example with a generic subdomain that is only integrated anyway. But as soon as your own core is affected or the upstream has a weak model, the translation layer you saved becomes a deferred debt. The ACL costs its setup once and pays back with every foreign change. I do this calculation explicitly instead of leaving the decision to the chance of the first integration sprint. In practice, I write it down as a short decision: which foreign model are we coupling to, how stable is it, what would a change cost us? Once you have answered this question deliberately, you no longer make it by accident under time pressure.\n\n## Recording boundaries declaratively\n\nSo that the context map does not rot as a photo of the whiteboard, I record it in a versionable form. With Context Mapper and its DSL, I write the relationships as text that sits in the repository next to the code and is versioned with every change:\n\n```text\nContextMap ShopMap {\n    contains Sales, Inventory, Billing\n\n    Inventory -> Sales : Customer-Supplier {\n        implementationTechnology = \"REST\"\n        downstreamRights = INFLUENCER\n        exposedAggregates = Product\n    }\n\n    Sales -> Billing : Conformist {\n        implementationTechnology = \"Messaging\"\n    }\n}\n```\n\nThis is not an end in itself. The value lies in the fact that the relationship – Customer-Supplier, who is upstream, which aggregate is exposed – is documented in a verifiable way. A new developer can read in one place how the contexts fit together instead of reconstructing it from call chains. I have discussions about boundaries on the diff of this file, not on the next wiped-clean whiteboard.\n\n## How I proceed in practice\n\nMy process is deliberately unspectacular and needs no toolchain. I get the domain experts and one or two developers into a room and let them tell the business flow – for larger domains, I use Event Storming as a discovery technique to get the events onto the wall. While doing so, I listen for breaks in language: as soon as the same word means two different things, I have probably found a context boundary. Then I name the contexts, classify them into core, supporting and generic, and draw the edges with their patterns. I immediately mirror every suspected boundary back to the domain experts: I retell the flow in their language and watch where they correct me. These corrections are worth their weight in gold, because they show me the places where my model and the domain as actually practiced still diverge. Only after that – and often only weeks later – do we talk about services, repositories and deployment.\n\nTo technology-driven teams, this approach feels slow at first. It is the opposite. The weeks I invest in language up front I save three times over later, because I no longer have to correct boundaries through a production system. Simple and elegant here means: few, well-founded boundaries instead of many accidental ones.\n\n## Conclusion\n\nThe common thread is an order. First the language: where does which model apply, where does a term break? That is the bounded context. Then the relationships: who is upstream, who translates, where do I protect my core with an Anti-Corruption Layer, where do I couple deliberately through a Shared Kernel? That is the context map. And only at the very end the deployment unit: which context becomes a microservice?\n\nIf you stick to this order, you can align services with domain boundaries instead of cutting them along technical layers. If you reverse it and count services before you understand the language, you risk a distributed Big Ball of Mud with more network in between. First comes the model boundary, then the decision about operations. Not every bounded context has to become its own service.\n\n## Further reading\n\n- [Martin Fowler – BoundedContext](https://martinfowler.com/bliki/BoundedContext.html)\n- [Martin Fowler – UbiquitousLanguage](https://martinfowler.com/bliki/UbiquitousLanguage.html)\n- [Martin Fowler – Conway's Law](https://martinfowler.com/bliki/ConwaysLaw.html)\n- [Vladik Khononov – Bounded Contexts are NOT Microservices](https://vladikk.com/2018/01/21/bounded-contexts-vs-microservices/)\n- [Context Mapper – Context Map](https://contextmapper.org/docs/context-map/)"},{"locale":"en","translation_key":"funktionale-muster-in-python","slug":"functional-patterns-in-python","title":"Functional Patterns in Python: Comprehensions, itertools and functools","summary":"Comprehensions, functools and itertools working together: how I show in projects when a comprehension is a better choice than map/filter, where lru_cache and groupby shine, and which pitfalls are waiting.","tags":["Software","Python","Backend"],"published_at":"2020-07-15T10:00:00+00:00","updated_at":"2026-07-13T13:19:52.630074+00:00","url":"https://www.mikebild.dev/en/blog/functional-patterns-in-python/","audio_url":null,"audio_duration_secs":null,"text":"```python\nfrom itertools import groupby\nfrom operator import itemgetter\n\nrecords = [\n    {\"team\": \"a\", \"pts\": 3},\n    {\"team\": \"b\", \"pts\": 5},\n    {\"team\": \"a\", \"pts\": 2},\n]\n\ntotals = {\n    team: sum(r[\"pts\"] for r in group)\n    for team, group in groupby(records, key=itemgetter(\"team\"))\n}\n# {\"a\": 2, \"b\": 5} – erwartet war {\"a\": 5, \"b\": 5}\n```\n\nNo traceback, no warning, just a wrong result. `groupby` only groups *consecutive* equal keys. Without sorting first, team `a` falls apart into two groups, and the second one overwrites the first in the dictionary. If you know `GROUP BY` from SQL, you expect the exact opposite here.\n\nThat is how Python’s functional tools behave across the board: they carry familiar names from Java, C# or SQL, but follow their own rules. If you want to work functionally in Python, you reach for `map` and `filter` less often and for comprehensions, `functools` and `itertools` more often. Together these three cover almost everything you know from functional programming – in a style that is typical for Python.\n\nI go through them in order: first comprehensions as the idiomatic replacement for `map`/`filter`, then the lazy combinators from `itertools`, then the helpers from `functools` – above all `lru_cache` – and finally the leaning toward immutability. In several places I show not only how it works, but where I regularly see mistakes in practice. If you have already looked at [advanced Python](https://www.mikebild.dev/en/blog/advanced-python-decorators-magic-methods-generators/), you know generators and decorators – here we build on that.\n\n## Comprehensions instead of map and filter\n\nLet us start with a concrete example. I want the squares of all even numbers from 0 to 9. In the `map`/`filter` version it reads like this:\n\n```python\nnums = range(10)\n\n# map/filter with lambdas – works, but reads inside out\nsquares_even = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, nums)))\n```\n\nThat works, but you read it from the inside out: first `filter`, then `map`, and the two `lambda` expressions sit between the arguments. The comprehension turns this around and puts the transformation in front and the condition at the end:\n\n```python\nnums = range(10)\n\n# comprehension – transform first, condition last, one line\nsquares_even = [n * n for n in nums if n % 2 == 0]\n```\n\nThis is the form that dominates in Python code, and the reason is simply readability. Idiomatic Python code usually prefers a comprehension over `map` or `filter` with `lambda`; PEP 8, however, does not prescribe this particular choice. Comprehensions come in three flavors – for lists, dictionaries and sets:\n\n```python\nwords = [\"alpha\", \"beta\", \"gamma\"]\n\n# list, dict and set comprehensions\nlengths = [len(w) for w in words]\nby_length = {w: len(w) for w in words}\ninitials = {w[0] for w in words}\n```\n\nOne detail is easy to miss: since Python 3, a comprehension has its own namespace. The loop variable `w` stays inside the comprehension and no longer leaks into the surrounding code – an old stumbling block from Python 2 days that you no longer need to fear.\n\nDoes that mean `map` and `filter` are superfluous? No. They are still idiomatic when a named function already exists. `map(str.upper, words)` is clearer than `[w.upper() for w in words]` – there is no `lambda` here, just a ready-made function, and the expression stays short:\n\n```python\nwords = [\"alpha\", \"beta\", \"gamma\"]\n\n# map shines with an existing named function – no lambda noise\nshouted = list(map(str.upper, words))\n```\n\nSo the `lambda` works as a signal: if there is one in `map` or `filter`, a comprehension would be the better choice. A named function in `map`, on the other hand, is perfectly fine.\n\nA related detail regularly causes confusion: the difference between the filter at the end and a conditional expression in front. Both use the keyword `if`, but they do opposite things:\n\n```python\nnums = range(10)\n\n# if at the end filters elements out – only evens survive\nevens = [n for n in nums if n % 2 == 0]\n\n# if ... else at the front transforms – all elements stay\nmasked = [n if n % 2 == 0 else 0 for n in nums]\n```\n\nThe `if` at the end selects and drops the odd numbers; the `if ... else` in front keeps every element and only replaces the odd ones with `0`. Two constructs that are easy to mix up and produce completely different results – I trip over this regularly in code reviews.\n\n## Lazy evaluation with map, filter and generator expressions\n\nOne point is often overlooked: in Python 3, `map` and `filter` no longer return lists, but iterators. They compute on demand – values are only produced when you ask for them. That is exactly why the examples above wrap them in `list(...)`; otherwise you would just get the iterator object.\n\nA comprehension, by contrast, materializes immediately: it builds the complete list in memory. For small amounts of data that does not matter; for large ones it can get expensive. This is where the generator expression comes in – syntactically almost identical to the list comprehension, just with parentheses instead of square brackets:\n\n```python\n# list comprehension: builds the whole list in memory\ntotal_eager = sum([n * n for n in range(1_000_000)])\n\n# generator expression: yields one value at a time, constant memory\ntotal_lazy = sum(n * n for n in range(1_000_000))\n```\n\nBoth return the same result, but the second version does not materialize a complete result list. It produces its values on demand; upstream data sources or individual operations can of course still take up memory. When I only iterate over an expression once anyway – say as an argument to `sum`, `any` or `max` – the generator expression is usually the right choice.\n\nA word of caution: a generator is exhausted after one pass. If you want to iterate over the same generator twice, the second pass returns an empty result. For repeated access you need a materialized list – or you design the pipeline so that one pass is enough.\n\nSo we have three ways to process a sequence, and each has its place:\n\n- Comprehension – readable, materializes immediately, its own namespace, filter and transformation in one expression.\n- `map`/`filter` – lazy, ideal in combination with an existing named function, less readable with `lambda`.\n- `itertools` – lazy combinators for long or infinite streams, constant memory, composes well.\n\nLet us take a closer look at the third one now.\n\n## itertools: lazy combinators for streams\n\n`itertools` is a collection of building blocks that all work lazily. They produce iterators, not lists, and can be plugged together into pipelines without intermediate results piling up in memory. A few that I use almost daily:\n\n```python\nfrom itertools import chain, islice, count\n\n# count: infinite counter, here 1, 3, 5, 7, 9\nfirst_five_odds = list(islice(count(1, 2), 5))\n\n# chain.from_iterable: flatten a list of lists lazily\nflat = list(chain.from_iterable([[1, 2], [3, 4], [5, 6]]))\n```\n\nBesides `chain`, `islice` and `count`, I often reach for `takewhile` and `dropwhile`. Both take a predicate and a stream: `takewhile` yields values as long as the condition holds and stops for good at the first `False`; `dropwhile` skips the leading block for which the predicate is true and returns everything from there on. On a sorted stream, this lets you cut out a range without checking the whole rest.\n\n`count(1, 2)` is an infinite counter – without `islice` it would never stop. `islice` cuts out the first five values and stops evaluation exactly there. That is the pattern behind lazy pipelines: you describe a potentially infinite source and limit it only at the end. `chain.from_iterable`, in turn, flattens nested sequences without copying the sublists together first.\n\nThe building block that triggers the most aha moments is `groupby`. It lets you group records by a key and aggregate them:\n\n```python\nfrom itertools import groupby\nfrom operator import itemgetter\n\nrecords = [\n    {\"team\": \"a\", \"pts\": 3},\n    {\"team\": \"a\", \"pts\": 2},\n    {\"team\": \"b\", \"pts\": 5},\n]\n\n# IMPORTANT: sort by the same key before grouping\nrecords.sort(key=itemgetter(\"team\"))\n\ntotals = {\n    team: sum(r[\"pts\"] for r in group)\n    for team, group in groupby(records, key=itemgetter(\"team\"))\n}\n# {\"a\": 5, \"b\": 5}\n```\n\nThis brings us back to the example from the beginning: if the input is not sorted by the same key first, you get several groups for the same key, and the result is silently wrong. The `records.sort(...)` before `groupby` is not optional; it is mandatory – it is the one line that makes the difference between `{\"a\": 5, \"b\": 5}` and `{\"a\": 2, \"b\": 5}`.\n\nA second point: the groups that `groupby` returns are transient iterators. As soon as you move on in the outer loop, the previous group becomes invalid. If you want to keep a group beyond the iteration, you have to materialize it with `list(group)` before moving on. In the example above that is no problem, because `sum(...)` evaluates the group directly in the same step.\n\nBefore we get to `functools`, a look at the big picture. The following sketch shows how raw data moves through such a pipeline – from the eagerly materializing comprehension through lazy generator expressions and `itertools` combinators to the final fold into a single value.\n\n```mermaid\ngraph LR\n    A[Raw data] --> B[Comprehension<br/>eager, materialised]\n    B --> C[Generator expr<br/>lazy, constant memory]\n    C --> D[itertools<br/>chain / islice / groupby]\n    D --> E[reduce / sum / prod<br/>fold to a value]\n    E --> F[Result]\n```\n\n## functools: partial, reduce and lru_cache\n\n`functools` bundles tools that act on functions themselves. Three of them are central to functional patterns.\n\n`partial` binds some of a function’s arguments in advance and returns a new callable function. That is handy for specializing general functions:\n\n```python\nfrom functools import partial\n\ndef power(base, exponent):\n    return base ** exponent\n\n# fix the exponent, get a specialised function\nsquare = partial(power, exponent=2)\ncube = partial(power, exponent=3)\n\nprint(square(5))  # 25\nprint(cube(5))    # 125\n```\n\n`reduce` folds a sequence into a single value – the classic of functional programming. In Python 3, `reduce` is deliberately no longer a builtin but was moved to `functools`. That is a clear signal: use it sparingly.\n\n```python\nfrom functools import reduce\n\nflat = [1, 2, 3, 4]\n\n# reduce works, but a built-in is almost always clearer\ntotal = reduce(lambda acc, x: acc + x, flat, 0)  # 10\nbetter = sum(flat)                                # same result, obvious intent\n```\n\nOne detail of `reduce` is easy to overlook: the third argument. It is the initial value of the fold and at the same time decides what happens with an empty sequence. With an initial value of `0`, `reduce` returns exactly that `0` for empty input; without an initial value, `reduce` raises a `TypeError` on an empty sequence instead. If you leave out the initial value, you buy yourself a special case that is easy to forget in tests – and that then strikes precisely in the edge case.\n\nThis is where the most common `functools` mistake I see shows up: `reduce` gets overused. Nested `reduce` lambdas are hard to read, and for most cases there are clearer alternatives – `sum` for sums, `math.prod` for products (since Python 3.8), a comprehension or simply a loop. `reduce` is justified when the fold is genuinely non-trivial and no specialized function exists. In all other cases, the more explicit way wins.\n\nFor me, the star of `functools` is `lru_cache`. The decorator memoizes a function’s results – the same arguments return the stored result instead of computing it again. The classic textbook example is the naive recursive Fibonacci function, whose runtime explodes exponentially without memoization:\n\n```python\nfrom functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fib(n: int) -> int:\n    return n if n < 2 else fib(n - 1) + fib(n - 2)\n\nprint(fib(50))          # 12586269025 – instant instead of minutes\nprint(fib.cache_info())  # CacheInfo(hits=48, misses=51, maxsize=None, currsize=51)\n```\n\nWith `lru_cache`, every Fibonacci value is computed exactly once – the complexity drops from exponential to linear. `cache_info()` gives insight into hits and misses, `cache_clear()` empties the cache. A note on style: I consistently write `@lru_cache(maxsize=None)` with parentheses. That is unambiguous across all versions and saves discussions about which Python version allows the call without parentheses.\n\nThere are two conditions you need to know. First: the arguments must be hashable – lists or dictionaries as parameters do not work, and tuples only if their elements are hashable too. Second: `lru_cache` fits when the result depends only on those arguments and the returned object can safely be reused. With side effects or mutable external state, the cache easily returns wrong results. And `maxsize=None` means an unbounded cache – with a great many different arguments, memory usage can grow without limit. For such cases you set a concrete `maxsize`.\n\n`functools` offers more than fits into one article – for example `singledispatch`, which lets a function resolve differently depending on the type of its first argument, or `cmp_to_key`, which turns an old comparison function into a `key` for `sorted`. For functional patterns in the narrower sense, though, `partial`, `reduce` and `lru_cache` are the three I reach for most often in practice.\n\n## The leaning toward immutability\n\nFunctional work and immutability go together. Python offers two immutable containers that help here: `tuple` for ordered sequences and `frozenset` for sets. Both are hashable as long as their elements are hashable, and can then be used as dictionary keys or as elements of a set – something you cannot do with `list` or `set`:\n\n```python\n# immutable, hashable – usable as dict keys or set members\npoint = (3, 4)\nallowed = frozenset({\"read\", \"write\"})\n\npermissions = {\n    frozenset({\"read\"}): \"viewer\",\n    frozenset({\"read\", \"write\"}): \"editor\",\n}\nprint(permissions[allowed])  # editor\n```\n\nThe advantage is not just hashability. Immutable data cannot change unnoticed while you send it through a pipeline. That is exactly the foundation of side-effect-free work: a function takes data in, returns new data and leaves the input untouched. Especially in larger systems, this separation makes transitions traceable.\n\nThat leads directly to the last pitfall I see often: side effects in comprehensions. A comprehension is supposed to produce values, not call `print`, append to a list or change state:\n\n```python\n# don't do this: a comprehension used only for side effects\n[print(w) for w in words]  # builds a useless list of None values\n\n# do this instead\nfor w in words:\n    print(w)\n```\n\nThe first version builds a list full of `None` values on the side that nobody needs. It misuses the comprehension for something the normal loop is there for. Comprehensions are meant for transformations – if no value is produced, the code belongs in a loop.\n\n## Making the right choice\n\nWhat matters is less knowing every tool than reaching for the right one at the right moment. The following decision tree sums up how I weigh things in practice.\n\n```mermaid\ngraph TD\n    A[Sequence to process] --> B{Build a new container?}\n    B -->|Yes| C[Comprehension<br/>list / dict / set]\n    B -->|No| D{Transform with a<br/>named function?}\n    D -->|Yes| E[map]\n    D -->|No| F{Large or infinite,<br/>save memory?}\n    F -->|Yes| G[Generator expr<br/>or itertools]\n    F -->|No| H{Fold to one value?}\n    H -->|Yes| I[sum / prod / reduce]\n```\n\nThe thread running through all of this: Python provides the functional tools, but expects you to use them in its own idiom. Comprehensions come before `map`/`filter` with `lambda` because they read better. Generator expressions and `itertools` step in when data gets large or streams are infinite – lazy and easy on memory. `functools` contributes `partial` for specialization, `reduce` for the rare genuine folds and `lru_cache` for memoizing pure functions. And the immutable containers `tuple` and `frozenset` keep the whole thing free of side effects.\n\nThe pitfalls I have shown are all of the same kind: `reduce` where `sum` would have been enough; `groupby` without sorting first; side effects in a comprehension. They do not come from missing knowledge, but from the habit of using a tool beyond its purpose. If you know these three groups of tools and use them with discipline, you write Python that stays compact and is still easy to read – and that is exactly the standard the language sets for functional code.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-python.en.html\n- Repository `introduction-python` – the examples from this article to try out.\n- [functools – Higher-order functions (Python 3.8)](https://docs.python.org/3.8/library/functools.html)\n- [itertools – Functions creating iterators (Python 3.8)](https://docs.python.org/3.8/library/itertools.html)\n- [List Comprehensions – Python Tutorial (3.8)](https://docs.python.org/3.8/tutorial/datastructures.html#list-comprehensions)\n- [map and filter – Built-in Functions (Python 3.8)](https://docs.python.org/3.8/library/functions.html#map)"},{"locale":"en","translation_key":"jsx-genau-die-regeln-hinter-dem-markup","slug":"jsx-precisely-the-rules-behind-the-markup","title":"JSX Precisely: The Rules Behind the Markup","summary":"A precise look at JSX – what the compiler turns it into, why curly braces hold expressions rather than statements, how attributes, children, conditions and lists work, and where beginners stumble.","tags":["Software","Frontend","React"],"published_at":"2020-06-24T10:00:00+00:00","updated_at":"2026-07-13T07:28:41.146176+00:00","url":"https://www.mikebild.dev/en/blog/jsx-precisely-the-rules-behind-the-markup/","audio_url":null,"audio_duration_secs":null,"text":"# JSX Precisely: The Rules Behind the Markup\n\nJSX isn’t a template language and it isn’t an HTML variant that somehow tolerates JavaScript. It’s a notation for function calls: every element you write is translated into a call before execution, and that call returns an ordinary JavaScript object.\n\n**Editorial note (July 2026):** The main text explains the classic JSX transform, which was the published state in June 2020. Since React 17, the automatic transform can use functions from `react/jsx-runtime`; that doesn’t change the mental model. How React later reconciles the resulting elements is covered in the article published afterward, [How React Renders and Updates the Tree](https://www.mikebild.dev/en/blog/how-react-renders-and-updates-the-tree/).\n\nThe React overview had a single sentence on this – looks like HTML, but is JavaScript. The sentence is true and still prevents none of the mistakes that happen in everyday work: reserved attribute names, statements in curly braces, a lonely `0` in the UI, keys from array indexes. So here are the rules in order, each with a tiny example and, where it matters, with the mistake you make if you don’t know the rule.\n\n## What the compiler really turns it into\n\nJSX isn’t a JavaScript language feature. No browser understands it. Before the code runs, a build step like Babel translates every JSX element into a normal function call. This one fact explains almost all the rules that follow.\n\nAs of June 2020, the target of this translation is `React.createElement`. The markup becomes a call, and the call becomes a plain object.\n\n```jsx\nconst el = <button className=\"primary\" onClick={handleClick}>Save</button>;\n```\n\nbecomes, roughly:\n\n```js\nconst el = React.createElement(\n  \"button\",\n  { className: \"primary\", onClick: handleClick },\n  \"Save\",\n);\n```\n\nThe returned object only describes what should be rendered – it’s not a DOM node, nothing happens in the browser yet. React later takes this object and creates or updates the real DOM from it. Such a description object is called a React element. With that in mind, it becomes clear why a typo in JSX often shows up as a perfectly normal JavaScript error: in the end, it is a function call.\n\n## Expression, not statement\n\nThe most important rule for the content of curly braces is: between `{` and `}` there’s an **expression**, not a **statement**. An expression is something that produces a value – `user.name`, `a + b`, `price > 0 ? \"ok\" : \"no\"`, a function call. A statement is something that does something but doesn’t yield a value – `if`, `for`, `while`, `switch`. Statements aren’t allowed inside the braces.\n\n```jsx\n// works – an expression\n<p>{user ? user.name : \"Guest\"}</p>\n\n// does not work – if is a statement\n<p>{if (user) { user.name }}</p>\n```\n\nThat’s why in JSX you reach so often for the ternary operator `? :` and the logical `&&`: they’re the expression variants of `if`. If you need a real branch with several arms, you pull it in front of the `return` and work there with a perfectly normal `if`:\n\n```jsx\nfunction Status({ status }) {\n  let text;\n  if (status === \"open\") text = \"Open\";\n  else if (status === \"paid\") text = \"Paid\";\n  else text = \"Unknown\";\n\n  return <span>{text}</span>;\n}\n```\n\nThat isn’t a detour. It’s the clean separation: logic at the top, presentation at the bottom. A common beginner reflex is to nest ever more complex ternaries until nobody reads them anymore. As soon as you reach two levels, the decision belongs at the top.\n\n## Attributes are props, and they’re named differently than in HTML\n\nJSX attributes look like HTML attributes but are the properties of the created object – that is, props. Because the target language is JavaScript and not HTML, they follow JavaScript’s rules, and in a few places that visibly differs from HTML.\n\nTwo names are reserved, because `class` and `for` are keywords in JavaScript. That’s why the class attribute is called `className` and the label attribute `htmlFor`:\n\n```jsx\n<label htmlFor=\"email\" className=\"field-label\">Email</label>\n<input id=\"email\" />\n```\n\nAll multi-word HTML attributes are written in camelCase: `tabindex` becomes `tabIndex`, `readonly` becomes `readOnly`, `maxlength` becomes `maxLength`. Event handlers are called `onClick`, `onChange`, `onSubmit` – with a capital C in the middle – and get a function, not a string:\n\n```jsx\n// correct – a function reference\n<button onClick={handleSave}>Save</button>\n\n// wrong – calls handleSave IMMEDIATELY on render and passes the return value\n<button onClick={handleSave()}>Save</button>\n```\n\nThe second case is one of the most common beginner mistakes. `onClick={handleSave()}` runs `handleSave` during rendering and attaches its result to the handler. If you want to pass arguments, you wrap the call in an arrow function: `onClick={() => handleSave(id)}`.\n\nYou give values in curly braces, fixed strings in quotation marks. An attribute without a value is implicitly `true`:\n\n```jsx\n<input type=\"text\" value={value} disabled />\n// disabled is equivalent to disabled={true}\n```\n\n## How values in content are rendered – and what disappears\n\nWhat React makes of an expression in the content depends on the type of the value, and a whole series of small surprises lurk here. Strings and numbers are output as text. Arrays are rendered element by element. But `null`, `undefined`, `true` and `false` render **nothing** – they disappear without a trace. That’s exactly what makes conditional rendering possible in the first place.\n\n```jsx\n<div>\n  {message}          {/* string or number -> gets displayed */}\n  {null}             {/* nothing */}\n  {isAdmin && <Panel/>} {/* Panel only when isAdmin is true */}\n</div>\n```\n\nA classic mistake lies in the `&&`. It renders the right-hand element only if the left side is truthy – but it returns the left side if it’s falsy. With booleans this is harmless, because `false` disappears. With a number, it isn’t:\n\n```jsx\n// pitfall: if count is 0, a 0 appears in the UI, not nothing\n{count && <List />}\n\n// correct: convert to a boolean first\n{count > 0 && <List />}\n```\n\nThe `0` simply isn’t `false` but a number, and numbers get rendered. If you’ve ever hunted for a lonely `0` in your UI, you know this mistake. The rule behind it is simple: in front of a `&&`, it’s best to have a real boolean, not a value that happens to be falsy.\n\n## One element, one root node – and fragments\n\nBecause a JSX expression ultimately produces a single object, a component has to return exactly one root element. Two elements side by side without wrapping are a syntax error. You could wrap everything in a `<div>`, but that creates an additional, often unwanted node in the DOM. That’s what the fragment is for – a wrapper that leaves nothing behind in the DOM:\n\n```jsx\nfunction Row() {\n  return (\n    <>\n      <td>Name</td>\n      <td>Amount</td>\n    </>\n  );\n}\n```\n\nThe short form `<>...</>` is almost always enough. Only when the fragment itself needs a `key` – say, as a direct child of a list – do you have to use the long form `<Fragment key={id}>...</Fragment>`, because the short form doesn’t accept attributes.\n\nBy the way, the parentheses around multi-line JSX after `return` aren’t cosmetics against indentation but protection against a JavaScript trap: if the first element is on a new line directly after `return`, JavaScript automatically inserts a semicolon, and the function returns `undefined`. The parentheses prevent that.\n\n## Lists and keys: the most underestimated rule\n\nYou render a list by using `map` to turn an array into an array of elements. Each of these elements needs a `key` attribute. The key isn’t a decorative detail – it’s the information React uses on the next render to recognize which old element corresponds to which new one.\n\n```jsx\n<ul>\n  {invoices.map((i) => (\n    <li key={i.id}>{i.number}</li>\n  ))}\n</ul>\n```\n\nThe key has to have two properties: it must be unique among its siblings, and it must be stable, that is, always the same for the same data. That’s why you use a domain ID, not a random value and – this is the sore point – preferably not the array index.\n\nThe index as a key seems to work as long as the list never changes. But as soon as you insert something at the front, delete or sort, the indexes shift, and React assigns the old states to the wrong elements. This shows up in ghostly bugs: an input field keeps its text even though the row should be a completely different one; a checkbox stays checked even though the corresponding element was deleted. The index describes a position, but the key is supposed to describe an identity – and position and identity are two different things. Only when a list is guaranteed to be static and never re-sorted is the index acceptable as a key. How React performs this comparison in detail when re-rendering is a topic of its own.\n\n## Spread, children and the small pitfalls on the side\n\nYou can set props individually or pass them through from an object with the spread operator. That’s convenient but deserves caution:\n\n```jsx\nconst props = { type: \"text\", value: value, onChange: handleChange };\n<input {...props} />\n```\n\nIt’s clean when you know exactly what’s in the object. It gets messy when you blindly pass through an entire foreign object and thereby unknowingly set attributes you didn’t want at all. If a single attribute follows the spread, the last one wins – `<input {...props} value={otherValue} />` overrides the `value` from the object.\n\nThe content between the opening and closing tag ends up in the special prop `children`. A component that renders `children` knows nothing about its content and is usable everywhere precisely for that reason. You can also pass `children` explicitly as an attribute, but that’s rarely nicer than natural nesting.\n\nA few more details that come up again and again: inline styles in JSX are an object, not a CSS string, and their keys are in camelCase – `<div style={{ backgroundColor: \"red\", fontSize: 14 }} />`, with double braces, because the outer pair starts the expression and the inner one is the object. You write comments inside JSX as an expression: `{/* so */}`. And you only insert raw HTML from a string via `dangerouslySetInnerHTML` – the unwieldy name is intentional, because this is exactly where cross-site scripting holes arise when the string comes from a foreign source. Normal text in JSX is automatically escaped by React and is therefore safe; this one path deliberately bypasses that protection.\n\n## Why precision pays off\n\nAll these rules follow from a single idea: JSX is a notation for function calls that produce a description object. The reserved names, the expression rule, the disappearance of `null` and `false`, the `0` trap, the requirement for one root node, the meaning of the key – none of it is arbitrary; it all follows from the fact that in the end JavaScript runs, not HTML.\n\nIf you read JSX this way, you stop working against the language. You no longer accidentally write `className` as `class`, you turn a number in front of `&&` into a real comparison, you assign keys from domain IDs instead of indexes – not because a linter complains, but because you understand what the compiler makes of it. The individual building blocks only touched on here – data flow through props, the question of state ownership, rendering on the server – have their own articles. JSX is the beginning of everything, and that’s exactly why it pays to be precise here.\n\n## Further reading\n\n- Repository introduction-react (JSX chapter and examples): https://github.com/mikebild/introduction-react\n- React, Writing Markup with JSX: https://react.dev/learn/writing-markup-with-jsx\n- React, JavaScript in JSX with Curly Braces: https://react.dev/learn/javascript-in-jsx-with-curly-braces\n- React, Rendering Lists and keys: https://react.dev/learn/rendering-lists"},{"locale":"en","translation_key":"aws-deployment-pipelines-architektur","slug":"aws-deployment-pipelines-are-architecture","title":"AWS Deployment Pipelines Are Architecture","summary":"Deployment pipelines are architecture because they determine how often, how safely and how reversibly a system is changed.","tags":["Software","AWS","Cloud"],"published_at":"2020-05-12T10:00:00+00:00","updated_at":"2026-07-13T08:38:49.427291+00:00","url":"https://www.mikebild.dev/en/blog/aws-deployment-pipelines-are-architecture/","audio_url":null,"audio_duration_secs":null,"text":"# AWS Deployment Pipelines Are Architecture\n\nThe time from a merged commit to the moment the change takes effect in production is under a quarter of an hour for some teams and a whole quarter for others – often with comparable application code. This span appears in no architecture diagram. It comes about where a change makes its way: in the steps between commit and runtime, in the controls it has to pass, and in what is left when it has to be taken back. The way there therefore belongs in the same design discussion as the choice of a database – and needs the same justification.\n\nThe concrete occasion for this text is a small GitHub Action that does nothing more than deploy an AWS CDK project. A few lines of YAML. And yet exactly this building block determines which error shows up early, which only in production – and who is allowed to trigger a change to the infrastructure at all.\n\n## The pipeline determines changeability\n\nArchitecture answers the question of what can be changed independently of each other. That is exactly the core question of a pipeline too. A system that can only be deployed in a quarterly release has a different architecture from one that rolls out the same codebase twenty times a day – even if both contain identical application code. Changeability isn’t only in how modules are split, but in the path from a commit to the runtime.\n\nOn AWS, this path has become especially visible since infrastructure itself became code. With the CDK, I describe Lambda functions, API gateways, tables and permissions in TypeScript. `cdk synth` translates that into a CloudFormation template, `cdk deploy` brings it into an account. This shifts something fundamental: the question “what does my infrastructure look like?” and the question “how does a change get there?” coincide. Both live in the same repository and go through the same review and the same pipeline. I wrote about this in more detail in [Infrastructure in a programming language](https://www.mikebild.dev/en/blog/cdk-early-days-infrastructure-in-a-programming-language/); here I’m interested in the step after that – what happens when this code is rolled out automatically.\n\nA minimal stack looks like this:\n\n```ts\nimport * as cdk from \"@aws-cdk/core\";\nimport * as lambda from \"@aws-cdk/aws-lambda\";\nimport * as apigw from \"@aws-cdk/aws-apigateway\";\n\nexport class ApiStack extends cdk.Stack {\n  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {\n    super(scope, id, props);\n\n    const handler = new lambda.Function(this, \"ApiHandler\", {\n      runtime: lambda.Runtime.NODEJS_12_X,\n      handler: \"index.handler\",\n      code: lambda.Code.fromAsset(\"dist/api\"),\n    });\n\n    new apigw.LambdaRestApi(this, \"Api\", { handler });\n  }\n}\n```\n\nThe example is deliberately small. It isn’t meant to show a complete application but to mark the boundary: everything here is part of the deployable artifact from now on. If I change the runtime, extend a permission or rebuild the API, it takes the same path as a code change. The exciting decision isn’t how many constructs I write, but which control stands between this code and production.\n\n## The “CDK Action” as the smallest honest building block\n\nThe simplest way to automate this deployment is a GitHub Action that reacts to every push to `main`:\n\n```yaml\nname: deploy\non:\n  push:\n    branches: [main]\n\njobs:\n  deploy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-node@v1\n        with:\n          node-version: 12\n      - run: npm ci\n      - run: npm test\n      - run: npx cdk deploy --require-approval never\n        env:\n          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}\n          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n          AWS_DEFAULT_REGION: eu-central-1\n```\n\nThat looks harmless, but it makes one architecture decision after another. `on: push` means: every merge to `main` is a deployment – the trunk is the delivery, not just an intermediate state. The `npm test` step before `cdk deploy` draws a quality line: whatever is red doesn’t go out. `--require-approval never` skips the CDK’s interactive prompt for security-relevant changes – convenient, but it shifts responsibility for IAM changes entirely to the review before. And the two secrets determine with which permissions this pipeline acts in the account; in practice, that’s where most of the unspoken power lies.\n\nThat is exactly why this small building block is more revealing than any big reference pipeline. You can walk through it with the team in five minutes, and every line stands for a conscious or unconscious decision about frequency, safety and responsibility.\n\n## The review point comes before the deploy, not after\n\nWith application code, we review the diff. With infrastructure, many people don’t – and are surprised when a merge opens a security group on the side or replaces a table. The CDK has a good tool for this that becomes the actual review artifact in a pipeline:\n\n```bash\n# what will actually change in the account\ncdk diff ApiStack\n```\n\n`cdk diff` doesn’t show my TypeScript diff but the difference between what is in the account and what I want to deploy – including the IAM statements CloudFormation derives from it. In a clean pipeline, this step runs automatically and attaches the result to the pull request. That way, a person decides about the effect, not about the source code. That’s a methodological difference with a direct operational effect: a reviewer who sees “this change adds `iam:PassRole`” stops it before it lands in the account. A reviewer who only reads `stack.ts` often misses it.\n\nThis is what the path looks like as a whole:\n\n```mermaid\nflowchart LR\n  Commit --> Build[\"Build & Test\"]\n  Build --> Synth[\"cdk synth<br/>CloudFormation template\"]\n  Synth --> Diff[\"cdk diff<br/>review artifact\"]\n  Diff --> Approve{\"Approval?\"}\n  Approve -->|yes| Deploy[\"cdk deploy\"]\n  Approve -->|no| Stop[\"Stop\"]\n  Deploy --> Observe[\"Metrics &<br/>alarms\"]\n  Observe -->|failure| Rollback[\"Rollback to<br/>previous revision\"]\n```\n\nEvery node in this sketch is an adjustment knob. Where the approval sits decides speed versus control. Whether anything is observed after `Deploy` at all decides whether a bad release is noticed before the customer reports it. And whether there is a real `Rollback` path decides whether a change is reversible – or just hopefully right.\n\n## The same artifact through several environments\n\nAs soon as more than one environment is involved – staging and production, often in separate AWS accounts – the pipeline becomes the actual definition of what “promoting” means. That only holds up under one condition: the same checked artifact moves through the stages, not a second build with slightly different ingredients. With the CDK, that means synthesizing the same app with a different context.\n\n```ts\nconst app = new cdk.App();\n\nnew ApiStack(app, \"ApiStack-staging\", {\n  env: { account: \"111111111111\", region: \"eu-central-1\" },\n});\n\nnew ApiStack(app, \"ApiStack-prod\", {\n  env: { account: \"222222222222\", region: \"eu-central-1\" },\n});\n```\n\nThis puts the environment topology in the same repository as the code, and it goes through the same review. The methodological gain is trust: when staging and production are synthesized from one source, staging actually tests what later runs in production – and not a plausible copy that differs in three places. It’s exactly these differences that otherwise only surface in the most expensive account. Splitting into separate accounts isn’t an operations detail but an architecture boundary: a deploy to staging can’t accidentally touch production because it simply lacks the permissions in the other account.\n\n## Trade-offs you have to name\n\nThe interesting work on a pipeline isn’t getting it to run but laying its compromises open. Three of them come up regularly:\n\n- Auto-deploy on `main` versus a manual gate. The automatic path shortens lead time drastically but requires a reliable test net and good alerts. The gate gives a feeling of safety, but in practice it collects changes into large, risky batches – the most common reason for rare, fear-ridden releases.\n- One stack versus many stacks. One big stack is easy to deploy, but every change touches everything. Separate stacks for API, data and static frontend let you keep risk small and roll out parts independently – at the cost of more coordination at the interfaces.\n- Rollback via redeploy versus fix-forward. CloudFormation can roll back automatically on a failed deploy. But that only holds as long as the change hasn’t already migrated data or extended a schema. From then on, “just go back” is an illusion, and you need additive, backward-compatible steps instead of an undo button.\n\nNone of these decisions is universally right. But they belong in an architecture conversation and in a short ADR, not in a YAML file someone committed a year ago that no one has questioned since.\n\n## Why a CTO should care\n\nFor technical leadership, all this translates into numbers that have had an established vocabulary since “Accelerate.” Four metrics describe the performance of delivery fairly completely, and all four are determined by the pipeline, not by the application code:\n\n- Deployment frequency – how often anything goes live at all. An auto-deploy on `main` raises it by orders of magnitude compared to a manual quarterly gate.\n- Lead time – how long from “code done” to “in production.” `cdk diff` in the PR plus an automatic deploy pushes that down from days to minutes.\n- Change failure rate – what share of releases causes a failure. The test step and the diff review before the deploy lower it without sacrificing frequency.\n- Time to restore – how quickly the normal state is back. A real, practiced rollback path is the difference here between minutes and a lost afternoon.\n\nThe important thing about these four: they make different sides of delivery capability visible. Small changes limit the scope of a review and of a possible failure; automated checks shorten feedback; a practiced recovery path lowers the time to repair. Whether a pipeline actually has this effect only shows in Lead Time for Changes, Change Failure Rate and Time to Restore Service in your own system. It is therefore not an add-on for the operations side but part of the architecture.\n\n## How I check a pipeline\n\nA pipeline design only holds up once the failure path is described too. The questions that uncover the most aim exactly there. What happens if `cdk deploy` aborts in the middle of a change – is a half-finished state left behind? Is the deploy idempotent enough that a second run heals it? Where is the line beyond which a rollback is no longer enough because data has already been migrated? And quite simply: who may trigger this pipeline, and is that logged in a traceable way?\n\nWhat I run into most often is overrating the happy path. In the demo account, everything runs cleanly. It gets interesting with partial failures, permissions that are just barely insufficient, resources that CloudFormation wants to replace instead of change, and that one deploy that hangs at 5 p.m. on a Friday. That’s exactly where it shows whether the pipeline model holds up – and whether “reversible” is a real promise or just a word in a presentation.\n\n## Conclusion\n\nThe temptation is to treat a pipeline as a tool question: which Action, which runner, which provider. The real substance lies elsewhere. A pipeline encodes how often a team may change its mind, how safely it does so and how easily it takes back a mistake. These are architecture properties, and they don’t come from the tool’s name but from the few deliberate decisions behind it – auto-deploy or gate, one stack or many, undo or fix-forward. If you name these decisions and measure their effect, you can change bottlenecks in a targeted way. If you leave them to an old YAML file, you make them anyway – only unconsciously and usually at the worst possible moment.\n\n## Further reading\n\n- AWS CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/home.html\n- AWS CDK Constructs: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n- AWS CloudFormation – how deployments and rollbacks work internally: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html\n- Nicole Forsgren, Jez Humble, Gene Kim: “Accelerate” – the four delivery metrics in detail."},{"locale":"en","translation_key":"python-advanced-decorators-generatoren","slug":"advanced-python-decorators-magic-methods-generators","title":"Advanced Python: Decorators, Magic Methods and Generators","summary":"Three building blocks that make code Pythonic: decorators wrap functions, magic methods bind your own objects to Python’s protocols, generators produce lazy sequences.","tags":["Software","Python","Backend"],"published_at":"2020-04-08T10:00:00+00:00","updated_at":"2026-07-13T10:00:30.74463+00:00","url":"https://www.mikebild.dev/en/blog/advanced-python-decorators-magic-methods-generators/","audio_url":null,"audio_duration_secs":null,"text":"Python code that you could have written line for line just the same in Java or C# is rarely wrong – it just doesn’t use the language. Three mechanisms make the difference, and none of them is magic: the `@` decorator, the dunder method and `yield`. All three are documented in the language core, each can be rebuilt yourself in a few lines, and each solves a problem you would otherwise solve with copy-paste or with too much memory.\n\nThe state here is early 2020, so Python 3.8. All examples run there without extra packages – just with `functools`, `time` and the standard library. The prerequisites are Python objects, functions and the usual built-in data types.\n\n## Decorators: functions that wrap functions\n\nGetting into decorators is easier than the `@` sugar suggests. In Python, functions are perfectly ordinary objects. You can assign them to a variable, pass them as an argument and return them from another function. A decorator is nothing more than a Higher-Order Function: it takes a function and returns a – usually wrapping – function.\n\n```python\nimport functools\nimport time\n\n\ndef timer(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.perf_counter()\n        result = func(*args, **kwargs)\n        elapsed = time.perf_counter() - start\n        print(f\"{func.__name__} took {elapsed:.4f}s\")\n        return result\n    return wrapper\n\n\n@timer\ndef slow_sum(n):\n    return sum(range(n))\n```\n\nThe notation `@timer` above `def slow_sum` is exactly syntactic sugar for `slow_sum = timer(slow_sum)`. Nothing else happens. After decorating, the name `slow_sum` no longer points to the original function but to `wrapper`. On every call, timing starts first, then the real function runs, and afterward the elapsed time is printed. The `*args, **kwargs` makes sure the wrapper passes through any signature without having to know anything about the arguments itself.\n\nHere’s the flow when calling a decorated function, drawn out – the wrapper brackets the actual work:\n\n```mermaid\nflowchart LR\n    Call[\"call slow_sum()\"] --> W[\"wrapper()\"]\n    W -->|\"before:<br/>start timer\"| F[\"original func()\"]\n    F -->|\"return value\"| W\n    W -->|\"after:<br/>print elapsed\"| Ret[\"return result\"]\n```\n\n### functools.wraps isn’t optional\n\nOne detail is missing from hand-written decorators with remarkable regularity: the line `@functools.wraps(func)`. Without it, the decorator still works, but the wrapper doesn’t take on the identity of the original function. `slow_sum.__name__` then returns `\"wrapper\"` instead of `\"slow_sum\"`, `slow_sum.__doc__` is the wrapper’s docstring, and `help(slow_sum)` shows the wrong signature.\n\n```python\ndef timer_broken(func):\n    def wrapper(*args, **kwargs):\n        return func(*args, **kwargs)\n    return wrapper\n\n\n@timer_broken\ndef greet(name):\n    \"\"\"Say hello to someone.\"\"\"\n    return f\"Hello, {name}\"\n\n\nprint(greet.__name__)   # -> \"wrapper\"\nprint(greet.__doc__)    # -> None\n```\n\n`functools.wraps` is a convenience wrapper around `functools.update_wrapper`. It copies `__module__`, `__name__`, `__qualname__`, `__annotations__` and `__doc__` from the original function to the wrapper and also sets `__wrapped__`, so that you can get back to the undecorated function if needed. For debugging, introspection and tools that look at metadata, this is the difference between useful and confusing. That’s why this line goes into every decorator I write.\n\n### Decorators with arguments\n\nOften you want to configure a decorator, for example: “Run the function three times.” For that you need one more level. A decorator with arguments is a function that returns a decorator, which in turn returns the wrapper – three nested functions.\n\n```python\ndef repeat(times):\n    def decorator(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            result = None\n            for _ in range(times):\n                result = func(*args, **kwargs)\n            return result\n        return wrapper\n    return decorator\n\n\n@repeat(times=3)\ndef ping():\n    print(\"ping\")\n```\n\n`@repeat(times=3)` is evaluated first: the call `repeat(times=3)` returns `decorator`, and this `decorator` is then applied to `ping`. Once you’ve read the structure from the inside out, the pattern opens up – and it shows up in exactly this form in many libraries, for example in routing decorators in web frameworks.\n\n## Magic methods: your own objects behaving like built-in ones\n\nThe second building block reaches deeper into the language. Magic methods – also called dunder methods, because of the double underscores – are the way your own classes plug into Python’s protocols. You never call these methods directly. Instead, the interpreter calls them when you put an object into a known context: `len(obj)` triggers `__len__`, `==` triggers `__eq__`, a `for` loop triggers `__iter__`, a `with` block triggers `__enter__` and `__exit__`.\n\nA few of the most common dunder methods and what triggers them:\n\n- `__init__` – construction when an instance is created\n- `__repr__` – `repr()` and the display in the REPL, ideally unambiguous and at best `eval`-able\n- `__str__` – `str()` and `print()`; if it’s missing, `__repr__` steps in\n- `__eq__` – comparison with `==`\n- `__len__` – the call `len(obj)`, which is also used for truth testing when `__bool__` is missing\n- `__iter__` and `__next__` – iteration in `for` loops and when unpacking\n- `__enter__` and `__exit__` – entering and leaving a `with` block\n- `__call__` – calling an instance like a function, `obj()`\n\nTo make this concrete, I build a class that provides lines from a file. It should have a proper `__repr__`, be comparable with `==`, work as a context manager and be iterable.\n\n```python\nclass LineStore:\n    def __init__(self, path):\n        self.path = path\n\n    def __repr__(self):\n        return f\"LineStore({self.path!r})\"\n\n    def __eq__(self, other):\n        return isinstance(other, LineStore) and self.path == other.path\n\n    def __enter__(self):\n        self._file = open(self.path, encoding=\"utf-8\")\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self._file.close()\n        return False   # do not swallow exceptions\n\n    def __iter__(self):\n        return (line.rstrip(\"\\n\") for line in self._file)\n```\n\nA `LineStore` now behaves like a built-in object. In the REPL it shows `LineStore('access.log')` instead of a meaningless memory address. Two instances with the same path are equal. And the real highlight is in the `with` block:\n\n```python\nwith LineStore(\"access.log\") as store:\n    for line in store:\n        if \"ERROR\" in line:\n            print(line)\n```\n\nThe `with` calls `__enter__`, binds the return value to `store`, runs the body and then – guaranteed, even on an exception – calls `__exit__`. That’s where the file gets closed. That’s exactly the point of a context manager: cleanup you can’t forget. The return value of `__exit__` decides how errors are handled. If the method returns `True`, an exception raised in the block is suppressed; a falsy value like `False` passes it on. I deliberately return `False` here, because an error while reading the file shouldn’t silently disappear.\n\nFor simple cases, by the way, you don’t have to implement the protocol by hand. `contextlib.contextmanager` turns a generator function into a context manager, with the `yield` separating setup and teardown. That leads us straight to the third building block.\n\n## Generators: lazy sequences with yield\n\nThe `LineStore` carries a peculiarity with it: its `__iter__` already returns a generator expression. Generators are the third pillar, and for me the most important in practice as soon as data grows larger than memory.\n\nAs soon as the keyword `yield` appears in a function, it’s no longer a normal callable but a generator function. Calling it doesn’t run the body but immediately returns a generator object. The code only runs when you iterate over the object – and it stops at every `yield`, remembers its state and continues exactly there on the next step.\n\n```python\ndef stream_lines(path):\n    with open(path, encoding=\"utf-8\") as fh:\n        for line in fh:          # a file object is itself an iterator\n            yield line.rstrip(\"\\n\")\n\n\nfor line in stream_lines(\"big.log\"):\n    if line.startswith(\"2020\"):\n        print(line)\n```\n\nHere only one line is in memory at a time. Whether the file is ten kilobytes or ten gigabytes – memory usage stays constant. That’s exactly the difference from a list. If I wrote `fh.readlines()`, Python would hold all lines at once. The generator produces them one at a time, on demand.\n\nThe same principle exists in compact form as a generator expression – syntactically like a list comprehension, just with round instead of square brackets:\n\n```python\n# list comprehension: builds the whole list in memory\nlengths_list = [len(line) for line in stream_lines(\"big.log\")]\n\n# generator expression: yields one length at a time\ntotal = sum(len(line) for line in stream_lines(\"big.log\"))\n```\n\nThe second variant sums the line lengths without ever creating a complete list. For aggregations over large amounts of data, that’s the standard way. And if you want to chain generators, `yield from` helps you delegate to another iterable without writing a loop yourself:\n\n```python\ndef chained(*paths):\n    for path in paths:\n        yield from stream_lines(path)\n```\n\n## Three pitfalls\n\nAs clear as the three building blocks are, the same stumbling blocks show up just as reliably in practice. These three cost the most time.\n\nThe classic is mutable default arguments. If you write an empty list as a default, you don’t get a fresh list on every call but always the same one.\n\n```python\ndef append_item(item, acc=[]):   # trap: shared across calls\n    acc.append(item)\n    return acc\n\n\nprint(append_item(1))   # [1]\nprint(append_item(2))   # [1, 2]  – surprise\n```\n\nThe default is evaluated exactly once, namely at `def`. After that, all calls share the same object. The solution is a guard on `None`:\n\n```python\ndef append_item(item, acc=None):\n    if acc is None:\n        acc = []\n    acc.append(item)\n    return acc\n```\n\nThe second stumbling block is the forgotten `functools.wraps`, the case shown above. A decorator without this line works, but it swallows the name, docstring and signature of the decorated function. In small scripts you don’t notice; as soon as someone introspects the function or a framework looks at the metadata, it becomes a puzzle.\n\nThe third hits generators: after one pass they’re exhausted, and that’s the flip side of lazy evaluation. A generator remembers its progress and doesn’t reset it. If you run through it twice, you get nothing the second time.\n\n```python\ngen = stream_lines(\"big.log\")\nfirst = list(gen)    # reads all lines\nsecond = list(gen)   # empty – the generator is exhausted\n```\n\nYou can iterate over a list as often as you like, over a generator only once. If you need the data several times, deliberately materialize it into a list – or call the generator function again to get a fresh object. Related to this: `len()` doesn’t work on a generator, because its length isn’t even known without a full pass.\n\n## Conclusion\n\nDecorators, magic methods and generators seem like advanced extras at first contact, but they’re basic tools in everyday work. Decorators cleanly separate recurring behavior – timing, logging, repetition – from the actual logic, as long as you don’t forget `functools.wraps`. Magic methods connect your own objects to the language, so that `len()`, `==`, `for` and `with` just work without the calling code having to know anything about the internals. And generators turn a function into a lazy sequence that delivers large amounts of data element by element instead of holding everything at once.\n\nWhat connects these three building blocks is a shared idea: Python provides clearly defined protocols, and your own code hooks into them. You don’t write against the language but with it. Once you’ve internalized that, you recognize the patterns everywhere in the standard library – and write code that can not only be run but also read.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-python.en.html\n- Repository `introduction-python` – chapters `13-decorators.md`, `14-magic-methods.md`, `15-iter.md` with the corresponding examples under `examples/` (`decorators.py`, `classes.py`, `functional.py`)\n- Python Data Model / Special Methods: https://docs.python.org/3.8/reference/datamodel.html\n- The `with` statement and the context manager protocol: https://docs.python.org/3.8/reference/compound_stmts.html#the-with-statement\n- `functools` with `wraps` and `update_wrapper`: https://docs.python.org/3.8/library/functools.html\n- `contextlib.contextmanager`: https://docs.python.org/3.8/library/contextlib.html\n- Yield expressions and generators: https://docs.python.org/3.8/reference/expressions.html#yield-expressions\n- Tutorial on generators and generator expressions: https://docs.python.org/3.8/tutorial/classes.html#generators\n- PEP 318 – Decorators for Functions and Methods: https://www.python.org/dev/peps/pep-0318/"},{"locale":"en","translation_key":"policy-as-code-fuer-cdk","slug":"policy-as-code-for-cdk","title":"Policy as Code for CDK","summary":"Policy as code makes a checkable part of your architecture rules executable and versionable.","tags":["Software","AWS","Cloud"],"published_at":"2020-03-12T10:00:00+00:00","updated_at":"2026-07-13T08:38:35.328116+00:00","url":"https://www.mikebild.dev/en/blog/policy-as-code-for-cdk/","audio_url":null,"audio_duration_secs":null,"text":"# Policy as Code for CDK\n\nIf you only write an architecture rule down, sooner or later you get it back as an incident. No publicly readable bucket, every table encrypted, no instance larger than necessary, everything tagged: this list is rarely complete in one place. It exists in a few heads, in a wiki nobody opens anymore, and in review comments that depend on who happens to be looking and how much time they have. One inconspicuous default is enough, and the good intention turns into an open bucket in production. This problem is exactly what this post is about – and `cloudpatrol` is my attempt to solve it.\n\nIn my [post about the early days of CDK](https://www.mikebild.dev/en/blog/cdk-early-days-infrastructure-in-a-programming-language/), the text ends with a subordinate clause: for rules that are not negotiable, an automated check of the synthesized template is worthwhile, a kind of policy as code for your own CDK output. Here I make good on that clause. It is less about yet another tool than about running well-founded guardrails as automated checks. Trade-offs remain architecture work.\n\n## Why rules fall out of the review\n\nA review is a human with limited attention. Today they see that a bucket has no encryption, and next week they miss it because the pull request is big, it’s Friday afternoon or the interesting discussion was happening elsewhere. That is no accusation. That’s how attention works. Knowledge that only exists in the review is as reliable as the reviewer’s form on the day.\n\nIt follows that a rule you can’t execute is not a rule. It is a hope. As long as “no public bucket” is a sentence in the onboarding document, it will be broken at some point – not out of ill will, but because a default slips through unnoticed. The point of policy as code is therefore less technical than cultural. It moves the rule from a place where it has to be remembered to a place where it is checked.\n\nThe CDK is what makes this shift possible. Because infrastructure here is code that is synthesized into a CloudFormation template, there is an intermediate step you can inspect before anything is created in the cloud. This intermediate step is exactly the right place for a check.\n\n## The checkpoint lies between synthesis and deployment\n\nYou can check cloud resources in many places. At runtime, a service that scans accounts finds violations only once they already exist. A weekly report is better than nothing but always comes too late for the person who made the mistake. It gets interesting when the check moves to where the decision is made: the moment the code generates the template.\n\n```mermaid\nflowchart LR\n  Source[\"CDK code (TypeScript)\"] --> Synth[\"cdk synth\"]\n  Synth --> Policy[\"Policy check\"]\n  Policy -->|violation| Fail[\"Feedback in the PR\"]\n  Policy -->|ok| Deploy[\"Deployment\"]\n```\n\n`cloudpatrol` comes in at exactly this point. It hooks into synthesis and evaluates the constructs while they are being created. That is an architecturally different approach from a downstream scanner. The check doesn’t see the raw JSON template but the typed constructs with their properties. That way you can write a rule against `s3.CfnBucket` instead of matching a string path in a YAML tree. The boundary where the check happens is the same boundary the developer thinks in.\n\nThe effect on the cycle is concrete. A violation that used to become visible as an incident – someone reports an open bucket, there is an investigation, a fix, a postmortem – now becomes visible as a red test run before the pull request is merged. The time between error and detection shrinks from days to seconds, and the cost of the correction drops accordingly.\n\n## A policy is code, not a config entry\n\nThe decisive design choice in `cloudpatrol` is that a rule is not a line in a YAML file but a class. It declares which construct type it applies to, and it contains a validator method that checks the concrete node and reports findings to a reporter.\n\n```ts\nimport { Policy, PolicyInterface, Reportable } from \"cloudpatrol\";\nimport * as s3 from \"@aws-cdk/aws-s3\";\n\nexport class BucketEncryptionPolicy extends Policy implements PolicyInterface {\n  public policyName = \"Bucket Encryption\";\n  public description = \"S3 buckets must be encrypted at rest.\";\n  public scope = s3.CfnBucket;\n\n  public validator(node: s3.CfnBucket, reporter: Reportable): void {\n    if (!node.bucketEncryption) {\n      reporter.addError(node, this, \"Bucket has no server-side encryption configured.\");\n    }\n  }\n}\n```\n\nThe `scope` is the selector: the validator only runs for buckets, not for every node in the tree. Inside the validator, I have the full expressive power of TypeScript. I can nest conditions, allow exceptions for certain environments, evaluate several properties together. This is exactly where a declarative rule language hits its limit – the interesting rules are rarely “field X must be Y” but “field X must be Y, unless Z, and then please with this justification”.\n\nThe whole thing is applied via a patrol that walks through a stack:\n\n```ts\nconst patrol = new AwsCdkPatrol(awsDefaults);\npatrol.check(stack);\n```\n\n`cloudpatrol` comes with a handful of built-in policies – encryption, versioning, instance types – but the built-in ones are only the starting point. The real value emerges when a team translates its own unwritten list into such classes. From then on, the list is no longer unwritten. It lives in the repository, it is versioned, it has an author and a history, and you can discuss it in a pull request like any other code.\n\n## warn or block is a design decision\n\nNot every rule carries the same weight. A missing cost center tag is annoying; a publicly readable bucket with customer data is an incident. That’s why the severity of a rule is not a detail but the central design decision. A warning reports and lets things through. An error blocks. If you block everything, you train your team to work around the check. If you block nothing, all you end up with is nicely formatted log output.\n\nHere I deliberately distinguish between guardrails and architecture police. Guardrails define the few boundaries that are truly non-negotiable: encryption, least privilege, no open networks, hard cost limits. Within these boundaries, the team stays able to act and stays fast. Architecture police, on the other hand, tries to centralize every decision and thereby shifts responsibility away from the teams. The first speeds up safe work; the second slows things down and frustrates. The difference lies not in the tool but in the question of how many rules you set to `block` and how well you justify those few.\n\n```ts\ntype Severity = \"warn\" | \"block\";\n\ntype RuleMeta = {\n  policyName: string;\n  severity: Severity;\n  reason: string;\n  suggestion: string;\n};\n```\n\n## Every rule needs a reason and a way out\n\nA check that only says “forbidden” is a wall. The developer stands in front of it, doesn’t understand why and looks for the shortest way around it. A check that delivers the reason and an alternative is learning feedback. It explains the decision exactly where it becomes relevant and makes the next developer a bit more independent.\n\n```json\n{\n  \"policy\": \"lambda-timeout-max\",\n  \"severity\": \"block\",\n  \"reason\": \"A timeout above 30s usually hides a synchronous call that should be async.\",\n  \"suggestion\": \"Move the work behind a queue or a Step Function and return early.\"\n}\n```\n\nThese three fields – reason, severity, way out – are the difference between a rule that creates friction and one that reduces it. The reason prevents the rule from being read as arbitrary. The way out turns blocking into a recommendation. That’s exactly why every policy in `cloudpatrol` has a `description` and a `link` field: the rule carries its own justification with it instead of parking it in a wiki that is decoupled from the code.\n\n## The pull request is the right place\n\nGuardrails work best before deployment, and the pull request is the natural place for that, because that’s where code, context and discussion come together. In practice, this means the policy check runs in the same pipeline that builds the code and ships the infrastructure. A red check is then not a bureaucratic step but the same kind of signal as a failed unit test.\n\nAt this point the benefit is measurable, on three levels. First, cycle time: a violation becomes visible when the pull request is opened, not days later in operation. Second, consistency: the check is always equally strict, regardless of who reviews and how full their calendar is. Third, review load: people no longer have to mechanically search for the same ten things but can focus on the questions a machine can’t answer – does the cut of the stack make sense, does the abstraction fit, is the cost profile right.\n\nThat is the real productivity gain: a machine takes over the same boring checking work every time, and the minds on the team are freed up for the interesting work.\n\n## Costs are an architecture signal\n\nOne side effect is worth mentioning because it is often overlooked. Cloud costs are not just a topic for accounting; they are a behavioral signal of the architecture. A function that starts too often, a resource that is sized too generously, a deployment that produces unnecessary artifacts – all of this leaves a cost trail before it gets named as an architecture problem.\n\n```mermaid\nflowchart LR\n  Usage[\"Usage\"] --> Cost[\"Cost trail\"]\n  Cost --> Signal[\"Signal\"]\n  Signal --> Rule[\"Policy as a guardrail\"]\n```\n\nA policy that flags an overly generous instance type or a missing lifecycle rule is therefore not just a technical check. It catches a cost decision before it shows up as a bill next month. Costs don’t replace design, but they are an honest touchstone for whether the architecture behaves the way you assumed when designing it.\n\n## Where policy as code reaches its limit\n\nIt would be a mistake to try to cast everything into a rule. Some decisions are not a check but a trade-off, and those belong to a human. A timeout above thirty seconds can be wrong or exactly right, depending on context. Such cases belong in an architecture conversation or a short ADR, not in a blunt blocker. The policy then doesn’t say “forbidden” but “this needs a justification”.\n\nThis gives policy as code a clear responsibility. It is suitable for the small set of non-negotiable guardrails whose violation is objectively recognizable. It is not suitable for matters of taste, nor for trade-offs where the right answer depends on the project. If you respect this boundary, you get a tool that creates trust. If you ignore it and turn every opinion into a blocking rule, you get a tool that gets bypassed.\n\nA second caveat concerns abstraction. `cloudpatrol` checks what synthesis produces. A self-written construct that encapsulates a dozen resources can unintentionally undermine a rule if it sets the checked property differently than you think. So the check is only as honest as the visibility of the constructs. That is not an argument against abstraction, but a reminder that a rule and the building blocks it runs against have to be designed together.\n\n## What I take away after a few weeks\n\n`cloudpatrol` is alpha, the API is moving, and I wouldn’t build a big initiative on it today. But the direction convinces me, and it is independent of the specific tool. As soon as infrastructure is code, its rules belong in the same cycle as the code: versioned, checked, open to discussion in the pull request. The gain is not that a machine finds errors. The gain is that an architecture decision no longer lives in the head of a single person but sits in the repository as an executable, justified rule that another developer can meaningfully disagree with tomorrow.\n\nWhether a rule is worth it comes down to three points. It has to prevent a real failure case that I can name, it has to deliver its reason, and it has to show a way out. If it does, the rule no longer depends on the reviewer’s form on the day but on a check that is always equally strict. Everything else remains a topic of conversation for humans – and that’s a good thing.\n\n## Further reading\n\n- AWS CDK, introduction and concepts: https://docs.aws.amazon.com/cdk/latest/guide/home.html\n- Constructs as building blocks: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n- Policy as code for the CDK (cloudpatrol): https://github.com/MikeBild/cloudpatrol"},{"locale":"en","translation_key":"aggregat-als-konsistenzgrenze","slug":"the-aggregate-as-a-consistency-boundary","title":"The Aggregate as a Consistency Boundary","summary":"An aggregate is neither an ORM entity nor a table but a consistency and transaction boundary: a cluster of objects that an Aggregate Root protects as a unit. Why a transaction changes exactly one aggregate and other aggregates are referenced only by ID.","tags":["Software","Architecture"],"published_at":"2020-02-19T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/the-aggregate-as-a-consistency-boundary/","audio_url":null,"audio_duration_secs":null,"text":"```typescript\n@Entity()\nclass Order {\n  @PrimaryGeneratedColumn() id: number;\n  @ManyToOne(() => Customer) customer: Customer;\n  @OneToMany(() => LineItem, (li) => li.order) lineItems: LineItem[];\n  @Column() status: string;\n}\n```\n\nThis class carries four annotations and not a single rule. Nothing stops code anywhere from calling `order.lineItems.push(...)` even though `status` has long been set to `'CONFIRMED'`. And through `order.customer.updateAddress(...)`, the same caller changes a second model on the side, in the same transaction. What you see here is an object graph: data classes with getters and setters, connected by foreign keys. And yet exactly this kind of class is regularly called an aggregate.\n\nAn aggregate comes into being earlier. It starts with the question of which rules have to hold at the same instant, and only after that does it become classes and tables. If you read the term this way, you make different decisions: about transactions, about references between objects, about the size of your models and about where eventual consistency begins. This continues a line of thought I have pursued elsewhere – that [CQRS is a domain boundary](https://www.mikebild.dev/en/blog/cqrs-is-a-domain-boundary-not-a-framework/) and not a framework. The aggregate is the next, smaller boundary in the same conceptual building.\n\n## What an aggregate really is\n\nMartin Fowler puts it concisely: an aggregate is “a cluster of domain objects that can be treated as a single unit”. The classic example is an `Order` with its `LineItems`. These are separate objects, but they are never loaded, changed or saved individually. They come out of the repository as a whole and go back as a whole. The aggregate is the basic unit of storage transfer.\n\nWithin this cluster there is exactly one distinguished component: the Aggregate Root. It is the only entity that may be referenced from outside. Nobody outside the aggregate ever holds a `LineItem` directly – you always go through the `Order`. That sounds like an annoying encapsulation rule, but it has a deep reason: only if all access goes through the root can the root guarantee that the state of the entire aggregate is correct.\n\nAnd that brings us to the core. Eric Evans, Vaughn Vernon and Fowler all mean the same thing when they talk about the aggregate: it is the consistency boundary. The invariants – the business rules that must always hold – are satisfied after every completed change. Not “eventually”, not “after the next batch run”, but immediately, transactionally. Vernon aptly calls this “must always be transactionally consistent”. An invariant might be: “After confirmation, no more line items may be added.” Or: “The sum of the line items equals the order total.” Such rules don’t belong in a service somewhere further up; they belong in the root itself.\n\nThis is the decisive change of perspective: the shape of an aggregate is determined by the invariants that have to be protected together. Which objects belong together in the domain follows from that – not the other way around.\n\n## The root protects its invariants\n\nLet’s look at this in code. The following example is illustrative – I care about the structure, not about a runnable system. What matters is what’s missing: public setters. The `lineItems` list is private, and the only way to change it is through methods that know the invariants.\n\n```typescript\ntype OrderStatus = 'DRAFT' | 'CONFIRMED';\n\nclass Order {\n  private status: OrderStatus = 'DRAFT';\n  private readonly lineItems: LineItem[] = [];\n\n  constructor(\n    readonly id: OrderId,\n    private readonly customerId: CustomerId,\n  ) {}\n\n  addLineItem(product: ProductId, quantity: number): void {\n    if (this.status === 'CONFIRMED') {\n      throw new Error('Cannot modify a confirmed order');\n    }\n    if (quantity <= 0) {\n      throw new Error('Quantity must be positive');\n    }\n    this.lineItems.push(new LineItem(product, quantity));\n  }\n\n  confirm(): void {\n    if (this.lineItems.length === 0) {\n      throw new Error('Cannot confirm an order without line items');\n    }\n    this.status = 'CONFIRMED';\n  }\n}\n```\n\nTwo invariants are expressed here: a confirmed order no longer accepts line items, and an empty order cannot be confirmed. Both are enforced in exactly one place, the root. There is no way to sneak a `LineItem` into the list past this check – because nobody outside the `Order` can get at the list. That is exactly what “the root ensures the integrity of the entire aggregate” means. The state can’t become invalid in the first place.\n\nCompare this with the annotated data class from the beginning, whose `lineItems` and `status` are wide open. There, any code anywhere can manipulate the list or set the status. The rule “no line items after confirmation” then exists at best as a convention, scattered across the codebase, and will be violated sooner or later. The aggregate moves it to a single place that cannot be bypassed.\n\n## One transaction changes exactly one aggregate\n\nThe transaction boundary follows directly from the consistency boundary. Evans and Vernon are clear here: transactions must not cross aggregate boundaries. The rule of thumb is that one transaction changes exactly one aggregate instance. Anything beyond that is not done in the same atomic commit but in separate transactions, connected through eventual consistency.\n\nThis rule reliably meets resistance, and the objection always sounds similar: “When an order is confirmed, the stock has to be reserved too – that belongs in one transaction.” It doesn’t. `Order` and `Inventory` are two aggregates, each with its own invariants. Forcing them into a shared commit couples them technically, creates lock contention and makes the system harder to scale. Instead, transaction T1 confirms the order and writes an `OrderConfirmed` event. A separate transaction T2 processes this event and reserves the stock in `Inventory`.\n\n```mermaid\ngraph LR\n  subgraph T1[\"Transaction T1\"]\n    O[\"Order<br/>confirm()\"]\n  end\n  subgraph T2[\"Transaction T2\"]\n    I[\"Inventory<br/>reserve()\"]\n  end\n  O -- \"OrderConfirmed (event)\" --> I\n```\n\nImportant, to counter a widespread misunderstanding: eventual consistency does not mean “no consistency”. Within an aggregate, everything is strictly and transactionally consistent – after T1, the `Order` is in a valid state no matter what. Between aggregates it is eventual: a short but finite amount of time passes until `Inventory` has caught up. Setting this boundary deliberately is a domain decision. The question is always: does this rule have to hold at the same instant, or may it hold a few milliseconds later? Only if the answer is “at the same instant” does the data belong in the same aggregate.\n\nIf you want to keep this separation of write intentions and the resulting facts clean, you quickly end up with the question of how to [separate commands, events and queries](https://www.mikebild.dev/en/blog/separating-commands-events-and-queries/) anyway. The event between T1 and T2 is exactly such a fact: something that happened and lets other aggregates react.\n\n## Reference other aggregates by identity only\n\nFor the transaction boundary to hold at all, a second rule is needed, and it is the one most often violated: an aggregate references another aggregate only through its identity, its ID, never through a direct object pointer. Vernon states this as a design rule of its own: “Reference Other Aggregates by Identity”.\n\nYou can already see this in the `Order` above. The root holds `customerId: CustomerId`, not `customer: Customer`. The difference is no small matter.\n\n```typescript\n// Wrong: the customer is pulled inside the order\nclass Order {\n  private customer: Customer; // pulls another aggregate inside the boundary\n}\n\n// Right: only the identity crosses the boundary\nclass Order {\n  private readonly customerId: CustomerId; // reference by identity\n}\n```\n\nAs soon as `Order` holds a real `Customer` object, the boundary blurs. The developer who sees the `Customer` reference will use it sooner or later – `order.customer.updateAddress(...)` – and suddenly two aggregates are changed in one transaction. Referencing by ID prevents this structurally: you can’t accidentally mutate a `CustomerId`. If you really need the customer aggregate, you load it beforehand through its own repository and pass in exactly what’s needed – so the ID reference forces a deliberate decision.\n\nThe side effect is valuable too: aggregates stay small. There is no eager loading of entire object graphs, no “loading the order pulls in the customer, which pulls in their addresses, which pull in their countries”. What lies within the boundary gets loaded, and nothing else.\n\nTo keep the rules together in one picture, here is the consistency boundary as a diagram. Inside the framed block is the `Order` aggregate with its root and inner objects; `Customer` lies outside, as an aggregate of its own, and is connected only through its identity.\n\n```mermaid\ngraph TB\n  ext[\"Client code\"]\n  subgraph agg[\"Aggregate: Order (consistency boundary)\"]\n    root[\"Order (Aggregate Root)\"]\n    li[\"LineItem\"]\n    money[\"Money (Value Object)\"]\n    root --> li\n    li --> money\n  end\n  cust[\"Customer<br/>(separate aggregate)\"]\n  ext -->|\"references the root only\"| root\n  root -. \"customerId (by identity)\" .-> cust\n```\n\nNote the arrows: external access points exclusively at the root, never at `LineItem` or `Money`. And the connection to `Customer` is dashed and labeled `customerId` – a reference, not containment.\n\n## Keep aggregates small\n\nThis leads to what may be Vernon’s most practical rule: “Design Small Aggregates”. The temptation to let aggregates grow is enormous, and it even has a name – “object graph greed”. Out of convenience, you include everything you’d like to have at hand while navigating. A `Customer` that holds all its `Orders` as a list is the standard example. In domain terms that sounds plausible; technically it’s a problem: every change to a single order would have to load and lock the entire customer aggregate including all orders. For a customer with a thousand orders, every small operation becomes expensive, and concurrent accesses block each other.\n\nThe heuristic against this is simple: model along real invariants, not along navigation wishes. The question is not “do I want to be able to navigate from A to B” but “does A have to become invalid when B changes, and immediately so”. Only if there is a real, instantaneous consistency rule between two objects do they belong in the same aggregate. For everything else there are references by ID and, if you want to navigate for reading, a read model. The aggregate is a write model; if you’re looking for navigation convenience for display, build a projection for it instead of bloating the aggregate.\n\nLet’s sum up the rules I use to check an aggregate during design:\n\n- All access from outside goes through the Aggregate Root; inner objects are encapsulated.\n- The root enforces the invariants, transactionally consistent after every change.\n- One transaction changes exactly one aggregate instance; everything else runs through eventual consistency and domain events.\n- Other aggregates are referenced only by their identity, never as an embedded object.\n- Aggregates stay small and are cut along real invariants, not along navigation wishes.\n\n## The three pitfalls\n\nThree confusions come up again and again, and it’s worth naming them.\n\nThe first and most common: equating the aggregate with a database table or an ORM entity. That is wrong. The aggregate is a modeling and consistency concept; how it is mapped to tables is an entirely separate question. An aggregate can be persisted across several tables, and one table can contain several value objects. Persistence is orthogonal to the model. A class annotated with `@Entity` and full of getters and setters is far from being an aggregate – it lacks the crucial part, the enforced invariant.\n\nThe second: misunderstanding the Aggregate Root as a “God Object”. Because the root is the only entry point, inexperienced teams tend to put everything into it. That is the opposite of the intent. The root is small and driven by invariants. It holds exactly what it needs to enforce its rules – no more. A root that holds everything is usually a sign that several aggregates have mistakenly been merged into one.\n\nThe third: direct object references between aggregates, the mistake from the beginning. It is so insidious because it feels harmless and because ORMs practically invite it – a `@ManyToOne` relationship is quickly annotated. But every such reference is an invitation to change several aggregates in one transaction and soften the boundary. The discipline is: reference by ID, and if you really need the other aggregate, load it beforehand through its repository – before calling the aggregate method, not in the middle of it.\n\n## A brief distinction\n\nBecause people constantly mix up what belongs together in the DDD world and what doesn’t, a brief clarification on the side. CQRS and Event Sourcing are not the same thing, and neither of them is the aggregate. CQRS separates the write model from the read model, command from query. Event Sourcing persists state as a sequence of events instead of a current snapshot. Both can be used independently of each other – you can use either one without the other, as Fowler and Greg Young emphasize. The aggregate, in turn, is a building block that appears in all of these worlds: it is the consistency boundary against which a command is validated and from which events arise. If you keep these terms cleanly apart, you save yourself many fruitless architecture discussions.\n\nAnd one more subtle but important distinction: the consistency boundary is not the transaction boundary of the database. It’s the other way around. The aggregate defines the logical boundary within which everything has to be consistent – and the database transaction has to respect it. It is not the available transaction mechanisms that determine how models are cut; the domain invariants determine how far a transaction may reach. If you turn this around and align your aggregates with the technical capabilities of the ORM, you have drawn the boundary at the wrong end.\n\n## Conclusion\n\nThe aggregate deserves its central place in DDD because it answers one of the hardest questions in software development: where does consistency end and where does coordination begin? It is neither a data container nor a persistence artifact, but a deliberately drawn consistency and transaction boundary with a root that relentlessly enforces its invariants. Almost everything else follows from this one idea: one transaction per aggregate, references between aggregates only through identity, small models along real rules, and eventual consistency wherever instantaneous consistency is neither necessary nor affordable.\n\nSo the first question before a domain model is not “which objects belong together” but “which rules have to hold at the same instant”. The answer cuts the aggregates – and with them half the architecture.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html\n- Martin Fowler: [DDD_Aggregate](https://martinfowler.com/bliki/DDD_Aggregate.html) – the compact definition of aggregate and Aggregate Root.\n- Vaughn Vernon: [Effective Aggregate Design](https://www.dddcommunity.org/library/vernon_2011/) (2011), parts I–III – the rules “Design Small Aggregates” and “Reference Other Aggregates by Identity”.\n- Eric Evans: *Domain-Driven Design* (2003), chapter 6 – the primary source for aggregates and Aggregate Roots.\n- Greg Young / Martin Fowler on distinguishing CQRS and Event Sourcing – useful for cleanly separating the aggregate from both.\n- From my own talk material: the deck “CQRS + Event Sourcing” (SlideShare), in which I play through this boundary-drawing with concrete examples."},{"locale":"en","translation_key":"ssmenv-cli-kleine-clis","slug":"ssmenv-cli-small-clis","title":"`ssmenv-cli`: Small CLIs for Big Order","summary":"A small CLI on top of AWS SSM shows how configuration gets from a named, access-controlled source into local processes and CI – including questions of versions and failures.","tags":["Software","Data","Tools"],"published_at":"2020-02-12T10:00:00+00:00","updated_at":"2026-07-20T13:27:22.94021+00:00","url":"https://www.mikebild.dev/en/blog/ssmenv-cli-small-clis/","audio_url":null,"audio_duration_secs":null,"text":"# `ssmenv-cli`: Small CLIs for Big Order\n\nConfiguration isn’t a file format. It is a data set with access rights, versions and a history – the `.env` file is only a copy of it, and rarely the only one.\n\nAnd copies multiply: one `.env` on the laptop, a second in CI, a third in the onboarding wiki, a fourth as a screenshot in a chat, a fifth “only on my machine”. At some point, nobody knows which value is authoritative anymore. That is where the bugs come from that can’t be reproduced, and the onboarding days you never get back. `ssmenv-cli` draws a consequence from this: the AWS Systems Manager Parameter Store holds the authoritative values, and the tool only translates them into the environment of a process.\n\n## The problem behind the tool\n\nThe classic pattern is the shared `.env` note. It works on day one and slowly falls apart afterwards. I know the typical symptoms by heart: a secret accidentally ends up in the Git history. A new colleague gets an outdated copy and loses half a day to “it doesn’t run for me”. A value is changed in production but not documented anywhere traceable. And nobody can say offhand who actually has the right to read a production secret.\n\nAt its core, this isn’t a tooling problem but a boundary problem. There is no clear answer to three questions: Which data is authoritative? Who may read and change it? Where does a change become traceable? As long as these boundaries stay blurry, even the nicest script won’t help. So the three questions come before the tool.\n\n## The decision: SSM as the single source\n\nThe load-bearing decision is: the AWS Systems Manager Parameter Store becomes the single source for configuration and secrets. Not Git, not the laptop, not the chat – a hierarchical namespace in AWS that is already there anyway if you deploy there.\n\nThat is a deliberate choice against a system of my own and against a large additional product. The Parameter Store brings exactly what I need for this boundary: a hierarchy via paths such as `/myapp/prod/DATABASE_URL`, encryption of sensitive values via KMS as `SecureString`, access control via IAM and a complete record via CloudTrail. That answers the three open questions from above without me operating a single line of infrastructure myself.\n\nAll that is missing now is the last mile: the way from the Parameter Store into the environment variables of a process. Exactly that – and nothing more – is the CLI’s job.\n\n## Architecture: a thin adapter, not a platform\n\nThe most important architecture decision about `ssmenv-cli` is what the tool deliberately does *not* do. It stores nothing, it decides on no permissions, it holds no state. It is a thin adapter between an authoritative data source and the 12-factor principle “config in the environment”.\n\nThis separation is the actual boundary. The Parameter Store is the store of truth. IAM is the permission boundary. KMS is the confidentiality boundary. The CLI is pure translation: it reads a path prefix, resolves `SecureString` values and provides them to a process as its environment. Because the tool itself has no authority, I can swap it out at any time without anything changing in the security or data model. That is the value of a cleanly drawn boundary: it makes the tool replaceable.\n\n## A small example\n\nThe practical core fits into a few lines. You set values once – ideally through automation, here by hand for illustration:\n\n```bash\n# Store a secret as an encrypted SecureString under a namespaced path\nssmenv set --path /myapp/prod DATABASE_URL \"postgres://db.internal:5432/app\"\n\n# List everything under a prefix (values masked by default)\nssmenv list --path /myapp/prod\n```\n\nThe real gain shows when loading. Instead of distributing a file, you resolve the environment at runtime:\n\n```bash\n# Run a process with the resolved environment, nothing written to disk\nssmenv exec --path /myapp/prod -- node server.js\n\n# Or export into the current shell for a quick local session\neval \"$(ssmenv export --path /myapp/staging)\"\n```\n\nAnd because two environments are rarely identical, comparing them is a full-fledged command and not an afterthought:\n\n```bash\n# Show which keys differ between staging and prod\nssmenv diff --path /myapp/staging --path /myapp/prod\n```\n\nThe example is deliberately small. It doesn’t simulate a complete platform; it shows the boundary: the CLI only touches the last mile between store and process. A good example isn’t the one with the most options but the one where you can discuss the decision after five minutes.\n\n## Sketch\n\n```mermaid\nflowchart LR\n  Store[\"SSM Parameter Store<br/>/myapp/prod/*\"] --> CLI[\"ssmenv-cli<br/>thin adapter\"]\n  IAM[\"IAM<br/>permission boundary\"] --> CLI\n  KMS[\"KMS<br/>SecureString decrypt\"] --> CLI\n  CLI --> Env[\"process env\"]\n  Env --> App[\"node server.js\"]\n```\n\nThe sketch makes the responsibilities visible: the store holds the truth, IAM and KMS draw the boundaries, the CLI translates. No box in this picture depends on a tool name – that is intentional.\n\n## Trade-offs: why small, why not more\n\nThe obvious counter-question is: why not go straight for a full-fledged secret management product? That is a trade-off, not dogma. A large system brings rotation, dynamic credentials and fine-grained policies – plus operations, a learning curve and another dependency. For many teams that deploy on AWS anyway, that is more machinery than the problem calls for.\n\nI build the smallest solution that cleanly answers the three boundary questions and leave room for a switch. Because `ssmenv-cli` is only an adapter, that switch is cheap. If a team later needs rotation on a large scale, I swap the backend store, not the mental model. The expensive decision – configuration is central, access-controlled and auditable – stays the same. That is exactly what a trade-off should look like: start small without blocking the way to expand.\n\nThe second trade-off concerns network dependency. Resolving values from the store at runtime means that a process start requires AWS to be reachable. That is a deliberate choice: I trade a short network call at startup for the permanent danger of outdated local copies. For local offline work, there is still an explicit export – a visible exception that someone has to trigger deliberately.\n\n## Operational consequences\n\nThe consequences of an architecture don’t show in the demo but in failures, load, rollback and review. Here the model holds, because the heavy tasks sit where they belong.\n\nAccess is an IAM question. Who may read `/myapp/prod/*` is written in a policy and not in a chat history – and can therefore be checked and revoked. Confidentiality is a KMS question: sensitive values are stored encrypted as `SecureString`, and the CLI only decrypts if the caller has the right to do so. Traceability is a CloudTrail question: every read and write access is recorded. When someone asks “who read this secret when?”, there is an answer instead of a shrug.\n\nReversibility is the strongest point. Because the Parameter Store keeps versions, a wrongly set value isn’t an emergency but a rollback to the previous version. That makes a change to configuration as manageable as a change to code.\n\n## Failure cases\n\nAn idea is only robust once the failure path is described. Three cases belong to it.\n\nMissing permission: if the caller isn’t allowed to read the path, the CLI must abort hard and clearly. An empty value that silently slips through as an empty string is the most dangerous bug – the application starts with half its configuration and only falls over deep in operation. An `exec` must therefore fail on missing or unreadable keys before the target process even starts.\n\nA partially resolved environment: if only nine of ten expected keys are there, that isn’t “almost right” but wrong. I treat it as an error with a clear message about which key is missing.\n\nNetwork and region errors: an unreachable store or a wrong region must not pass through a cryptic SDK exception but a message that names the path and the cause. The difference between demo and operations almost always lies in exactly these unexciting error messages.\n\n## The same boundary in CI\n\nThe real test of a configuration boundary is the pipeline. In CI, it isn’t a human with personal permissions that runs but a role – and that is exactly what makes the model clean. Instead of duplicating secrets as CI variables, the build job gets an IAM role that may read exactly the path it needs, and no other. A staging deploy sees `/myapp/staging/*`, a production deploy `/myapp/prod/*`, and the separation isn’t a convention but a permission.\n\n```bash\n# In CI: the job's role grants read on /myapp/staging/* only\nssmenv exec --path /myapp/staging -- npm run deploy\n```\n\nThat makes the whole class of “the secret now also lives in CI” copies disappear. There is no second source that can go stale, and the principle of least privilege applies to machines just as it does to people. If a CI token is compromised, the damage is limited to exactly the path this job was allowed to read – traceable in CloudTrail, revocable in a policy. That literally the same command runs locally, in CI and in production, just with a different path, is the core of reproducibility.\n\n## Business outcome: shorter cycles, less friction\n\nThe benefit is measurable, even if the tool is small. Onboarding that used to mean “get the current `.env` from somebody” becomes a single command against a path – half a day of friction turns into minutes. The whole class of “works for me, not for you” bugs disappears, because dev, CI and production use the same authoritative source and differ only in the path prefix. And the risk of leaving a secret in the Git history drops structurally, because there is no longer any reason to put secrets in files that get versioned.\n\nThese are the three levers that count for technical decision-makers: shorter cycles when setting up and switching environments, less friction in everyday work and higher quality through reproducible configuration. The gain isn’t in the tool’s name but in the decision to treat configuration like a verifiable data system.\n\n## The pattern for small CLIs\n\n`ssmenv-cli` deliberately stays an adapter. Whether the Parameter Store can really be the authoritative source is decided by write permissions, the handling of versions and the behavior when it’s unreachable. The CLI solves none of these questions; it only makes the answer that was chosen usable for local processes and CI.\n\nThat’s why I prefer to build many small, sharply delimited CLIs rather than one large, blurry framework. Each does one job, has a visible boundary and at least one honest failure case. The same way of thinking is in `ssmenv-cli`: small in scope, clear in responsibility, replaceable in detail. Big order doesn’t come from big tools but from many small ones with clear responsibilities.\n\n## Closing\n\nMore important than how `ssmenv-cli` works is where the boundary runs: configuration central and auditable, the tool deliberately thin and replaceable. This decision still holds when the tool has long been replaced by another one – and that is exactly why you can reuse it in the next team conversation.\n\n## Further reading\n\n- Repository ssmenv-cli: https://github.com/MikeBild/ssmenv-cli\n\nThe source helps you cross-check the concrete implementation."},{"locale":"en","translation_key":"github-actions-mit-aws-cdk","slug":"github-actions-with-aws-cdk","title":"GitHub Actions with AWS CDK","summary":"GitHub Actions and AWS CDK connect code changes, infrastructure and deployment into a reviewable pipeline – and make the architecture decision visible in the pull request.","tags":["Software","AWS","Cloud"],"published_at":"2020-01-12T10:00:00+00:00","updated_at":"2026-07-13T07:55:50.690283+00:00","url":"https://www.mikebild.dev/en/blog/github-actions-with-aws-cdk/","audio_url":null,"audio_duration_secs":null,"text":"# GitHub Actions with AWS CDK\n\nTwo commands carry this setup: `cdk diff` in the pull request and `cdk deploy` on `main`. The first changes nothing and shows everything – new resources, changed permissions, deleted tables. The second changes everything and shows nothing that was not already in the review.\n\n**Editorial note (July 2026):** The workflow and CDK code show the state of January 2020: Actions v1, Node 12, CDK v1 and permanently stored AWS keys. A setup today calls for current action versions, CDK v2 and short-lived AWS credentials via OpenID Connect in the workflow. The review idea around `cdk diff` is not affected by this.\n\nThis order holds the difference between automation and architecture. Connecting GitHub Actions and AWS CDK takes an hour. What is more interesting is which decision it brings to the table earlier.\n\n## Why this combination is more than automation\n\nGitHub Actions has been generally available for a few weeks, and the obvious reaction is to rebuild the familiar flow with it: build the tests, package the artifact, deploy via script. That works, but it gives away the real lever. Because with AWS CDK, I describe my infrastructure in the same TypeScript repository as my application – Lambda, API Gateway, IAM roles, tables. That turns infrastructure into code that can be reviewed, versioned and tested like any other.\n\nThe point I care about only emerges from the interplay. When application code and infrastructure code sit in the same pull request and run through the same pipeline, a change is no longer “new handler” plus “someone clicks a role together in the console later.” It is a single, traceable unit. The code change and its operational consequence sit side by side before anything goes to production. That is the architectural gain – not the clicks saved.\n\nThis boundary is often drawn somewhere else. Infrastructure then lives in a wiki, in terminal commands, in the heads of two people. The pipeline deploys the code, but nobody in the review can say which permissions, which resources and which costs a change brings with it. CDK plus GitHub Actions turns this question into an artifact you can discuss.\n\n## Approval comes before the workflow\n\nBefore I write YAML, I clarify three concrete points: Who may trigger a deployment? Which changes must be visible in the pull request? And what is the way back if the new stack does not hold? GitHub Actions answers none of these questions. The workflow only enforces the answers. If, for example, a protected environment with approval is missing, `cdk deploy` on `main` quickly becomes an automatism that is faster than the control behind it.\n\n## `cdk diff` as a review artifact\n\nFor me, the methodological core of this combination is a single command: `cdk diff`. It compares the synthesized CloudFormation state with what is actually running in AWS and shows the difference – new resources, changed permissions, deleted tables. If I pull this command into the pull request run, every review gets an honest preview of the operational consequence.\n\nThat noticeably changes the quality of a review. A reviewer does not just see that a handler is being added but that this handler brings along a new IAM policy with `dynamodb:*`. This line in the diff is the moment a bad decision stands out – before the merge, not in the next security audit. I thereby move an error from “expensive and late” to “cheap and early,” and that is the concrete effect this is about.\n\nThe diff also uncovers a class of problems that otherwise stays invisible: drift. If someone changes a resource by hand in the console, the real state deviates from the code. Without a diff, nobody notices until a deployment silently overwrites the manual change and something breaks that “was still working yesterday.” With the diff in the pull request, this deviation becomes a visible signal – and an opportunity to ask the real question: why was someone working in the console, and how do I bring this change back into the code where it belongs? The diff is thus not just a review tool but a quiet way of disciplining the whole team toward “the code is the truth.”\n\n## A small stack\n\nThe basis is a deliberately small stack – a Lambda behind an API Gateway. It is not meant to simulate a complete application but to show the boundary.\n\n```ts\nimport * as cdk from \"@aws-cdk/core\";\nimport * as lambda from \"@aws-cdk/aws-lambda\";\nimport * as apigw from \"@aws-cdk/aws-apigateway\";\n\nexport class ApiStack extends cdk.Stack {\n  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {\n    super(scope, id, props);\n\n    const handler = new lambda.Function(this, \"ApiHandler\", {\n      runtime: lambda.Runtime.NODEJS_12_X,\n      handler: \"index.handler\",\n      code: lambda.Code.fromAsset(\"dist/api\"),\n      timeout: cdk.Duration.seconds(10)\n    });\n\n    new apigw.LambdaRestApi(this, \"Api\", { handler });\n  }\n}\n```\n\nWhat is interesting is less what is here than what is not here. `LambdaRestApi` is a construct that creates an API, an integration and the matching execution role in the background. That is the value of a good abstraction: it reduces repetition and encapsulates sensible defaults. And that is also its risk – it must not hide which resources, permissions and costs actually come about. `cdk diff` is exactly the control that makes the hidden visible again.\n\nA good example has few features and one point you can argue about after five minutes. The `timeout` is such a point: ten seconds is an operational decision, not a detail, and it belongs in the code, not in a verbal agreement.\n\n## The pipeline\n\nThe pipeline has two jobs that I keep cleanly separate. In the pull request, it shows the diff without changing anything. On `main`, it deploys. This separation is not cosmetic – it ensures that the preview has no consequences and the deployment has a clear trigger.\n\n```yaml\nname: deploy\n\non:\n  push:\n    branches: [main]\n  pull_request:\n\njobs:\n  diff:\n    if: github.event_name == 'pull_request'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v1\n      - uses: actions/setup-node@v1\n        with:\n          node-version: \"12\"\n      - run: npm ci\n      - run: npm run build\n      - run: npx cdk diff\n        env:\n          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}\n          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n          AWS_DEFAULT_REGION: eu-central-1\n\n  deploy:\n    if: github.ref == 'refs/heads/main'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v1\n      - uses: actions/setup-node@v1\n        with:\n          node-version: \"12\"\n      - run: npm ci\n      - run: npm run build\n      - run: npx cdk deploy --require-approval never\n        env:\n          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}\n          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n          AWS_DEFAULT_REGION: eu-central-1\n```\n\nThe credentials are stored as GitHub secrets in the repository and passed to the CDK CLI via environment variables. That is the pragmatic route I take today – and at the same time the place with the greatest responsibility; more on that in a moment.\n\nThe flow as a sketch:\n\n```mermaid\nflowchart LR\n  PR[Pull request] --> Diff[cdk diff<br/>visible in review]\n  Diff --> Merge[Merge to main]\n  Merge --> Build[Build + synth]\n  Build --> Deploy[cdk deploy]\n  Deploy --> CFN[CloudFormation<br/>Change Set]\n  CFN --> Observe[Logs + metrics]\n```\n\n## An environment you can reproduce\n\nAs soon as the first stack is running, the question of staging and production comes up. And this is where it shows why infrastructure as code is more than a more convenient deployment. Because my stack is a TypeScript class, I can parameterize it and instantiate it twice – the same definition, different names, different accounts. Staging is then, by construction, an exact copy of production, not an environment that slowly drifts apart over months until nobody knows anymore which difference was intended and which was chance.\n\nThis is one of the methodological consequences I value most. The classic break between “works on my machine” and “works in production” almost always comes from environment differences that nobody documented. When the environment itself is versioned, this break does not disappear completely, but it becomes a question I can answer in the repository instead of a puzzle I solve under time pressure in the production system. That is exactly why, for me, CDK belongs to the topic of reproducibility. The deployment steps saved are just the visible side effect.\n\n## Permissions that do not grow with every convenience\n\nThe most tempting shortcut is a deploy identity with `AdministratorAccess`. It always works, it never explains an error, and it is the reason a compromised repository becomes a compromised account. The trade-off is real: a narrowly cut role means that a deployment occasionally fails on a missing permission and I have to tighten things up. But this failure is cheap and instructive, while silent full access only gets expensive once.\n\nServerless moves operational work; it does not remove it. Permissions, logs, cold starts, timeouts, costs and the ability to roll back still have to be designed explicitly. The difference is that with CDK I design them in the same review in which I write the handler – instead of postponing them to “we’ll do it later.” In practice, “later” is the name for “never.”\n\n## Rollback and the happy-path fallacy\n\nThat leaves overrating the happy path. Many pipelines look clean as long as every deployment succeeds. It gets interesting with partial failures: one resource is created, the next one fails, and the stack is stuck halfway.\n\nWhat helps here is that CDK builds on CloudFormation. A failed deployment rolls back to the last consistent state, and this behavior is part of the platform, not of my script. That is a strong reason to stay with CDK instead of stringing individual resources together with imperative CLI calls: I get a defined transaction boundary for free. Still, I have to know it. A deployment that migrates data is not automatically reversible just because the stack is – the question of idempotency and repeatability remains mine.\n\n## What changes measurably as a result\n\nWhen these parts work together, the work changes noticeably, and in a direction I can explain to a technical decision-maker. The cycle from “idea” to “running in production” gets shorter because there is no longer a manual handover step between code and infrastructure. Friction in the team drops because nobody holds deployment knowledge as personal gatekeeping knowledge anymore – it lives in the repository. And quality rises because `cdk diff` moves an error to where it is cheap: into the pull request.\n\nConcretely, it looks like this: in a team without this setup, an infrastructure change takes as long as the available person with AWS access needs – plus the time until someone notices that the change turned out differently in staging and production. With the pipeline, the same change is a pull request that two colleagues can read without having console access themselves. The “one person with permissions” bottleneck disappears, and with it the silent queue that nobody ever sees on a board. That is developer productivity in the literal sense: not typing faster, but fewer handovers, fewer follow-up questions, fewer states in which someone is waiting for someone else.\n\nThat is the arc from mechanics to effect. GitHub Actions and CDK are interchangeable tools. The reusable decision behind them – treating infrastructure as a reviewable part of every change – is not.\n\n## What I check in the review\n\nWhen reviewing this setup, I ask three questions. Does the pull request show the operational consequence, that is, the diff, or only the application code? Is the deploy identity cut so narrowly that I can explain a permission error instead of configuring it away? And is it clear what happens when a deployment has run halfway?\n\nIf one of these questions remains open, the pipeline is still missing something – a visible diff, a sharper role or a clarified rollback path. A construct should reduce repetition and encapsulate good defaults, but never obscure which resources, permissions and costs come about. It is exactly at this edge between convenient abstraction and honest visibility that it is decided whether the combination holds.\n\n## Further reading\n\n- AWS CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/home.html\n- AWS CDK Constructs: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n- [GitHub Actions: OpenID Connect with AWS](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws)\n- Repository aws-cdk-js-github-action: https://github.com/MikeBild/aws-cdk-js-github-action\n\nThe sources help you cross-check platform behavior. The actual statement remains the architecture decision in the concrete example.\n\n## Closing\n\nBringing GitHub Actions and CDK together is done quickly. The return lies in the boundary between application and platform moving into the pull request. That is where the benefit arises for developers, architects and technical decision-makers. It hinges on a reusable decision: taking infrastructure as seriously as the code that runs on it. The tool name is interchangeable."},{"locale":"en","translation_key":"pouchdb-offline-first","slug":"pouchdb-and-offline-first","title":"PouchDB and Offline-First","summary":"If you allow writes while offline, you move from request/response to replication – and the revision tree of PouchDB and CouchDB turns conflicts into a job for the domain model.","tags":["Software","Architecture"],"published_at":"2019-11-12T10:00:00+00:00","updated_at":"2026-07-14T17:08:56.769898+00:00","url":"https://www.mikebild.dev/en/blog/pouchdb-and-offline-first/","audio_url":null,"audio_duration_secs":null,"text":"# PouchDB and Offline-First\n\nOffline is treated as a special case: first finish building the application, then shortly before the release put a cache in front of it, catch failed requests, show a “You are offline” banner. This assumption holds exactly until the first write without a network. Reads can be cached – writes cannot. As soon as a user is allowed to change a record on the train, the question is no longer how to cache responses but: Where does the truth live while the connection is missing? And what happens if two devices have changed the same record in the meantime?\n\nThat makes offline-first not a feature checkbox you tick off at the end. It is an architecture decision that swaps out the application’s communication model: replication instead of request/response. The offline-first movement has been saying this for years – the term comes from the circle around hood.ie and offlinefirst.org, long before Progressive Web Apps brought the topic to a wide audience. Still, in everyday work it is often shortened to “service worker plus cache.” But the service worker solves only half of the task: it delivers the application itself without a network – HTML, JavaScript, CSS. The data is the real problem, and for that you need a different tool.\n\n## Replication instead of request/response\n\nIn the request/response model, the server is the single source of truth. The client asks, the server answers, and without a connection there simply is no state. In this model, every offline feature is a detour: a queue for pending POSTs, a cache for stale responses, retry logic, lots of special cases that cut across the actual application.\n\nIn the replication model, this flips around. The application reads and writes exclusively locally, against a database in the browser. Synchronization is a separate process that runs in the background when a connection is available – and pauses when it is not. At first, the UI notices nothing of the network at all.\n\n```mermaid\nflowchart LR\n  subgraph rr[\"Request/Response\"]\n    UI1[\"UI\"] -->|\"HTTP request<br/>blocks without network\"| API[\"API server\"]\n    API --> DB1[(\"central<br/>database\")]\n  end\n  subgraph repl[\"Replication\"]\n    UI2[\"UI\"] -->|\"read and write<br/>locally\"| LOCAL[(\"PouchDB<br/>IndexedDB\")]\n    LOCAL <-->|\"sync when<br/>network is available\"| REMOTE[(\"CouchDB\")]\n  end\n```\n\nThe difference shows first in perceived speed: local reads and writes take milliseconds, regardless of dead zones, latency or server load. But the real gain and the real price lie elsewhere. The replication model accepts that at times there are several valid views of the same data. In it, conflicts are not an operational accident but an expected consequence of the architecture – and that is exactly why they belong in the domain model, not in an error handler.\n\n## PouchDB in the browser, CouchDB at the other end\n\nPouchDB is a JavaScript database that builds on IndexedDB in the browser and replicates CouchDB’s HTTP API – including the CouchDB replication protocol. This protocol is openly documented and describes how two peers exchange their changes: read the changes feed, determine missing revisions, transfer documents, write a checkpoint. If the connection drops, the next run picks up at the last checkpoint, not at the beginning.\n\nThat you can set up bidirectional synchronization with this in a few lines almost seems suspicious on first contact:\n\n```js\nconst localNotes = new PouchDB('notes');\nconst remoteNotes = new PouchDB('https://couch.example.com/notes');\n\nlocalNotes.sync(remoteNotes, { live: true, retry: true })\n  .on('change', info => renderChange(info))\n  .on('paused', () => setSyncStatus('idle'))\n  .on('active', () => setSyncStatus('syncing'))\n  .on('error', err => reportSyncError(err));\n```\n\n`sync` is nothing magical here, just two one-way replications, one in each direction. `live` keeps the changes feed open, `retry` bridges connection drops with backoff. The `paused` and `active` events work as an honest status display: `paused` means “everything transferred or no network right now,” `active` means “changes are flowing.” In small applications, I have truly never needed more sync code than this – the rest is conflict handling, more on that shortly.\n\nImportant for putting this in context, as of today with PouchDB 7 and CouchDB 2.x: the replication protocol is not an internal detail but an interface. Anything that speaks it can participate – a CouchDB cluster, a second browser tab, a Node process with express-pouchdb in front. Synchronization logic thus becomes infrastructure. What remains in the application is the domain question that no library can answer: What does it mean when two states diverge?\n\n## The revision tree\n\nThe core of the model is the versioning of every single document. Every change creates a new revision, and every write must name the revision it wants to continue. If that does not match, the database rejects it immediately:\n\n```js\nasync function saveNote(note) {\n  try {\n    await localNotes.put(note);\n  } catch (err) {\n    if (err.status !== 409) throw err;\n    // optimistic locking: fetch the current revision and retry once\n    const current = await localNotes.get(note._id);\n    await localNotes.put({ ...note, _rev: current._rev });\n  }\n}\n```\n\nThis 409 is the immediate conflict: two writers on the same database, classic optimistic locking, easy to handle. The second case is more interesting. Two devices change the same document offline, both writes are perfectly valid locally, and only replication brings the states together. Then a revision tree with two branches appears in the document:\n\n```mermaid\ngraph TD\n  R1[\"Rev 1-a4f<br/>shared starting state\"] --> R2A[\"Rev 2-c91<br/>changed on device A\"]\n  R1 --> R2B[\"Rev 2-b07<br/>changed on device B\"]\n  R2A --> R3[\"Rev 3-e12<br/>merge<br/>by the application\"]\n  R2B -. \"losing branch<br/>is kept\" .-> R3\n```\n\nIn this situation, CouchDB and PouchDB deterministically choose a winner: the longer revision path wins; on a tie, the lexicographically higher revision hash. Deterministic means every node arrives at the same result without coordination – a cluster needs no consensus algorithm for that. It explicitly does not mean: correct for the domain. The losing branch is not deleted either but stays attached to the document as `_conflicts`. The database keeps both states and waits for someone to decide. That “someone” is the application.\n\n## Conflicts are the normal case\n\nThis is where cache thinking finally parts ways with the replication model. If you retrofit offline capability, you treat conflicts as errors that should ideally not occur. If you replicate, you treat them as an ordinary event with a domain answer. The database cannot give that answer, because it does not know what the data means. Whether the longer text wins for a note, whether two shopping lists can be combined as sets or whether a human has to decide – that lives in the domain model, nowhere else.\n\nThe resolution itself is mechanically unspectacular: fetch the conflicting revisions, merge them, write the result, remove the losers.\n\n```js\nasync function resolveConflicts(id) {\n  const winner = await localNotes.get(id, { conflicts: true });\n  if (!winner._conflicts) return winner;\n\n  const losers = await Promise.all(\n    winner._conflicts.map(rev => localNotes.get(id, { rev }))\n  );\n\n  const merged = mergeNotes(winner, losers); // domain-specific merge\n  await localNotes.put(merged);\n  await Promise.all(\n    losers.map(loser => localNotes.remove(loser._id, loser._rev))\n  );\n  return merged;\n}\n```\n\nWhat matters is `mergeNotes` – and that this function exists at all. In code reviews, I have noticed that exactly this function is almost always missing: sync built in, demo running, and the conflict case gets pushed to later because it simply does not occur during development. A single developer with one device and stable Wi-Fi produces no conflicts. Two field reps with tablets in a dead zone produce them on day one. If the resolution is missing then, the deterministic algorithm silently wins, and from the user’s point of view the loser’s changes have vanished – not deleted, but invisible. That is the most expensive kind of bug: no crash, no log entry, just quiet data loss from the point of view of the person in front of the screen.\n\nThat is why a conflict strategy also needs a visibility strategy. A small indicator saying “three changes waiting to sync” costs little and noticeably changes trust in the application. Users forgive waiting times when they can see where they stand.\n\n## What this does to the data model\n\nReplication and conflicts feed back into how you split documents. A document is the unit that gets replicated and fought over – so it pays to split documents in a way that makes conflicts rare and, when they do occur, resolvable. A few rules have proven themselves for me:\n\n- One document per domain unit that a user edits in one go – no collective document for half the application state.\n- Meaningful IDs like `note:2019-11-12` instead of pure random UUIDs where the domain allows it; that makes direct access predictable and saves you some indexes.\n- Append instead of overwrite where possible: if you write events as new documents instead of changing an existing one, you structurally get fewer conflicts.\n- Treat deletions as part of the model: deleted documents persist as `_deleted` revisions so that the deletion itself can be replicated.\n\nFor queries beyond key access, there are Mango queries via pouchdb-find, now part of the standard build:\n\n```js\nawait localNotes.createIndex({ index: { fields: ['updatedAt'] } });\n\nconst recent = await localNotes.find({\n  selector: { updatedAt: { $gte: '2019-11-01' } },\n  sort: [{ updatedAt: 'desc' }],\n  limit: 20\n});\n```\n\nOn top of that comes a browser reality you should know about: IndexedDB storage is not guaranteed. The browser may clean up under pressure, and storage quotas differ significantly by platform. You can request persistent storage through `navigator.storage.persist()`, but I would not rely on it – the copy on the server remains the life insurance; the local database is the working state.\n\n## Two experiences of my own\n\nIn 2016, I used graphql-pouch to try out how far the idea could be pushed: a GraphQL runtime directly on PouchDB, Schemas in GraphQL shorthand notation, as a standalone service with CouchDB synchronization and master/master replication. The prototype showed me two things. First, how much backend the replication protocol replaces: sync endpoints, retry logic, delta calculation – all code I never wrote because the protocol brings it along. Second, that the conflict question catches up with you on the server side too. As soon as two instances replicate against each other, the “server” carries the same revision trees as the browser. So the architecture decision does not disappear when you push it to the server side; it only changes location.\n\nOn the side, I have been maintaining the list awesome-pouchdb for a few years, where I collect tools, plugins and articles around PouchDB. The view of the ecosystem is itself a data point: a striking number of entries revolve around exactly the places where the model pinches – pouchdb-find for queries, express-pouchdb for your own sync endpoints, pouchdb-authentication for logging in against CouchDB. Where a community builds many tools, it is rarely a coincidence but a recurring problem.\n\n## Where I would not use it\n\nAs convincing as the model is for notes, forms and field service scenarios – it has clear limits, and you should know them before the decision, not after:\n\n- Fine-grained access rights: CouchDB authorizes per database, not per document. The usual remedy is one database per user, which noticeably complicates operations and server-side analysis.\n- Large amounts of data that need central analysis: what the browser holds has to be replicated there. For dashboards over millions of rows, the approach is the wrong tool.\n- Strictly consistent processes: account balances, inventory levels, bookings with hard invariants need central coordination. You cannot configure away eventual consistency.\n- Data that must not leave the device but would – or, conversely, must not be on it in the first place. Replication distributes copies; that is its purpose.\n\nFiltered replication can limit the amount of data per client, but it has its own price: the filter runs over the complete changes feed, and changing filters later is tedious. If you only want to synchronize a subset, you should take that into account early when splitting documents, for example with separate databases per tenant or project.\n\n## Bottom line\n\nYou decide on offline-first at the beginning of a project, not at the end – because document splitting, conflict behavior and the permission model depend on it. PouchDB and CouchDB take the mechanics off your hands completely: replication protocol, revision trees, checkpoints, resumption after a drop. What they do not take off your hands is the domain answer to the one question everything hinges on: What should happen when two devices have changed the same thing? If you have an answer to that, you get, with surprisingly little code, an application that works in a dead zone just as well as in the office. If you do not, you get one anyway – only then a hash comparison decides about your users’ data.\n\n## Further reading\n\n- [awesome-pouchdb – curated list of PouchDB tools and plugins](https://github.com/MikeBild/awesome-pouchdb)\n- [graphql-pouch – GraphQL runtime on PouchDB with CouchDB sync](https://github.com/MikeBild/graphql-pouch)\n- [PouchDB Guide: Replication](https://pouchdb.com/guides/replication.html)\n- [PouchDB Guide: Conflicts](https://pouchdb.com/guides/conflicts.html)\n- [CouchDB Replication Protocol (official specification)](https://docs.couchdb.org/en/stable/replication/protocol.html)\n- [Offline First – offlinefirst.org](http://offlinefirst.org/)"},{"locale":"en","translation_key":"commands-events-queries-trennen","slug":"separating-commands-events-and-queries","title":"Cleanly Separating Commands, Events and Queries","summary":"Command, event and query are three kinds of messages with clear semantics: a request that can be rejected, a fact that has happened and a query without side effects. If you name and separate them cleanly, you gain clarity in the model – without a big CQRS setup.","tags":["Software","Architecture"],"published_at":"2019-10-08T10:00:00+00:00","updated_at":"2026-07-19T18:46:18.505233+00:00","url":"https://www.mikebild.dev/en/blog/separating-commands-events-and-queries/","audio_url":null,"audio_duration_secs":null,"text":"`updateOrder(...)` is not a domain message. The name doesn’t say whether someone wants something or whether something has already happened – it only describes that fields change. Method names like this are the reason models get blurry: request, fact and question travel under the same name through the same classes, and nobody can tell from the signature which of them is currently on its way.\n\nCommand, event and query clean this up. The three differ in three points that you can check on every single message: in their tense, in whether they may be rejected and in the number of recipients. The following sections go through these points – first conceptually, then in TypeScript, then along the mistakes that regularly happen along the way.\n\nThe form of a message follows its meaning. JSON objects that look the same can still carry completely different contracts.\n\n::::comparison{title=\"Telling messages apart by what they state\" role=\"primary\" preferredPattern=\"comparison-matrix\"}\n:::side{label=\"Command\"}\n- Meaning · request to attempt a state change\n- Time reference · aimed at an intended future\n- Outcome · can be rejected or fail\n:::\n:::side{label=\"Event\"}\n- Meaning · a fact that has already occurred\n- Time reference · immutable past\n- Outcome · is not rejected after the fact\n:::\n:::side{label=\"Query\"}\n- Meaning · request for existing information\n- Time reference · view of the current or a specified state\n- Outcome · does not change the domain state\n:::\n::::\n\nThis distinction makes names, error paths and responsibilities more precise before any framework comes into play.\n\n## Three messages, three meanings\n\nLet’s start with the core, because this is where everything is decided. A command, an event and a query are fundamentally different things, even if they look superficially similar in code – in the end, each of them is an object with a few fields. The difference is not in the structure but in the meaning.\n\nA **command** is an imperative wish. “Do X.” `CreateOrder`, `ShipProduct`, `CancelReservation`. A command expresses an intention that has not happened yet. And this is crucial: a command is a request that can be rejected. It goes through validation and business rules, and if something isn’t right, it fails. Exactly one handler is responsible; a command is directed – it has an intended recipient.\n\nAn **event** is the exact opposite on the timeline. It is a fact that has already occurred. `OrderCreated`, `ProductShipped`, `ItemOrdered` – named in the past tense. An event is immutable, because you can no longer change the past. And an event cannot be rejected: you cannot say “no” to something that has happened. It is the result of a successfully processed command. While a command has exactly one handler, an event can have zero, one or many consumers – it is a notification to potentially many.\n\nFinally, a **query** retrieves data without changing anything. `GetOrderSummary`. It returns a result and leaves the observable state of the system untouched – it is free of side effects. A query reads, ideally from a view optimized for reading, and can be repeated harmlessly as often as you like.\n\nThis semantic separation is the whole point. Bertrand Meyer formulated it decades ago as Command-Query Separation: every method is either a command that changes state but returns nothing, or a query that returns something but doesn’t change state – never both. The event joins as a third kind when we want not only to order state changes but also to report on them.\n\n## The name carries the semantics\n\nWhen I come across blurry models in reviews, it is almost always down to naming. The name of a message is not decoration – it is the semantics made visible. A command in the imperative, an event in the past tense. This discipline sounds trivial, but it is the cheapest and most effective lever I know.\n\nLet’s compare the three kinds directly:\n\n- A command is in the imperative and present tense (`CreateOrder`): an intention, directed at exactly one handler, that can be rejected and can fail.\n- An event is in the past tense (`OrderCreated`): a fact, immutable and not rejectable, directed at zero to many consumers.\n- A query usually starts with `Get` or `Find` (`GetOrderSummary`): a question, free of side effects; it returns data and changes nothing.\n\nOnce a team has internalized this naming convention, the code almost reads itself. You see `CreateOrder` and know: someone wants something here that can go wrong. You see `OrderCreated` and know: this has already happened, I can count on it. The name replaces half the documentation.\n\n## The flow: from wish to fact to answer\n\nSo how do the three fit together? The typical flow is surprisingly straightforward. A command arrives and is checked by its handler. The handler validates and applies business rules. If everything checks out, it emits one or more events – the facts that follow from the successful command. These events then update the read model, the view for reading. And finally, a query reads from exactly this read model without touching the write path at all.\n\nMartin Fowler describes this as two separate paths: the changed state is routed through the command model, and the display comes from the query model. Writing goes via command to event, reading goes straight to the read model.\n\n```mermaid\nflowchart LR\n  C[Command: CreateOrder] --> H[Command Handler]\n  H -->|validate / business rules| E[Event: OrderCreated]\n  E --> RM[(Read Model)]\n  Q[Query: GetOrderSummary] --> RM\n```\n\nIn this picture, you can see the asymmetry that defines the whole approach. The write path is a process with a check: command, validation, and only then the fact. The read path is a direct query without a detour. Both share the read model, but they approach it from opposite sides – one writing via events, the other reading via queries.\n\n## Cast in code\n\nEnough theory – let’s look at what this looks like in TypeScript. The following code is illustrative, not a runnable repository; it is meant to show the semantics, not to replace a framework. Let’s start with the message types themselves, modeled as discriminated unions:\n\n```ts\ntype LineItem = { sku: string; quantity: number };\n\ntype Command =\n  | { type: 'CreateOrder'; orderId: string; customerId: string; items: LineItem[] };\n\ntype DomainEvent =\n  | { type: 'OrderCreated'; orderId: string; customerId: string; occurredAt: Date };\n\ntype Query =\n  | { type: 'GetOrderSummary'; orderId: string };\n```\n\nYou can already read the semantics from the types. The command is in the imperative. The event is in the past tense and carries an `occurredAt` – the point in time at which the fact occurred, because an event lives from its place in time. The query starts with `Get` and visibly carries nothing but a question.\n\nNow the command handler. It is the heart of the write path: it checks, decides and emits. What matters is that a command can be rejected – and that the return value is a list of events, because a command may well entail several facts:\n\n```ts\nclass RejectedCommand extends Error {}\n\nfunction handleCreateOrder(cmd: Extract<Command, { type: 'CreateOrder' }>): DomainEvent[] {\n  if (cmd.items.length === 0) {\n    throw new RejectedCommand('order needs at least one item');\n  }\n\n  return [\n    {\n      type: 'OrderCreated',\n      orderId: cmd.orderId,\n      customerId: cmd.customerId,\n      occurredAt: new Date(),\n    },\n  ];\n}\n```\n\nThis is where the semantics become concrete. The handler validates, and if the request cannot be fulfilled, it rejects it – the command fails before any fact comes into being. Only when the check passes is the event born. No event without passed validation; that is the order we want.\n\nOn the other side is the query handler. It does exactly one thing: read. No mutation, no emitted event, no side effect:\n\n```ts\ninterface OrderReadModel {\n  findSummary(orderId: string): OrderSummary;\n}\n\ntype OrderSummary = { orderId: string; itemCount: number; status: string };\n\nfunction handleGetOrderSummary(\n  q: Extract<Query, { type: 'GetOrderSummary' }>,\n  readModel: OrderReadModel,\n): OrderSummary {\n  return readModel.findSummary(q.orderId); // read only, no mutation, no events\n}\n```\n\nAnd to close the circle: how does the read model get its data in the first place? Through a projection that reacts to events. The projection takes an `OrderCreated` and updates the read view – this is how the fact flows from the write path into the view that queries later read:\n\n```ts\nfunction applyOrderCreated(\n  event: Extract<DomainEvent, { type: 'OrderCreated' }>,\n  store: Map<string, OrderSummary>,\n): void {\n  store.set(event.orderId, {\n    orderId: event.orderId,\n    itemCount: 0,\n    status: 'created',\n  });\n}\n```\n\nIf you lay these four building blocks side by side – command type, command handler, projection, query handler – you see the entire flow at a glance. The command is the wish, the handler checks it, the event is the fact, the projection carries it into the read model, and the query reads from there. Every message has its place and its meaning.\n\n## The pitfalls I keep seeing\n\nAs clear as the theory is, the mistakes in practice are just as stubborn. I keep running into four of them.\n\nThe most common one is **inverted naming**. An `OrderCreated` that is actually a command, or a `CreateOrder` that flies around as an event. As soon as that happens, the team loses the distinction between “intention that can fail” and “fact that has already occurred”. The name lies, and the model with it. When I find an event in the imperative in a review, that is my first red flag.\n\nThe second pitfall is the **query with a side effect**. A supposed query that writes on the side, increments a counter or fires an event. That breaks the freedom from side effects that Meyer demands for queries. A query has to be harmlessly repeatable – if I call it twice, nothing in the system may change. As soon as a query mutates state, it is no longer a query but a command in disguise.\n\nThe third mistake is conceptual: **confusing CQRS with Event Sourcing**. Separating command, event and query doesn’t need Event Sourcing. Nor does it necessarily need two databases or an asynchronous message bus. You can cleanly separate the three kinds of messages in a perfectly ordinary service with a single database. Greg Young sums up the relationship in one rule of thumb: you can use CQRS without Event Sourcing; if you use Event Sourcing, you practically need CQRS. Not the other way around.\n\nThe fourth pitfall is the **anemic command as a setter**. An `UpdateOrder(status = 'shipped')` reveals nothing about the domain intention. Why is the status changing? Because the product was shipped. Then the command is called `ShipProduct`, not `UpdateOrder`. A command should express a domain intention, not a generic data manipulation. The difference between `UpdateOrder` and `ShipProduct` is the difference between a form and a story.\n\n## A quick look beyond: CQS, CQRS and the costs\n\nSo that the terms don’t get mixed up, a clean distinction pays off. **CQS** – Command-Query Separation according to Meyer – is a principle at the method level: every method is either a command or a query. **CQRS** – coined by Greg Young and popularized by Fowler – lifts the same principle to the object or service level: a separate model for writing and a separate model for reading. Fowler puts it this way: you can use a different model to update information than the model you use to read information.\n\nAnd that comes with a sentence that often gets lost: CQRS is not a default. Fowler explicitly warns that CQRS adds risky complexity and is only justified when there is a clear benefit. Separate models, possibly separate stores, asynchronous consistency – you don’t want that everywhere. If you introduce CQRS everywhere by reflex, you take on more problems than you solve. I have described in more detail elsewhere why [CQRS is a domain boundary, not a framework](https://www.mikebild.dev/en/blog/cqrs-is-a-domain-boundary-not-a-framework/) – the decision for separate models belongs at the domain consistency boundary, not in every service.\n\nThe good news: the purely semantic separation of command, event and query costs almost nothing and almost always pays off. It is not CQRS. It is the conceptual hygiene that CQRS can later build on, if you need it at all. You can name commands in the imperative, events in the past tense, keep queries free of side effects – and stay in a completely conventional service while doing so. This clarity in the small is the real gain.\n\n## The common thread\n\nThe question from the beginning – does someone want something, or has something happened? – can be answered for every message as soon as it carries an honest name. A command is the wish that gets checked and can fail. An event is the fact that follows from it, immutable and not negotiable. A query is the question that reads without touching. Three messages, three meanings, three names – and the name carries the meaning outward.\n\nThis separation is not a big architecture project. It starts with discipline in naming and with refusing to let a query secretly write. You don’t have to introduce Event Sourcing or set up two databases to reap the benefits. If you consistently distinguish between `CreateOrder`, `OrderCreated` and `GetOrderSummary` in your next model, you have already done most of the work. Everything else – CQRS, projections, separate stores – is a question you ask later, and only when there is a real need. The semantic separation itself costs nothing but attention, and that attention pays off in every model.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html\n- Martin Fowler, [CQRS](https://martinfowler.com/bliki/CQRS.html) – the compact definition, including the warning about complexity.\n- Martin Fowler, [CommandQuerySeparation](https://martinfowler.com/bliki/CommandQuerySeparation.html) – Meyer’s original principle at the method level.\n- Martin Fowler, [What do you mean by “Event-Driven”?](https://martinfowler.com/articles/201701-event-driven.html) – on classifying events as messages and facts.\n- Greg Young, [CQRS](https://gregfyoung.wordpress.com/2012/03/02/cqrs/) – the origin of the object/service level and the relationship to Event Sourcing.\n- Vaughn Vernon, *Implementing Domain-Driven Design* (2013), chapter on domain events – on naming events and their meaning in the domain.\n- My own talk material “CQRS + Event Sourcing” (SlideShare) – the slides in which I go through this separation in more detail."},{"locale":"en","translation_key":"infrastructure-as-code-code-reviews","slug":"infrastructure-as-code-needs-code-reviews","title":"Infrastructure as Code Needs Code Reviews","summary":"Once infrastructure is code, a small diff decides about security, cost and the risk of outages – that is why it belongs in the same review process as application code.","tags":["Software","AWS","Cloud"],"published_at":"2019-09-24T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/infrastructure-as-code-needs-code-reviews/","audio_url":null,"audio_duration_secs":null,"text":"# Infrastructure as Code Needs Code Reviews\n\nIf you wave a wildcard permission through, you have granted it. The merge is the moment of decision, not the audit a year later in which the same line gets marked red. And this moment looks harmless: a few changed lines, a green build, a thumbs-up.\n\nThe trigger is the AWS CDK, which became stable this summer. With it, I no longer describe cloud infrastructure in a thousand lines of YAML but in TypeScript – with types, functions and abstractions. That is noticeably more productive, and that is exactly the catch.\n\nBecause a change to the infrastructure now looks like any other pull request. But what is in this inconspicuous diff is not a Feature Flag. It is an IAM policy, a security group or the memory allocation of a function that is billed per invocation. The friction of making changes has dropped – the risk per change has not. This widening gap is the real topic.\n\n## What Infrastructure as Code really changes\n\nBefore, infrastructure lived in click sessions in the console and in the heads of two or three people. Nobody could review a change, because there was no diff. Whoever opened a rule in a security group left no traceable trail. Outages turned into archaeological digs: Who changed what and when, and why?\n\nInfrastructure as Code turns this around. Every change becomes a commit, every commit is versioned, every version can be checked. The real gain is not the nicer syntax. It is that infrastructure is finally subject to the same control mechanisms as the rest of the system. Rollback becomes a `git revert`, traceability becomes a `git blame`, knowledge becomes a readable repository instead of a conversation at the bar.\n\nThe catch: review discipline did not automatically grow along with this shift. We have been reviewing application code for years with a clear eye for side effects, edge cases and security. With infrastructure code, many teams read the same diff with half their attention, because it looks short and the build is green. With IaC, though, a green build only means that synthesis ran through – not that the resulting infrastructure is secure, affordable and can be rolled back.\n\n## The diff I really have to review\n\nCDK works with constructs: building blocks that encapsulate one or more CloudFormation resources along with sensible defaults. That is the strength and the trap at the same time. A high-level construct can create a dozen resources from three lines of TypeScript – a function, a log group, an execution role, a few permissions. The TypeScript diff shows me the intent. It does not show what actually gets provisioned.\n\nThe real review artifact is therefore the `cdk diff`, not the code alone: the comparison of the current and planned CloudFormation state. Only there does it become visible that an inconspicuous line creates a role with a wildcard permission or opens a security group.\n\n```ts\nconst handler = new lambda.Function(this, \"ApiHandler\", {\n  runtime: lambda.Runtime.NODEJS_10_X,\n  handler: \"index.handler\",\n  code: lambda.Code.fromAsset(\"dist/api\")\n});\n```\n\nThese four lines are deliberately small. But they create more than a function: a log group, an execution role with basic permissions and the links between them. The review question is not “does the handler run?” but “which permissions does this role get, how long do the logs stay around, and what does an invocation cost?” A good construct reduces repetition and encapsulates good defaults – but it must not hide which resources, permissions and costs arise. That is exactly the boundary I check in the review.\n\n## The most expensive line is often a permission\n\nThe classic mistake is the convenient permission. It works right away if I give a function broad access, and nobody notices in the demo that the boundary is drawn too wide.\n\n```ts\n// convenient, and wrong\nbucket.grantReadWrite(handler);\ntable.grant(handler, \"dynamodb:*\");\n```\n\nThat runs. It is also the kind of line that gets marked red in a security audit a year later. Least privilege is not a chore for later. The decision about it is made in the review, at the moment of the merge – after that, the role is in operation, and “I will tighten it later” rarely turns into anything. That is why I ask concretely in the review: Does this function really need write permissions, or only read? Does it need the whole table or one action? Every wildcard is a claim that needs evidence.\n\nThe pattern repeats with public buckets, open security groups and shared secrets. None of these mistakes is technically difficult. All of them are cheap to prevent if someone reads the diff with the right question – and expensive if nobody does.\n\n## Cost belongs in the review\n\nWith serverless infrastructure, the bill is a direct result of lines of code. A function’s memory size, provisioned concurrency, a NAT gateway, an instance type chosen too large, a retention setting that keeps logs forever – all of these are one-line changes with an ongoing monthly consequence.\n\nI have seen a single changed line double a team’s cloud bill because a default was adopted without thinking. The diff was inconspicuous, the build green, the review a formality. Cost transparency in the review does not mean predicting every bill. It means asking the question at all: What does this line change about the running costs – one-time, per invocation or per month? Serverless shifts operational work; it does not remove it. Permissions, logs, cold starts, timeouts, cost and the ability to roll back still have to be designed explicitly.\n\n## What I look for in an infrastructure review\n\nAcross the individual examples, I always check the same boundaries. Is the permission as narrow as possible, or does the diff open more than the task needs? How big is the blast radius if this resource is misconfigured – does it hit one service or the entire account? Is the change idempotent and reversible, or does a second deployment create a different state than the first? What happens on a failed deployment – is there a clean way back, or does someone have to repair things by hand at night? And does operations produce enough signals – logs, metrics, alarms – to explain an error later at all?\n\nThese questions seem dry. But they are the difference between a system that looks clean in the demo and one that holds up under repetition, partial failures, old data and wrong permissions. The happy path is never the problem. Infrastructure gets interesting exactly where something goes wrong.\n\n## The trade-off of abstraction\n\nCDK offers constructs on several levels: thin wrappers around individual CloudFormation resources, convenient building blocks with good defaults and entire patterns made of several resources. The higher the level, the less code I write – and the more decisions I delegate to defaults I do not see.\n\nThat is not an argument against abstraction. It is an argument for choosing the level of abstraction deliberately and making it visible in the review. A high-level construct is a good trade if its defaults match my requirements for security and cost. It is a bad trade if I have never checked its defaults and get to know them by surprise in production. The methodical consequence is simple: the `cdk diff` belongs in every pull request, so that the level at which I delegate does not stay implicit.\n\n## Where the review belongs in the pipeline\n\n```mermaid\nflowchart LR\n  Source --> Synth\n  Synth --> Diff[\"cdk diff\"]\n  Diff --> Review[\"Review<br/>Permissions · Cost · Rollback\"]\n  Review --> Deploy\n  Deploy --> Observe\n```\n\nThe diff is not a formality at the end. It is the place where the review takes hold: before the deployment, as a visible artifact in the pull request. This moves the error from operations into the review phase – and that is the whole point. A configuration error that stands out in the diff costs ten minutes of discussion. The same error in production costs an incident, a night shift and trust.\n\n## What the machine checks, what the human checks\n\nA good review process does not waste human attention on things a rule can handle. Much of an infrastructure review is mechanical and can be automated: open security groups, unencrypted buckets, wildcard policies, missing log retention. Static analysis of the synthesized CloudFormation template – for example with cfn_nag – catches this class of errors in the pipeline before a human even looks at it.\n\nBecause the infrastructure is now code, I can also pin down assumptions as tests. CDK allows assertions against the synthesized template: “this role must not contain a wildcard action,” “this bucket is not public.” Such a test fails as soon as someone loosens the boundary – not only in the audit a year later. It is the same reflex I know from application code: what was right once and has to stay right becomes a test, not a mnemonic.\n\nAutomation does not take the work away from the human review; it focuses it. When the machine enforces the same rules every time, the human can concentrate on what no rule can decide: Is this level of abstraction the right one? Is the blast radius acceptable? Does the cost consequence fit the task? These questions are exactly why the review exists at all.\n\n## The mistake of taking the tool for the solution\n\nA tool does not create good architecture; it can only express it. CDK is not a security concept. CloudFormation is not a permission model. Serverless is not an operations strategy. These tools make it easier to draw good boundaries – they do not draw them by themselves. If you believe that switching to Infrastructure as Code settles the security and cost question, you have only changed the medium in which the same decisions are now made faster and less visibly.\n\nThat is exactly why Infrastructure as Code needs the review more, not less. The low friction that makes the whole approach so attractive is at the same time its biggest risk. Changing has become cheap – understanding has to stay.\n\n## What it gives the team\n\nThe benefit is measurable, even if it shows up as an absence. Errors that used to appear as incidents now show up as comments in a pull request. The cloud bill stays predictable, because cost changes are named instead of discovered. Onboarding gets shorter, because new people read the infrastructure instead of guessing. And lead time even drops: there is not less checking; there is less to repair.\n\nA review costs minutes. An open bucket, a wildcard role or a doubled NAT gateway costs days and, in the worst case, customer data. Infrastructure as Code has finally brought infrastructure into a format in which this trade pays off. It would be a shame to skip the review as the only step that turns a diff into a decision.\n\n## Further reading\n\n- AWS CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/home.html\n- AWS CDK Constructs: https://docs.aws.amazon.com/cdk/latest/guide/constructs.html\n\nThe sources help you double-check platform behavior and defaults. But the actual decision is not in the docs. It is in the concrete diff – and it depends on someone reading it before it goes live."},{"locale":"en","translation_key":"secrets-im-build","slug":"secrets-in-the-build-are-product-decisions","title":"Secrets in the Build Are Product Decisions","summary":"Secrets in the build are a trust problem: who may see, store and deploy what, and when?","tags":["Software","DevOps","Architecture"],"published_at":"2019-09-12T10:00:00+00:00","updated_at":"2026-07-13T08:38:07.947838+00:00","url":"https://www.mikebild.dev/en/blog/secrets-in-the-build-are-product-decisions/","audio_url":null,"audio_duration_secs":null,"text":"# Secrets in the Build Are Product Decisions\n\n```console\n$ docker history --no-trunc myapp:staging\nIMAGE      CREATED BY\n<missing>  /bin/sh -c #(nop) COPY file:3f2a… in /app/.env\n<missing>  /bin/sh -c #(nop) ENV DATABASE_URL=postgres://app:S3cr3t@db.prod.internal:5432/app\n```\n\nTwo lines of layer metadata, readable by anyone with pull rights on the registry. In one project, half the configuration lived in an `.env` file that was copied into the image via `COPY`. That went well for months, until someone pulled the image from the registry, ran `docker history` and read the database URL including the password in plain text. No attack, no exotic bug – just an artifact that knew more than it was allowed to.\n\nThe mistake wasn’t forgotten encryption. The mistake was an unspoken boundary: the team had never decided whether a build artifact may know secrets. It had just copied a tutorial. And that is exactly where this stops being an operations question. Where a token, a password or a certificate is created, stored and injected into an artifact determines who may deliver without checking with anyone and who has to wait. That decides a team’s speed, friction and error rate – long before any tool has been chosen.\n\n## The real question is trust, not encryption\n\nEncryption solves a narrow problem: protecting data at rest and in transit. It doesn’t answer the question that gets expensive in everyday work – who in the process gets their hands on the secret at all. A KMS-encrypted value that every CI job may decrypt is convenient and still an open boundary.\n\nBefore I choose a tool, I clarify four questions. Which component is authoritative for the value? Who may read it, and in which environment? When is it read – at build time or at runtime? And what has to be traceable later if it is compromised? These answers decide rotation and blast radius. Encryption alone answers none of them.\n\n## Build time and runtime are two different trust zones\n\nThe most important boundary runs between build and runtime. A build produces an artifact that travels through several environments and lands in a registry that more people often have access to than you’d think. Everything baked into this artifact is therefore exactly as confidential as the registry – and no more.\n\nThe classic anti-pattern looks harmless:\n\n```dockerfile\n# ANTI-PATTERN: the secret becomes part of a shared, promotable artifact\nCOPY .env /app/.env\n```\n\n```dockerfile\n# ANTI-PATTERN: build args stay recoverable via `docker history`\nARG NPM_TOKEN\nRUN echo \"//registry.npmjs.org/:_authToken=${NPM_TOKEN}\" > .npmrc \\\n  && npm ci \\\n  && rm .npmrc\n```\n\nThe `rm` fakes security. The token remains visible in the layer metadata, and the `.env` travels along as a layer of its own. Both survive every later `docker run` in every environment. The real problem is not the command but the mixed trust zone: an artifact that is supposed to be identical in staging and production suddenly carries production secrets.\n\nThe architectural answer is a clean separation. The build produces an environment-neutral artifact without secrets. Configuration is only added at runtime, injected from a source that is separate per environment. A multi-stage build makes this intention visible in the code:\n\n```dockerfile\n# build stage produces an artifact that knows nothing about any environment\nFROM node:12 AS build\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci\nCOPY . .\nRUN npm run build\n\n# runtime stage receives config from the environment, never from the image\nFROM node:12-slim\nWORKDIR /app\nCOPY --from=build /app/dist ./dist\nCMD [\"node\", \"dist/server.js\"]\n```\n\nThe same thinking applies to build secrets the build really needs – a private registry token, for example. They come in via a secret mount that isn’t persisted in the final image, instead of via an `ARG` that stays in the history. The principle remains: a secret that only the build needs must not reach the runtime artifact.\n\n## Parameter Store as an interface, not a database\n\nOnce the separation is in place, Parameter Store becomes interesting. Its value comes from the structure it enforces, not from the fact that it stores values. The hierarchical path is the real lever: it encodes the environment, and the environment is the boundary where permissions take hold.\n\n```bash\n# resolve runtime config just-in-time, scoped by environment path\naws ssm get-parameters-by-path \\\n  --path \"/myapp/production/\" \\\n  --with-decryption \\\n  --query \"Parameters[].{Name:Name,Value:Value}\"\n```\n\nThe path `/myapp/production/` is more than cosmetics. It makes it possible to express least privilege cleanly: a deploy job for staging gets an IAM policy that points exactly at `staging/*` and can’t even read production.\n\n```json\n{\n  \"Effect\": \"Allow\",\n  \"Action\": \"ssm:GetParametersByPath\",\n  \"Resource\": \"arn:aws:ssm:eu-central-1:123456789012:parameter/myapp/staging/*\"\n}\n```\n\nThis anchors the domain intention in the infrastructure instead of in a sentence in a wiki. The value is resolved at runtime and never written into the repo or the image:\n\n```bash\n#!/usr/bin/env bash\nset -euo pipefail\n# inject secrets at container start, keep them out of the image and the repo\nexport DATABASE_URL=\"$(aws ssm get-parameter \\\n  --name \"/myapp/production/database-url\" \\\n  --with-decryption --query \"Parameter.Value\" --output text)\"\nexec node dist/server.js\n```\n\nWhether Parameter Store, Secrets Manager or a vault sits behind it is the smaller question. The bigger one is that access is separated per environment, auditable and rotatable. The tool expresses the boundary – it doesn’t create it.\n\n## Sketch\n\n```mermaid\nflowchart LR\n  Repo[Code<br/>without secrets] --> Build[Build<br/>reproducible artifact]\n  Build --> Registry[Artifact<br/>same for every environment]\n  Store[Parameter Store<br/>separate per environment] --> Runtime\n  Registry --> Runtime[Runtime<br/>injects config just-in-time]\n```\n\nThe sketch shows the one statement that matters: the left path is identical everywhere, the secret path comes separately and is only added at the very right. Exactly at this junction it is decided whether a team can deliver fast and safely or trades one off against the other.\n\n## The trade-offs you really weigh\n\nNo approach is free. An environment-neutral artifact plus runtime injection needs a working secret source in every environment and makes container startup depend on another service. If Parameter Store fails, the service doesn’t start – that is a deliberate price for the boundary, not an oversight. You cushion it with caching and clear error messages, not by baking secrets back in after all.\n\nConversely, the convenience of the `.env` in the image is real: one artifact, no dependency at startup, easy to reproduce locally. The price for it only comes due later – at rotation, at a leak, at the question of who had the staging image with production credentials in their hands. Architecture here means moving the price to a place where you can control it, instead of shifting it into a later incident.\n\nThe second trade-off concerns centralization. A central secret source simplifies rotation and auditing but itself becomes a critical path and a coveted boundary. That’s why the path and IAM structure is not a formality: it is the difference between “one service knows everything” and “every service knows exactly its own”. The actual product decision lies between the two.\n\n## The failure path decides, not the happy path\n\nA secrets architecture is only robust once the failure path is described. In demo mode, every approach looks clean. It gets interesting exactly where systems normally break.\n\nRotation is the most honest test. Can I change a compromised value without rebuilding an image and promoting it through all environments? With runtime injection, that is a parameter update plus a restart. With a baked-in secret, it is a full release cycle under time pressure – the worst moment for a long road.\n\nRollback is the second test. With clean separation, a rolled-back image only brings back old code, not old secrets. If you mix the two, rolling back the code also silently rolls back expired or rotated credentials. And third, the audit: if a value leaks, I want to reconstruct which job read it when. A central store with access logs answers that; a file in a layer doesn’t. These questions seem dry, but they are the difference between a demo and operations.\n\n## The business outcome is speed with controlled risk\n\nThe reason I treat secrets as a product decision is measurable. When a team no longer has to pass secrets along manually, a whole class of waiting time disappears. A developer deploys to staging without someone from the ops team copying a password via chat – the IAM policy allows exactly this path and nothing beyond it. That shortens the cycle from idea to running change and at the same time lowers the risk, because access is narrowly scoped. Speed and security are not in conflict here; the right boundary delivers both.\n\nLess friction also comes from the boundary living in the code and not in one person’s head. New team members read from the path structure and the policy what is allowed instead of having to ask. And quality goes up, because the most expensive mistake – a secret in a shared artifact – structurally can no longer happen, instead of only being prevented by discipline. That is exactly what I mean by developer productivity: not typing faster, but waiting less often and cleaning up less often.\n\nThe effect is not a soft promise; it can be observed. I measure it by three numbers: the time from “the password has to be changed” to “changed and in operation”, the number of manual handoffs per release, and how many environments a single credential can read. Each of these numbers drops once the build-runtime boundary is in place – and when in doubt, each is more convincing than the claim that things are now more secure.\n\n## Typical mistakes\n\nThe first mistake is confusing the tool with the solution. A secret store is not an architecture, KMS is not an access boundary, and a `--build-arg` is not confidentiality. These tools can express good boundaries, but they don’t create them automatically. If you introduce the store without drawing the build-runtime boundary, you have only moved the file to a different place.\n\nThe second mistake is overestimating the happy path. Many setups look clean on the first deploy and only show their weakness at the first urgent rotation. The third is treating everything as equally confidential. A feature flag configuration and a database password need different boundaries; if you throw both into the same pot, you make the harmless case expensive and the critical case convenient.\n\n## What I check\n\nThree checks are usually enough for me. First: is a build artifact environment-neutral, or does it know secrets? A `docker history` and a look at the layers answer that in a minute. Second: is access separated per environment, so that a staging job can’t read production? Third: can I rotate a secret without rebuilding, and trace access after the fact?\n\nIf one of these questions ends with a no, part of the architecture is still missing – not another tool, but a deliberately drawn boundary. I wouldn’t make a big initiative out of it but start with a small, verifiable result: a multi-stage Dockerfile, an IAM policy with path scope, a startup script that resolves the value just-in-time. Concrete enough that another developer can meaningfully disagree. Agreement is good, but disagreement often reveals the hidden assumption.\n\n## Conclusion\n\nStoring a secret safely is the smaller half of the work. The bigger half is the reasoning for why the boundary between build and runtime runs exactly there. What matters is the concrete risk, the permitted access and the question of whether a compromised value can be rotated independently of the artifact. The name of the secret store comes after that."},{"locale":"en","translation_key":"product-discovery-vor-der-ersten-zeile","slug":"product-discovery-before-the-first-line-of-code","title":"Product Discovery Before the First Line of Code","summary":"Discovery lowers the risk of efficiently building the wrong thing. I show a continuous track that tests assumptions before they tie up expensive delivery – not a phase before development.","tags":["Software","Product"],"published_at":"2019-06-26T10:00:00+00:00","updated_at":"2026-07-14T20:59:37.10998+00:00","url":"https://www.mikebild.dev/en/blog/product-discovery-before-the-first-line-of-code/","audio_url":null,"audio_duration_secs":null,"text":"The most expensive lines of code I have seen in projects were technically flawless. Cleanly tested, elegantly structured, shipped several times a day in a continuous delivery pipeline. The only problem: they solved a problem nobody had. Half a year of development capacity, a flawless feature, and at the first real contact with users, the underlying assumption collapsed. Clean craftsmanship simply says nothing about whether anyone gets anything out of it in the end. No pipeline asks that question.\n\nThis is exactly where product discovery comes in. And I don’t mean an upfront analysis phase in which documents are produced for six weeks before anyone is allowed to touch code. I mean a parallel, continuous track. An assumption is confronted with the cheapest sensible experiment before the team builds it out as a feature. That is what this article is about.\n\n## Discovery and delivery are two tracks, not phases\n\nThe most common reasoning error is to see discovery as a preliminary stage. First think, then build. That is waterfall in new clothes. The approach that Marty Cagan and Jeff Patton popularized under the term dual-track agile means something else: two tracks that run side by side permanently. The discovery track clarifies *what* should be built. The delivery track builds it solidly. Both run in every sprint, not one after the other.\n\nThe trick lies in the size of the handoff. Before a team commits a large or hard-to-reverse undertaking to delivery, the riskiest assumption behind it should have been tested. Small technical spikes and thin, reversible slices may go into delivery earlier and generate evidence themselves. Dual track isn’t a hard lock between thinking and building.\n\n```mermaid\nflowchart LR\n  subgraph Discovery\n    A[Idea] --> B[Assumption]\n    B --> C[Experiment]\n    C --> D[Validated item]\n  end\n  subgraph Delivery\n    E[Build] --> F[Test]\n    F --> G[Release]\n  end\n  D -->|only validated work<br/>enters delivery| E\n```\n\nThe arrow in the middle is the real message. It is a filter. Everything that passes through it has passed a test. Everything that fails in the discovery track has never burdened a development team. That is the lever: a discarded experiment costs hours, a discarded feature costs months.\n\nJust as important is who does discovery. It isn’t a task that an upstream analysis department completes and then hands over as a finished specification. Teams that do this well put product management, design, and engineering on the discovery track together – the trio Marty Cagan describes. The developer who assesses feasibility hears in the same user interview why a feature is wanted in the first place. The designer who builds a prototype understands the technical limits firsthand. This shared responsibility is why discovery stays fast: decisions are made where the knowledge sits, without the detour through handoff documents. If you delegate discovery to a single role, you bring back the waterfall dynamic that the dual-track approach is meant to avoid.\n\n## The four big risks discovery addresses\n\nWhen you ask *why* a particular feature should be built, the answer in discussions usually covers only a single dimension. In the second edition of *INSPIRED*, Cagan named four classes of risk that any serious discovery has to probe:\n\nValue risk asks whether users want it at all and whether they will switch or pay for it. Usability risk asks whether they can use it. Feasibility risk asks whether we can build it with our time, our data, and our technology. And viability risk asks whether it fits the business – legally, economically, strategically.\n\nFeasibility attracts attention because it is the question developers most like to answer. “Can we build it?” can almost always be answered with “yes.” But the expensive failures sit in value and viability risk. Discovery forces you to look at all four before the first story is sliced.\n\n## Making assumptions visible and prioritizable\n\nThe most practical step is both banal and effective: write down the assumptions. Every product idea is a stack of unspoken bets. “Users want to configure their reports themselves.” “The payment API meets our latency requirement.” “Sales can sell this without training.” As long as these sentences stay in people’s heads, you can’t test them and can’t prioritize them.\n\nWith assumptions mapping, David J. Bland established a simple tool: a matrix with two axes. One axis measures how important an assumption is – does the whole undertaking fall apart if it is wrong? The other measures how much evidence we already have. The top-right quadrant, important and barely supported, gets tested first. That is the riskiest assumption, and it deserves the first test.\n\n```mermaid\nquadrantChart\n  title Assumptions Map\n  x-axis Low evidence --> High evidence\n  y-axis Low importance --> High importance\n  quadrant-1 Test first\n  quadrant-2 Keep as leap of faith\n  quadrant-3 Ignore for now\n  quadrant-4 Already known\n  Users self-configure reports: [0.2, 0.9]\n  Payment API meets latency SLA: [0.35, 0.85]\n  Sales can sell without training: [0.6, 0.4]\n  Login flow is usable: [0.8, 0.3]\n```\n\nI store this state versioned in the repository instead of pinning it to a whiteboard. An assumption register next to the code makes the bets part of the project and not part of a forgotten workshop:\n\n```yaml\n# assumptions.yaml — reviewed before any story enters delivery\nassumptions:\n  - id: A-1\n    statement: \"Users will self-configure their reports instead of asking support\"\n    type: desirability\n    importance: high\n    evidence: low\n    test: landing-page\n    kill_criterion: \"signup-to-config rate below 20% after 200 visitors\"\n  - id: A-2\n    statement: \"The payment API stays under our latency budget at peak load\"\n    type: feasibility\n    importance: high\n    evidence: low\n    test: spike\n    kill_criterion: \"p95 response time above 200ms in a load test\"\n  - id: A-3\n    statement: \"Sales can close the feature without extra training\"\n    type: viability\n    importance: medium\n    evidence: low\n    test: interview\n    kill_criterion: \"3 of 5 reps ask for a dedicated enablement session\"\n```\n\nFor a confirmatory test, `kill_criterion` is the crucial field. If you only decide after the test what a good result would have been, you easily find an explanation for why your favorite idea won after all. Exploratory discovery may start more openly; as soon as a concrete hypothesis is to be decided, the criterion belongs on record beforehand.\n\n## Progress means validated learning, not shipped features\n\nIn *The Lean Startup*, Eric Ries coined the term I still orient myself by today: validated learning. Progress is measured by assumptions we have settled reliably, not by features in a release. The build-measure-learn loop revolves around exactly this question: what is the fastest way to test a bet?\n\nThis is where the biggest misunderstanding around the MVP lurks. A minimum viable product isn’t a cheap, half-finished product. It is the experiment with the greatest learning yield per effort. Very often, it contains no code at all. A landing page that advertises a feature that doesn’t exist yet and counts sign-ups. A concierge approach, in which a human manually does what software is supposed to do later. A demo video that measures the reaction. For assumption A-1 above, the landing page is faster and more honest than any implementation. It answers the value question in days instead of months.\n\nIf the result clearly speaks against the assumption, the right reaction isn’t to build anyway. It is the pivot – change direction and go after a different bet. Teams find that hard, because discarded ideas feel like failure. They are the opposite. Every assumption that is knocked over early is capital saved.\n\n## Technical assumptions need testing too\n\nDiscovery isn’t purely a product or UX topic. Feasibility risk is often the quietest and most expensive bet. “The payment API meets our latency” is a technical assumption that you can make tangible before a feature builds on it. I phrase assumptions like these as executable tests – a Fitness Function in the sense of *Building Evolutionary Architectures*. It makes a quality goal measurable and repeatable:\n\n```typescript\n// fitness function — runs the riskiest technical assumption as a test\nimport { measureP95 } from \"./load-harness\";\n\nconst SLA_MS = 200;\n\ntest(\"checkout endpoint stays under the latency budget at peak load\", async () => {\n  const p95 = await measureP95({\n    endpoint: \"/api/checkout\",\n    concurrentUsers: 500,\n    durationSeconds: 60,\n  });\n\n  expect(p95).toBeLessThan(SLA_MS);\n});\n```\n\nThe value of this test shows at the moment it turns red before a feature goes live. Then we know: the technical assumption doesn’t hold. Better now than in production. The same way of thinking applies to failure behavior. If a feature depends on an external service, the assumption “the service is available” is a bet that you defuse with stability patterns such as a circuit breaker from Michael Nygard’s *Release It!* – and with consumer-driven contract tests that check whether two services still understand each other before the break shows up in production.\n\n## Why efficiency alone doesn’t protect you\n\nThe obvious objection is: “But we already ship quickly and reliably.” And yes, that is valuable. The book *Accelerate* by Nicole Forsgren, Jez Humble, and Gene Kim used four metrics to show how delivery quality can be measured: Deployment Frequency, Lead Time for Changes, Change Failure Rate, and Mean Time to Restore. Teams that are strong here ship often, fast, and with few failures.\n\nBut none of these metrics measures whether the right thing is being built. They measure how well the delivery track runs. A team with top scores can ship features nobody needs at a high frequency. Speed at building the wrong thing is still waste – just faster. That is why both tracks belong together: discovery makes sure we work on the right thing, delivery excellence makes sure we build it well. If you only optimize the second half, you end up building yourself the most efficient way to burn money.\n\nThat is the economic core. Discovery isn’t an additional process layer that slows down cycles. It shortens the cycle that really counts: from idea to validated insight. A landing page test takes days. A misguided feature takes months and still fails. Discovery trades the expensive, late feedback of the market for cheap, early feedback in an experiment.\n\n## What this looks like day to day\n\nI boil the method down to a few habits that don’t need a heavy framework. Before every larger undertaking, the assumptions are written down and placed on the two-axis matrix. The riskiest assumption gets a suitable experiment; a confirmatory test gets a decision criterion defined in advance. Technical bets are tested as a Fitness Function or a spike, not nodded through on gut feeling. As long as the biggest uncertainty is open, the delivery investment stays small and reversible.\n\nThat sounds like more work up front. In practice, it can shorten big detours, but it doesn’t guarantee that. The teams I work with this way argue less about opinions and more about evidence. A landing page with two hundred visitors can deliver a signal if the target group, traffic source, and expected effect fit; it replaces neither proper sample design nor qualitative follow-up questions. What disappears is part of the unproductive friction between opinions without data. The productive friction around the problem remains.\n\n## Conclusion\n\nThe first line of production code increases the investment, but it isn’t an irreversible border crossing. Product discovery keeps the riskiest decisions small until there is enough evidence for the next stake. Discovery and delivery run in parallel: one track clarifies what to build, the other delivers small, reliable steps and can itself be part of the experiment.\n\nThe common thread is simple: you can do everything right technically and still deliver the wrong thing. Efficiency in delivery is necessary, but it is no substitute for the question of whether we are working on the right thing. If you make assumptions visible, test the riskiest one first, and set a decision criterion for confirmatory tests, you improve your chances of shorter learning cycles and well-founded decisions. Discovery remains work; its value lies in not confusing expensive certainty with unsupported confidence.\n\n## Further reading\n\n- Marty Cagan: *INSPIRED* (2nd edition, 2017) and the “four big risks” at svpg.com/four-big-risks\n- Jeff Patton and Marty Cagan on dual-track agile, jpattonassociates.com and svpg.com\n- Eric Ries: *The Lean Startup* (2011), build-measure-learn and MVP, theleanstartup.com\n- David J. Bland: assumptions mapping, precoil.com and strategyzer.com\n- Nicole Forsgren, Jez Humble, Gene Kim: *Accelerate* (2018)\n- Neal Ford, Rebecca Parsons, Patrick Kua: *Building Evolutionary Architectures* (2017)\n- Michael Nygard: *Release It!* on circuit breakers and stability patterns"},{"locale":"en","translation_key":"cqrs-fachliche-grenze-kein-framework","slug":"cqrs-is-a-domain-boundary-not-a-framework","title":"CQRS Is a Domain Boundary, Not a Framework","summary":"CQRS separates the model for writing from the model for reading – a domain decision, not an installable framework. When the boundary pays off, how to start small and which mix-ups get expensive.","tags":["Software","Architecture"],"published_at":"2019-06-25T10:00:00+00:00","updated_at":"2026-07-13T08:37:17.581144+00:00","url":"https://www.mikebild.dev/en/blog/cqrs-is-a-domain-boundary-not-a-framework/","audio_url":null,"audio_duration_secs":null,"text":"Every application asks its data two questions: What should change? And what should be displayed? Most systems answer both with the same model – the same entities, the same mapping, the same objects. CQRS answers them with two.\n\nStill, the most common follow-up question about the acronym – Command Query Responsibility Segregation – is about tools: Which library, which package? You’ll look for that in vain. The boundary between the write model and the read model runs through the domain, not through the dependency tree. What CQRS is, what it explicitly isn’t, when the separation pays off and where the most expensive mistakes lie – that’s what this article is about. The result is less spectacular than the acronym promises, and that’s exactly the good news.\n\n## Where the term comes from\n\nCQRS stands for Command Query Responsibility Segregation. The core is a single idea: you use a different model to change information than the model you use to read it. What is a single conceptual model in classic systems – the same entities you write and read with – is deliberately split into two separate models. One for commands, that is, for intentions and changes. One for queries, that is, for views and queries.\n\nMartin Fowler sums up the reasoning: for many problems, particularly in more complicated domains, a shared conceptual model for commands and queries leads to a model that does both jobs worse than two specialized models would. Fowler himself first heard the term from Greg Young, who coined and fleshed out CQRS around 2010.\n\nWhat matters is the distinction from an older principle that CQRS is often confused with: Command Query Separation, CQS for short, by Bertrand Meyer. CQS separates at the method level – a method is either a command that changes state and returns nothing, or a query that returns a value without changing state. CQRS lifts exactly this principle to the architecture level: no longer two kinds of methods, but two separate object models. Conceptually, CQRS builds on CQS, but it works at a much coarser grain.\n\n## The two sides have a different shape\n\nThe write side and the read side don’t just have different jobs; they have a different shape. That’s not a cosmetic observation but the actual reason for the separation.\n\nThe write side works with a rich domain model. This is where the invariants live, the domain rules that decide whether a change is allowed at all. A command is the expression of a domain intention – phrased imperatively, nameable, rejectable. `DeactivateInventoryItem` isn’t a record update but a statement: “I want to deactivate this item.” That fits perfectly with task-based UIs, in which users express intentions instead of filling in form fields.\n\nThe read side, by contrast, doesn’t want to decide anything. It wants to display. Its natural shape is flat DTOs tailored to presentation – often a direct projection of what appears on screen. Rules, invariants, behavior: the read side needs none of that. You only force it into a rich domain model because that model happens to exist already.\n\nThis is exactly where CQRS comes in. Instead of squeezing both sides into one model that serves neither of them well, you give each side the shape it deserves.\n\n```mermaid\nflowchart LR\n    Client -->|Command| CommandHandler\n    CommandHandler --> WriteModel\n    WriteModel --> Store[(Store)]\n    Client -->|Query| QueryService\n    QueryService --> ReadModel\n    ReadModel --> Store\n```\n\nNote: both paths can use the same store. More on that in a moment – it’s more important than it looks.\n\n## A look at the write side\n\nIllustrative, in TypeScript. The write side receives a command, loads the rich write model, lets it enforce the domain rule and saves.\n\n```ts\ninterface DeactivateInventoryItem {\n  itemId: string;\n  reason: string;\n}\n\nclass InventoryCommandHandler {\n  constructor(private readonly repo: InventoryItemRepository) {}\n\n  handle(cmd: DeactivateInventoryItem): void {\n    const item = this.repo.findById(cmd.itemId); // rich write model\n    item.deactivate(cmd.reason);                 // domain rule enforced here\n    this.repo.save(item);\n  }\n}\n```\n\nThe interesting part is in the middle line. `item.deactivate(cmd.reason)` is where the domain logic sits. Whether an item may be deactivated, whether a reason is mandatory, whether an already deactivated item rejects the command: the domain object decides that, not the handler. The command handler is deliberately thin. It orchestrates; it doesn’t decide.\n\n## And a look at the read side\n\nThe read side completely ignores this rich model. It queries a view optimized for display and returns a flat DTO.\n\n```ts\ninterface InventoryListItemDto {\n  id: string;\n  name: string;\n  isActive: boolean;\n}\n\nclass InventoryQueryService {\n  constructor(private readonly readDb: ReadDatabase) {}\n\n  listActiveItems(): InventoryListItemDto[] {\n    return this.readDb.query(\n      \"SELECT id, name, is_active FROM inventory_view WHERE is_active = true\",\n    );\n  }\n}\n```\n\nNo repository, no domain object, no invariant. Just a query against a view that delivers exactly what the list needs. You could object that raw SQL sits directly in a service here – for the read side, that’s often exactly right. There is nothing to protect, no rule to uphold. The detour through a rich model would be pure ceremony.\n\nThe point it all comes down to: these two classes don’t know each other. They share no common model. They are two separate answers to two separate questions. That’s CQRS.\n\n## Start small – one store is enough\n\nAnd now comes the part that surprises most people. Nothing in the two examples above requires two databases. `InventoryItemRepository` on the write side and `readDb` on the read side can point to the same database. Fowler puts it unmistakably: the models can share the same data store – the database then acts as the communication between the two models.\n\nThis means: you can practice CQRS without introducing a single additional store. A rich write model that works against the tables. A view that the read side queries directly. Both in the same database. You get the domain separation without buying into a second data store and its consequences.\n\nOn one project, we had put off the pattern for years because it was considered unaffordable – too much infrastructure, too much operations. The concern was based on a mix-up: CQRS was equated with one specific, elaborate expansion stage of CQRS. Separating the models is cheap. What costs money is separate stores, and they are optional.\n\n## What CQRS is – and what it isn’t\n\nBecause so many half-truths gather around the term, here is a clear sorting. CQRS is:\n\n- the domain separation of the write model and the read model,\n- a pattern for selected bounded contexts,\n- combinable with Event Sourcing when the domain justifies it,\n- practicable with a single store from the start.\n\nCQRS is not:\n\n- a framework or a library,\n- a synonym for Event Sourcing,\n- an obligation to have two databases,\n- a system-wide architecture standard that you roll out everywhere.\n\nMost of the trouble I see in reviews hinges on this second list.\n\n## The three most expensive mix-ups\n\nThe first is trying to use CQRS everywhere. It’s a minority case, not a default. Fowler explicitly warns that for most systems CQRS adds risky complexity and that you should be very cautious about using it. The separation belongs in a single bounded context where the domain justifies it – not in every module, not in every entity. If you roll out CQRS system-wide, you pay the cost of the separation everywhere and reap the benefit only in the few places where the models really drift apart.\n\nThe second is confusing CQRS with Event Sourcing. That’s the most common mix-up of all, and I understand where it comes from – the two almost always appear together in talks and examples. But they are independent patterns. Event Sourcing is a decision about persistence: instead of storing the current state, you store the sequence of events that led to it. CQRS is a decision about models: writing and reading get separate models. You can have either without the other. Vaughn Vernon’s IDDD samples do show contexts that combine Event Sourcing and CQRS – but even there, it remains a deliberate combination of two patterns, not a definition in which one contains the other. If you say CQRS and mean Event Sourcing, you’ll constantly talk past each other in discussions.\n\nThe third is introducing two databases too early. Separate read and write stores are an optional, later optimization – usually driven by asymmetric load, when you want to scale the read side and the write side independently. If you introduce them too early, you take on two costs before any need has been proven: the synchronization effort between the stores and, more seriously, eventual consistency. From the moment the read store lags behind the write store, users may see data that is already outdated. That’s a domain problem, not a technical detail – and you should only take it on when you have a concrete reason for it.\n\nThis is what that expansion stage would look like – one you deliberately take only when the load demands it:\n\n```mermaid\nflowchart LR\n    CommandHandler --> WriteModel\n    WriteModel --> WriteStore[(Write Store)]\n    WriteStore -.->|projection<br/>eventual consistency| ReadStore[(Read Store)]\n    QueryService --> ReadStore\n```\n\nThe dashed arrow is the price. There is now a projection between the write store and the read store, and with it a delay. As long as this arrow isn’t needed, it shouldn’t exist.\n\n## When the boundary really pays off\n\nAfter all these warnings, the constructive side: there are situations in which CQRS is the right answer. I see essentially three.\n\nThe first is complex domains in which a shared model serves neither side well. When the write model is barely queryable because of all its invariants and behavior, and the read side painfully works its way through this model to produce simple lists, both are fighting the same structure. The separation frees both.\n\nThe second is asymmetric load. Many systems read orders of magnitude more often than they write. Separate models – and, in the expansion stage, separate stores – let you scale the read side independently without touching the write side.\n\nThe third is task-based UIs. When the UI thinks in intentions anyway – “deactivate item,” “cancel order” – instead of in CRUD forms, the command side of CQRS is already in the air. You just have to name it.\n\nAll three criteria have the same origin: the structure follows from the domain, not from the wish for a modern diagram. CQRS isn’t a goal. It’s an answer – and only right where the domain asks the matching question.\n\n## Conclusion\n\nIf you understand CQRS as a framework, you’re looking in the wrong place. There is nothing to install. The only decision that counts is a domain decision: Does this domain benefit from writing and reading getting different models? If yes, you draw the boundary – small, with a single store, without Event Sourcing, in a single bounded context. If no, you leave it, and that’s the more common case.\n\nThe separate databases, the projections, eventual consistency – all of these are later, optional expansion stages that you take when the load demands it, and not earlier. Equating CQRS with these expansion stages is the mistake that makes the pattern expensive and intimidating. In its essence, it’s the opposite: an unspectacular, cheap, domain-driven separation. Two questions, two models. That’s all you need to get started.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html\n- Martin Fowler, “CQRS”: [martinfowler.com/bliki/CQRS.html](https://martinfowler.com/bliki/CQRS.html)\n- Martin Fowler, “CommandQuerySeparation”: [martinfowler.com/bliki/CommandQuerySeparation.html](https://martinfowler.com/bliki/CommandQuerySeparation.html)\n- Greg Young, “CQRS Documents” (PDF): [cqrs.wordpress.com](https://cqrs.wordpress.com/documents/)\n- Vaughn Vernon, “Implementing Domain-Driven Design,” chapter 4 (Architecture / CQRS), and the [IDDD_Samples](https://github.com/VaughnVernon/IDDD_Samples)\n- My own talk material “CQRS + Event Sourcing” (SlideShare), which some of the examples shown here come from"},{"locale":"en","translation_key":"nodejs-training-event-loop-architektur","slug":"nodejs-training-from-event-loop-to-architecture","title":"Node.js Training: From the Event Loop to Architecture Decisions","summary":"You can’t explain Node.js through a framework. You explain it through the event loop, through streams and through the question of which architecture decision a team will still understand tomorrow – and that is exactly what I practice with participants in the introduction-nodejs repo.","tags":["Software","Node.js","Backend"],"published_at":"2019-05-12T10:00:00+00:00","updated_at":"2026-07-13T08:37:03.3766+00:00","url":"https://www.mikebild.dev/en/blog/nodejs-training-from-event-loop-to-architecture/","audio_url":null,"audio_duration_secs":null,"text":"# Node.js Training: From the Event Loop to Architecture Decisions\n\nExpress answers exactly one question: which function runs for which URL. It doesn’t answer the questions that actually break a Node backend in production – what happens when a single call blocks the only thread, when a response grows larger than the free memory, when a promise is rejected and nobody is listening. If you start with a framework, you memorize an API. If you start with the event loop, you understand why that API looks the way it does and what exactly happens when you use it wrong.\n\nStill, the question “Why don’t we just build this with Express?” comes up very early in Node trainings – whether I run them directly or through partners like [Grossweber](https://grossweber.com/). It’s a fair question, and it’s still premature. So the starting point is somewhere else: a single line that, at first glance, has nothing to do with architecture.\n\n## The first snippet already shows everything\n\n```js\nconst fs = require(\"fs\");\n\nconst data = fs.readFileSync(\"input.txt\");\nconsole.log(data.toString());\nconsole.log(\"Fertig\");\n```\n\nThis isn’t exciting code. That’s exactly why it works as a starting point. `readFileSync` blocks the process until the file has been read completely. Only then does the next line run. I let participants run this code, then I change one line:\n\n```js\nconst fs = require(\"fs\");\n\nfs.readFile(\"input.txt\", (err, data) => {\n  if (err) return console.error(err);\n  console.log(data.toString());\n});\nconsole.log(\"Fertig\");\n```\n\nNow “Fertig” shows up first in the console, even though that line comes later in the source. For beginners, this is often the first small moment of shock: the code doesn’t run from top to bottom, at least not the way you’re used to from other languages. You can hang the entire rest of the training on this tiny difference. At its core, Node.js isn’t a framework and isn’t a collection of modules. It’s a decision: a program reacts to a slow input/output operation by moving on instead of waiting.\n\n## The event loop is architecture, not a footnote\n\nNode runs on Chrome’s V8 engine and in a single JavaScript thread. That regularly surprises participants, because the server can still handle thousands of concurrent connections. The contradiction dissolves as soon as you distinguish between concurrent and parallel. At any given moment, Node only processes one piece of JavaScript, but while that piece waits for an answer from the disk, the network or a database, Node hands the work down to libuv, the kernel or an internal thread pool. The event loop is the part that picks up the returned results and calls the matching callbacks as soon as the main thread is free.\n\nThis is where I deliberately slow down in the training, because this is where the real architectural statement lives: concurrency in Node isn’t an implementation detail you can ignore as long as the code works. It determines which work may happen right away and which has to wait, and it determines what a single blocking call means for every other request running at the same time. A CPU-heavy loop, a synchronous JSON.parse over several megabytes, a nested regex with catastrophic backtracking – none of these just stalls the one request that triggered it. They stall the entire process, because there is no second thread that could take over in the meantime.\n\n```mermaid\nflowchart LR\n  subgraph Call[\"Call stack (one thread)\"]\n    direction TB\n    JS[\"Your JavaScript\"]\n  end\n  JS -->|\"hands off I/O\"| LibUV[\"libuv / kernel / thread pool\"]\n  LibUV -->|\"result is ready\"| Queue[\"Callback queue\"]\n  Queue -->|\"call stack is empty\"| JS\n```\n\nFor participants who come from Java or .NET environments, this is often the biggest adjustment. The sentence I want to stick isn’t “Node is fast.” It’s this: Node is fair as long as you don’t sneak blocking work into it. That’s an operational promise, not a marketing line, and it has direct consequences for what is allowed to end up in a Node service at all.\n\n## Why callbacks, EventEmitter, streams and promises come in exactly this order\n\nIn the `introduction-nodejs` repo, which I work through together with participants, the chapters deliberately follow this order: callbacks first, then EventEmitter, then streams, then promises and, at the very end, RxJS. It looks like an arbitrary list of async tools, but it’s actually a learning curve with clear logic behind it, and that logic is worth spelling out once.\n\nA callback delivers exactly one result, exactly once, and error handling is pure convention: the first argument is set in case of an error, otherwise it isn’t. This convention is called error-first, and it only works if every function sticks to it with discipline. An EventEmitter goes one step further and delivers any number of events over time, but it has no built-in error channel. An `error` event is just an agreement, and if nobody listens to it, Node throws the exception further up, uncaught. At its core, a stream is a specialized EventEmitter that adds two things that matter in everyday work: a fixed role (Readable, Writable, Duplex or Transform) and backpressure, a built-in brake for when the destination is slower than the source. Finally, a promise goes back to exactly one result, exactly once, but gains a real, composable error channel through `.catch` that neither the callback nor the EventEmitter has. RxJS combines both properties at the end: many values over time, as with the EventEmitter, but with the same reliable error and completion contract that promises introduced.\n\nOnce participants have seen this arc, they stop asking for the “best” async pattern. The question shifts to something more useful: How many values do I expect, how many times may an error happen, and who is responsible for handling it?\n\n## Streams and backpressure in a concrete example\n\nNo chapter in the training produces as many aha moments as streams, because they show for the first time that Node architecture is also a question of memory and throughput, not just syntax. A small example that gets shown a lot is all you need:\n\n```js\nconst fs = require(\"fs\");\nconst zlib = require(\"zlib\");\n\nfs.createReadStream(\"input.txt\")\n  .pipe(zlib.createGzip())\n  .pipe(fs.createWriteStream(\"input.txt.gz\"));\n```\n\nAt first glance, this is just a convenient way to compress a file. The line only gets interesting when you ask what happens when `input.txt` is ten gigabytes. Without streams, you would have to load the entire file into memory before compression could even start. With `pipe`, Node reads a chunk, compresses it, writes it, and only then does the next chunk get its turn – and automatically only as fast as the write target can keep up. That’s backpressure: a built-in queue that prevents a fast source from flooding a slow destination with data until the process chokes on its memory limit.\n\n```mermaid\nflowchart LR\n  Source[\"Readable<br/>(e.g. file)\"] --> Transform[\"Transform<br/>(e.g. gzip)\"]\n  Transform --> Sink[\"Writable<br/>(e.g. target file)\"]\n  Sink -. \"Backpressure\" .-> Transform\n  Transform -. \"pause / resume\" .-> Source\n```\n\nFor the architecture of a backend, this isn’t niche knowledge for file conversion. Every file upload, every CSV export, every log tail and every forwarded HTTP response body benefits from exactly the same principle. If you instead collect the entire request body in a buffer before anything happens with it, you have built in a memory limit that never shows up in a test with a small test file and very much does show up in production with real user files.\n\n## Express is not an architecture pattern\n\nThis finally brings us to the question participants actually wanted to start with. Express is an excellent, lean routing tool, but it doesn’t make a single one of the decisions that actually define a web architecture. Those decisions live elsewhere: Does the server respond with fully rendered HTML, as in classic server-side rendering? Does it respond with structured data to an RPC-style call, where a function and its parameters sit in the body? Or does it follow the RESTful idea, where resources are addressed through URIs and HTTP methods carry their own meaning?\n\nFor the latter, I like to use the Richardson Maturity Model in the training as a small orientation aid, because it makes the levels tangible. At level 0, there is only a single URI, usually with POST, and the actual action sits in the body – basically RPC over HTTP. Level 1 adds several URIs for different resources, but still without proper use of HTTP methods. Level 2 uses GET, POST, PUT, DELETE and status codes the way they are meant: 200 for success, 201 for created, 204 for no content, 404 when the resource is missing. Level 3 adds hypermedia, meaning links in the response that tell the client which next steps are possible, instead of the client having to know that up front. Most systems I see in projects stop at level 2, and that’s usually perfectly fine. What matters is that the decision is made deliberately and isn’t simply the result of whichever Express examples you happened to copy first.\n\nWhat Express actually contributes is something else, and it has a surprising connection to streams: a middleware pipeline.\n\n```js\nconst express = require(\"express\");\nconst app = express();\n\napp.use(express.json());\napp.use((req, res, next) => {\n  console.log(`${req.method} ${req.url}`);\n  next();\n});\n\napp.get(\"/invoices/:id\", async (req, res, next) => {\n  try {\n    const invoice = await loadInvoice(req.params.id);\n    if (!invoice) return res.status(404).json({ error: \"not_found\" });\n    res.status(200).json(invoice);\n  } catch (err) {\n    next(err);\n  }\n});\n\napp.use((err, req, res, next) => {\n  console.error(err);\n  res.status(500).json({ error: \"internal\" });\n});\n\napp.listen(3000);\n```\n\nEach middleware gets the request and the response, does something and passes control on with `next()`, or it aborts with an error that ends up in the four-parameter error handler. Structurally, that’s the same principle as the streams above: a source, a chain of transformations, a destination and a separate channel for the error case. As soon as participants see this kinship, Express stops being a list of calls to memorize. It becomes one of several forms of the same pipeline idea that runs through the whole training.\n\n## Scaling without illusions\n\nA single Node process uses exactly one CPU core. That regularly surprises participants with servers that have eight or sixteen cores, because under load only one of them gets anything to do unless you take further steps. For this, Node offers `child_process` with three tools of different granularity: `spawn` starts any system command and delivers its output as a stream, `exec` does something similar but collects the output entirely in memory before it returns, and `fork` specifically starts another Node script as a separate process with a built-in message channel. For compute-heavy work that would otherwise block the event loop, that’s the clean way: offload the work instead of sacrificing the only thread.\n\nIn the repo, a `fork` looks like this, for example:\n\n```js\nconst { fork } = require(\"child_process\");\n\nconst worker = fork(\"./heavy-computation.js\");\nworker.send({ numbers: [1, 2, 3, 4, 5] });\nworker.on(\"message\", (result) => {\n  console.log(\"Result from worker process:\", result);\n});\n```\n\nThe main process stays free while `heavy-computation.js` computes in its own process and sends the result back through the built-in message channel. That’s coarser than a thread, because every `child_process` brings its own V8 context and its own memory, but in many cases this very isolation is an advantage: a crashed worker doesn’t take the main process down with it.\n\nRight now, in spring 2019, this picture is getting more interesting. Node 10 is the long-term support version that currently runs in production in most projects, solid and mature. Node 12 came out a few weeks ago and brings two things I already talk about in the training without recommending them for production: Worker Threads, which now run without a command-line flag but which the Node maintainers themselves don’t yet call fully mature, and experimental support for ECMAScript modules behind the `--experimental-modules` flag. Both show where Node is heading, but if you ship something today, you stay with `require`, with CommonJS and with the 10 line until 12 becomes the LTS version. I find this distinction important enough to make it explicit: curiosity about the new and responsibility for what’s running are two different things, and a good training shows both.\n\n## Errors are architecture too, not just a try/catch\n\nIn the Express example above, an error ends up in the four-parameter handler because I explicitly passed it there with `next(err)`. That’s the clean case. It gets interesting with the errors nobody passed on explicitly. For those, Node offers two global safety nets, and I deliberately show participants that they are nets, not repair tools.\n\n```js\nprocess.on(\"uncaughtException\", (err) => {\n  console.error(\"Unexpected error, process is in an undefined state:\", err);\n  // only synchronous cleanup, then exit\n  process.exit(1);\n});\n\nprocess.on(\"unhandledRejection\", (reason) => {\n  console.error(\"Promise rejected without .catch:\", reason);\n});\n```\n\nThe Node documentation is unusually clear at this point: after an `uncaughtException`, the process is in an undefined state. That sentence is meant literally. Some module may have stopped in the middle of an operation, a file half written, a connection half established. So you don’t carry on in the handler. You clean up as quickly and as synchronously as possible and end the process, so that a supervisor – `pm2`, systemd, Kubernetes, whatever runs in the project – restarts it fresh. `unhandledRejection` is the promise variant of the same problem: a promise that was rejected without a `.catch` waiting for it anywhere.\n\nFor participants who come from a world with central exception handling, this takes some getting used to. The actual lesson is this: a global handler never replaces the `try/catch` or the `.catch` at the place where the error means something for the domain – that an invoice wasn’t found, that a payment failed, that a file doesn’t exist. It’s the last safety net for whatever fell through all the deliberately placed nets. It fits that Node allows a controlled shutdown through `process.on(\"SIGINT\", ...)` and related signals: finish serving open connections, close database connections cleanly, and only then exit. Behind this is the same idea as with backpressure: a system says honestly when it’s done instead of simply being killed.\n\n## Test before it hurts\n\nThe last building block I deliberately don’t skip in the training is testing, for a simple reason: everything shown so far – backpressure, error paths, the order of middleware – can be broken invisibly in no time if nobody has captured an expectation about it. I work with Mocha, because in 2019 it’s a proven, unexcited standard, and with the built-in `assert` module, because you don’t need an extra library to understand the idea.\n\n```js\nconst assert = require(\"assert\");\nconst { describe, it } = require(\"mocha\");\n\ndescribe(\"Array.reverse\", () => {\n  it(\"reverses the order of elements\", () => {\n    const sut = \"ABC\".split(\"\");\n    const actual = sut.reverse();\n    assert.deepEqual(actual, [\"C\", \"B\", \"A\"]);\n  });\n});\n```\n\nArrange, Act, Assert: set up test data, run the function, check the result. These three steps sound trivial, but most hard-to-read tests violate exactly this separation by happily mixing setup and checks. With asynchronous code, Mocha pays off even more, because a test either accepts a `done` callback or simply returns a promise:\n\n```js\nit(\"resolves with the expected value after the async call\", () => {\n  return computeAsync().then((actual) => {\n    assert.equal(actual, 2);\n  });\n});\n```\n\nIf the test function returns a promise, Mocha automatically waits for it before evaluating the result. If you forget the `return`, the test may report success before the actual assertion has even run – a bug that’s easy to miss in code reviews, because the test is green after all. For integration tests, `before`, `after`, `beforeEach` and `afterEach` come in, for example to set up a test database once and bring it back to a known state after each test. The test pyramid remains the guardrail: many fast unit tests at the base, fewer but meaningful integration tests in the middle, a handful of end-to-end tests at the top. If you invert this distribution, you usually only notice it in the runtime of the build pipeline, when it’s too late to change it cheaply.\n\n## The repository itself is architecture\n\nOne point I like to explain to participants only at the end, because it would be too abstract earlier: `introduction-nodejs` is itself built as a Yarn Workspaces monorepo and not just a folder full of Markdown files. The root directory has a `package.json` with `\"private\": true` and a `workspaces` field that points to a `packages` folder, and each example lives below it as a standalone package: `ARCHITECTURE`, `BASICS`, `ECMA`, `EVENTEMITTER`, `EXPRESSJS`, `FUNCTIONALJS`, `HTTP2`, `RXJS`, `STREAMS`, `TESTING`, `TYPESCRIPT`. Each of these packages has its own dependencies and can be installed and run on its own, without the examples polluting each other.\n\nThat isn’t a coincidence, and it isn’t just a way of keeping things tidy. It’s the same lesson that already came up with streams and with Express, one level higher: clear boundaries between building blocks, each with its own responsibility, connected through an explicit, visible mechanism instead of silent dependencies. I deliberately show participants this structure of the repo itself, because a monorepo with clean workspace boundaries solves pretty much the same architecture problem as a backend made up of several services: Where may something be shared, and where must it stay separate so that a change in one place doesn’t surprisingly break something somewhere else?\n\n## How I actually run the training\n\nI rarely show a slide without opening the code right after it. The slide overview for the training is available for reference and for anyone who wants to see the overview again between sessions, here: [Introduction to Node.js – slides](https://slides.mikebild.dev/introduction-nodejs.en.html). But the slide is the signpost, not the path itself. The real learning happens in the repository, together: I type, a participant types, we deliberately introduce a bug and look at the error message together, then we fix it together. If you only watch, you remember the syntax for the moment. If you type yourself and forget to return the callback yourself or put the `await` in the wrong place, you remember the boundary – and boundaries are what you can still recall a year later, not syntax.\n\nThat’s why the training is carried by the repo [introduction-nodejs](https://github.com/mikebild/introduction-nodejs) and not by the slide deck. The 23 chapters are set up as standalone Markdown files that you can look up in any order and that, as a whole, form a learning curve from the first script to production readiness – from the introduction through the event loop, streams and error handling to Express, testing, promises, RxJS and TypeScript. The accompanying `EXAMPLES` are runnable code, not pseudocode – exactly the code we change together in the room.\n\n## What should stick at the end\n\nOn the last day of the training, I sometimes ask participants what they’re taking away. The answer that makes me happiest is rarely “I know Express now.” It’s more like: “I now know when to reach for a callback and when for a stream, and I know why an `await` is still something I have to think about.” That’s exactly the difference between a list of tools and an understanding of architecture. You can pick up a framework over a weekend. A feel for which decision will come back to bite you later takes practice on real, sometimes deliberately broken code.\n\nNode.js works as a training subject for a reason that has nothing to do with being current or popular: its central design decision – non-blocking I/O in a single thread – is so uncompromising that it forces its own consequences. You can’t ignore it without the server eventually behaving strangely. And it’s exactly in these strange moments that you learn the most.\n\nEven Ryan Dahl, who invented Node ten years ago, publicly questioned some of his own design decisions a while ago in a widely noted talk and has been experimenting with a possible successor ever since. Regardless of where this experiment leads, I find that remarkably healthy for an ecosystem: the inventor himself is willing to say what he would do differently today. That’s exactly the attitude I try to convey in the training. Node.js isn’t a finished, closed worldview that you memorize. It’s a series of decisions, each with its price, each open to debate. Once you have internalized that, you’ll also read the next technology that will be in vogue in five years as another set of decisions that you can understand and, if needed, refute – and not as the truth.\n\n## Further reading\n\n- Repository introduction-nodejs (the basis for the joint exercises): https://github.com/mikebild/introduction-nodejs\n- Slide overview for the training: https://slides.mikebild.dev/introduction-nodejs.en.html\n- Node.js, Event Loop and timers (official documentation): https://nodejs.org/learn/asynchronous-work/event-loop-timers-and-nexttick\n- Node.js Streams API: https://nodejs.org/api/stream.html\n- Node.js 12 release announcement: https://nodejs.org/en/blog/release/v12.0.0/\n- Richardson Maturity Model, overview: https://martinfowler.com/articles/richardsonMaturityModel.html"},{"locale":"en","translation_key":"cdk-infrastruktur-als-programmiersprache","slug":"cdk-early-days-infrastructure-in-a-programming-language","title":"CDK Early Days: Infrastructure in a Programming Language","summary":"With the CDK, infrastructure moves into the same toolchain as application code, which means tests, reviews, and logical identities suddenly decide whether production data survives.","tags":["Software","AWS","Cloud"],"published_at":"2019-03-12T10:00:00+00:00","updated_at":"2026-07-13T13:43:01.671293+00:00","url":"https://www.mikebild.dev/en/blog/cdk-early-days-infrastructure-in-a-programming-language/","audio_url":null,"audio_duration_secs":null,"text":"# CDK Early Days: Infrastructure in a Programming Language\n\nThe AWS Cloud Development Kit has been available as a developer preview for a few weeks now, and it noticeably changes how I think about infrastructure. Instead of writing YAML and hoping the indentation is right, I write TypeScript. I get types, autocompletion, loops, functions, and classes. That sounds like a pure convenience upgrade, but it is a shift in responsibility. If you describe infrastructure in a real programming language, you inherit all the tools of that language. But you also inherit its classes of bugs.\n\n**Editorial note (July 2026):** The CDK is not a programming language of its own but a framework for defining infrastructure in existing languages and provisioning it through CloudFormation. The code shows the developer preview and later CDK v1: separate `@aws-cdk/*` packages and the Lambda runtimes of that time. CDK v2 bundles the stable Construct Library in `aws-cdk-lib`; new projects should therefore not copy the examples verbatim. The same applies to the deployment action further down: current GitHub Actions workflows should connect to AWS via OIDC and short-lived role credentials, not via long-lived access keys in repository secrets.\n\nIn what follows, I use a small, plausible stack as the common thread: an S3 bucket that users upload files into, and a Lambda function that processes those files. This example shows the interesting architecture question better than a list of features would.\n\n## From template to program\n\nAnyone who has worked with AWS for a while knows CloudFormation. You describe the target state declaratively, and the service reconciles it. The model is robust, but the format is tedious. Repetition can only be expressed through parameters and mappings, and as soon as a template grows beyond a thousand lines, you lose track of which resource actually depends on which.\n\nThe CDK reverses the direction. I write code, and in the end this code generates a CloudFormation template again. This step is called synthesis. What matters is that CloudFormation is still doing the work underneath. The CDK doesn’t replace the provisioning mechanism; it puts a programming layer on top of it. The advantage is obvious: abstraction, reuse, type checking. The price is that there is now a translation step between my source code and the real resources, and I should know its result.\n\nIn the current preview release, the library is split up by service. There is a core package and one package per AWS service. If you use S3 and Lambda, you install exactly those packages. That is unusually granular, but it has the effect of keeping your own dependencies small.\n\n## The three levels: App, Stack, Construct\n\nThe model has three layers, and it pays to keep them cleanly apart, because each has a different job.\n\nAt the very bottom are the constructs. A construct is a building block. It encapsulates one or more CloudFormation resources along with sensible defaults. An S3 bucket is a construct, a Lambda function is a construct, and a self-written module that combines both into an upload processor is one as well. Constructs can be nested, and that is exactly where reusability comes from.\n\nOne level above is the stack. It is the unit that gets deployed and corresponds one to one to a CloudFormation stack. Whatever is in a stack is rolled out together and, in case of an error, rolled back together.\n\nAt the very top sits the app. It is the entry point and bundles one or more stacks. When the app runs, a template is generated for each stack.\n\n```mermaid\nflowchart TD\n  App[\"App (entry point)\"] --> Stack[\"Stack (deployment unit)\"]\n  Stack --> C1[\"Construct: S3 bucket\"]\n  Stack --> C2[\"Construct: Lambda function\"]\n  C1 --> Synth[\"Synthesis\"]\n  C2 --> Synth\n  Synth --> CFN[\"CloudFormation template\"]\n  CFN --> AWS[\"Resources in the cloud\"]\n```\n\nThis hierarchy is not an end in itself. It determines what can be changed independently and what can’t. Two things in the same stack share their fate during a rollback. Two things in separate stacks can be updated separately, but then they have to express their connection explicitly through references.\n\n## The stack as code\n\nThis is what the upload processor I mentioned looks like in the current library. Deliberately kept small so that the decision stays visible and doesn’t disappear in the trimmings.\n\n```ts\nimport cdk = require(\"@aws-cdk/core\");\nimport s3 = require(\"@aws-cdk/aws-s3\");\nimport lambda = require(\"@aws-cdk/aws-lambda\");\n\nclass UploadStack extends cdk.Stack {\n  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {\n    super(scope, id, props);\n\n    // Storage for incoming files.\n    // RETAIN keeps the bucket even when the stack is deleted.\n    const uploads = new s3.Bucket(this, \"Uploads\", {\n      removalPolicy: cdk.RemovalPolicy.RETAIN\n    });\n\n    const handler = new lambda.Function(this, \"ProcessUpload\", {\n      runtime: lambda.Runtime.NODEJS_10_X,\n      handler: \"index.handler\",\n      code: lambda.Code.fromAsset(\"dist/handler\"),\n      environment: {\n        // The bucket name is resolved at runtime, not hard-coded.\n        BUCKET_NAME: uploads.bucketName\n      }\n    });\n\n    // Instead of writing an IAM policy by hand:\n    // the construct grants the necessary permissions and nothing more.\n    uploads.grantReadWrite(handler);\n  }\n}\n\nconst app = new cdk.App();\nnew UploadStack(app, \"UploadStack\");\napp.synth();\n```\n\nThree places deserve a second look. The call `uploads.grantReadWrite(handler)` doesn’t write a policy by hand; it derives from the relationship between the two constructs which actions the function needs on the bucket. That is more than convenience, because it makes the principle of least privilege the default path instead of the exception. The line `BUCKET_NAME: uploads.bucketName` shows that at synthesis time, `bucketName` is not a finished string but a reference that CloudFormation resolves later. And `removalPolicy: RETAIN` is the small, inconspicuous line I will come back to shortly, because leaving it out gets expensive.\n\nWhat stands out here: it is regular code. I can refactor it, extract it into a function, iterate over a list of environments. That is exactly the appeal. And that is exactly where the responsibility begins.\n\n## What you take on with a programming language\n\nAs long as infrastructure lives in YAML, it is static and boring, but easy to oversee. As soon as it is code, the laws of code apply. A typo in a loop doesn’t create one wrong resource but fifty. A changed constant takes effect everywhere it is read. An abstraction that hides too much also hides costs and permissions from whoever reviews the stack.\n\nThis shifts what diligence means here: when infrastructure becomes programmable, it has to be treated like application code. It needs tests, it needs reviews, and it needs an understanding of what happens when you change it. That is not a burden the CDK imposes on us, but the honest consequence of using a real language.\n\nTests are not an add-on here. The library already ships an assertion module that lets you check the synthesized result without deploying at all:\n\n```ts\nimport { expect, haveResource } from \"@aws-cdk/assert\";\n\ntest(\"Bucket survives deletion of the stack\", () => {\n  const app = new cdk.App();\n  const stack = new UploadStack(app, \"TestStack\");\n\n  expect(stack).to(haveResource(\"AWS::S3::Bucket\", {\n    DeletionPolicy: \"Retain\"\n  }, undefined, true));\n});\n```\n\nThis test deploys nothing. It checks the generated template. That lets you pin down a rule that otherwise only exists in the head of an experienced colleague: this bucket must not disappear by accident. Checks like these are exactly what separate a stack that survives a demo from one that survives a change in staff.\n\n## The mistake that actually happens\n\nThe most dangerous mistake in the CDK is not a syntax error, because the compiler catches those. It has to do with the logical identity of resources, and it is so treacherous because the code looks perfectly fine afterward.\n\nCloudFormation identifies every resource by a logical ID. The CDK generates this ID from the construct’s path in the tree, so essentially from the second argument of the constructor, the name. In my example, the bucket is called `\"Uploads\"`. Suppose someone finds this name unattractive and renames it purely for cosmetic reasons:\n\n```ts\nconst uploads = new s3.Bucket(this, \"UploadBucket\", {\n  removalPolicy: cdk.RemovalPolicy.RETAIN\n});\n```\n\nFunctionally, nothing changes. The code compiles, and the tests for the function’s behavior keep passing. But the logical ID has changed. For CloudFormation, that doesn’t mean the same resource with a new name. It means the old resource is gone and a new one has been added. So on the next deployment, a new, empty bucket is created, and the application then points to this empty storage. The deletion or replacement policy applies to the old resource.\n\nThis is where the inconspicuous line from before saves you. If `removalPolicy: RETAIN` is in the code, the old bucket is not deleted but released from the stack and remains as an orphaned resource. The data survives, even if the application can no longer find it, until someone cleans up manually. If this policy is missing, CloudFormation tries to remove the old resource. CloudFormation doesn’t silently empty a non-empty S3 bucket in the process; the deletion fails as long as it contains objects, unless a mechanism such as `autoDeleteObjects` has also been set up. That doesn’t make the rename harmless: the application already points to a new, empty bucket, and with other deletable resources or explicit automatic emptying, the replacement can actually destroy data.\n\nThe crucial point is not the individual policy. The point is that a harmless rename in the code triggers a destructive operation in the infrastructure, and that this consequence is not visible in the source code. It only becomes visible in `cdk diff`, which marks a replacement as such. If you read the diff before deploying, you see the damage coming. If you skip it because the last deployment went through just fine, you see it afterward.\n\n```text\n$ cdk diff\nResources\n[-] AWS::S3::Bucket Uploads      destroy\n[+] AWS::S3::Bucket UploadBucket  create\n```\n\nThis leads to a concrete operating rule: for stacks with state, the diff is not an optional intermediate step but part of the review. And stateful resources – buckets, databases, tables – get an explicit removal policy so that deleting or replacing a stack never silently takes data with it.\n\n## Abstraction is a decision, not a free convenience\n\nThe `grantReadWrite` call is a good example of a successful abstraction, because it removes repetition and enforces a safe default. But there is the other kind, too. A self-written construct that encapsulates an entire microservice with a database, queue, function, and alarm is tempting. It keeps the calling code short. But it also makes invisible which twelve resources and which permissions come into being.\n\nA good abstraction in the CDK reduces repetition and encapsulates reasonable defaults without obscuring what it costs and which permissions it hands out. The touchstone for your own construct is therefore not its elegance. It is the question of whether someone in the review still understands what they are buying into. If the only answer is that it works, the abstraction isn’t mature yet.\n\nIt helps to look at the result of the synthesis now and then. A `cdk synth` writes the finished template to the console. For an inconspicuous stack, that quickly adds up to a few hundred lines, and it is worth consciously noticing this ratio between short code and an extensive template. It is the most honest indicator of how much the abstraction is doing for you right now.\n\n## How this fits into a pipeline\n\nInfrastructure as code only shows its value when nobody deploys by hand anymore. In 2019, I built a small GitHub Action for this that installs the CDK in a container and runs `deploy` with AWS credentials from repository secrets. This credential pattern is historical; for new workflows, I use OIDC and a time-limited AWS role. What has remained is the appeal of the same mechanism shipping both application code and infrastructure. A pull request then changes not only the service but also its foundation, and both go through the same review.\n\nThis is exactly where the circle closes back to responsibility. If a merge is enough to change production infrastructure, then the review is the last place where a human can step in. The diff belongs in that review. The tests run before deployment. And for rules that are non-negotiable, such as that no bucket may be publicly readable, an automated check of the synthesized template pays off – a kind of policy as code for your own CDK output. That way, knowledge that otherwise depends on the reviewer’s form on the day moves into a check that is always equally strict.\n\n## What I take away from the first weeks\n\nThe CDK is still young, the API is moving, and some things will change before the stable version. Still, the direction is clear, and it convinces me. Infrastructure becomes testable, reusable, and refactorable. That is a real gain over handwritten YAML.\n\nBut the gain is tied to an attitude. If you program infrastructure, you have to treat it like software, with everything that goes with it: small, verifiable building blocks, a test for every assumption that would be expensive if it broke, a diff that gets read before every deployment, and a conscious decision about what an abstraction may hide and what it may not. The logical ID and the removal policy are not footnotes here; they are the places where it is decided whether a refactoring stays harmless or costs data.\n\nSo the tool switch from YAML to TypeScript is the smaller part of the story. The bigger part is that operations and code quality are now the same topic. If you embrace that, you get infrastructure that you can read, check, and change with confidence. If you ignore it, all you end up with is the old mistakes in a new language.\n\n## Further reading\n\n- [AWS CDK v2, introduction](https://docs.aws.amazon.com/cdk/v2/guide/home.html)\n- [Constructs as building blocks](https://docs.aws.amazon.com/cdk/v2/guide/constructs.html)\n- [CloudFormation `DeletionPolicy`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html) and [`UpdateReplacePolicy`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-updatereplacepolicy.html)\n- [GitHub OIDC with AWS](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws)\n- GitHub Action for CDK deployment: https://github.com/MikeBild/aws-cdk-js-github-action\n- Policy as code for the CDK (cloudpatrol): https://github.com/MikeBild/cloudpatrol"},{"locale":"en","translation_key":"aws-parameter-store-im-build","slug":"aws-parameter-store-in-the-build","title":"AWS Parameter Store in the Build","summary":"Parameter Store in the build makes configuration explicit, but it raises hard questions about secrets and reproducibility.","tags":["Software","Frontend","AWS"],"published_at":"2019-02-12T10:00:00+00:00","updated_at":"2026-07-13T08:36:48.631838+00:00","url":"https://www.mikebild.dev/en/blog/aws-parameter-store-in-the-build/","audio_url":null,"audio_duration_secs":null,"text":"# AWS Parameter Store in the Build\n\n```bash\n$ gatsby build\nsuccess Building production JavaScript and CSS bundles - 42.108s\nDone in 71.4s\n\n$ grep -o \"undefined/graphql\" public/app-8f2c1a.js\nundefined/graphql\n```\n\n`GATSBY_API_URL` wasn’t in `process.env` during the build. The build still went green, the artifact is deployable, and the empty value is baked into the shipped JavaScript – the first place it will show up is a user’s browser. No crash, no error message in the pipeline, just a static bundle that talks to nothing.\n\nThe concrete reason for writing this down is a small Gatsby plugin I built: [gatsby-plugin-aws-parameter-store-environment](https://github.com/MikeBild/gatsby-plugin-aws-parameter-store-environment). During the build, it pulls configuration values from AWS Systems Manager Parameter Store and provides them as environment variables. Fifty lines of code, a very manageable problem – and still a good opportunity to make visible an architecture question that is considerably bigger than the plugin itself.\n\nThe question isn’t “How do I get a value from an AWS service?” but “Where does the configuration of a static frontend belong, who owns it, and what does the answer cost me in operations?” This boundary is exactly where it is decided whether a deployment runs smoothly or every release remains a small manual feat of strength. A tiny plugin is often the most honest place to think through a decision like this, because nothing distracts from the actual question.\n\n## The problem: configuration in a static build\n\nGatsby generates static HTML, CSS, and JavaScript at build time. That is the core of the JAMstack promise: fast, cache-friendly delivery without a server in the request path. The price for this is a shift that many underestimate – configuration isn’t read at runtime but baked in at build time. Whatever is in `process.env` during `gatsby build` ends up in the result. Whatever is missing stays missing until the next build runs.\n\nIn practice, a familiar pattern quickly grows out of this. Every environment – local, staging, production – gets its own `.env` file. Some values live in the CI system as secrets, others in the Git repository, a few only in the head of whoever deployed last. There is no single source, just scattering. And scattering creates drift: staging runs against a different API endpoint than intended, a feature flag is set differently in production than documented, a rotated access key was updated in three of four places.\n\nThat isn’t an exotic edge case. It is the most common source of friction between “the code is done” and “the change is live.” And it is expensive, because it doesn’t show up as an outage but as creeping uncertainty: nobody knows for sure anymore which configuration a particular build actually saw.\n\n## The idea: a single source for build configuration\n\nParameter Store reverses this scattering. Instead of maintaining many `.env` files, I define the configuration hierarchically in one place in AWS, organized by application and environment:\n\n```bash\n# One source of truth, organized by app and environment\naws ssm put-parameter \\\n  --name \"/mikebild-dev/production/GATSBY_API_URL\" \\\n  --value \"https://api.mikebild.com/graphql\" \\\n  --type \"String\"\n\naws ssm put-parameter \\\n  --name \"/mikebild-dev/production/CONTENTFUL_DELIVERY_TOKEN\" \\\n  --value \"cda-xxxxxxxx\" \\\n  --type \"SecureString\" \\\n  --key-id \"alias/build-config\"\n```\n\nThe build then pulls the entire subtree of an environment and exports it as environment variables. In `gatsby-config.js`, this looks deliberately unspectacular:\n\n```js\nmodule.exports = {\n  plugins: [\n    {\n      resolve: \"gatsby-plugin-aws-parameter-store-environment\",\n      options: {\n        // Pull the whole subtree for this environment\n        path: `/mikebild-dev/${process.env.DEPLOY_ENV}/`,\n        withDecryption: true,\n      },\n    },\n  ],\n};\n```\n\nThe hierarchy is the real gain, not the API call. A path like `/app/environment/KEY` gives the configuration a structure that you can slice with an IAM policy: the production build may read `/mikebild-dev/production/*`, nothing else. Values of type `SecureString` are stored encrypted with KMS, and every access leaves a trace in CloudTrail. “There is a file somewhere” becomes “a named, versioned, access-controlled value with an audit trail.”\n\n## Architecture: build time versus runtime\n\nBefore I use the plugin, I draw a line. It is the most important decision of the whole topic, and the plugin doesn’t make it for me.\n\n```mermaid\nflowchart LR\n  PS[\"Parameter Store<br/>/app/env/*\"] -->|build time| B[\"gatsby build\"]\n  B --> OUT[\"Static bundle<br/>HTML / JS / CSS\"]\n  OUT --> CDN[\"CDN / Browser\"]\n  RT[\"Runtime secrets<br/>never here\"] -.->|not in bundle| OUT\n```\n\nEverything that moves into the static bundle at build time is public. Period. An API endpoint, a public content delivery key, a feature flag, an analytics ID – these may be in the shipped JavaScript, because they are visible to every browser anyway. Gatsby even makes this explicit through the `GATSBY_` prefix convention: these variables are deliberately embedded in the client bundle.\n\nAnything that is a real secret – write access to a database, a private API key, a signing key – never belongs in a build-time value for a frontend. Not because Parameter Store couldn’t protect it, but because the target is a static artifact that is delivered publicly. The most secure storage in the world doesn’t help if I then write the decrypted value into a file that ends up on a CDN.\n\nParameter Store is a little seductive here, and that is the hard question about secrets: because it offers `SecureString` and KMS, every value feels “secure.” But the security ends at the boundary of the build. That is why I sort every parameter in advance into exactly one of two drawers: “may be public” or “is a runtime secret.” The plugin may only touch the first drawer at all. Real runtime secrets belong in a serverless function or a backend that reads them from Parameter Store itself at runtime and never hands them to the client.\n\n## The second trade-off: reproducibility\n\nThe second hard question is subtler and easily overlooked. The moment the build reads external configuration, it is no longer a pure function of the repository. The same Git commit no longer necessarily produces the same result – it produces the result that matches the external state of Parameter Store at build time.\n\nThat is a real loss. If someone changes a value in Parameter Store and doesn’t trigger a rebuild, the deployment and the declared configuration drift apart without any commit showing it. A rollback to an old commit may not restore the old configuration, because the parameter values have changed in the meantime. “Works on my machine” gets a new, unpleasant dimension: on my machine with yesterday’s parameters.\n\nParameter Store has a tool for this problem, and I consider it the decisive methodological lever: every parameter is versioned. I can reference a specific version – `/app/prod/KEY:4` – instead of “whatever the current value is.” That makes the build more deterministic again: a commit plus a pinned set of parameters yields a reproducible artifact. The price is deliberate discipline, because someone has to bump the version and thereby treat the configuration change exactly like a code change: visible, traceable, rollback-capable. That is exactly the point where configuration stops being a sideshow and becomes part of the architecture.\n\n## What this measurably improves\n\nThe effort pays off because it has a concrete effect in three places, not just elegance.\n\nShorter cycles: a new environment is a new path in Parameter Store, not a new ritual of `.env` files, copy and paste, and questions in the chat. A deploy no longer needs manual preparation, because the configuration lives where the build picks it up anyway. The path from “change the value” to “the value is live” shrinks to a parameter update plus a build.\n\nLess friction: access is tied to environments via IAM, not to people with file access. A developer can set a staging configuration themselves without getting at a production secret. Self-service within clean boundaries replaces the bottleneck that otherwise consists of a single person who “knows the `.env`.”\n\nHigher quality: config drift becomes structurally less likely, because there is only one source left. And if something does go wrong, there is an audit trail. CloudTrail answers the question “Who changed which value when?” – the question that, with a scattering of files and CI secrets, remains fundamentally unanswerable.\n\nThere is a fourth effect that is easily overlooked but saves a lot of friction day to day: the same mechanism works locally. A developer who is allowed to read the staging values runs their local build against exactly the same path in Parameter Store as the pipeline – no manual copying of an `.env`, no outdated local state, no discussion about why something behaves differently locally than in staging. That closes one of the most annoying gaps in the development cycle, namely the one between the configuration on the laptop and the configuration in CI. With that, the “works on my machine” from above loses one of its most common causes, because the laptop and the pipeline read from the same source. The boundary still matters here: locally, only the public, build-safe subtree may be visible, never a production runtime secret.\n\n## What I check before using it\n\nAn idea only holds up once its failure path is described. Before I hook the plugin into a pipeline, I go through a few questions that all stay invisible in demo mode and decide things in operations.\n\nWhat happens if Parameter Store isn’t reachable during the build or an expected value is missing? A build that silently runs through with an empty `process.env.GATSBY_API_URL` is more dangerous than one that aborts loudly – because it produces a broken but deployable artifact. Here I want a hard fail-fast, not an `undefined` that only shows up in the user’s browser.\n\nIs access scoped narrowly enough? Via an IAM role, the build runner should be allowed to read exactly the one environment path, with `withDecryption` only for the values it really needs. Broad `ssm:GetParametersByPath` access across the entire hierarchy is convenient, and it is exactly the kind of convenience that makes a security review expensive later.\n\nAnd the crucial question: is there accidentally a real secret in the path the build reads? That isn’t a technical mistake but a disciplinary one – and the most common one. That is why I separate the hierarchy right in the naming, so that build-public values and runtime secrets never end up in the same subtree in the first place, and access that is too broad doesn’t immediately mean a leak.\n\n## The typical mistake\n\nThe most tempting mistake with this topic is confusing the tool with the solution. Parameter Store isn’t a configuration architecture, any more than encrypted storage is automatically a secrets strategy. It is a very good place to express a boundary – the boundary between build-public configuration and a runtime secret, between environments, between what a build may read and what it should never see. But I create this boundary, not the service.\n\nThat is exactly where the real value of this small plugin lies. It forces me to answer the question that the `.env` scattering successfully hid: what part of my frontend’s configuration is public, what is secret, and who owns each of these values across its lifecycle? As soon as that answer is in place, the technical rest – a path, a plugin, a `GetParametersByPath` – is almost trivial.\n\n## Closing\n\nParameter Store in the build is a good example of how the interesting decision rarely lies in the tool’s name. The plugin fetches values from AWS – that is the easy half. The load-bearing half is the method behind it: make configuration explicit, keep it in exactly one place with clear access boundaries, enforce the separation of public and secret, and get reproducibility back through pinned versions.\n\nIf you draw these lines, you gain shorter deploy cycles, less friction with every environment, and fewer silent errors in operations. If you don’t, you end up with very secure storage from which secrets still seep into a public bundle. The difference isn’t in the service but in the decision it makes visible."},{"locale":"en","translation_key":"docker-eigene-registry","slug":"running-your-own-docker-registry","title":"Running Your Own Docker Registry","summary":"How I set up a private Docker registry with registry:2 in projects: tagging, pushing and pulling images, then securing it with htpasswd and TLS.","tags":["Software","Platform"],"published_at":"2018-11-27T10:00:00+00:00","updated_at":"2026-07-13T07:28:25.481931+00:00","url":"https://www.mikebild.dev/en/blog/running-your-own-docker-registry/","audio_url":null,"audio_duration_secs":null,"text":"A Docker registry is not a file server where you drop images. It is the namespace through which Docker addresses images in the first place: a fully qualified image name has the form `host:port/name:tag`, and its host part decides where a `push` goes and where a `pull` comes from. If it is missing, Docker Hub is meant – even when the image contains your own application code.\n\n**Editorial note (July 2026):** This tutorial describes the state of 2018. Docker Content Trust is based on Notary v1 and is being retired by Docker; for new signing and verification workflows, Docker points to Sigstore or Notation. Portus is no longer a current product recommendation either: the project was archived in 2023. Basic registry operation with `registry:2`, TLS, authentication and immutable digests is not affected by this.\n\nIf you set this host part yourself, you also decide where your images live, where they come from and who answers for production running exactly what was built and checked. The way there is short. First we clarify why a private registry makes sense at all. Then we start `registry:2` with a single command, tag an image, push it and pull it down again on another host. Because an open registry is a real problem, we secure it with basic auth and TLS. Finally, we go beyond the tool: to the provenance, signing and operational responsibility for your own images. If you already know Docker Compose – for example from my article on [Node.js and Redis with Docker Compose](https://www.mikebild.dev/en/blog/nodejs-and-redis-with-docker-compose/) – you will find your way around here quickly.\n\n## Why your own registry at all?\n\nDocker Hub is convenient. You push an image, it sits in the cloud, anyone can pull it. But in many company contexts, that is exactly the problem: your own application code is in the image, and it should not be publicly visible. Sure, Docker Hub has private repositories, but then the entire deployment chain depends on an external service and on an internet connection that can be slow or disrupted at times.\n\nA private registry in your own network solves these points in one go. The images stay internal, pulling runs over the local network and is noticeably faster, and you keep full control over where the data lives and how long it is kept. Especially in a CI/CD pipeline that pushes many builds around every day, this shows quickly.\n\nTo make the differences tangible, I like to put the two side by side:\n\n- I host the private registry myself, in my own network, with full control over storage location and lifecycle – in return, I also operate and secure it myself.\n- Docker Hub is a hosted service with accounts, organizations, a web UI and official images – in return, it depends on the internet and lives outside your own infrastructure.\n\nBoth have their place. I still pull official base images such as `node`, `redis` or `registry` itself from Docker Hub. My own application images, on the other hand, go into the private registry. One does not exclude the other.\n\n## The registry itself is just a container\n\nLet’s get to the actual tool. The open source registry that uses the same technology behind Docker Hub is called “Docker Distribution” and is provided as the ready-made image `registry:2`. No separate server, no elaborate installation – one `docker run`, and the registry is running. By default it listens on port 5000.\n\n```bash\ndocker run -d \\\n  -p 5000:5000 \\\n  --restart=always \\\n  --name registry \\\n  -v /mnt/registry:/var/lib/registry \\\n  registry:2\n```\n\nA few things here are set deliberately. `-d` starts the container in the background. `--restart=always` makes sure the registry comes back up on its own after a restart of the Docker daemon or the host – for a service the whole pipeline depends on, you want that. And most important: the volume with `-v`. By default, the registry stores its images under `/var/lib/registry` via the filesystem storage driver. Without a volume, this data lives only in the container. Delete the container, and the images are gone. With the mounted directory `/mnt/registry`, they persist.\n\nWith that, the registry is running. But it does nothing visible yet – it is waiting for its first image.\n\n## Tag, push, pull\n\nThe decisive point when working with your own registry is the image name. Docker does not use a separate configuration switch to decide which registry an image goes to; it uses the name itself. A fully qualified image name has the form `host:port/name:tag`. If the host part is missing, Docker automatically assumes Docker Hub (`docker.io`). If I put my own registry host in front of the name, Docker knows exactly where to go on `push` and `pull`.\n\nLet’s say I have built an image `app:1.0` locally. Then I retag it for my registry:\n\n```bash\ndocker tag app:1.0 registry.local:5000/app:1.0\n```\n\n`docker tag` copies nothing and rebuilds nothing – it just attaches a second name to the same image. Then I push it into the registry:\n\n```bash\ndocker push registry.local:5000/app:1.0\n```\n\nDocker reads the host part `registry.local:5000` from the name and uploads the individual layers there. On another machine in the same network – or on the CI runner that later handles the deployment – I pull the image down again the same way:\n\n```bash\ndocker pull registry.local:5000/app:1.0\n```\n\nThat is the complete cycle. Build, tag, push, pull somewhere else. I like to capture exactly this arc as a diagram, because it shows how the pieces fit together at a glance:\n\n```mermaid\nflowchart LR\n    A[docker build<br/>app:1.0] --> B[docker tag<br/>registry.local:5000/app:1.0]\n    B --> C[docker push]\n    C --> D[(Private Registry<br/>:5000)]\n    D --> E[docker pull<br/>other host / CI]\n```\n\nSo the whole mechanism hinges on the registry host. That also explains why retagging before the push is necessary: an image named just `app:1.0` would be sent toward Docker Hub.\n\n## The weak spot: out of the box, everything is open\n\nThe registry we just started runs without any protection. No password, no encryption. Anyone who can reach `registry.local:5000` on the network can push and pull. For a quick local test on your own machine, that is fine. But as soon as the registry is reachable from more than one machine, it must not stay like this.\n\nSecuring it consists of two independent building blocks that you should not confuse:\n\n- TLS encrypts the transport so nobody can read what goes over the wire.\n- Basic auth via htpasswd protects access so only authorized users can push and pull.\n\nOne does not replace the other. TLS without auth encrypts, but lets everyone in. Auth without TLS, in turn, is not accepted by the registry at all – the passwords would go over the network in plain text, and `registry:2` deliberately does not allow that. So both belong together.\n\nLet’s look at auth first. For basic auth, the registry needs an `htpasswd` file, and it must use bcrypt hashes. The easiest way to create it is with the `httpd` image, which ships the `htpasswd` tool:\n\n```bash\ndocker run --rm --entrypoint htpasswd httpd:2 \\\n  -Bbn deploy s3cret > auth/htpasswd\n```\n\nThe flags are quickly explained: `-B` forces bcrypt (mandatory for the registry), `-b` passes the password directly on the command line, and `-n` prints the result to stdout instead of writing it to a file – which is why I redirect the output to `auth/htpasswd` myself. The result is a user `deploy` with the password `s3cret`.\n\nFor TLS, I need a certificate and the matching key. In a real environment they come from an internal CA or from Let's Encrypt; in a test network, a self-signed pair will do. I put the two files as `domain.crt` and `domain.key` into a `certs` directory.\n\nNow I restart the registry – this time with both layers of protection. I pass the configuration through environment variables that the registry reads at startup:\n\n```bash\ndocker run -d \\\n  -p 5000:5000 \\\n  --restart=always \\\n  --name registry \\\n  -v \"$(pwd)\"/auth:/auth \\\n  -v \"$(pwd)\"/certs:/certs \\\n  -v /mnt/registry:/var/lib/registry \\\n  -e REGISTRY_AUTH=htpasswd \\\n  -e \"REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm\" \\\n  -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd \\\n  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \\\n  -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \\\n  registry:2\n```\n\nThe `REGISTRY_AUTH_*` variables turn on htpasswd authentication and point to the file we just created in the mounted `/auth` directory. The two `REGISTRY_HTTP_TLS_*` variables enable TLS with the certificate and key from `/certs`. From now on, you have to log in before you can push anything:\n\n```bash\ndocker login registry.local:5000\n```\n\nAfter logging in with username and password, `push` and `pull` work as usual again – just secured. Docker remembers the login locally, so the pipeline runs through after a one-time `docker login`.\n\nFor completeness: instead of setting everything through environment variables, you can also give the registry its own `config.yml`. It contains the same settings in structured form under `auth.htpasswd`, `http.tls` and `storage.filesystem`. You then build a small image `FROM registry:2`, copy the configuration into it and start it with the matching entrypoint. Both ways are common; for getting started, I find the environment variable variant clearer, because you see everything in one command.\n\nThis picture shows how the two layers of protection work together and where the insecure emergency exit is:\n\n```mermaid\nflowchart LR\n    C[Client] -->|TLS| R[Registry container :5000]\n    R -->|htpasswd auth| S[(Storage volume<br/>/var/lib/registry)]\n    C2[Client without TLS] -.HTTP.-> I[insecure-registries<br/>test network only]\n    I -.-> R\n```\n\n## When no TLS is at hand\n\nWhen you are trying things out quickly, it happens that no certificate is at hand, but you still want to test a push. Then you run into a typical error message: `http: server gave HTTP response to HTTPS client`. By default, the Docker client expects HTTPS and refuses to talk to a plain HTTP registry.\n\nFor exactly this case there is an exception – but you should really only use it in an isolated test network. On every client, you add the registry as “insecure” to the file `/etc/docker/daemon.json`:\n\n```json\n{\n  \"insecure-registries\": [\"registry.local:5000\"]\n}\n```\n\nThen the Docker daemon has to be restarted for the change to take effect. The important part is “on every client”: the entry applies locally per machine, not centrally in the registry. If you use the registry on five hosts, you maintain the entry five times. For a registry in permanent operation, that is no way to run things – there is no way around TLS. By the way, if you use a self-signed certificate, you have to install it as a CA on the clients, otherwise the Docker client distrusts it just the same.\n\n## The registry as a checkpoint in the supply chain\n\nSo far, the registry has mainly been a means of transport: build, tag, push, pull. But the real leverage sits one level higher. As soon as all your own images run through a registry that you control yourself, it becomes the central point where the provenance of what runs in production is decided. In many company contexts, that counts for more than the few seconds a pull saves on the local network.\n\nThe first point is provenance. A tag like `registry.local:5000/app:1.0` is convenient, but mutable. Nothing stops someone from later overwriting the same tag with different content – the name stays the same, the image behind it is a different one. If you want to know for certain which image is running, you reference it by its digest instead of its tag:\n\n```bash\ndocker pull registry.local:5000/app@sha256:9b2a4c...\n```\n\nThe digest is the hash over the image content and therefore immutable. When a CI runner or a production host pulls an image by digest, it is guaranteed to get exactly the bits that were once built and checked – not whatever happens to sit under the tag right now. In the pipeline, this means: the build outputs the digest, the deployment pins exactly this digest, and the tag remains only a readable name for humans, not an anchor of trust.\n\nThe second point is signing. Provenance via the digest says “it is the same image,” but not yet “it comes from whoever it is supposed to come from.” That is what Docker Content Trust is for. If I set `DOCKER_CONTENT_TRUST=1`, Docker signs the images on push and requires a valid signature on pull:\n\n```bash\nexport DOCKER_CONTENT_TRUST=1\ndocker push registry.local:5000/app:1.0\n```\n\nIn the background, a Notary service manages the signatures and the associated keys. The gain is that a client recognizes a planted or tampered image and refuses the pull instead of running it blindly. This takes effort – keys need to be created, stored securely and rotated – and it is overkill for a pure test setup. But as soon as images run all the way into production, the question “did we build this, and has nobody touched it since?” is no longer academic.\n\nThe third point is operational responsibility, the flip side of all that control. If you run the registry yourself, you do not just decide who may push and pull. You are also responsible for the service running, being patched, keeping its data and staying recoverable if needed. This responsibility does not disappear; it only changes owners. With Docker Hub, the provider carries it; with your own registry, I carry it.\n\nIn 2018, this produced the real decision criterion. `registry:2` was enough as long as provenance and access were covered with digests, a handful of htpasswd users and Content Trust. But as soon as many teams, fine-grained permissions, traceable audit logs and a reliable separation between “built” and “approved for production” were required, products such as Portus, Sonatype Nexus or JFrog Artifactory came into play. Portus has since been archived; for a selection today, maintenance and support status has to be checked again.\n\n## What to keep an eye on in operation\n\nTwo things tend to get lost in the first wave of enthusiasm. The first is the persistence already mentioned: without a mounted volume, you lose all images on the next container restart. So the volume is not optional but basic equipment.\n\nThe second is disk space. The filesystem backend grows with every push, and old layers that have long been unneeded do not disappear on their own. Over time, the disk fills up. The registry ships a garbage collection for this, which you should run regularly to clean up blobs that are no longer referenced. This is easily forgotten in operation and takes its revenge months later with a full disk. A backup of the storage directory belongs here as well – with a self-hosted registry, nobody else takes care of it. These are the concrete chores behind the words operational responsibility. The fact that `registry:2` starts with one command does not take them off your hands – from then on, they are mine.\n\n## Conclusion\n\nYour own Docker registry sounds like an infrastructure project, but technically it is a matter of a few minutes – as long as you have internalized the decisive points. The registry itself is just a container, `registry:2`, and the registry host is addressed through the image name `host:port/name:tag`. Out of the box everything is open, and securing it always needs both building blocks – TLS for encrypted transport and htpasswd for access control. The `insecure-registries` entry is a crutch for test networks, not a way to operate.\n\nThe real gain only shows in operation. Your own images live in your own network, are available faster and shorten the paths in the pipeline. With digests and the Docker Content Trust common at the time, fast delivery became traceable delivery – you knew what was running and where it came from. The limits are just as clear: where governance across many teams, fine-grained permissions and complete audits are required, `registry:2` ends and a specialized product begins. For everything before that, a container, a cleanly set host part in the image name and two layers of protection are enough.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-docker-kubernetes.en.html\n- [Deploy a registry server – docs.docker.com](https://docs.docker.com/registry/deploying/)\n- [Run an externally-accessible registry (basic auth + TLS)](https://docs.docker.com/registry/deploying/#run-an-externally-accessible-registry)\n- [Registry configuration reference (config.yml)](https://docs.docker.com/registry/configuration/)\n- [Test an insecure registry (daemon.json)](https://docs.docker.com/registry/insecure/)\n- [docker tag / docker push / docker pull / docker login – CLI reference](https://docs.docker.com/engine/reference/commandline/tag/)\n- [Docker Content Trust and Notary v1](https://docs.docker.com/engine/security/trust/)\n- [Docker: retired products and recommended alternatives](https://docs.docker.com/retired/)\n- [Portus – archived repository](https://github.com/SUSE/Portus)\n- [Node.js and Redis with Docker Compose](https://www.mikebild.dev/en/blog/nodejs-and-redis-with-docker-compose/)"},{"locale":"en","translation_key":"kubernetes-grundlagen-deployment-druck","slug":"kubernetes-basics-under-deployment-pressure","title":"Kubernetes Basics Under Deployment Pressure","summary":"Under the pressure of a real deployment, the Kubernetes concepts sort themselves by importance – from the pod through deployment and service to the ingress.","tags":["Software","Platform"],"published_at":"2018-10-24T10:00:00+00:00","updated_at":"2026-07-14T17:06:45.428736+00:00","url":"https://www.mikebild.dev/en/blog/kubernetes-basics-under-deployment-pressure/","audio_url":null,"audio_duration_secs":null,"text":"# Kubernetes Basics Under Deployment Pressure\n\nAt two in the morning, a container dies. No attack, no hardware defect – the Node.js process inside tripped over a memory leak, the operating system killed it, and with the process, the container is gone too. From this moment on, a single question decides how the rest of the night goes: Who restarts it when nobody is watching? On a classically operated server, the answer is always a chain of people and semi-automation – monitoring that calls someone, a systemd unit with a restart rule, an admin with SSH access and little sleep. The lesson from such nights is the real reason Kubernetes exists: a system in which the restart isn’t a human reaction but the normal operation of a machine that continuously compares desired and actual state.\n\n## The docs explain everything except the order\n\nIf you try to learn Kubernetes from the concept documentation, you get a vocabulary list: pods, ReplicaSets, deployments, services, endpoints, ingress, ConfigMaps, secrets, volumes, namespaces, DaemonSets, StatefulSets, jobs, CronJobs. All correctly described, all side by side with equal weight. That is exactly the problem. The docs are a reference work, not a learning order – and without an order, Kubernetes feels like a foreign language where you are only allowed to speak once you know the entire dictionary by heart.\n\nI noticed this this year in a project in which an existing Node.js application, including its database, was supposed to move into a cluster – with a deadline, not someday. Under this deployment pressure, something interesting happened: the concepts sorted themselves. Not by the structure of the documentation, but by the question of which object the application can’t run without right now. What remained was a surprisingly short list:\n\n- Pod – what actually runs\n- Deployment – what keeps pods alive\n- Service – a stable address in front of unstable pods\n- Ingress – the door to the outside\n- ConfigMap and Secret – configuration out of the image\n\nEverything else – StatefulSets, DaemonSets, NetworkPolicies, the finer points of RBAC – only came up later, when the application was already running and the pressure had eased. The examples I used to play through this order are public in the repository [introduction-kubernetes](https://github.com/MikeBild/introduction-kubernetes): a collection of material around a small todo application with frontend, backend and database that you can follow locally with Minikube.\n\n## Desired state instead of command choreography\n\nThe most important basic insight isn’t in any YAML example but behind them: Kubernetes is declarative. You don’t tell the cluster what to do; you describe what the world should look like when everything is fine. Three copies of this container, reachable under this name, with this configuration. A controller loop compares this desired state with reality nonstop and corrects the difference. If a pod dies, one is missing – so one gets started. Not because someone gives a command, but because desired and actual state no longer match.\n\n```mermaid\nflowchart LR\n  M[Manifest<br/>todo-api.yaml] -->|kubectl apply| A[API server]\n  A --> E[(etcd<br/>desired state)]\n  C[Controller loop] -->|reads desired| E\n  C -->|measures actual| P[Pods in the cluster]\n  C -->|corrects difference| P\n```\n\nThat also explains why `kubectl apply -f` is the central command – and not a choreography of “start this, then that, then wire both together”. On the old server, a deployment was a screenplay: shell scripts in the right order, and heaven help you if step four fails while step three has already gone through. In Kubernetes, this screenplay no longer exists. There is only a description of the desired state, and `apply` hands it over. What happens afterwards is the controllers’ business – even at two in the morning.\n\n## The pod: what actually runs\n\nA pod is the smallest unit Kubernetes starts: one or more containers that share network and lifecycle. In practice, almost always one container per pod. The second insight under pressure: pods are disposable. You rarely create them directly, you don’t look after them, you don’t repair them. A pod that dies isn’t healed but replaced – with a new name and a new IP address. Once you accept that, you understand the rest of the system almost by itself. If, on the other hand, you try to cling to individual pods, climb into them with `kubectl exec` and rescue state, you fight against the platform instead of working with it.\n\n## The deployment: self-healing as the core idea\n\nBecause pods are mortal, something is needed to keep them alive. That is the deployment – for me, the actual heart of it all:\n\n```yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: todo-api\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: todo-api\n  template:\n    metadata:\n      labels:\n        app: todo-api\n    spec:\n      containers:\n        - name: todo-api\n          image: mikebild/todo-api:1.4.2\n          ports:\n            - containerPort: 3000\n          readinessProbe:\n            httpGet:\n              path: /health\n              port: 3000\n            initialDelaySeconds: 5\n          livenessProbe:\n            httpGet:\n              path: /health\n              port: 3000\n            initialDelaySeconds: 15\n```\n\nSince Kubernetes 1.9, `apps/v1` has been the stable API version for this; the guesswork of the early beta versions is over. The deployment describes three things: how many copies should run, what a pod has to look like and how the cluster recognizes whether a pod is healthy. The readiness probe decides whether a pod gets traffic; the liveness probe decides whether it gets restarted. I underestimated this distinction at first – until a backend needed twenty seconds at startup to connect to the database, and without a readiness probe, requests happily ran into a system that wasn’t ready yet.\n\nThe moment Kubernetes “clicked” for me was a deliberately provoked failure:\n\n```bash\nkubectl apply -f todo-api.yaml\nkubectl get pods --watch\nkubectl delete pod todo-api-7d9f6c8b45-x2x7k   # simulate a crash\n# a replacement pod appears within seconds\nkubectl rollout status deployment todo-api\nkubectl rollout undo deployment todo-api        # roll back a bad release\n```\n\nYou delete a pod, and before you have read the output, the replacement is already there. That is the answer to the two-in-the-morning question – not as a feature promise but observable in the terminal. And `rollout undo` turns a failed release from an emergency into a step back to the last working desired state.\n\n## The service: a stable address in front of unstable pods\n\nIf pods constantly come and go and change their IP addresses in the process, nobody can connect to them directly. The service solves exactly this problem: a stable virtual address and a DNS name, with a changing set of pods behind it, selected via labels.\n\n```yaml\napiVersion: v1\nkind: Service\nmetadata:\n  name: todo-api\nspec:\n  selector:\n    app: todo-api\n  ports:\n    - port: 80\n      targetPort: 3000\n```\n\nFrom now on, every pod in the cluster reaches the backend at `http://todo-api` – no matter which three pods happen to be behind it, no matter how often they have been replaced. The todo application’s frontend no longer knows any IP addresses, only this name. For me, this was the point at which the migration work paid off for the first time: service discovery, which previously consisted of maintained configuration files and hope, is simply DNS in the cluster.\n\n## The ingress: the door to the outside\n\nAt first, services are only reachable inside the cluster. For the way out, there is the ingress – a rule that maps hostnames and paths to services, executed by an ingress controller such as ingress-nginx:\n\n```yaml\napiVersion: extensions/v1beta1\nkind: Ingress\nmetadata:\n  name: todo-api\nspec:\n  rules:\n    - host: todo.example.com\n      http:\n        paths:\n          - path: /\n            backend:\n              serviceName: todo-api\n              servicePort: 80\n```\n\n```mermaid\nflowchart LR\n  B[Browser] --> I[Ingress<br/>todo.example.com]\n  I --> S[Service<br/>todo-api]\n  S --> P1[Pod]\n  S --> P2[Pod]\n  S --> P3[Pod]\n```\n\nTo be honest, the ingress is the most unfinished corner of this list: the resource has been in beta status for years (`extensions/v1beta1`), the controller isn’t part of the cluster but has to be installed separately, and depending on the environment – Minikube, your own cluster, GKE – things behave slightly differently. Still, it belongs to the basic equipment, because without a door to the outside, even the nicest application remains a monologue.\n\n## ConfigMap and Secret: configuration out of the image\n\nThe last building block on the pressure list sounds unspectacular but has the biggest effect on everyday work: configuration doesn’t belong in the container image. An image that has to be rebuilt for staging because a database address is different isn’t an artifact but a hack. ConfigMaps and secrets pull these values out of the image and into the cluster:\n\n```yaml\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: todo-api-config\ndata:\n  DATABASE_HOST: \"postgres\"\n  LOG_LEVEL: \"info\"\n```\n\nIn the deployment, `envFrom` turns this into a set of environment variables, and the same image runs unchanged locally in Minikube and in the cluster at the cloud provider. With secrets, a sober look is worth it: the values are Base64-encoded, not encrypted. That separates them cleanly from the rest of the configuration and keeps them out of Git, but it isn’t a vault.\n\n## Debugging without SSH\n\nSomething else you learn immediately under pressure: debugging works differently than on a server. There is no SSH into “the machine”, because it’s unclear which machine would even be meant. Instead, you ask the cluster what it knows about the state:\n\n```bash\nkubectl describe pod todo-api-7d9f6c8b45-x2x7k\nkubectl logs todo-api-7d9f6c8b45-x2x7k\nkubectl logs todo-api-7d9f6c8b45-x2x7k --previous   # logs of the crashed container\nkubectl get events --sort-by=.metadata.creationTimestamp\n```\n\n`describe` shows the events – that is where the classics are spelled out in plain text: `ImagePullBackOff` when the image can’t be found, `CrashLoopBackOff` when the container dies at startup. And `logs --previous` shows the output of the container that just crashed – exactly what you want to know at two in the morning. That isn’t necessarily easier than before, but it is more systematic: the cluster logs what it decided, and you don’t have to piece it together from four different log files.\n\n## What the pressure doesn’t argue away\n\nHonesty also includes the other side. For a single small application, there are now five YAML files in the repository, together well over a hundred lines – for something that Docker Compose would describe in twenty lines. Helm promises relief through packaging, but in version 2, with Tiller, it brings its own server component with far-reaching permissions into the cluster – trading YAML volume for operational and security questions, a trade I wouldn’t make in every project yet. And even though Amazon, as the last of the big providers, has offered managed Kubernetes with EKS since June, and GKE and AKS take cluster setup off your hands: they don’t take the concepts off your hands, and a cluster you set up yourself with kubeadm is a whole operational task of its own.\n\nThat’s why the sober counter-check comes before the migration starts. A single host with Docker Compose is simply enough when a few things come together:\n\n- the application runs on one machine, and short outages are tolerable\n- a restart policy in the Compose file covers the nightly process death well enough\n- there is no team deploying in parallel and no load that requires scaling\n\nThen Kubernetes mostly buys you complexity and gives little back. The point at which the calculation flips can be named surprisingly precisely: as soon as the question “who restarts it when nobody is watching?” may no longer be answered with “the one machine, hopefully”.\n\n## What I take away from it\n\nDeployment pressure is an unpleasant but honest teacher. It didn’t replace the concept docs for me, but it sorted them: first the pod as what actually runs, then the deployment as its guardian, then the service as a stable address, the ingress as the door to the outside, ConfigMap and secret as externalized configuration. Five objects with which a real application runs in production – the rest of the dictionary can wait until it is needed.\n\nThe deeper insight is the declarative way of thinking. The switch from the screenplay (“execute these steps”) to the desired state (“this is how it should look”) changes how you think about operations – outages are no longer incidents but differences that a controller evens out. And the two-in-the-morning question from the beginning gets its best answer: nobody restarts it. When the first person looks at the dashboard in the morning, the restart is a line in the events – happened, logged, done.\n\n## Further reading\n\n- Repository with the examples: https://github.com/MikeBild/introduction-kubernetes\n- Kubernetes documentation on deployments: https://kubernetes.io/docs/concepts/workloads/controllers/deployment/\n- Kubernetes documentation on services: https://kubernetes.io/docs/concepts/services-networking/service/\n- Kubernetes documentation on ingress: https://kubernetes.io/docs/concepts/services-networking/ingress/\n- Using ConfigMaps in pods: https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/"},{"locale":"en","translation_key":"docker-logging-mit-elk","slug":"central-logging-with-the-elk-stack-in-docker","title":"Central Logging with the ELK Stack in Docker","summary":"Container logs are scattered across many containers and they are ephemeral. This article shows how an ELK stack of Elasticsearch, Logstash and Kibana in a Compose setup centralizes logs, indexes them and makes them searchable.","tags":["Software","Platform"],"published_at":"2018-09-18T10:00:00+00:00","updated_at":"2026-07-13T10:00:10.602524+00:00","url":"https://www.mikebild.dev/en/blog/central-logging-with-the-elk-stack-in-docker/","audio_url":null,"audio_duration_secs":null,"text":"`docker logs <container>` scales up to exactly one. With a frontend, an API, a database and a cache, that’s four calls in four terminals; with three hosts and a few replicas, it quickly becomes fifteen – and each one shows only its own slice, and only as long as the container lives.\n\n**Editorial note (July 2026):** The example deliberately uses Docker Compose and ELK 6.4 from 2018. It is not a current production template. Regardless of the version, the Docker GELF driver supports both UDP and TCP; the earlier claim that it could only do UDP was already wrong in 2018.\n\nThe decision behind it is less a technical one than a strategic one. The question isn’t “which logging driver do I configure?” but “how much visibility into my system do I want, and what do I pay for it in storage, compute and operational effort?” Central logging isn’t a feature you switch on. It’s an investment with running costs. If you treat the ELK setup as a pure API exercise, you will reliably build a system that either shows too little or fills up the disk. That’s why placing logs in context comes here before the first reconfigured container.\n\nThis is exactly where the ELK stack comes in. In this article I walk the path I also take in projects: first place logs within the observability strategy, then understand where Docker actually writes the logs and which logging drivers exist, then set up a complete ELK stack with Docker Compose, send the logs of an app container there and finally make them searchable in Kibana. Along the way I collect the pitfalls I’ve run into most often in practice.\n\n## Logs as one of three pillars\n\nBefore you switch a single driver, the context needs to be clear: logs are only one of three pillars that visibility into a distributed system rests on, and none of the three replaces the others. Metrics are aggregated numbers over time – requests per second, error rate, memory usage – and answer “is something broken right now, and since when?”. Logs are individual events with context and answer “what exactly happened in this one case?”. Traces follow a request across several services and answer “where in the path is it stuck?”. The ELK stack covers the middle pillar, and it helps enormously to know that consciously: if you try to watch an error rate over time with logs alone, you pay far more than a simple metric would have cost.\n\nAnd that brings us to the heart of the matter: cost. Logs are the most tempting and at the same time the most expensive of the three pillars, because every single line is stored and, in Elasticsearch, indexed by default. The cost driver is called cardinality. A field with few possible values – say a `log_level` with `info`, `warn`, `error` – is cheap to index. A field with an almost unlimited number of distinct values – a `request_id`, a `user_id`, a full query string – drives up the size of the index and with it the storage and RAM requirements. With metrics, such high cardinality quickly becomes an existential threat; with logs it’s expensive but manageable, as long as you control it deliberately.\n\nThat control is the actual design work, and it comes down to a few levers. First: what ends up in the log at all, and at which level? A `DEBUG` that keeps running in production is a pure cost driver with no return. Second: how long do I keep logs? The daily index I build further down is exactly the lever for that – entire days can be deleted in one go. Third: does every event really need to be fully indexed, or is a sample enough at high volume? The rule behind it is simple and still annoying to implement: you don’t log everything that’s possible, you log what you actually want to read when something goes wrong – and you don’t pay for the rest. The rest of this article shows the mechanics; whether they are set up with cost awareness decides whether the setup still holds after three weeks.\n\n## Where Docker logs end up by default\n\nDocker has a concept that surprises many people at first: it doesn’t care what happens in your application, only what gets written to STDOUT and STDERR. Everything the process with PID 1 in the container writes to these two streams is captured by Docker and handed to a so-called logging driver.\n\nThe default driver is called `json-file`. It writes each log line as a JSON object to a file on the host, typically under `/var/lib/docker/containers/<id>/<id>-json.log`. This is exactly the file `docker logs` reads from. That’s also the reason for a quirk that causes confusion in practice: `docker logs` only works with `json-file` (and `journald`). If you switch the driver to `gelf` or `syslog` because you want to send the logs somewhere else, the local `docker logs` command for that container is empty. The logs haven’t disappeared, they just aren’t kept locally anymore.\n\nThe drivers available as of 2018 are quite a list:\n\n- `json-file` and `journald` – local, readable with `docker logs`.\n- `syslog`, `gelf`, `fluentd`, `splunk` – forwarding to a central receiver.\n- `awslogs`, `gcplogs`, `etwlogs` – platform-specific targets.\n- `none` – logging switched off entirely.\n\nFor centralization, `gelf` and `syslog` are the most interesting. They send the log lines over the network to an endpoint – and that endpoint can be Logstash.\n\nYou can set a logging driver per container with `docker run`:\n\n```bash\ndocker run \\\n  --log-driver=gelf \\\n  --log-opt gelf-address=udp://logstash:12201 \\\n  --log-opt tag=\"myapp\" \\\n  myorg/myapp:latest\n```\n\nIn Compose, the same thing per service looks like this:\n\n```yaml\nversion: \"3\"\nservices:\n  app:\n    image: myorg/myapp:latest\n    logging:\n      driver: \"gelf\"\n      options:\n        gelf-address: \"udp://logstash:12201\"\n        tag: \"myapp\"\n```\n\nA detail worth knowing: the `gelf` driver supports UDP and TCP. This example uses UDP. It’s fast and lean, but it doesn’t confirm receipt – if a message gets lost under load, it’s gone. TCP is connection-oriented, but that still doesn’t turn a log transport into a tamper-proof audit trail.\n\n## The three roles in the ELK stack\n\nBefore we write Compose, it’s worth a look at the three letters. ELK stands for Elasticsearch, Logstash and Kibana, and each component has exactly one clearly defined job. Elasticsearch stores and indexes: it’s the search engine at the center that makes every log line searchable and holds the data. Logstash receives, parses and transforms – it’s the front door that accepts logs from various sources, gives them structure and passes them on to Elasticsearch; its pipeline consists of `input`, `filter` and `output`. And Kibana visualizes and searches: the web UI where you filter logs, build dashboards and make patterns visible.\n\nThe data flow is a short chain:\n\n```mermaid\nflowchart LR\n    A[App Container] -->|stdout / gelf| B[Logstash]\n    B -->|index| C[Elasticsearch]\n    C -->|query| D[Kibana]\n    E[Browser] -->|http :5601| D\n```\n\nThe app writes to STDOUT, the Docker driver forwards to Logstash, Logstash indexes into Elasticsearch, and Kibana makes the whole thing visible in the browser. The important part: the application itself knows nothing about any of this. It logs to STDOUT and STDERR – the way the Twelve-Factor principle intends – and transport is the infrastructure’s job. No custom log file handling in the container, no rotation logic in the app. That keeps the application clean and makes the log path replaceable.\n\n## The Compose stack\n\nNow let’s build the stack. I deliberately pin the images to a fixed version – in this case the 6.4 line – because an untagged `elasticsearch:latest` is the most reliable source of “but it looks different on my machine.” Here’s the `elk-compose.yml`:\n\n```yaml\nversion: \"3\"\nservices:\n  elasticsearch:\n    image: docker.elastic.co/elasticsearch/elasticsearch:6.4.0\n    environment:\n      - discovery.type=single-node\n      - \"ES_JAVA_OPTS=-Xms512m -Xmx512m\"\n    volumes:\n      - es-data:/usr/share/elasticsearch/data\n    ports:\n      - \"9200:9200\"\n      - \"9300:9300\"\n\n  logstash:\n    image: docker.elastic.co/logstash/logstash:6.4.0\n    volumes:\n      - ./pipeline:/usr/share/logstash/pipeline\n    ports:\n      - \"12201:12201/udp\"\n    depends_on:\n      - elasticsearch\n\n  kibana:\n    image: docker.elastic.co/kibana/kibana:6.4.0\n    environment:\n      - ELASTICSEARCH_URL=http://elasticsearch:9200\n    ports:\n      - \"5601:5601\"\n    depends_on:\n      - elasticsearch\n\nvolumes:\n  es-data:\n```\n\nA few points in the configuration are there on purpose. Elasticsearch gets `discovery.type=single-node` so it doesn’t look around in vain for cluster peers. The heap is fixed at 512 megabytes with `ES_JAVA_OPTS` – that’s enough for trying things out; in production you would size it more generously, but always with the same `Xms` and `Xmx`. And the data lives on a named volume `es-data` so it survives a container restart. That’s not a detail: if you forget the volume, every `docker-compose down` loses all indexed logs – especially annoying for, of all things, the log system.\n\nKibana gets the address of Elasticsearch through `ELASTICSEARCH_URL`. The service name `elasticsearch` works as a hostname because Compose puts all services on the same network and provides name resolution.\n\nWhat’s still missing is the Logstash pipeline. It lives as `pipeline/logstash.conf` next to the Compose file and defines how Logstash accepts messages and where it writes them:\n\n```ruby\ninput {\n  gelf {\n    port => 12201\n  }\n}\n\nfilter {\n  # room for grok, mutate, date & co.\n}\n\noutput {\n  elasticsearch {\n    hosts => [\"elasticsearch:9200\"]\n    index => \"docker-logs-%{+YYYY.MM.dd}\"\n  }\n}\n```\n\nThe `gelf` input listens on port 12201 – exactly the port our app service sends its logs to. The `filter` block is empty here, but in real setups that’s where the actual work happens: splitting lines into fields with `grok`, normalizing timestamps with `date`, renaming fields with `mutate`. The `output` block writes to Elasticsearch, into a daily index `docker-logs-2018.09.18`. This pattern is chosen on purpose: one index per day makes cleaning up old logs easy later, because you can delete whole indexes instead of hunting for individual documents.\n\n## Connecting the app\n\nWhat’s still missing is the application whose logs we want to see. I add an app service to the same stack and give it the `gelf` logging driver:\n\n```yaml\n  app:\n    image: myorg/myapp:latest\n    logging:\n      driver: \"gelf\"\n      options:\n        gelf-address: \"udp://localhost:12201\"\n        tag: \"myapp\"\n    depends_on:\n      - logstash\n```\n\nThe `gelf` driver has a stumbling block that almost certainly shows up the first time you set it up: the `gelf-address` is resolved by the Docker daemon on the host, not from inside the container network. That’s why it says `udp://localhost:12201` with the mapped host port, not the service name `logstash`. The daemon doesn’t know Compose’s internal DNS – it only sees the port Logstash publishes on the host.\n\nWhen you start the stack with `docker-compose -f elk-compose.yml up`, Elasticsearch comes up first, then Logstash and Kibana, then the app. From now on, every log line of the app flows as a GELF message to Logstash, gets indexed and is visible in Kibana.\n\nA word about ordering: `depends_on` only controls the order in which Docker starts the containers – not whether the respective service is ready yet. After starting, Elasticsearch needs a few seconds until the index is green, and during that time Kibana likes to report “Kibana server is not ready yet” in the browser. That’s not an error, that’s the reality of asynchronous startup. Take a breath, reload the page.\n\n## Searching in Kibana\n\nKibana runs on port 5601. On first access it asks for an index pattern – you enter `docker-logs-*`, pick the time field, and the Discover tab already shows the log lines trickling in. From here you filter by the `tag` field (`myapp`), run full-text searches on the messages, narrow down time ranges and build visualizations if needed. The aha moment reliably comes right here: scattered `docker logs` calls across several terminals turn into a single searchable UI.\n\n## Pitfalls from practice\n\nThree things go wrong most often with this setup, and I’ve experienced all three live more than once.\n\nThe classic is that Elasticsearch doesn’t even start and the log says `max virtual memory areas vm.max_map_count [65530] is too low`. Elasticsearch 6.x requires `vm.max_map_count=262144` on the host. That’s a kernel setting, not a container parameter, and it has to be set on the Docker host:\n\n```bash\nsudo sysctl -w vm.max_map_count=262144\n```\n\nOn a Docker Machine with VirtualBox, you set it in the VM accordingly. If you forget it, no container restart helps – Elasticsearch dies reproducibly on startup.\n\nThe second pitfall is log volume. The default driver `json-file` writes to disk without limit. A chatty container can fill up a development machine overnight. That’s why `json-file` always needs a limit:\n\n```yaml\n    logging:\n      driver: \"json-file\"\n      options:\n        max-size: \"10m\"\n        max-file: \"3\"\n```\n\nAnd for the UDP transport of `gelf` chosen here, what I touched on above applies: under load, messages can get lost without anything blowing up anywhere. For critical logs, GELF over TCP or a buffered collector are options. Whether a log has to be complete, immutable and provable remains a separate business requirement beyond that.\n\nThe third point is the startup coupling already mentioned. Logstash and Kibana need a reachable Elasticsearch. `depends_on` only guarantees the start, not readiness. In production you solve that with health checks and retry logic; when trying things out locally, it’s usually enough to know that “not ready” in the first few seconds is normal and no reason to panic.\n\n## Two ways of forwarding\n\nFinally, a bit of context that shows the logging driver isn’t the only way. There are basically two approaches to getting logs from containers to Logstash. The first is the one we took here: the Docker logging driver on the app service forwards directly. The second is a log collector as a sidecar – an additional container such as logspout that reads the Docker socket and forwards the collected logs of all containers via syslog. The advantage of the collector approach is that you don’t have to change anything on the app services and `docker logs` keeps working, because the containers stay on the default driver. The downside is one more moving part in the stack. Which way fits better depends on how much control you have over the individual services – with third-party images, the collector is often the more pragmatic choice.\n\nIf you want to embed the ELK stack in a larger Compose setup, [Node.js and Redis with Docker Compose](https://www.mikebild.dev/en/blog/nodejs-and-redis-with-docker-compose/) covers the basics for multi-part stacks. Compose keeps several parallel projects apart through their own project names and the networks derived from them.\n\n## Conclusion\n\nContainer logs are local and ephemeral by default – that’s no problem with one container and a big one with twenty. The ELK stack solves this with a clear division of labor: Logstash receives and transforms, Elasticsearch stores and indexes, Kibana makes things searchable. With its logging drivers, Docker provides the bridge to get a container’s logs there in the first place, without having to touch the application.\n\nThe effect I care about is a shift in day-to-day work. The path from incident to cause gets shorter, because you no longer piece together `docker logs` across several terminals but filter in one UI. Friction drops, because the app stays clean – it logs to STDOUT and STDERR, and transport stays the infrastructure’s job and therefore replaceable. And the quality of diagnoses goes up, because a searchable history reveals patterns that get lost in an ephemeral single log. If you know the three big pitfalls – `vm.max_map_count`, unlimited log volume and readiness at startup – you can cover this path in an afternoon.\n\nKnowing the limits is just as important. Logs are one of several telemetry signals, not all of observability: for trends over time, metrics are cheaper; for the path of a request through several services, traces are the right tool. Costs grow with volume and cardinality, which is why retention, log levels and the question of which fields get indexed have to remain deliberate decisions. And the `gelf` over UDP used here is fine for non-critical application logs, but not for audit trails or billing data, where no message may get lost. Within these limits, the core stays simple: the app logs to STDOUT and STDERR, everything else is infrastructure – and what that infrastructure costs is up to you.\n\n## Further reading\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-docker-kubernetes.en.html\n- [Docker GELF logging driver – TCP and UDP configuration](https://docs.docker.com/engine/logging/drivers/gelf/)\n- [Docker 17.11 release notes – introduction of GELF TCP support](https://docs.docker.com/engine/release-notes/17.11/)\n- [Docker: Configure logging drivers](https://docs.docker.com/config/containers/logging/configure/)\n- [Docker: json-file logging driver](https://docs.docker.com/config/containers/logging/json-file/)\n- [Docker: gelf logging driver](https://docs.docker.com/config/containers/logging/gelf/)\n- [Docker: syslog logging driver](https://docs.docker.com/config/containers/logging/syslog/)\n- [Elastic: Getting started with the Elastic Stack and Docker Compose](https://www.elastic.co/blog/getting-started-with-the-elastic-stack-and-docker-compose)\n- [Elasticsearch 6.4: Install with Docker](https://www.elastic.co/guide/en/elasticsearch/reference/6.4/docker.html)\n- [Kibana 6.4: Running Kibana on Docker](https://www.elastic.co/guide/en/kibana/6.4/docker.html)\n- [Logstash 6.4: Running Logstash on Docker](https://www.elastic.co/guide/en/logstash/6.4/docker.html)\n- [Reference stack: deviantony/docker-elk](https://github.com/deviantony/docker-elk)"},{"locale":"en","translation_key":"micro-frontends-teamschnitt-browser","slug":"micro-frontends-team-boundaries-in-the-browser","title":"Micro-Frontends: Team Boundaries in the Browser","summary":"Why the real work in micro-frontends is not the integration technique but the team split – shown with a runnable example landscape of a gateway, four applications and a component library.","tags":["Software","Frontend"],"published_at":"2018-08-21T10:00:00+00:00","updated_at":"2026-07-14T17:04:47.915864+00:00","url":"https://www.mikebild.dev/en/blog/micro-frontends-team-boundaries-in-the-browser/","audio_url":null,"audio_duration_secs":null,"text":"# Micro-Frontends: Team Boundaries in the Browser\n\nFour teams, one `index.html`, one shared deployment per week. The math behind it looks harmless and is not: every release requires two days of code freeze, a regression round over the entire UI and four approvals. If one team is not done, three others wait. With fifty working weeks a year, that is at best fifty opportunities to ship something – and in practice far fewer, because a single failed smoke test holds back the entire release. Yet the backends of these teams have long been separate services with their own pipelines. In the browser, though, all four come together again in a single JavaScript bundle, and with the bundle returns exactly the bottleneck that splitting into services was supposed to remove.\n\n## An organizational problem with a technical symptom\n\nMicro-frontends are often discussed as a frontend topic: which framework, which integration technique, how small a fragment may be. Over the past few months, I have noticed that this discussion regularly misses the core. The real question is: Does the structure in the browser reflect the structure of the organization – or does it work against it? Conway’s observation from 1968 applies here too: systems mirror the communication paths of the organization that builds them. When four teams work separately by domain but maintain a shared single-page application, friction arises exactly at this seam – as merge conflicts in the router configuration, as coordination rounds over CSS classes, as a release calendar that becomes a permanent topic.\n\nThe pattern is not new. The ThoughtWorks Technology Radar has listed “Micro Frontends” since November 2016, and since May of this year in the “Trial” ring. With the Mosaic project and the layout service Tailor, Zalando has been running such an architecture in production for a good two years. What is new, at most, is the insight that comes when you rebuild it: the technical part is the easy one.\n\n## A runnable example landscape\n\nSo as not to merely claim this, in July I put together the repository `introduction-micro-frontends` – a runnable example landscape with a gateway on port 7000 and, behind it, four standalone applications: Home (7010), Docs (7020), Products (7030) and Contact (7040), plus a catalog API, a GraphQL API on port 9000 and a shared component library on port 5000. Each application starts on its own, has its own build and could be run by its own team. The gateway knows the applications through a simple service discovery – from files, from Docker/Kubernetes or from Google Cloud, as you prefer – and routes by path.\n\n```mermaid\nflowchart LR\n  B[Browser] --> G[Gateway<br/>:7000]\n  G -->|/| H[home-app<br/>:7010<br/>Team A]\n  G -->|/docs| D[docs-app<br/>:7020<br/>Team B]\n  G -->|/products| P[products-app<br/>:7030<br/>Team C]\n  G -->|/contact| C[contact-app<br/>:7040<br/>Team D]\n  P --> Q[graphql-api<br/>:9000]\n  H -. shared UI .-> L[components-library<br/>:5000]\n  P -. shared UI .-> L\n```\n\nThe diagram already shows the central design decision: the dividing lines run vertically. Each team owns a domain slice from the route to the API – not a horizontal layer such as “all buttons” or “all of the CSS.” This split is exactly what makes independent deployments possible in the first place; everything else is craftsmanship.\n\n## The easy part: integration\n\nThe integration techniques are quickly listed, and none of them is spectacular.\n\nThe oldest is the hyperlink. If `/products` and `/contact` are separate applications, an `<a href=\"/contact\">` is enough – the browser loads the next page, the next team takes over. No shared code, no shared runtime, but a visible page change. For many transitions, that is entirely sufficient, and it is the only integration that is guaranteed never to break.\n\nIf fragments from different teams should appear on one page, you compose on the server side. Every nginx supports server-side includes out of the box:\n\n```nginx\n# gateway: compose one page from team fragments\nlocation / {\n  ssi on;\n  proxy_pass http://home-app:7010;\n}\n\nlocation /fragment/header {\n  proxy_pass http://components-library:5000/header;\n}\n```\n\n```html\n<!-- home-app: index.html -->\n<!--#include virtual=\"/fragment/header\" -->\n<main>\n  <!--#include virtual=\"/fragment/product-teaser\" -->\n</main>\n```\n\nZalando’s Tailor takes the same principle further and streams fragments in parallel, with a timeout and fallback per fragment. Edge-side includes move composition into the Varnish or CDN layer. What all variants have in common: the page is built from independently deployable parts, and a slow fragment does not block the whole release, at most its own placeholder.\n\nOn the client side, Custom Elements are the cleanest bracket – native in Chrome and Safari since v1, in Firefox and Edge currently still via polyfill:\n\n```js\n// products-app: expose a fragment as a custom element\nclass ProductTeaser extends HTMLElement {\n  connectedCallback() {\n    const sku = this.getAttribute('sku');\n    fetch(`/products/api/teaser/${sku}`)\n      .then((res) => res.text())\n      .then((html) => { this.innerHTML = html; });\n  }\n\n  disconnectedCallback() {\n    // team C cleans up its own listeners here\n  }\n}\n\ncustomElements.define('product-teaser', ProductTeaser);\n```\n\nThe receiving team writes `<product-teaser sku=\"42\"></product-teaser>` and does not need to know which framework the fragment is built with internally. The DOM interface – attributes in, events out – is the contract between the teams. Then there are iframes: disreputable, but the only technique with complete isolation of CSS, JavaScript and global state. For a third-party payment form or a legacy module nobody wants to touch anymore, still a legitimate choice. And finally, single-spa orchestrates several framework applications within one single-page application – that solves the routing problem elegantly, but pulls all teams back into a shared runtime with a shared failure domain.\n\nWhich technique works is decided by a few questions:\n\n- How many page changes can the user flow tolerate – is a link enough?\n- Must the page deliver a usable first view without JavaScript (SSI, Tailor), or is the audience logged in anyway (client-side composition)?\n- How strictly must fragments be isolated – is naming discipline enough, or do you need the iframe boundary?\n- Who operates the composition point: a platform team running the gateway, or each team its own entry point?\n\n## Due diligence: routing, dependencies, CSS\n\nYou still have to settle three things cleanly, or the monolith will catch up with you through the back door.\n\nFirst, routing ownership. The URL is the public interface of the entire application, so it needs an owner. In the example repository, the gateway owns the top level – `/products` belongs to team C, completely, including all subpaths. As soon as two teams have to negotiate over a path, the split is drawn wrong. Deep links have to work like on any decent website: a reload on `/products/42` lands at the right team without a central client router having to know about it. The gateway itself deliberately stays dumb – it knows paths and targets, but no domain logic. Every additional rule at this point turns it into the next shared deployment that everyone has to coordinate on again.\n\nSecond, shared dependencies. Four applications that each bundle their own React send the framework over the wire four times – with a library of a good 100 KB, that is measurable but rarely the end of the world. The alternative, a centrally mandated framework version for everyone, sounds more economical and costs more: every framework update becomes a four-team project again, and the shared release cadence is back. That is why in the repository, each application bundles for itself. I pay this price deliberately, because it is paid in kilobytes instead of meetings.\n\nThird, CSS isolation. CSS has a global namespace, and in a composed page that is the gateway for action at a distance: team B changes a class `.card`, and team C’s layout shifts. Prefix conventions per team help immediately and cost nothing. Shadow DOM encapsulates styles completely, but depends on the same browser support as Custom Elements. The most reliable protection remains discipline: no global selectors, no element selectors, no `!important` across team boundaries.\n\n## The hard part: who owns the header?\n\nUp to this point, everything was technology, and technology can be tried out. The questions where such undertakings actually get stuck are not in any nginx configuration.\n\nThe header is the best example. It appears on every page, belongs to nobody in domain terms and to everybody technically. In one project, we played through three answers. A dedicated “header team” creates a new horizontal layer and thus a new bottleneck – every domain change becomes a ticket for another team. The second answer: one domain team owns the header, and all others embed it as a fragment. That works as long as this team takes the wishes of the others seriously – the header becomes an internal product with internal customers. The third answer is in the example repository: the header lives in the component library, versioned, and each team updates at its own pace. The price is honesty about reality – for a few days, two header versions are live at the same time. If you cannot live with that, you have decided against independent deployments and should call it that.\n\nThe design question has the same structure. A shared look and feel does not come from a central CSS file but from a styleguide that is maintained like a product: with versions, a changelog and contacts. Atomic Design provides a useful vocabulary for this – small, dumb building blocks are shared, composed views belong to the teams. The higher a component sits in this hierarchy, the more expensive it is to share.\n\n## What shared state costs\n\nThe hardest currency is shared state. The standard example: on the product page, team C adds an item to the cart, and the mini cart in the header – owned by another team – should show the new count. The obvious reflex is a global store that all fragments read and write. With that, you bring back exactly the coupling you just got rid of: a shared state schema whose changes affect all teams at once, plus the question of whose version of the store gets loaded.\n\nThe cheaper answer: fragments do not share memory; they share events. The DOM brings the mechanism along, without any additional library:\n\n```js\n// products-app: announce the change, share no memory\nwindow.dispatchEvent(new CustomEvent('cart:item-added', {\n  detail: { sku: '42', quantity: 1 }\n}));\n\n// header fragment: react and re-fetch its own truth\nwindow.addEventListener('cart:item-added', () => {\n  fetch('/cart/api/summary')\n    .then((res) => res.json())\n    .then((summary) => updateBadge(summary.count));\n});\n```\n\nThe header keeps its own state and fetches the truth from the cart API; the event is only the trigger. The contract between the teams shrinks to an event name and a small `detail` object – both can be documented and extended in a backward-compatible way.\n\nThe login status, the second perennial candidate for shared state, is a similar case. No fragment needs another team’s session object: a cookie on the shared domain, checked by the gateway, is enough as a shared fact – each fragment decides for itself what to show a logged-out visitor. Where that is not enough, for example for the display name in the header, a small API again provides the answer instead of a global object being passed through all fragments. Still: every such event is an interface, and interfaces need maintenance. When the list of cross-team events reaches double digits, that is not a tooling problem but a sign that the domain split is wrong – the teams are then long since working on the same thing, just against each other.\n\n## Bottom line\n\nThe rule of thumb I take away from building the example landscape: you do not buy micro-frontends as a technology; you buy them as a form of organization – the technology can be learned in two weeks, the team split cannot. If you have only one frontend team, you do not need any of this; a well-structured monolith with clean module boundaries is then the more honest architecture. The rebuild becomes interesting when approval rounds, code freezes and release queues measurably cost time and several teams could actually deliver independently if you let them. Then it pays to settle the uncomfortable questions first – who owns the header, who maintains the styleguide, which events form the contract – and only then choose between SSI, Custom Elements and iframes. In the end, the integration technique is interchangeable. The team split it extends into the browser is not.\n\n## Further reading\n\n- Repository with the runnable examples: https://github.com/MikeBild/introduction-micro-frontends\n- ThoughtWorks Technology Radar on Micro Frontends: https://www.thoughtworks.com/radar/techniques/micro-frontends\n- Zalando Tailor, layout service from Project Mosaic: https://github.com/zalando/tailor\n- single-spa, router for several framework applications: https://github.com/single-spa/single-spa\n- MDN on Custom Elements: https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements"},{"locale":"en","translation_key":"frontend-schnittstellen-sind-apis","slug":"frontend-interfaces-are-apis","title":"Frontend Interfaces Are APIs","summary":"Why props, URLs, events, CSS classes and localStorage deserve the same versioning discipline as a REST endpoint – at the latest when several teams work in the same browser.","tags":["Software","Frontend"],"published_at":"2018-08-12T10:00:00+00:00","updated_at":"2026-07-14T20:57:53.475496+00:00","url":"https://www.mikebild.dev/en/blog/frontend-interfaces-are-apis/","audio_url":null,"audio_duration_secs":null,"text":"# Frontend Interfaces Are APIs\n\n```diff\n UserCard.propTypes = {\n-  name: PropTypes.string.isRequired,\n+  fullName: PropTypes.string.isRequired,\n   avatarUrl: PropTypes.string,\n   onSelect: PropTypes.func\n };\n```\n\nA diff like this sails through review. A rename, the new name is more descriptive, your own application runs, the tests are green, merged. Three weeks later, another team pulls the new version of the shared component library, and their browser console says:\n\n```\nWarning: Failed prop type: The prop `fullName` is marked as required\n  in `UserCard`, but its value is `undefined`.\n```\n\nThat is still the good case, because `propTypes` at least makes noise. The worse case: the card simply renders without a name, nobody looks at the console, and the bug only gets noticed when a user reports it – two releases later, with a diff in which nothing suspicious remains.\n\nIf someone had done the same with a field in a REST response – renamed `name` to `fullName` without comment, without announcement and without a version bump – there would be plenty of trouble, and rightly so. With a component prop, exactly this happens all the time, and hardly anyone calls it what it is. Yet the situation is identical: there is a contract between two codebases that are changed and shipped by different teams at different times. That is the definition of an API. The fact that the contract consists of JSX instead of HTTP doesn’t change that.\n\n## More surfaces than the architecture diagram shows\n\nIn a portal project I worked on for quite a while, application parts from four teams ran in the same browser tab: a shell, two business applications, an embedded widget. When, after a particularly stubborn integration bug, we once wrote down what these parts actually talk to each other about, we ended up with a list that was considerably longer than anything that had ever appeared in an architecture diagram:\n\n- props and callbacks of the shared component library\n- URLs with paths and query parameters that are linked to\n- CustomEvents and `postMessage` messages between parts of the page\n- CSS classes and CSS custom properties that other parts use deliberately\n- localStorage keys that more than one module reads\n\nEach of these surfaces had consumers outside the team that maintained it. None of them was versioned. Only the first was documented at all. The REST APIs of the same project, by contrast, had version prefixes, changelogs and a deprecation policy – because everyone understood there that other people’s code depended on them. In the frontend, the same dependency existed, just invisibly.\n\n```mermaid\nflowchart LR\n  subgraph FE[One team’s frontend]\n    P[Props & callbacks]\n    U[URLs & parameters]\n    E[CustomEvents /<br/>postMessage]\n    C[CSS classes &<br/>custom properties]\n    S[localStorage<br/>keys]\n  end\n  A[Team B:<br/>business application] --> P\n  B[Users: bookmarks,<br/>shared links] --> U\n  M[Emails, campaigns,<br/>monitoring checks] --> U\n  W[Widget in an iframe] --> E\n  T[Team C:<br/>theming] --> C\n  X[Old portal script] --> S\n```\n\nThe diagram is no exaggeration but the tidied-up version of our list back then. And it explains why “we’re only refactoring internally” goes wrong so often in the frontend: what looks internal has long had consumers.\n\n## Props: the contract between teams\n\nFor the component library, we drew the obvious conclusion: it is treated like an API. In concrete terms, that means three things. First, the prop signature is the contract, and `propTypes` make it machine-readable. Second, Semantic Versioning applies for real – a removed or renamed prop is a breaking change and therefore a major version, no matter how small the diff looks. Third, every change gets a deprecation window: the old form keeps working but warns in development mode.\n\nFor the `UserCard` example above, it looks like this:\n\n```jsx\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\n// v2.3.0: `name` is deprecated in favor of `fullName`.\n// Both work until v3.0.0, where `name` will be removed.\nexport function UserCard({ fullName, name, avatarUrl, onSelect }) {\n  const displayName = fullName || name;\n\n  if (name && process.env.NODE_ENV !== 'production') {\n    console.warn(\n      'UserCard: prop `name` is deprecated, use `fullName` instead. ' +\n      'Support for `name` will be removed in v3.0.0.'\n    );\n  }\n\n  return (\n    <div className=\"user-card\" onClick={onSelect}>\n      {avatarUrl && <img className=\"user-card__avatar\" src={avatarUrl} alt=\"\" />}\n      <span className=\"user-card__name\">{displayName}</span>\n    </div>\n  );\n}\n\nUserCard.propTypes = {\n  fullName: PropTypes.string,\n  name: PropTypes.string, // deprecated, see above\n  avatarUrl: PropTypes.string,\n  onSelect: PropTypes.func\n};\n```\n\nThat is more code than the pure rename, and exactly this extra effort is the point. It forces the question of whether the rename is worth the price. For an internal helper function, the answer is almost always yes, because the compiler or a search finds all callers. For a published prop, you can’t find the callers – they sit in repositories you have no access to.\n\nFor documentation, Storybook has proven itself for us – as a living contract description, not just as a pretty component catalog: for each component there are stories that show the supported prop combinations, including a story for the deprecated form as long as it exists. If you want to know what `UserCard` can do, you don’t look at the component team’s source code but at the built Storybook instance of the version you use. The team that maintains the library also notices earlier itself when a change touches the contract – a broken story is a clear signal.\n\n## URLs: the contract with everyone else\n\nThe second surface is underestimated even more often: the URL. Routes feel like an internal implementation detail of the router, but they are the exact opposite – the most public interface a frontend has. Bookmarks point to a route, as do links shared by email, campaigns, monitoring checks, the neighboring team’s documentation and occasionally a PDF that was printed two years ago. None of these consumers gets an update when someone renames `/clients` to `/customers` in the code.\n\nRenaming a route is therefore a breaking change with especially long-lived consumers, and here the deprecation phase is called a redirect. With React Router v4, it’s one line plus discipline:\n\n```jsx\nimport { Switch, Route, Redirect } from 'react-router-dom';\n\n<Switch>\n  <Route path=\"/customers/:customerId\" component={CustomerPage} />\n  {/* Deprecated 2018-08: keep this redirect for at least 12 months. */}\n  <Redirect from=\"/clients/:customerId\" to=\"/customers/:customerId\" />\n</Switch>\n```\n\nThe discipline lies in the comment: the redirect stays until the old links are realistically gone from the world, not until the next cleanup commit. In the portal project, at some point we counted hits on old routes before a redirect was removed – the same practice you use to switch off an old REST endpoint. The numbers were regularly sobering: links we thought were dead were still being called months later.\n\nThe same goes for query parameters. If you support `?tab=invoices`, you have entered into a contract as soon as the first user shares the link. And the URL is also persisted state: what’s in it survives reloads and travels between browsers – one more reason to design it deliberately instead of leaving it to router chance. Designing deliberately mainly means: domain identifiers instead of internal IDs, no implementation details in the path, and a scheme that a colleague can guess without looking at the code. In my experience, a URL you can read out over the phone also survives the next redesign.\n\n## Events and messages: contracts at runtime\n\nAs soon as several application parts run in the same browser, at some point they talk to each other directly – for us via CustomEvents on `window` and via `postMessage` to the embedded widget. These messages are the most fleeting form of interface: no type check, no shared repository, often not even a shared deployment. That is exactly why they need the most explicit contract.\n\nWe treated every message like a small wire format – a named type, a documented payload schema, a version field:\n\n```js\n// Contract: 'cart:item-added' (version 1)\n// detail: { version: number, sku: string, quantity: number, source: string }\nwindow.dispatchEvent(new CustomEvent('cart:item-added', {\n  detail: { version: 1, sku: 'A-4711', quantity: 1, source: 'product-page' }\n}));\n\n// Consumer side: tolerate unknown versions instead of guessing.\nwindow.addEventListener('cart:item-added', (event) => {\n  if (event.detail.version !== 1) return;\n  updateCartBadge(event.detail.quantity);\n});\n```\n\nThe version field seems overly cautious until the first time two parts of the page with different release levels run in the same tab. Then it is the difference between an ignored event and an `undefined` that explodes three functions further on. With `postMessage`, the origin check comes on top, but the principle stays the same: the receiver validates, the sender promises backward compatibility within a version. Custom Elements v1, by the way, makes this way of thinking official – an element with attributes and events is nothing but an API registered in the browser.\n\n## CSS and localStorage: the contracts nobody wanted to make\n\nThe last two surfaces are the most unpleasant, because they are contracts nobody ever entered into deliberately. If you write BEM classes like `user-card__avatar` into the DOM, you publish them. Somewhere, another team styles against this class, a test selects it, an analytics snippet hooks into it. By the same logic, CSS custom properties that a theme offers to the outside – `--brand-primary`, `--spacing-unit` – are a real, intended API and should be maintained as such: named, documented, stable. The unintended variant can be contained by clearly separating which classes are part of the contract and which are generated or marked as private. But the basic rule remains: whatever is observable and stays stable long enough will be used – regardless of what the documentation says about it.\n\nlocalStorage is the same case, only worse: global per origin, without namespaces, without a schema. A key like `user-settings` that two modules read is an unintended database API including a migration problem – if one module changes the format, the other parses garbage. On top of that comes a property that sets storage apart from all other surfaces: the old values are already out there. A deployment swaps the code but not the data in thousands of browsers – every format change hits values there that an older version wrote. Since the portal project, I therefore give such keys a prefix with the module name and a version number in the value, and the reading code treats an unknown format like a missing value. Not because that’s elegant, but because the alternative is a production bug you can only diagnose with “clear storage in the DevTools panel”.\n\n## Versioning is communication, not bureaucracy\n\nThe objection is obvious: that’s a lot of process for a frontend. But the effort is tiered, and most of it is simply communication. For the component library in our Lerna monorepo, the window for a breaking change looked like this:\n\n- announce the change in the changelog, with the old and the new contract\n- a minor version in which both work and the old form warns in development mode\n- mark the Storybook story for the old form as deprecated\n- removal only in the next major version, with a migration note\n\nThat costs maybe an hour per change. The prop rename without this window cost us several days back then, counting everyone involved – debugging in someone else’s codebase, a hotfix, a special release, and the trust between two teams along with it. I have written about the sloppy treatment of code that sits between areas of responsibility before, among other places in [Build Scripts as Product Code](https://www.mikebild.dev/en/blog/build-scripts-as-product-code/); frontend interfaces get overlooked in the same way, only more teams depend on them here.\n\nWhat struck me is that teams don’t fail at the discipline but at the perception. Nobody refuses to version an API cleanly – you just don’t see that you have one. The most effective step was therefore not the tooling but the list from the beginning: write down once which surfaces your own frontend actually offers and who depends on them. Everything on this list that has a consumer outside your own team deserves the three familiar ingredients – an explicit contract, a semantic version, a deprecation window.\n\n## Bottom line\n\nA frontend is not a leaf at the end of the dependency tree but itself a provider of interfaces: props, URLs, events, CSS surfaces, stored keys. As long as a single team owns all of it and ships it in one step, you can ignore that. At the latest when several teams work in the same browser – and the design system and micro-frontend movement is currently making sure that this becomes the norm – the rules apply that have been taken for granted in the backend for years. A breaking change means a major version. Renaming means deprecating. And a harmless-looking diff is exactly as harmless as the number of consumers nobody asked.\n\n## Further reading\n\n- Semantic Versioning 2.0.0 (German version): https://semver.org/lang/de/\n- React documentation: typechecking with PropTypes: https://legacy.reactjs.org/docs/typechecking-with-proptypes.html\n- MDN: CustomEvent: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n- MDN: Window.postMessage: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage\n- Storybook: https://storybook.js.org/"},{"locale":"en","translation_key":"docker-compose-nodejs-redis","slug":"nodejs-and-redis-with-docker-compose","title":"Node.js and Redis with Docker Compose","summary":"How I describe a two-container app of Node.js and Redis with Docker Compose in projects: one YAML file for the whole stack, service discovery via the service name, persistence through a volume – and why depends_on doesn’t wait for readiness.","tags":["Software","Platform"],"published_at":"2018-07-24T10:00:00+00:00","updated_at":"2026-07-13T09:59:53.348841+00:00","url":"https://www.mikebild.dev/en/blog/nodejs-and-redis-with-docker-compose/","audio_url":null,"audio_duration_secs":null,"text":"A second container doesn’t double the work, it changes it. A single `docker run` is about one image, one port, maybe two environment variables. As soon as a Node process depends on Redis, new questions come up that you can only answer with tedious command-line acrobatics: Which network are both containers in? At which address does one find the other? Who starts first – and where does the data go when a container gets replaced?\n\nDocker Compose answers these questions in a single place. Afterwards, the knowledge of how the stack starts lives in a versioned file instead of in people’s heads and a setup doc: `git clone`, `docker-compose up`, running. A new team member no longer loses half a day to Node versions, a local Redis installation and occupied ports. You pay for it with a file that needs maintenance – a deal that pays off quickly.\n\nI walk the technical path completely: from the `docker-compose.yml` through service discovery and persistence to the pitfall that easily costs half an hour the first time. The state is summer 2018, so Compose file v3 and the hyphenated CLI `docker-compose`.\n\n**Editorial note (July 2026):** Current Docker Compose can wait for a successful health check with the long form of `depends_on` and `condition: service_healthy`. The application should still cope with dropped connections and restarts on its own; a health check doesn’t replace a retry strategy. The main text keeps the limitation of the Compose v3 format of the time.\n\n## Why Compose at all\n\nA single container is quickly explained. But as soon as two containers have to work together, the imperative variant gets tedious: create a network, start both containers in it, publish ports, set environment variables, mind the start order. That is a lot of commands nobody reproduces from memory without mistakes – least of all the colleague who clones the project tomorrow for the first time.\n\nCompose turns this around. Instead of a sequence of commands, I write a declarative description of the target state. The file says which services exist, which images they use, which ports are open and how they relate. The start command is always the same afterwards. If you have worked with Docker before, you know the principle from the Dockerfile – Compose just lifts it one level higher, from one image to a whole application.\n\nThe whole thing follows a simple idea: reproducible, encapsulated environments that start the same way on every machine.\n\n## The docker-compose.yml\n\nHere is the file I start with. Two services, kept minimal so that every line has a recognizable job.\n\n```yaml\nversion: '3'\nservices:\n  web:\n    build: .\n    environment:\n      NODE_ENV: production\n      REDIS_HOST: 'redis'\n      REDIS_PORT: '6379'\n    ports:\n      - '8080:8080'\n    depends_on:\n      - 'redis'\n  redis:\n    image: redis:4.0.11\n```\n\nThe first line is mandatory in 2018: `version: '3'`. Without this key, Compose refuses to read the file. Below it come the top-level keys that interest us here – `services:` for sure, `volumes:` and `networks:` in a moment.\n\nTwo lines are worth a closer look. The `web` service has `build: .` – Compose builds the image locally from the Dockerfile in the current directory. The `redis` service has `image: redis:4.0.11` – here a ready-made image is pulled from the registry. That is the central contrast:\n\n- I use `build:` for my own code, which doesn’t exist as a finished image yet. Compose runs a `docker build` in the background.\n- I use `image:` for everything I take over unchanged – databases, caches, message brokers. I pin Redis to a concrete version (`4.0.11`) instead of `latest` so the environment stays reproducible.\n\nIn case my web service has already been built and pushed to a registry, I simply swap `build: .` for `image: mikebild/compose-nodejs-redis:1.0.0`. The same file, a different source – exactly what you want in a deploy context.\n\nWhat’s missing from the `redis` service is also striking: no `ports`. That is intentional. Only `web` publishes a port to the host with `'8080:8080'`, because only the web service should be reachable from outside. Redis stays internal to the containers and therefore doesn’t need to be published on the host. I’ll come back to this isolation point below, because it has a very real security side.\n\n## Service discovery: Redis is simply called “redis”\n\nThat leaves the question of how the Node process knows at which address to find Redis. There is no IP written anywhere, after all.\n\nOn startup, Compose automatically creates a default network named after the project, something like `<projekt>_default`. Every service is attached to this network and reachable in it under its service name via built-in DNS. In other words: every service reaches every other service under that service’s name. The name `redis` from the YAML becomes the hostname in the network.\n\nThat is why I set `REDIS_HOST: 'redis'` in the file. The Node client connects to `redis:6379` – no hardcoded IP, no `--link` acrobatics. If Compose gives the container a different internal address tomorrow, it doesn’t matter, because resolution happens via the name.\n\n```mermaid\ngraph LR\n  Client[\"Client / Browser\"] -->|\"Host port 8080\"| Web\n  subgraph net[\"Compose default network\"]\n    Web[\"web container\"] -->|\"DNS: redis:6379\"| Redis[\"redis container\"]\n  end\n  Redis --> Vol[(\"volume<br/>redis-data (/data)\")]\n```\n\nFrom outside, exactly one way leads in, via the published host port 8080 to `web`. Internally, `web` talks to `redis` via the service name. And the Redis data lives in a volume, which we’ll get to in a moment.\n\nIf you want to make the default network visible, you can also write it out explicitly. I like to do that once in a new project to make it clear there is no magic involved:\n\n```yaml\nversion: '3'\nservices:\n  web:\n    build: .\n    environment:\n      REDIS_HOST: 'redis'\n      REDIS_PORT: '6379'\n    ports:\n      - '8080:8080'\n    networks:\n      - app-net\n    depends_on:\n      - 'redis'\n  redis:\n    image: redis:4.0.11\n    networks:\n      - app-net\nnetworks:\n  app-net:\n```\n\nFunctionally, this changes nothing compared to the first file – Compose would have built a network anyway. But the mechanism is now visible in the file, and the network is no longer an implicit side effect.\n\n## The Node client\n\nSo the connection doesn’t stay abstract, here is the relevant excerpt of the server. It is a lean Express server that uses `node_redis` in version `^2.8`, common in 2018 – so the callback API, not yet the later promises.\n\n```js\nconst SERVICE_PORT = process.env.SERVICE_PORT || 8080;\nconst REDIS_HOST = process.env.REDIS_HOST || 'localhost';\nconst REDIS_PORT = process.env.REDIS_PORT || '6379';\n\nconst express = require('express');\nconst redis = require('redis');\nconst app = express();\nconst client = redis.createClient(REDIS_PORT, REDIS_HOST);\n\nclient.on('error', err => {\n  console.error(`Redis connection error.\\n${err.message}`);\n  process.exit(1);\n});\n\napp.get('/redis', (req, res, next) => {\n  client.get('foo', (error, result) => {\n    if (error) return next(error);\n    res.send(result);\n  });\n});\n\napp.post('/redis', (req, res, next) => {\n  client.set('foo', 'bar', (error, result) => {\n    if (error) return next(error);\n    res.status(201).send('done');\n  });\n});\n\napp.listen(SERVICE_PORT, () => console.log(`Listen on ${SERVICE_PORT}`));\n```\n\nThe crucial line is `redis.createClient(REDIS_PORT, REDIS_HOST)`. Host and port come from the environment, and Compose fills the environment through the `environment` block. That keeps the code free of addresses. On my laptop it runs against `localhost`, in the Compose network against `redis` – without a single line of application code changing.\n\nThere is one detail I keep in mind: the `client.on('error', …)` handler terminates the process with `process.exit(1)` as soon as the Redis connection fails. That is deliberately harsh and leads straight to the most important pitfall.\n\n## The pitfall: depends_on doesn’t wait for “ready”\n\n`depends_on: ['redis']` reads as if Compose waits until Redis is ready before starting `web`. It doesn’t. `depends_on` only controls the start order: Compose starts the Redis container before the web container. But it doesn’t wait until Redis accepts connections – only until the container has been started.\n\nThe difference sounds academic until the harsh error handler above strikes. Redis needs a moment until the server inside the container is actually listening. If `web` starts in this window and tries to connect immediately, `client.on('error')` fires, the process exits with exit code 1 – and the freshly started stack is already half dead again. On slower machines, this happens reproducibly.\n\nThe clean solution isn’t in the YAML but in the application. It has to tolerate dropped connections and attempt a reconnect with retry instead of bailing out on the first error. Where I don’t want to touch the application code, in 2018 I put a small wait script in front of the start – `wait-for-it.sh`, `dockerize` or `wait-for` checks whether `redis:6379` is reachable before the Node process starts.\n\nOne thing needs an explicit no here: the long form `depends_on: {redis: {condition: service_healthy}}`, which waits for a health check, doesn’t exist in Compose v3 in 2018. If you write it into a v3 file, it simply isn’t recognized. So the wait logic belongs in the application or a wait script, period.\n\n## Persistence: Redis needs a volume\n\nThe second pitfall is quieter, but more annoying. In the starting file, Redis has no volume. As long as the container runs, all is well – the data lives in the container file system under `/data`. But as soon as the container gets replaced, for example after `docker-compose down` and another `up`, the cache is empty. The container is ephemeral, and so is its file system.\n\nIf you use Redis as more than a throwaway cache, mount a named volume on `/data`. The redis image stores its RDB snapshots exactly there.\n\n```yaml\nversion: '3'\nservices:\n  web:\n    build: .\n    environment:\n      REDIS_HOST: 'redis'\n      REDIS_PORT: '6379'\n    ports:\n      - '8080:8080'\n    depends_on:\n      - 'redis'\n  redis:\n    image: redis:4.0.11\n    volumes:\n      - 'redis-data:/data'\nvolumes:\n  redis-data:\n```\n\nThe named volume `redis-data` survives the container’s lifecycle. I can rebuild `web`, shut the stack down and bring it back up – the Redis data is still there. Only an explicit `docker-compose down -v` also cleans up the volumes.\n\nWith that, I have the four building blocks that make up a Compose file:\n\n- `services` are the application’s containers, here `web` and `redis`.\n- `ports` defines which container ports are published to the host; only `web` gets one.\n- `volumes` keeps data in named volumes that should survive the container, here `redis-data`.\n- `networks` describes the mostly automatic network that enables service discovery by service name.\n\n## The cycle: up, logs, down\n\nIn operation, it’s only a handful of commands, and they stay the same across projects. I start the stack in the background, look at the logs and shut everything down again at the end.\n\n```bash\ndocker-compose up -d\ndocker-compose logs web\n\ncurl -X POST http://localhost:8080/redis\ncurl http://localhost:8080/redis\n\ndocker-compose down\n```\n\n`up -d` starts both containers detached. `logs web` shows the web service’s output specifically, which helps when debugging the startup window above. The two `curl` calls first write the value to Redis and then read it back – proof that `web` actually reaches its neighbor under the name `redis`. `down` stops and removes the containers and the default network; the named volumes stay unless I add `-v`.\n\nBy the way, if you use Docker Toolbox instead of Docker for Mac or Windows, you don’t reach the stack at `localhost` but at the IP of the docker-machine, `192.168.99.100` in the default configuration. In 2018 that is still reality on many machines and costs a few puzzled minutes the first time.\n\n## The real gain: time to the first commit\n\nThe YAML is only the means. The result is an environment that everyone on the team gets with the same two commands. Whoever joins the project today clones the repository, types `docker-compose up` and shortly after has a running stack of Node and Redis in front of them – without hunting for the right Node version by hand, without installing Redis locally, without the silent assumption that port 6379 is free. The environment lives in the file, not on a wiki page nobody maintains.\n\nThis is where Compose pays off in business terms. Onboarding is expensive, and the most expensive part is rarely understanding the code – it is setting up an environment in which the code runs at all. Compose moves exactly this part from every single developer into a versioned file. The time to the first commit, which can otherwise be anywhere between half a day and a full day, shrinks to the duration of an image pull.\n\nIt isn’t free. I take on an additional abstraction the team has to understand, and a file that needs maintenance. Version pinning is discipline: a `redis:latest` undermines exactly the reproducibility I use Compose for in the first place. And Compose covers development and local integration, not production operations with their questions of fault tolerance, scaling and secrets.\n\nSo the decision falls at a clear boundary. As soon as more than one process works together and more than one person touches the project, Compose quickly earns back its effort – every setup hour avoided per new team member already makes the file worth it. For a single tool without neighbors, `docker run` remains the more honest answer. What tips the scale is less the technology than the friction it saves.\n\n## A word on security\n\nThe missing `ports` entry for Redis is intentional and the actual core of the isolation. `ports` publishes on all host interfaces. If I exposed Redis with `'6379:6379'`, an open Redis instance, unsecured by default, would sit on the network – and Redis has repeatedly made negative headlines for exactly that. Inside the Compose network, `web` reaches its cache via the service name anyway. Nobody should reach it from outside. So I leave Redis unpublished. The principle stays simple: only services that must be reachable from the host get a published port.\n\nAs an aside: the `links` entry you come across in older examples is legacy. In v3, the default network with its DNS makes it unnecessary. If you still have it in place, you can remove it.\n\n## Conclusion\n\nCompose turns a handful of `docker run` commands into a single, readable file that describes the whole stack. `image` versus `build` separates adopted services from self-built ones. Service discovery via the service name gets hardcoded IPs out of the way completely – `REDIS_HOST: 'redis'` is enough, and the Node client connects to `redis:6379`. A named volume on `/data` saves the Redis data across the container lifecycle. And `ports` publishes only what really needs to be reachable from outside.\n\nThe one point that matters most to me: `depends_on` orders the start but doesn’t guarantee readiness. If you don’t know that, you chase a race condition bug that no YAML line fixes – the wait logic belongs in the application or a small wait script. If you know it, you build the stack to be resilient from the start.\n\nBut more important than any single YAML line is what it saves the team. A reproducible environment shortens the loop from cloning to the first commit, takes the friction out of onboarding and turns “works on my machine” into a verifiable statement instead of a hope. As a side effect, that raises quality, because everyone develops and tests against the same state. The boundary stays clear: Compose is a tool for development and local integration, not a production orchestrator. Within that boundary, `docker-compose up` feels like a single, reliable move every time – and that is exactly the gain.\n\n## Further reading\n\n- [Docker Compose: startup order and `service_healthy`](https://docs.docker.com/compose/how-tos/startup-order/)\n\n- Slide deck on this topic: https://slides.mikebild.dev/introduction-docker-kubernetes.en.html\n- [Compose file v3 reference](https://docs.docker.com/compose/compose-file/)\n- [Networking in Compose (DNS, default network)](https://docs.docker.com/compose/networking/)\n- [Control startup order in Compose](https://docs.docker.com/compose/startup-order/)\n- [Compose CLI overview](https://docs.docker.com/compose/reference/overview/)\n- [redis Official Image, tag 4.0.11](https://hub.docker.com/_/redis)"},{"locale":"en","translation_key":"containerisierung-falsche-sicherheit","slug":"containerization-and-false-security","title":"Containerization and False Security","summary":"Why “runs in a container” means neither isolation nor reproducibility nor well-run operations – and which steps actually close the three gaps.","tags":["Software","Platform"],"published_at":"2018-07-12T10:00:00+00:00","updated_at":"2026-07-14T17:00:42.669323+00:00","url":"https://www.mikebild.dev/en/blog/containerization-and-false-security/","audio_url":null,"audio_duration_secs":null,"text":"# Containerization and False Security\n\n“It runs in a container” has turned into a kind of seal of quality in project conversations. The sentence is supposed to prove three things at once: the application is isolated, the build is reproducible, and operations are under control. None of these three statements follows from the packaging. A container is first of all just an ordinary process with a restricted view of the system – whether it brings security and repeatability along is decided in the Dockerfile and the startup configuration, not in the word “container”.\n\nI have been noticing this confusion in reviews for a few months now. One team shows a clean deployment on Kubernetes 1.10, everything green, and when asked about the patch level of the base image, they shrug. Another team has been building on `node:latest` for a year and wonders why the CI build behaves differently from the local one. These three false senses of security are worth a closer look, because they need three different remedies.\n\n## First false sense of security: isolation\n\nA container is not a small virtual machine. A VM brings its own kernel and talks to the host through a hypervisor. A container shares the kernel with the host and with all other containers on the same machine. What separates it are kernel namespaces for processes, network and file system, plus cgroups for resources – useful mechanisms, but a much thinner wall than a hypervisor.\n\n```mermaid\nflowchart TB\n  subgraph VM[\"Virtual machine\"]\n    A1[App] --> K1[Guest kernel]\n    K1 --> H1[Hypervisor]\n    H1 --> HW1[Host kernel<br/>+ hardware]\n  end\n  subgraph CT[\"Container\"]\n    A2[App as a process] --> NS[Namespaces<br/>+ cgroups]\n    NS --> HW2[shared<br/>host kernel]\n  end\n```\n\nThe practical consequence: if you run as root in the container, you run as root on the host. UID 0 is UID 0. User namespaces, which map container root to an unprivileged host user, have existed in Docker for a while – but they are opt-in via `--userns-remap`, and in the environments I have seen this year, the feature was switched on exactly zero times. As long as that’s the case, the only thing separating a root process in the container from the host is the question of whether it finds a way out.\n\nA `--privileged` container is guaranteed to find that way. The flag unlocks all capabilities and grants device access – which lets you mount the host file system from inside the container. I have found the flag in production setups, set months earlier “because otherwise it didn’t run”, and never questioned again. A privileged container is not an isolation layer with a weakness; it is an open door with a curtain in front of it.\n\nFor a while now, Docker has shipped a default seccomp profile that filters risky syscalls, plus AppArmor profiles on Ubuntu hosts. That helps, but it doesn’t change the principle: the boundary is the kernel, and the kernel is shared. In January, Meltdown and Spectre additionally showed that even process boundaries can wobble at the CPU level. If you need real tenant separation, that is, if you run third-party or untrusted code, you still use VMs – or take a look at gVisor, which Google introduced in May: a userspace kernel between container and host. An exciting approach, but in July 2018 too fresh to base a production decision on.\n\nWhat you can already do today is shrink the attack surface at startup:\n\n```bash\ndocker run -d \\\n  --read-only \\\n  --cap-drop ALL \\\n  --cap-add NET_BIND_SERVICE \\\n  --security-opt no-new-privileges \\\n  --memory 256m \\\n  order-service:1.4.2\n```\n\nAll of this has been available for years; none of it is the default. That is exactly the point: with containers, isolation is not a state but a configuration that someone has to actively set up.\n\n## Second false sense of security: reproducibility\n\nThe second assumption goes: because the application is shipped as an image, the build is reproducible. That is only true for the finished image – the same image ID starts the same state everywhere. It isn’t true for the path there. A Dockerfile like this one is not a description but a snapshot:\n\n```dockerfile\nFROM node:latest\nWORKDIR /app\nCOPY . .\nRUN apt-get update && apt-get install -y imagemagick\nRUN npm install\nENV API_SECRET=changeme-in-prod\nEXPOSE 3000\nCMD [\"node\", \"server.js\"]\n```\n\nAlmost every line here is a time bomb. `node:latest` is not a version but a bet on when the build happens – last year you got Node 8, for a few weeks now Node 10, and nobody made a decision. `apt-get install` without a version pulls whatever the mirror server offers today. `npm install` without a lockfile rolls the dice on dependency versions at build time; since npm 5 that’s solvable with `package-lock.json`, but only if the file is checked in and respected. And the secret in the `ENV` line now sits in the image history forever – `docker history` shows it to anyone allowed to pull the image.\n\nOn top of that come build args as a silent variable: an `ARG` that is set differently on the CI server than on the developer machine produces two different images from identical source – and because the argument isn’t anywhere in the repository, you only see the difference once you put both images side by side. So two builds of the same Dockerfile six weeks apart can differ in low-level OS layers, system packages and npm dependencies without a single line in the repository having changed. In a project this spring, we lost an afternoon over exactly this: the hotfix build for a six-week-old state behaved differently from the running system, because the base image under the same tag had meanwhile become a different one. The honest formula is: an image is a result. It only becomes reproducible once all inputs are nailed down – base image by tag or, better, by digest (`node:8.11-alpine@sha256:...`), system packages with versions, application dependencies via the lockfile.\n\n## Third false sense of security: operations\n\nThe third assumption is the quietest: the container runs, so operations are taken care of. Yet an image doesn’t only freeze the application but also every library underneath – including its vulnerabilities. On a classically administered server, `unattended-upgrades` installs security updates at night. In a container, this path doesn’t exist. The only patch route is: new base image, new build, new deployment. If you haven’t set up this chain as a routine, you are running a fleet that goes quietly more out of date every day while the dashboard stays green.\n\nBefore that comes a question that surprisingly often goes unanswered: which images are actually running, and from which state were they built? On a cluster with a few dozen deployments, that is pure archaeology without an inventory. When the first Meltdown patches arrived in January, I saw in one project how long the inventory alone takes when tags like `latest` and `stable` are in circulation – you then literally don’t know what you are running, only that it runs.\n\n```mermaid\nflowchart LR\n  CVE[CVE in the base image<br/>published] --> BASE[Base image<br/>updated]\n  BASE --> BUILD[Rebuild<br/>of all services]\n  BUILD --> SCAN[Image scan<br/>e.g. Clair]\n  SCAN --> DEPLOY[Rollout]\n  DEPLOY -. without routine<br/>the chain breaks here .- BUILD\n```\n\nThat operations are the real weak flank was shown this year by a prominent case: in February it became known that Tesla’s Kubernetes administration console was reachable from the internet without password protection. The attackers didn’t need a kernel vulnerability and didn’t break out of any container – they settled in via the open console, deployed crypto-mining pods, throttled the CPU load and hid the mining pool behind Cloudflare to avoid attention. Same category: Docker daemons whose remote API listens unauthenticated on port 2375 and that get grazed by mining scripts one after another. In both cases, the container technology was completely innocent. What was vulnerable was the operating model around it – exposed admin interfaces, missing access control, nobody looking.\n\nFor me, this is the most important lesson from the case: the platform shifts the operational questions; it doesn’t answer them. If you used to have to know which packages are on the server, you now have to know which layers are in the images. If you used to secure SSH, you now have to secure the kubelet, API server and dashboard. The effort hasn’t disappeared; it has changed its address.\n\n## What concretely helps\n\nNone of this is an argument against containers – it is an argument against the seal of quality. The remedies are unspectacular and have been available for quite some time. In the Dockerfile itself, it looks like this:\n\n```dockerfile\n# build stage\nFROM node:8.11-alpine AS build\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm install\nCOPY . .\nRUN npm run build && npm prune --production\n\n# runtime stage\nFROM node:8.11-alpine\nWORKDIR /app\nRUN addgroup -S app && adduser -S app -G app\nCOPY --from=build /app/dist ./dist\nCOPY --from=build /app/node_modules ./node_modules\nUSER app\nEXPOSE 3000\nCMD [\"node\", \"dist/server.js\"]\n```\n\nMulti-stage builds have existed since Docker 17.05, so they have been established for more than a year and are no longer an experiment. The effect: compilers, dev dependencies and build tools stay behind in the first stage, and only what is needed at runtime gets shipped. The `USER` directive makes sure the process doesn’t start as root in the first place – one line that defuses a large part of the isolation problem from the first section, because a breakout then lands with an unprivileged user. The pinned base image takes the dice out of the reproducibility question. A pleasant side effect of the small runtime stage: the image scanner has less to report, simply because fewer packages are on board – an Alpine image with a handful of libraries produces findings you actually read, instead of a list with three hundred entries that nobody opens anymore after the second week.\n\nBeyond that, a few points have settled in as a checklist for my reviews:\n\n- Choose small base images – `alpine` for everyday use, and for compiled languages the distroless images that Google released last year, which contain nothing except the application and its runtime dependencies, not even a shell.\n- Pin tags, and for production deployments also record the digest – `latest` has no place in a deployment manifest.\n- Hook image scanning into the CI chain: Clair or Anchore match the layers against known CVEs and turn “we should patch at some point” into a red build.\n- Never put secrets into the image – not as `ENV`, not as `ARG`, not as a copied file. They end up in the history or in the build context. Secrets come from outside at runtime, for example as a Kubernetes Secret or via the orchestrator.\n- Trim capabilities at startup and treat `--privileged` like open root access: anyone who wants to set it has to justify why.\n\nNone of these points is hard. The real obstacle is that they are invisible as long as everything runs – and that’s exactly why they belong in the review and not in the “we’ll do it when there’s time” category.\n\n## Bottom line\n\nContainers have made our delivery noticeably better: the same artifacts in all environments, fast startups, a clean interface between build and operations. What they don’t deliver is what the phrase “runs in a container” so readily claims. Isolation is a configuration, not a property – without `USER`, without trimmed capabilities and with a shared kernel, the wall is thinner than the word suggests. Reproducibility is a discipline, not a property – unpinned tags and packages turn the Dockerfile into a photo instead of building instructions. And operations are a routine, not a property – an image that nobody rebuilds is a server that nobody patches, only without the nightly updates.\n\nWhen someone tells me today that an application is secure because it is containerized, I ask three things: as which user does the process run? How does the next build know that it builds the same thing as the last one? And who rebuilds when a vulnerability in the base is published tomorrow? The answers show pretty reliably whether the team has an operating model – or just a seal of quality.\n\n## Further reading\n\n- Repository introduction-docker: https://github.com/MikeBild/introduction-docker\n- Docker documentation on multi-stage builds: https://docs.docker.com/build/building/multi-stage/\n- Docker Engine Security Overview: https://docs.docker.com/engine/security/\n- Clair, static analysis of container images: https://github.com/quay/clair\n- Distroless images from Google: https://github.com/GoogleContainerTools/distroless\n- Report on the Tesla incident (CNBC, February 2018): https://www.cnbc.com/2018/02/21/hackers-hijack-teslas-cloud-system-to-mine-cryptocurrency-redlock.html"},{"locale":"en","translation_key":"mvp-kleinstes-lernendes-produkt","slug":"my-working-definition-of-an-mvp","title":"My Working Definition of an MVP: Learning Instead of Shipping Half-Finished","summary":"I use MVP for an experiment that honestly tests a risky assumption. This working definition keeps a merely reduced feature set from counting as learning.","tags":["Software","Product"],"published_at":"2018-05-24T10:00:00+00:00","updated_at":"2026-07-13T13:21:51.091079+00:00","url":"https://www.mikebild.dev/en/blog/my-working-definition-of-an-mvp/","audio_url":null,"audio_duration_secs":null,"text":"If you leave out half and call the result an MVP, you haven’t reduced any risk; you have only postponed the day the mistake becomes obvious. The build time is spent, something half-done has shipped, and the most expensive question is still in the room, unchanged: How do we know we are building the right thing at all?\n\nStill, the word is attached in exactly this sense to roadmaps, ticket titles and budget lines. Fewer buttons, fewer screens, less backend – MVP has become a polite expression for “the product, but worse”. The reduced feature set doesn’t answer a single open question. It confuses speed in building with speed in learning.\n\nFor my work, I stick to the reading from Lean Startup: an MVP is an experiment, the smallest version of a product with which a concrete, risky assumption can be tested honestly. The term is used differently in practice, too; this working definition is my deliberate choice. From it follows what belongs in, what doesn’t, and why the apparent detour via learning can be the fastest way to a viable product.\n\n## The definition that carries everything\n\nIn 2011, Eric Ries put the term like this in “The Lean Startup”: an MVP is “that version of a new product which allows a team to collect the maximum amount of validated learning about customers with the least effort.” The core is in two words: *validated learning*. The purpose is learning confirmed by real data, namely about the *leap-of-faith assumptions* – the assumptions the whole idea rests on and that nobody has backed up so far.\n\nThat makes the MVP not a delivery step but the build part of an experiment. Ries places it in the *Build-Measure-Learn* loop: we build something, measure the reaction, learn from it and decide. The outcome of an MVP is always a decision, which Ries calls *pivot or persevere* – stay the course, or discard the assumption and turn.\n\n```mermaid\nflowchart LR\n  A[Risky assumption] --> B[Build:<br/>MVP as an experiment]\n  B --> C[Measure:<br/>real users, real metric]\n  C --> D[Learn:<br/>validated learning]\n  D --> E{pivot or<br/>persevere?}\n  E -->|persevere| A\n  E -->|pivot| A\n```\n\nFor this working definition, this yields a hard criterion that is missing in everyday practice: an MVP without a defined learning question and without a metric is then not an experiment but just a small product. The difference isn’t academic. If nobody wrote down beforehand which assumption is being tested and how you recognize the outcome, the result can’t refute anything either. You build, launch, find it “pretty okay” and carry on – you have learned nothing.\n\nSteve Blank states the other side of the misunderstanding directly: “A minimum viable product is not always a smaller/cheaper version of your final product.” His customer development approach revolves around a single imperative: *get out of the building*. The truth about the product isn’t in the meeting room; it is with the users. The MVP is the tool you use to go out.\n\n## A vertical slice instead of a horizontal amputation\n\nThe difference can be shown with two cuts through the same planned scope.\n\nThe wrong MVP is a horizontal cut. You take all planned features and build each one to forty percent. The registration form is half done, the search returns results without filters, the checkout ends in a dead end. Nothing works end to end. At no point does the user get from the start to the value. There is nothing to measure, because there is no complete path anyone could go through.\n\nThe MVP is often a vertical slice: a thin but continuous path from the user to the value, with a measurement at its end. With concierge, Wizard-of-Oz or landing page experiments, though, the smallest reliable test can look different. What matters is not the shape of the cut but whether it honestly tests the risky assumption.\n\n```mermaid\nflowchart TB\n  subgraph L[Horizontal: half-finished]\n    L1[Feature A – 40%]\n    L2[Feature B – 40%]\n    L3[Feature C – 40%]\n  end\n  subgraph R[Vertical: smallest learning product]\n    R1[Entry] --> R2[one continuous path] --> R3[Value] --> R4[Metric]\n  end\n```\n\nThis is exactly where the meaning of “viable” lies. The word doesn’t refer to quality; it refers to scope. Minimal is the scope, not the care. A buggy, cobbled-together MVP distorts the learning signal, because in the end you don’t know whether users reject the idea or just the broken implementation. “Viable” means: good enough to produce an honest signal. The narrow path has to be clean, otherwise you are measuring noise.\n\n## The MVP doesn’t have to be code\n\nThe strongest evidence that “viable” doesn’t mean “fully built” are two MVP types that existed long before 2018 and get by entirely without a finished product.\n\nIn a *concierge MVP*, a human first provides by hand the service that software is supposed to provide later. You don’t pretend there is a product – you deliver the value directly and personally to a handful of real users and observe whether they want it at all. In a *Wizard-of-Oz MVP*, the user sees a real UI, but behind it there is no system but a human who enters the answers by hand. The user believes in software, the learning comes from real behavior, and almost nothing has been built.\n\nBoth test a hypothesis before a single line of production code exists. They prove the thesis in the clearest way: “viable” means enough to learn honestly, not enough to sell.\n\nWhat matters here is the separation from the prototype, without turning it into an artificial wall. A prototype usually examines feasibility or usability and can of course be tested with real users for that. An MVP in my working definition, on the other hand, tests a market or value hypothesis. What counts are the question and the evidence, not whether the artifact is shown internally or externally.\n\n## The hypothesis as code\n\nIf an MVP is an experiment, then the experiment should be declared so precisely that it can be refuted. In the projects where this held up, the hypothesis came before the first line of code – structured, versioned, next to the code in the repository instead of on a forgotten slide.\n\n```yaml\n# experiment.yaml – declares the MVP before any code is written\nexperiment:\n  name: \"concierge-checkout\"\n  riskiest_assumption: \"users will connect a payment method to finish an order\"\n  hypothesis: \"at least 30% of activated users will add a payment method\"\n  target_metric: activation_rate      # added payment / reached checkout\n  success_threshold: 0.30\n  kill_criteria: \"activation_rate < 0.10 after 200 sessions\"\n  sample_size: 200\n  cohort: \"new signups, region DE\"\n```\n\nThe decisive point is the last fields. Without `success_threshold` and `kill_criteria`, it isn’t an experiment. An experiment that can’t be allowed to fail measures nothing. Agreement most often breaks down at `kill_criteria`, and that is exactly where its value lies: it forces the team to agree beforehand when the idea is refuted – before emotional attachment to its own solution clouds the judgment. Ries calls the opponents of these honest numbers *vanity metrics*: figures such as total registrations, which always point upward and never force a decision. The `target_metric` has to be an *actionable metric* that can topple an assumption.\n\n## Cutting the narrow path cleanly on the technical side\n\nThe vertical slice also has a technical side, and here two worlds connect that are often discussed separately: product thinking and delivery.\n\nThe wrong MVP grows for weeks in a long feature branch next to the main line and at some point lands in a big, risky merge. The better way is to build the experiment on trunk and switch it on for the experiment cohort only through a feature flag. Everyone else sees the status quo; the narrow new path is fully live for a small group.\n\n```javascript\n// the MVP path ships on trunk, gated by a flag – not hidden in a long branch\nfunction renderCheckout(user, cart) {\n  if (featureFlags.isEnabled(\"concierge_checkout\", user)) {\n    trackExperiment(\"concierge-checkout\", user);\n    return conciergeCheckout(cart); // narrow but complete path to value\n  }\n  return standardCheckout(cart);     // everyone else: unchanged status quo\n}\n```\n\nThat is more than a technical trick. It makes visible what an MVP is: a narrow but fully working segment – not a feature that is half visible everywhere and finished nowhere. Trunk-Based Development and short-lived branches make sure the experiment can be shipped at any time and switched off again just as quickly. Techniques such as *canary release* and *blue-green deployment* give the same principle its operational side: a small cohort gets the new thing, the rest stays safe.\n\nIf the experiment reaches beyond one service, another angle helps with honest testing. Instead of faking a full integration, the MVP service fulfills a minimal but real *consumer-driven contract*. The consumer writes down what it really needs, and the MVP fulfills exactly that – no more.\n\n```groovy\n// consumer-driven contract: the MVP fulfils a real, minimal contract\n// instead of faking a full integration\nPact.provider(\"payment-service\").upon(\"checkout\")\n  .given(\"an activated user\")\n  .uponReceiving(\"a request to attach a payment method\")\n    .withRequest(method: \"POST\", path: \"/methods\")\n  .willRespondWith(status: 201, body: [status: \"attached\"])\n```\n\nThe point behind it: the narrow path is real, not a facade. It really integrates against what it needs, but only against that. That keeps the learning signal clean without having to finish building the whole system.\n\n## Why this is faster, even though it sounds like more effort\n\nThe most common objection: setting up experiments, metrics, flags and contracts sounds like more work, not less. The objection confuses two quantities – effort per delivery and effort per insight gained.\n\n“Accelerate” by Forsgren, Humble and Kim provides part of the technical foundation for this. The four DORA metrics of the time – deployment frequency, lead time for changes, change fail rate and time to restore – stand for delivery capability, not for the market value of an experiment. A team that can ship small changes frequently and stably does, however, lower the technical hurdle for short experiments and quick rollbacks.\n\nAn MVP that is only a reduced feature set saves build time once and pushes the risk to the back. An MVP as an experiment costs some discipline up front and makes the risk visible earlier. That is no guarantee of less friction or higher quality. But it separates the question “Can we deliver it?” from the more important question “Which assumption are we testing with it?”.\n\nBy the way, if you take the MVP as an experiment seriously, you think toward a viable architecture from the start. An approach such as *evolutionary architecture* with *fitness functions* fits exactly, because it accepts that the product evolves along what you learn – not along a plan nobody has tested.\n\n## Conclusion\n\nAn MVP isn’t an amputated product. In my working definition, it is an experiment that honestly tests a risky assumption – the smallest version with which you can really test a hypothesis. A confirmatory test needs a learning question and a decision criterion set in advance; exploratory discovery may start more openly. Often that is a vertical slice through to the value, sometimes a concierge test or a landing page. “Minimal” refers to the necessary scope, not to carelessness. And it doesn’t even have to be code.\n\nWhen a team switches from “the product, but less” to “the smallest version that honestly tests an assumption”, it isn’t the toolbox that changes but the guiding question. No longer “What else can we leave out?” but “What do we need to learn next, and what does the smallest honest test for it look like?”. This question doesn’t prevent wrong decisions, but it makes visible which learning is supposed to justify the next investment.\n\n## Further reading\n\n- Eric Ries, *The Lean Startup* (2011) – definition of the MVP, Build-Measure-Learn, validated learning, vanity vs. actionable metrics\n- Steve Blank, “A minimum viable product is not always…” (blog, 2013) and *The Four Steps to the Epiphany* (2005) – customer development\n- Melissa Perri, “Finding the Truth Behind MVPs” (2016) – concierge and Wizard-of-Oz MVP\n- Nicole Forsgren, Jez Humble, Gene Kim, *Accelerate* (2018) – the four DORA metrics\n- Neal Ford, Rebecca Parsons, Patrick Kua, *Building Evolutionary Architectures* (O’Reilly, 2017) – fitness functions\n- Martin Fowler, “FeatureToggle” (2017) and trunkbaseddevelopment.com – feature flags and Trunk-Based Development\n- Consumer-Driven Contracts (Fowler/Robinson, 2006) and the contract testing tool Pact"},{"locale":"en","translation_key":"graphql-schema-in-der-fachsprache","slug":"a-graphql-schema-in-the-domain-language","title":"A GraphQL Schema in the Domain Language","summary":"A GraphQL schema is the best place there has ever been for the ubiquitous language of a domain – and if the domain is German, it may stay German there, too.","tags":["Software","GraphQL","API"],"published_at":"2018-04-24T10:00:00+00:00","updated_at":"2026-07-14T16:58:22.628285+00:00","url":"https://www.mikebild.dev/en/blog/a-graphql-schema-in-the-domain-language/","audio_url":null,"audio_duration_secs":null,"text":"# A GraphQL Schema in the Domain Language\n\nThe German word “Fachsprache” has two readings, and the more common one is explicitly not meant here. It isn’t about jargon – not the vocabulary an industry uses to keep outsiders at a distance. What I mean is what Eric Evans described in 2003 in “Domain-Driven Design” as the ubiquitous language: the one shared language that the business side and development actually speak in a project. The same words in the meeting, in the ticket, in the model, in the code. One vocabulary for everyone – not two vocabularies with a translation table in between.\n\nThe idea is fifteen years old, and in practice it rarely fails for lack of will. It fails for lack of a place. A glossary in the wiki goes stale from the day it is created, because nobody updates it when a field gets renamed. The code would be the more honest place, but the code belongs to only one side: the business department doesn’t read Java classes. What was missing all these years was an artifact that both sides can read and that is checked by machines at the same time.\n\nSince I started working with GraphQL, I’m convinced this artifact now exists: the schema. And – this is the more uncomfortable part of the thesis – you may speak the domain language there in German, too.\n\n## Translating twice, losing twice\n\nIn projects with a German-speaking business side, I have run into the same pattern again and again over the years. The business department says “Angebot” (offer). The database says `OFFER`, the class in the service is called `Quote`, and a `Proposal` shows up in the frontend – three translations of the same word, created at three points in time under three different deadlines. Ever since, every conversation between the business side and development translates twice: on the way in while listening, on the way back while answering.\n\nEach of these translations doesn’t just cost time, it distorts. Whether “Angebot” should be called offer, quote, bid or proposal isn’t a neutral choice – each of these words carries its own meaning in English, and none matches exactly what the business side means. In the end, a developer under deadline pressure makes the decision, and it then stays in the system for years – unnoticed, but effective in every single conversation about exactly this field.\n\n```mermaid\nflowchart LR\n  F[\"Business side<br/>says “Angebot”\"] -->|translate| E[\"Development<br/>Offer? Quote? Bid?\"]\n  E -->|translate| S[\"System<br/>OFFER, Quote, Proposal\"]\n  S -->|translate back| E\n  E -->|translate back| F\n```\n\nThe most expensive misunderstandings I have seen in reviews were rarely technical in nature. They were terms that had changed their meaning on the way through this chain – a “storniertes Angebot” (canceled offer) that was a `cancelled quote` in the system, even though the business side understood something different by “Stornierung” than development did by cancelled.\n\n## The experiment: uber-ng\n\nIn March, I created a small repository for this: [uber-ng](https://github.com/MikeBild/uber-ng), a deliberately manageable recreation of a ride-hailing service like the one you know from Uber. Not a product – a prototype with in-memory data, a few Mocha tests and a single question: How does a GraphQL schema read when the domain terms stay German?\n\nThe schema sits there as a separate file in schema notation – the SDL that is currently being added to the GraphQL specification after years of being merely a tooling convention. The core looks like this:\n\n```graphql\nenum STATUS {\n  angefragt\n  warteAufBestaetigung\n  angenommen\n}\n\ntype Angebot implements Node {\n  id: ID!\n  fahrgast: Fahrgast\n  von: String!\n  nach: String!\n  fahrer: Fahrer\n  wartezeit: String\n  status: STATUS\n}\n\ntype Mutation {\n  fahrtAnfragen(input: AnfrageInput!): Angebot\n  angebotAnnehmen(input: AngebotAnnehmenInput!): Angebot\n  angebotAblehnen(input: AngebotAblehnenInput!): Angebot\n}\n\ntype Subscription {\n  onAngebotChanged: Angebot\n}\n```\n\nIf you read this, you don’t need a glossary next to it. A ride is requested (“fahrtAnfragen”); what results is an offer (“Angebot”); an offer can be accepted or declined – and whoever declines must give a reason, because `AngebotAblehnenInput` requires a `grund: String!`. The mutations are verbs of the domain, not CRUD prose. `fahrtAnfragen` even enforces a domain distinction that a `createOffer` would have swallowed: what gets requested is a ride – the offer is the system’s answer to it, not something the passenger creates themselves. I only noticed this difference while formulating the schema, not before.\n\nThe clients’ requests then speak this language, too:\n\n```graphql\nmutation {\n  fahrtAnfragen(input: {\n    fahrgastId: \"f1\"\n    von: \"Alexanderplatz\"\n    nach: \"Flughafen Tegel\"\n  }) {\n    id\n    status\n    wartezeit\n  }\n}\n```\n\nYou can read this mutation out loud in a meeting, and the business side understands it without an interpreter. That is no small thing. It is the moment an API stops being a pure developer artifact.\n\nTechnically, the setup is deliberately ordinary: Node, a GraphQL server, subscriptions over WebSockets, as they have become established with `subscriptions-transport-ws` by now. `onAngebotChanged` pushes every state change of an offer to the connected clients – the passenger sees when `angefragt` (requested) turns into `warteAufBestaetigung` (awaiting confirmation) without having to ask. For the experiment, that is a side issue. The only interesting part is that this channel speaks the domain language, too: what arrives at the client is called Angebot, not `OfferDTO`.\n\n## What makes the schema a glossary\n\nA glossary describes a language. The schema enforces it – and that is exactly what it has over every glossary I have come across so far:\n\n- Every query is validated against the schema. Whoever invents or misspells a term gets an error instead of a silent misunderstanding.\n- Introspection makes the vocabulary queryable: GraphiQL shows types, fields and descriptions while you type – the glossary delivers itself.\n- `@deprecated` retires terms in an orderly way, with a reason and visible to every client. In uber-ng, exactly such a note is attached to `fahrgastId`.\n- The schema lives in version control. Every change of a term is a diff, and a diff can get a review in which the business side takes part, too.\n\nThen there are the description texts: the SDL allows a description on every type, every field and every enum value, and introspection delivers it along. So it doesn’t just say that there is an `Angebot`, but what the business side means by it – the definition travels with the term instead of aging in another system.\n\nA wiki can do none of this. Neither can a UML model. To my knowledge, the GraphQL schema is the first artifact that is at the same time readable by humans, checkable by machines and binding for operations. The schema is the glossary – not a copy of it.\n\n## States have names\n\nThe most inconspicuous part of the schema carries the most weight: the enum. `STATUS` with its three values is a complete, checkable description of an offer’s lifecycle – and the values are named the way the business side would say them on the phone.\n\nIn older systems, I rarely found this lifecycle written down anywhere. There, it is scattered across status strings in the database, if cascades in the service and the memory of the longest-serving colleague. Here, it is a few lines long, versioned and visible to every client:\n\n```mermaid\nstateDiagram-v2\n  [*] --> angefragt: fahrtAnfragen\n  angefragt --> warteAufBestaetigung: Matching in progress\n  warteAufBestaetigung --> angenommen: angebotAnnehmen\n  warteAufBestaetigung --> [*]: angebotAblehnen\n```\n\nThis is also where the first ugly spot shows: `warteAufBestaetigung`. GraphQL names only allow ASCII – letters, digits, underscore. The “ä” has to stay out; the domain language only gets into the schema filtered. I write this down deliberately instead of hiding it: if you choose German identifiers, you also choose `Bestaetigung`, `Strasse` and `ueberweisen`. In running text, that would be a spelling mistake; in the schema, it is the price of the decision, and you should know it before you make it.\n\n## Schema in German, implementation in English\n\nThe second question the experiment was supposed to answer: Where does the boundary run? After a few weeks, for me it lies exactly at the resolver map. The schema carries the domain language; everything behind it stays English – variables, helper functions, comments. Simplified, and written here with `graphql-subscriptions`, the pattern looks like this:\n\n```javascript\nconst uuid = require('uuid/v4');\nconst { PubSub } = require('graphql-subscriptions');\n\nconst pubsub = new PubSub();\nconst offers = {}; // in-memory store, resets on restart\n\nconst resolvers = {\n  Query: {\n    angebote: (root, { take = 10, skip = 0 }) =>\n      Object.values(offers).slice(skip, skip + take),\n  },\n  Mutation: {\n    fahrtAnfragen: (root, { input }) => {\n      // a ride request creates a new offer in its initial state\n      const offer = {\n        id: uuid(),\n        von: input.von,\n        nach: input.nach,\n        status: 'angefragt',\n      };\n      offers[offer.id] = offer;\n      pubsub.publish('offerChanged', { onAngebotChanged: offer });\n      return offer;\n    },\n    angebotAnnehmen: (root, { input }) => {\n      const offer = offers[input.angebotId];\n      // accepting is only valid while the offer awaits confirmation\n      if (offer.status !== 'warteAufBestaetigung') return offer;\n      offer.status = 'angenommen';\n      pubsub.publish('offerChanged', { onAngebotChanged: offer });\n      return offer;\n    },\n  },\n  Subscription: {\n    onAngebotChanged: {\n      subscribe: () => pubsub.asyncIterator('offerChanged'),\n    },\n  },\n};\n```\n\nThe German words appear exactly where the schema demands them: as keys of the resolver map and as enum values. The rest is ordinary English code. This separation has proven surprisingly stable, and it corresponds to the domain truth: `offers` and `pubsub` are technology and may be English. `Angebot` is a term with domain meaning, and it belongs to the business side – not to whoever happens to be implementing it.\n\nA side effect I hadn’t expected: the tests suddenly read like domain texts, too. A Mocha test that calls `fahrtAnfragen` and then checks whether the status is `angefragt` describes a domain fact – you could copy it almost word for word into the ticket as an acceptance criterion. Test coverage turns into a piece of documented domain knowledge, without needing an additional tool.\n\n## What speaks against it\n\nLet me stay honest: the experiment also made the resistance visible, and it isn’t small.\n\nThe break in style first. `type Angebot implements Node` mixes two languages in one line. `onAngebotChanged` glues an English prefix onto a German noun and appends an English participle – an identifier made of three language layers. camelCase is built for English word boundaries; with German compounds it gets bumpy, and nobody reads `warteAufBestaetigung` fluently. That bothers you while reading, a little bit every day, and it never stops bothering you.\n\nThen there is the ecosystem. Every tutorial, every Stack Overflow answer, every example in the Apollo documentation is in English – whoever transfers snippets now translates in the opposite direction. And the hardest limit is the team itself: as soon as a colleague joins who doesn’t speak German, the calculation flips completely. Then the German schema is no longer a bridge to the business side but a wall right through development.\n\nAnd a practical point that counts in everyday work: searchability. If you search for an error message along with `angebotAnnehmen`, you find nothing – if you search with `acceptOffer`, you at least find other people’s discussions that half fit. German identifiers decouple a project to some extent from the web’s collective debugging. For a prototype, that doesn’t matter; for a team under deadline pressure, it does.\n\n## When the domain language wins\n\nSo the trade-off isn’t a matter of taste but a question to the domain: In which language is the domain itself written?\n\nA ride-hailing service is a rewarding playground, but the real use case is domains that are German – not out of habit, but by law. Contracts under German law. Collective wage agreements. Billing rules whose terms a German regulation prescribes word for word. In a billing project a few years ago, words such as “Abschlag” (installment) and “Gutschrift” (credit note) were legally defined; their English translations in the code regularly triggered discussions that didn’t exist in the domain at all – was the `discount` now an “Abschlag” or rather a “Rabatt”? When the law speaks German and the business side thinks in German, an English API layer is the only place in the system that translates. And therefore the only place that can lie without anyone noticing.\n\nThe reverse holds just as well. An international team, a product for several markets, a public API – there, English is the domain language, and then it belongs consistently in the schema. By the way, the SDL comes with a usable middle path: English identifiers, but German description texts on types and fields. Then the schema at least carries the definitions of the terms, if not their names – and the translation table sits where it is checked and versioned instead of gathering dust in a wiki.\n\n## The bottom line\n\nuber-ng won’t become a product, and it never had to. The experiment showed me two things. First: the place is right. A GraphQL schema can deliver what glossaries, wikis and model documents promised for fifteen years and didn’t keep – a shared language that is checked instead of merely described. Second: the language in the schema is an architecture decision, not a question of style. German in the schema has a cost – breaks in style, ASCII crutches, friction with the ecosystem. It pays off exactly when the domain is German and every translation would create a second, unchecked truth.\n\nFor the projects in between, the question stays open, and that is fine. All that matters to me is that it gets asked at all. So far, in every schema I have seen, it was silently answered with “English” – and silent answers are rarely the well-considered ones.\n\n## Further reading\n\n- [uber-ng – GraphQL demo with a German schema (GitHub)](https://github.com/MikeBild/uber-ng)\n- [GraphQL documentation: Schemas and Types](https://graphql.org/learn/schema/)\n- [GraphQL Specification](https://spec.graphql.org/)\n- [Martin Fowler: Ubiquitous Language](https://martinfowler.com/bliki/UbiquitousLanguage.html)\n- [Eric Evans: Domain-Driven Design Reference](https://www.domainlanguage.com/ddd/reference/)"},{"locale":"en","translation_key":"angular-react-uebergaenge","slug":"angular-react-and-the-value-of-transitions","title":"Angular, React and the Value of Transitions","summary":"Whether a framework switch becomes a move or a rebuild depends on how cheaply two worlds can run side by side for months.","tags":["Software","Frontend"],"published_at":"2018-03-12T10:00:00+00:00","updated_at":"2026-07-14T16:56:24.827181+00:00","url":"https://www.mikebild.dev/en/blog/angular-react-and-the-value-of-transitions/","audio_url":null,"audio_duration_secs":null,"text":"# Angular, React and the Value of Transitions\n\nA decision like “we are rewriting the frontend from scratch” does not do its damage right away but with a delay of about nine months. By then, two half products exist: an old AngularJS frontend, officially frozen, that still gets hotfixes all the time because paying users work with it – and a new one that feels about sixty percent done and has no release date, because “everything has to be finished first.” From then on, every business requirement is negotiated twice: once for the old world, once for the one that has not shipped yet. The team quietly splits into keepers and rebuilders, and both groups slow down.\n\nI have now seen this course of events up close more than once, most recently in a product team with an AngularJS application that had grown over years. The mistake was never the target framework. It was a word missing from the decision: transition. In practice, a framework switch is not a rewrite but a state in which two worlds run in parallel for months. And whether this state turns out cheap or ruinous has surprisingly little to do with Angular or React.\n\n## The driver: AngularJS gets an expiration date\n\nSince the end of January, what had long been looming is official: AngularJS 1.x gets one last development cycle with version 1.7 and then moves into a three-year long-term support phase. From then on, there will only be security fixes and adjustments to new browser and jQuery versions, no more features. For teams with large 1.x applications, this is the moment when “at some point we have to get out of there” becomes a date.\n\nAccordingly, many migration decisions are being made right now. Whether the target is called Angular 5 (Angular 6 is due in the coming months) or React 16 – I find the direction secondary. What is interesting is how the decision is phrased. “We are rewriting” is a project with an end date, and that end date almost always slips. “We run both worlds in parallel and move piece by piece,” on the other hand, is a state you can steer, measure and stop if necessary.\n\n## Rewrite or move\n\nThat brings me to the actual thesis: the quality of a frontend architecture does not show in how modern its framework is, but in how cheap it would be to run two frameworks in parallel. If you have kept domain logic framework-free – plain modules, services without DI magic, state outside the components – you move. If you have poured calculations, validations and API calls into controllers, directives and components, you rewrite, whether you want to or not. The framework was then never a frame but the load-bearing structure of the entire building, and you do not swap load-bearing structures while the building is in use.\n\nIn the product team I mentioned, we did not migrate anything at all for two weeks before the first migration step. We pulled domain logic out of directives and moved it into simple ES modules, with the existing AngularJS services as a thin shell on top. Only after that was it even possible to decide which part would be a move and which part had to remain a rebuild. The distinction was sobering in its concreteness: whatever got by without an `angular.module` import could be moved like a piece of furniture. Everything else had to be assessed individually.\n\n## Hybrid operation with ngUpgrade\n\nFor the direction from AngularJS to Angular, running in parallel is not a trick but a documented, officially supported mode. The `UpgradeModule` starts the old application inside the new one:\n\n```typescript\n// app/app.module.ts — Angular 5 hosting AngularJS 1.6\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { UpgradeModule } from '@angular/upgrade/static';\n\n@NgModule({\n  imports: [BrowserModule, UpgradeModule],\n})\nexport class AppModule {\n  constructor(private upgrade: UpgradeModule) {}\n\n  ngDoBootstrap() {\n    // AngularJS boots inside Angular, not the other way around\n    this.upgrade.bootstrap(document.documentElement, ['orderApp'], { strictDi: true });\n  }\n}\n```\n\nFrom this point on, both frameworks run in the same DOM tree. New Angular components can be passed down into old templates:\n\n```typescript\n// expose a new Angular component to old AngularJS templates\nimport { downgradeComponent } from '@angular/upgrade/static';\nimport { InvoiceFooterComponent } from './invoice-footer.component';\n\nangular\n  .module('orderApp')\n  .directive('invoiceFooter', downgradeComponent({ component: InvoiceFooterComponent }));\n```\n\nConversely, old services can be passed up into the new dependency injection. That sounds convenient, and that is exactly where the danger lies: if you use the bridge too often, you intertwine both worlds more tightly than they were before the migration. Two change detection mechanisms run at the same time: AngularJS’s digest cycle and Angular’s zone-based detection. Every event that crosses the boundary is translated into both worlds, and bugs at this seam are unpleasant to track down. Hybrid operation is a tool for getting through a transition period – not for extending it. It needs an end that someone says out loud.\n\n## Route by route: the strangler approach\n\nThe idea behind it is much older than any of the frameworks involved. Back in 2004, Martin Fowler described how new systems grow around old ones like a strangler fig around its host tree – the Strangler Application. Translated to a frontend, that means: a thin shell owns the router and decides per route which world renders. There is now even a small framework of its own for exactly this pattern, single-spa, but at its core, routing discipline is enough.\n\n```mermaid\nflowchart LR\n  B[Browser] --> S[Router shell]\n  S --> O[\"/orders<br/>AngularJS 1.6\"]\n  S --> I[\"/invoices<br/>Angular 5\"]\n  S --> R[\"/reports<br/>Angular 5\"]\n  O -. \"moves over<br/>route by route\" .-> I\n```\n\nSplitting along routes has three properties that I have not found in this combination in any other migration split:\n\n- Every step can be rolled back individually – switching a route back is a router entry, not a rollback drama.\n- Progress is measurable and visible to everyone: this many routes old, this many new.\n- The boundary is about the domain, not the technology. “Invoices have moved” is something the product owner understands too; “the directive layer has been ported” is something nobody outside the team understands.\n\nThe big-bang alternative has none of these properties. It only has a deadline, and deadlines do not defend themselves.\n\nIncidentally, the route split also changes the team dynamics. Instead of a keepers group and a rebuilders group, there is one team that runs the same application and rebuilds it route by route along the way. Every completed step lands in production and gets put through its paces by real users – feedback arrives after weeks, not after a year and a half. That is unspectacular, but that is exactly where its value lies.\n\n## Domain logic that survives the move\n\nThe cheapest thing to move is code that knows nothing about any framework. In the application I mentioned, the invoice total logic was such a candidate – previously spread across a directive and two controllers, afterward a single module:\n\n```javascript\n// billing/invoice-totals.js — plain ES module, no framework imports\nexport function calculateInvoiceTotal(items, taxRate) {\n  const net = items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n  const tax = net * taxRate;\n  return { net, tax, gross: net + tax };\n}\n```\n\nThe old world uses the module through an AngularJS component:\n\n```javascript\n// old world: AngularJS 1.6 component wrapping the plain module\nimport { calculateInvoiceTotal } from '../billing/invoice-totals';\n\nangular.module('orderApp').component('invoiceFooter', {\n  bindings: { items: '<', taxRate: '<' },\n  controller: function InvoiceFooterController() {\n    this.$onChanges = () => {\n      this.totals = calculateInvoiceTotal(this.items, this.taxRate);\n    };\n  },\n  template: '<strong>{{ $ctrl.totals.gross | currency }}</strong>',\n});\n```\n\nThe new world – deliberately React 16 here, to show that the direction does not matter – uses the same module unchanged:\n\n```jsx\n// new world: React 16 component, same module untouched\nimport { calculateInvoiceTotal } from '../billing/invoice-totals';\n\nexport function InvoiceFooter({ items, taxRate }) {\n  const totals = calculateInvoiceTotal(items, taxRate);\n  return <strong>{totals.gross.toFixed(2)} €</strong>;\n}\n```\n\nThe direction of dependencies is the actual rule here, not the module format:\n\n```mermaid\nflowchart TD\n  OLD[\"AngularJS components<br/>old world\"] --> CORE[\"Domain logic modules<br/>without framework import\"]\n  NEW[\"React or Angular components<br/>new world\"] --> CORE\n  CORE -. \"forbidden:<br/>core knows no UI\" .-> OLD\n```\n\nMore can be kept framework-free than you might think at first glance: calculations and validations as pure functions, API access behind a module of its own instead of `$http` or `HttpClient` directly in components, application state in a store of its own. Redux is a good example here, because it is deliberately built to be framework-neutral – `react-redux` and `ng-redux` are just thin bindings. A Redux store including its reducers moves from AngularJS to React without a single changed line. What remains are thin components that take data and emit events. Those are exactly what then get rewritten – and that is the part of the work that goes quickly and carries little risk.\n\n## Custom Elements as a neutral bridge\n\nIf you are not migrating from AngularJS to Angular but, say, have to reconcile Angular and React in the same product, you have no `UpgradeModule`. The most neutral bridge emerging here is the web platform itself: Custom Elements. A component registered in the DOM as `<invoice-footer>` can be rendered by any world – React simply writes the tag into JSX, AngularJS into a template, a server-rendered CMS into its HTML stream.\n\nWith Angular Elements, an official labs project has been announced for exactly this, which is supposed to become tangible with Angular 6: packaging Angular components as Custom Elements, without an adapter per target framework. I find the direction remarkable, because it pulls the bridge out of the framework dispute and puts it on a browser standard. You have to stay honest about the browser situation: Custom Elements v1 run natively in Chrome and Safari; elsewhere, polyfills are still needed for now. For internal applications, that is usually acceptable; for public sites, it needs to be weighed.\n\n## The honest price: two bundles\n\nRunning in parallel is not free, and I do not believe in downplaying that. If you ship AngularJS and Angular – or Angular and React – at the same time, you send two framework runtimes over the wire. Depending on the combination, that quickly adds up to 150 kilobytes of additional compressed JavaScript before the first line of your own code is loaded. On top of that come two rendering models in the same browser tab, duplicate date and number formatting, and in the worst case duplicate HTTP layers with separate caches.\n\nThe freshly released webpack 4 at least makes the bundle side easier to handle: `splitChunks` replaces the old CommonsChunkPlugin and automatically pulls shared modules – such as the framework-free domain logic packages – into shared chunks. But tools only ease the price; they do not remove it. That is why an honest transition includes a budget: a measured upper limit for the total weight, a date after which the old bundle may no longer grow and a target quarter in which it disappears. Running in parallel is a loan. You may take it out – you should just know the interest rate and write down the repayment plan.\n\n## What I take away from this\n\nThe LTS announcement for AngularJS has just handed many teams a deadline, and deadlines tempt you into heroic decisions. The big-bang rewrite is one such heroic decision: it feels good on the day of the decision and, nine months later, like two half products. The transition is the unspectacular alternative – hybrid operation where it exists, a strangler split along the routes, Custom Elements as a bridge, an honestly quantified load weight.\n\nBut what really occupies me about the topic is looking back at your own architecture. Running in parallel is a test bench: it reveals how much of the application really belongs to us and how much to the framework. Domain logic in plain modules, state outside the components, API access behind boundaries of your own – that does not only pay off during a migration, but during a migration the bill comes due mercilessly. And since, after this switch, the next one will come at some point, I write the new world right away so that it makes the transition after next cheap. That may be the most useful question to ask of any frontend design, with no migration pressure at all: How expensive would it be to start a second world next to this application?\n\n## Further reading\n\n- Angular documentation: Upgrading from AngularJS: https://angular.io/guide/upgrade\n- Martin Fowler: StranglerApplication (2004): https://martinfowler.com/bliki/StranglerApplication.html\n- Angular blog: Stable AngularJS and Long Term Support: https://blog.angular.io/stable-angularjs-and-long-term-support-7e077635ee9c\n- single-spa: https://single-spa.js.org/"},{"locale":"en","translation_key":"javascript-prototypen-modell-hinter-class","slug":"prototypes-the-object-model-behind-javascript-classes","title":"Prototypes: The Object Model Behind JavaScript Classes","summary":"class in ES2015 is essentially syntactic sugar over prototypes: if you understand the [[Prototype]] chain, Object.create, and the new sequence, you debug this errors and shared methods with more confidence.","tags":["Software","Frontend"],"published_at":"2017-11-21T10:00:00+00:00","updated_at":"2026-07-13T13:21:34.260955+00:00","url":"https://www.mikebild.dev/en/blog/prototypes-the-object-model-behind-javascript-classes/","audio_url":null,"audio_duration_secs":null,"text":"```js\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n  speak() {\n    return this.name + ' makes a sound';\n  }\n}\n\nconst minka = new Animal('Minka');\nconst rex = new Animal('Rex');\n\nminka.speak === rex.speak;                         // true\nminka.hasOwnProperty('speak');                     // false\nObject.getPrototypeOf(minka) === Animal.prototype; // true\n```\n\nThree lines of output, and the whole article is in them. The method `speak` exists exactly once, even though two instances call it. Neither instance owns it – `hasOwnProperty` says no. It is found on a third object, `Animal.prototype`, which both instances point to with an internal reference.\n\n`class` didn’t invent this third object; it just moved it out of sight. In JavaScript, the reference to it carries every method lookup, every inheritance relationship, and every lost `this` binding. That is why I build up the model from the bottom here: first plain prototypes with `Object.create`, then constructor functions and the `new` sequence, then `class` as the facade that combines both.\n\n## Every object has a link upward\n\nThe foundation is surprisingly simple. Every object in JavaScript carries an internal reference, called `[[Prototype]]` in the specification. This reference points either to another object – the prototype – or to `null`. When you access a property that the object itself doesn’t have, the language doesn’t give up and return `undefined`. It first follows the `[[Prototype]]` link and keeps searching there. And if it finds nothing there, it goes one link higher. That is how the prototype chain comes about, and it ends at `null`.\n\nYou see this most clearly without any `class` and without `new`, using only `Object.create`:\n\n```js\nconst animal = {\n  describe() {\n    return this.name + ' makes ' + this.sound;\n  }\n};\n\nconst dog = Object.create(animal);\ndog.name = 'Rex';\ndog.sound = 'woof';\n\ndog.describe(); // 'Rex makes woof'\n\nObject.getPrototypeOf(dog) === animal; // true\ndog.hasOwnProperty('describe');        // false\ndog.hasOwnProperty('name');            // true\n```\n\nLook at what happens here. The object `dog` itself only owns `name` and `sound` – `hasOwnProperty` confirms that. It doesn’t find the method `describe` on itself but only one step higher, on `animal`. During the call, though, what counts is who the receiver was: `this` is `dog`, which is why `describe` reads `Rex` and `woof`. The method lives on the prototype, the data lives on the instance, and the lookup connects the two. That is the whole mechanism – no classes, no constructors, just one object pointing to another.\n\n`Object.create` makes this link explicitly visible: the first parameter becomes the new object’s `[[Prototype]]` directly. You can even write `Object.create(null)` and get an object with no prototype at all – no `toString`, no `hasOwnProperty`, a bare dictionary. Useful when you want an object as a pure key-value store and don’t want inherited properties getting in the way.\n\n## The chain, visualized\n\nWhen `dog.describe()` is called, the lookup walks up the chain. The following diagram shows the stations up to the end at `null`:\n\n```mermaid\ngraph TD\n  A[\"dog<br/>own: name, sound\"] -->|\"[[Prototype]]\"| B[\"animal<br/>own: describe\"]\n  B -->|\"[[Prototype]]\"| C[\"Object.prototype<br/>own: hasOwnProperty, toString\"]\n  C -->|\"[[Prototype]]\"| D[\"null\"]\n```\n\nEvery arrow is a `[[Prototype]]` reference, and the lookup climbs along them. If the language looks for `describe`, it finds it at `animal`. If it were looking for `toString`, it would go one station further to `Object.prototype`. And if it were looking for something that exists nowhere, it would arrive at `null` and return `undefined`. This chain is not a special case for hand-built objects – every object, every array, every function hangs on a chain like this, with `Object.prototype` at its root.\n\n## Constructor functions: the way before `class`\n\nBefore ES2015, you built reusable “types” with constructor functions. The trick lies in two parts that you have to keep apart. First: every function has a property called `prototype` – an ordinary object that serves as a template. Second: the `new` operator connects a fresh object to exactly this template.\n\n```js\nfunction Animal(name) {\n  this.name = name;\n}\n\nAnimal.prototype.speak = function () {\n  return this.name + ' makes a sound';\n};\n\nconst cat = new Animal('Minka');\ncat.speak(); // 'Minka makes a sound'\n\nObject.getPrototypeOf(cat) === Animal.prototype; // true\ncat.hasOwnProperty('speak');                     // false\n```\n\nWhat exactly does `new Animal('Minka')` do? The sequence has – simplified – three steps. First, a new, empty object is created, and its `[[Prototype]]` is set to `Animal.prototype`. Then `Animal` is called with `this` pointing to this new object – that is how `this.name = name` ends up as an own property on the instance. And finally: if the function itself doesn’t return an object, the new object becomes the result. That is why `speak` isn’t on the instance but on `Animal.prototype`, and is shared by all cats.\n\nBefore `class`, inheritance was manual work – and precisely this manual work shows what `extends` later automates:\n\n```js\nfunction Dog(name) {\n  Animal.call(this, name);       // Parent-Konstruktor auf eigenem this\n}\n\nDog.prototype = Object.create(Animal.prototype); // Kette einhängen\nDog.prototype.constructor = Dog;                 // constructor wieder setzen\n\nDog.prototype.speak = function () {\n  return this.name + ' makes woof';\n};\n\nconst rex = new Dog('Rex');\nrex.speak();                 // 'Rex makes woof'\nrex instanceof Dog;          // true\nrex instanceof Animal;       // true\n```\n\nThree lines carry the load here. `Animal.call(this, name)` calls the parent constructor on your own `this` so that `name` gets set. `Dog.prototype = Object.create(Animal.prototype)` hooks in the prototype chain, so that a Dog instance searches first at `Dog.prototype`, then at `Animal.prototype`, then at `Object.prototype`. And the third line repairs something the second one broke: overwriting `Dog.prototype` lost the `constructor` back-reference, which we restore manually. Details like these are exactly what you forget in practice – and what `class` takes off your hands.\n\n## The same thing as a `class`\n\nNow the same code in ES2015 syntax, imagined side by side. The result is identical in the object model – the same prototype objects, the same chain, the same shared methods:\n\n```js\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n  speak() {\n    return this.name + ' makes a sound';\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name) {\n    super(name);\n  }\n  speak() {\n    return this.name + ' makes woof';\n  }\n}\n\nconst rex = new Dog('Rex');\nObject.getPrototypeOf(rex) === Dog.prototype;              // true\nObject.getPrototypeOf(Dog.prototype) === Animal.prototype; // true\n```\n\nCompare this with the ES5 version, and the translation becomes immediately visible. The `speak` methods in the class body end up on `Animal.prototype` and `Dog.prototype` – not on the instance. `extends Animal` takes care of hooking in the chain, for which we just wrote `Object.create(Animal.prototype)` by hand. And `super(name)` replaces the manual `Animal.call(this, name)`. The last line proves it: `rex` points to `Dog.prototype`, and that points to `Animal.prototype`. The same chain as before, just without the boilerplate and without the forgotten `constructor` line.\n\nYou still have to be honest, though: `class` is syntactic sugar, but not exclusively. A class body always runs in strict mode. A class can’t be called without `new` – the attempt throws an error, whereas a constructor function could also be misused as a regular function. And `class` declarations aren’t hoisted to the top and initialized like `function` declarations; they sit in a temporal dead zone and can’t be used before the line where they are defined. `super` in methods also relies on an internal mechanism (`[[HomeObject]]`) that you can’t replicate one to one in plain ES5. So the facade is convenient and, at a few edges, stricter than the original – but the model underneath is still prototypes.\n\n## Cleanly separating `prototype`, `__proto__`, and `Object.create`\n\nThe most common confusion I run into in code reviews revolves around two similar-sounding names. `prototype` and `__proto__` are not the same, and mixing them up produces bugs you stare at for a long time. This list sorts out the three tools:\n\n- A constructible function usually has its own `prototype` property. `new` uses the object referenced there as the prototype of the instance. Ordinary instances don’t have their own `prototype` property; arrow functions and methods aren’t constructible and don’t have such a template either.\n- `__proto__` (or the internal `[[Prototype]]`) is the actual chain link that every object carries. The canonical access goes through `Object.getPrototypeOf(obj)`; `__proto__` itself is only standardized in ES2015 via Annex B and is considered legacy.\n- `Object.create(proto)` creates an object and sets its `[[Prototype]]` directly to `proto` – with no constructor function at all. That is the direct way to lay down a chain link.\n\nThe crucial difference: `Fn.prototype` is the template on the function, `instance.[[Prototype]]` is the link on the created object. When `new Fn()` is called, one becomes the other. And to untangle it once and for all – the function itself is also an object and has its own link:\n\n```js\nfunction Fn() {}\nconst obj = new Fn();\n\nObject.getPrototypeOf(obj) === Fn.prototype; // true  (Instanz-Link)\nobj.prototype;                               // undefined (Instanz hat keine)\nObject.getPrototypeOf(Fn) === Function.prototype; // true (Fn ist selbst Objekt)\n```\n\nPay attention to the last line. `Fn.__proto__` is `Function.prototype`, not `Fn.prototype`. If you mix these two up, you look for methods in the wrong place. When in doubt, `Object.getPrototypeOf` always helps you walk the chain step by step instead of guessing.\n\n## The most expensive pitfall: methods in the constructor\n\nNow to the point that costs memory in real codebases and often slips through reviews. It makes a tangible difference whether a method lives on the prototype or is created in the constructor:\n\n```js\nfunction WidgetBad() {\n  this.render = function () { /* ... */ }; // pro Instanz eine neue Funktion\n}\n\nfunction WidgetGood() {}\nWidgetGood.prototype.render = function () { /* ... */ }; // geteilt\n\nconst a1 = new WidgetBad();\nconst a2 = new WidgetBad();\na1.render === a2.render; // false  -> zwei getrennte Funktionen\n\nconst b1 = new WidgetGood();\nconst b2 = new WidgetGood();\nb1.render === b2.render; // true   -> eine Funktion, geteilt\n```\n\nThe proof is in the comparisons. With `WidgetBad`, every instance gets its own `render` function – with a thousand widgets, that is a thousand identical functions in memory. With `WidgetGood`, `render` lives once on `WidgetGood.prototype`, and all instances share it. That is exactly what `class` does automatically: methods in the class body end up on the prototype, not on the instance. So with `class`, you don’t have to make any effort for the good case – you just must not destroy it with an assignment in the `constructor`.\n\nThe second common pitfall is losing `this`. A prototype method only knows its receiver when it is called as `obj.method()`. If you detach it, the binding is gone:\n\n```js\nconst cat = new Animal('Minka');\n\nconst fn = cat.speak;\nfn(); // this ist nicht mehr cat -> Fehler oder falsches Ergebnis\n\nconst bound = cat.speak.bind(cat);\nbound(); // 'Minka makes a sound' -> this wieder gebunden\n```\n\nThat is not a bug but a direct consequence of the model: `this` is determined at call time, not at definition time. If you pull `cat.speak` out into a free variable, the receiver is missing. The tools against this are established in 2017: `.bind(cat)` creates a permanently bound variant, or you wrap the call in an arrow function that takes `this` from the surrounding scope. A side note on what is coming: class fields with arrow functions are in the works and are meant to make exactly this binding more elegant – but at the end of 2017, that is still a TC39 proposal and not a standard. If you need it in production today, reach for `bind` or an arrow wrapper.\n\n## Why this pays off\n\nYou can write JavaScript with `class` for years without ever saying “prototype.” Until the day `this` is `undefined` in an event handler, an inherited method can’t be found, or a profiler shows the same function a thousand times in the heap. That is when the people who know the model part ways with the people who guess. The three recurring symptoms – lost `this`, a method in the wrong place, memory per instance – are not quirks of the language but logical consequences of a chain of objects pointing to each other.\n\n`class` has its place: readable, strict, and it takes the error-prone boilerplate of ES5 inheritance off your hands. But it is a facade, and behind the facade there is still `Object.create`, `Fn.prototype`, and a `new` that connects the two. The next time you write `extends`, think briefly about the three lines it replaces – the hooked-in chain, the `super` call, the `constructor` back-reference. Then `class` is no longer magic but a shortcut whose long form you could write out yourself at any time.\n\nThis prototypal thinking is the same common thread that runs through the [JavaScript patterns that stayed](https://www.mikebild.dev/en/blog/javascript-patterns-that-stayed/) – objects pointing to objects, functions as building blocks. If you understand this foundation, you build on frameworks more calmly.\n\n## Further reading\n\n- MDN, Inheritance and the prototype chain: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain\n- MDN, Object.create: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create\n- MDN, Object.getPrototypeOf: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf\n- MDN, Object.setPrototypeOf: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf\n- MDN, Object.prototype.\\_\\_proto\\_\\_: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto\n- MDN, Classes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\n- MDN, new operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new\n- ECMAScript 2015 (ES6) Spec: https://www.ecma-international.org/ecma-262/6.0/\n- ECMAScript 2017 (ES8) Spec: https://www.ecma-international.org/ecma-262/8.0/"},{"locale":"en","translation_key":"redux-als-protokoll","slug":"redux-as-a-protocol-for-ui-changes","title":"Redux as a Protocol for UI Changes","summary":"The store is the most boring part of Redux – the value lies in the message protocol of named, serializable actions that makes UI changes traceable, testable and open to discussion.","tags":["Software","Frontend"],"published_at":"2017-10-12T10:00:00+00:00","updated_at":"2026-07-14T17:09:15.018598+00:00","url":"https://www.mikebild.dev/en/blog/redux-as-a-protocol-for-ui-changes/","audio_url":null,"audio_duration_secs":null,"text":"# Redux as a Protocol for UI Changes\n\nIn networking, a protocol is not software but an agreement: it defines which messages may flow between parties, how each message is structured and what it means. TCP doesn’t dictate to anyone which program runs at the endpoints – it only determines the shape of the packets and the rules of the exchange. Exactly this notion, applied to a user interface, describes Redux more accurately than the usual shorthand.\n\nThat shorthand goes: Redux is a global state container for React applications. That isn’t wrong, but it points at the most boring part. Every application has an object that holds application state – as `window.appState` if need be, and that alone gains you nothing. What’s interesting about Redux is the agreement on how this object may change: exclusively through named, serializable messages. Redux is less a container than a protocol for changes – between the parts of the UI and, which is easily overlooked, across time. When you dispatch an action today, you are also talking to the colleague who reads the action log of a bug report in three months.\n\n## Three building blocks, very unevenly weighted\n\nRedux consists of three parts: the store, which holds the state, the actions, which describe changes, and the reducers, which compute the new state from the old state and an action. The store itself is surprisingly unspectacular – a few dozen lines around an object, a `dispatch` function and a list of subscribers. If you read the source code of `createStore`, you’re done in one cup of coffee.\n\nThe value lies in what the other two building blocks enforce. An action is a simple object with a `type` and a payload:\n\n```js\n// actions.js\nexport const ORDER_SUBMITTED = 'ORDER_SUBMITTED';\nexport const ORDER_ACCEPTED = 'ORDER_ACCEPTED';\nexport const ORDER_REJECTED = 'ORDER_REJECTED';\n\nexport const submitOrder = order => ({\n  type: ORDER_SUBMITTED,\n  payload: { orderId: order.id, items: order.items }\n});\n```\n\nNo function pointer, no class instance, no reference to a component. Just data that can be written down as JSON. That looks like a restriction – and it is meant to be exactly that. A message that can be serialized can also be recorded, sent, compared and still read years later. A method call can do none of that.\n\nThe reducer is the second half of the agreement: a pure function that never triggers anything itself but only answers what a message means for the state.\n\n```js\n// ordersReducer.js\nimport { ORDER_SUBMITTED, ORDER_ACCEPTED } from './actions';\n\nconst initialState = { pending: [], accepted: [] };\n\nexport default function ordersReducer(state = initialState, action) {\n  switch (action.type) {\n    case ORDER_SUBMITTED:\n      return { ...state, pending: [...state.pending, action.payload.orderId] };\n    case ORDER_ACCEPTED:\n      return {\n        ...state,\n        pending: state.pending.filter(id => id !== action.payload.orderId),\n        accepted: [...state.accepted, action.payload.orderId]\n      };\n    default:\n      return state;\n  }\n}\n```\n\nAlmost everything teams value about Redux follows from this separation – message here, meaning there. It is usually filed under “predictability”. A different sorting helps me more:\n\n- Every change can be recorded and replayed, because it exists as a data object.\n- Every change can be tested without a browser, because the reducer is a pure function.\n- Every change has a name that you can talk about in code review and with the business side.\n- Every change can be observed from outside without touching the UI.\n\nThese are not four features. This is the same property four times: there is a protocol.\n\n## Time travel is not magic\n\nThe Redux DevTools demonstrate this most impressively. Every action appears there as a line in a log, and because the state results only from folding all previous actions over the reducers, you can jump back anywhere in the log – the UI follows. The first time you show it, it looks like a trick. In fact, it is the mundane consequence of the protocol idea: if you know all messages and apply a deterministic function to them, you can reconstruct every intermediate state. Network people have known this forever – a packet capture plus a state machine gives you the complete session.\n\nIn a project this summer, exactly this spared us a stubborn bug. A user reported a state nobody could reproduce: an order that was displayed as open and confirmed at the same time. Instead of collecting guesses, we had the exported action history sent to us and replayed it locally. The faulty order – `ORDER_ACCEPTED` arrived before `ORDER_SUBMITTED` because two requests had overtaken each other – was there in black and white in the log after five minutes. With scattered `setState` calls, the same diagnosis would have been an afternoon with a debugger and luck.\n\nTesting also benefits from the message form, without any test infrastructure at all:\n\n```js\n// ordersReducer.test.js\nimport ordersReducer from './ordersReducer';\nimport { submitOrder } from './actions';\n\nit('moves a submitted order into pending', () => {\n  const state = ordersReducer(undefined, submitOrder({ id: '42', items: [] }));\n  expect(state.pending).toEqual(['42']);\n});\n```\n\nNo DOM, no mock of a store, no rendering. Input, output, done. Reducer tests are among the few frontend tests I have never seen be flaky.\n\n## Events instead of commands\n\nThis is also exactly where the value gets lost fastest, though – not because of the library but because of how the messages are cut. In a code review this spring, I was looking at a reducer whose action list looked like this: `SET_LOADING_TRUE`, `SET_LOADING_FALSE`, `SET_ORDERS`, `SET_ERROR`, `RESET_ERROR`. Formally, everything was correct: named, serializable objects, pure reducers, the DevTools work. Still, the protocol was worthless, because the messages didn’t describe what had happened but which field value the sender would like. That’s not an event protocol; those are remote assignments – `setState` with a detour and more typing.\n\nThe difference becomes clear in a direct comparison:\n\n```js\n// commands: the sender prescribes how state must change\ndispatch({ type: 'SET_LOADING_TRUE' });\ndispatch({ type: 'SET_ORDERS', payload: orders });\ndispatch({ type: 'SET_LOADING_FALSE' });\n\n// events: the sender reports what happened in the domain\ndispatch({ type: 'ORDERS_REQUESTED' });\ndispatch({ type: 'ORDERS_LOADED', payload: { orders } });\ndispatch({ type: 'ORDERS_LOADING_FAILED', payload: { error } });\n```\n\nThe event variant has three properties that the command variant lacks. First, it brings domain language into the code: `ORDER_SUBMITTED` is a sentence the product owner understands too; `SET_LOADING_TRUE` is understood only by the author of the component. In review we then talk about the question “May a rejected order be resubmitted?” instead of boolean choreography. Second, an event is in the past and therefore undisputed – it is reported, not ordered. The sender doesn’t need to know who is listening. Third, and precisely for that reason, the circle of receivers scales: if a second reducer later needs to count the number of open orders for a badge, it simply subscribes to `ORDER_SUBMITTED` as well. With `SET_ORDERS`, the sender would have to be rebuilt. A command knows its receiver, an event knows only its cause – in the protocol picture, that’s the difference between an RPC call and a broadcast.\n\nSince then, I read action files like a message directory. If they contain a vocabulary of the domain in the past tense, the protocol holds. If they contain a list of setters, the team has built a second `setState` mechanism, only more cumbersome.\n\n```mermaid\nsequenceDiagram\n  participant V as View\n  participant M as Middleware\n  participant R as Reducer\n  participant S as Store\n  V->>M: dispatch(ORDER_SUBMITTED)\n  Note over M: Listening point:<br/>logging, analytics, DevTools\n  M->>R: action (unchanged)\n  R->>S: new state\n  S-->>V: notify + render\n```\n\n## Middleware: listening in on the protocol\n\nIf you take actions seriously as messages, you get a second capability for free that stays invisible in the container view: you can tap into the message stream. That’s exactly what middleware is – a function that sits between `dispatch` and the reducer and sees every message before it acquires meaning.\n\n```js\n// analyticsMiddleware.js\nconst analyticsMiddleware = store => next => action => {\n  if (action.type.startsWith('ORDER_')) {\n    trackEvent(action.type, action.payload);\n  }\n  return next(action);\n};\n```\n\nThe triple-nested signature takes some getting used to, but it’s simply applied currying – I took apart how such function chains come about a few weeks ago in [JavaScript Patterns That Stayed: Modules, Higher-Order Functions, Currying](https://www.mikebild.dev/en/blog/javascript-patterns-that-stayed/). More important than the form is the consequence: analytics doesn’t need a single call in a component. In the ordering project, the product analytics hang entirely on this one file. When a new metric was requested – how often a rejection follows a submission – that was a change in the middleware, not in thirty components. The same goes for logging in the error case: writing the last fifty actions into a ring buffer and attaching them to the error report costs twenty lines.\n\nIn the end, the async question is a protocol question too. Whether `redux-thunk` for the simple cases or `redux-saga` and `redux-observable` when flows have to be orchestrated – all three are middleware, and all three eventually flow back into ordinary actions. The asynchronous part doesn’t change the language; it just speaks it with a delay. How push and pull data flows fundamentally differ is covered in [RxJS: Push and Pull](https://www.mikebild.dev/en/blog/rxjs-telling-push-and-pull-apart/) – Redux consistently lives on the push side.\n\n## The limit: not every change deserves a message\n\nAs useful as the protocol is, it has a price per message: a constant, an action creator, a reducer branch, and if in doubt a test. Only what is worth it should pay this price. Whether a dropdown is currently open, which tab is active, what is in an input field before it is submitted – that is local UI state, and it belongs in the component, in a plain `setState`. Nobody wants to read thirty `INPUT_CHANGED` between two domain events in the action log; the protocol gets noisy, and time travel turns into a slide show.\n\nDan Abramov himself wrote this down clearly last year in “You Might Not Need Redux”, and the text is not a distancing but a price list: the benefits of Redux arise precisely from its constraints, so it only pays off where you actually cash in those benefits. My check questions before state moves into the store:\n\n- Do several components that are far apart in the tree read this state?\n- Does the change have a domain name that would explain something in a bug report?\n- Does anyone care about the history of these changes – support, analytics, debugging?\n\nThree times no means: component. React has always been able to handle local state itself, and the just-released React 16 hasn’t changed that – the new Fiber core renders differently, but `setState` stays `setState`. The two mechanisms don’t compete; they serve different questions.\n\n```mermaid\nflowchart TD\n  A[State comes into being] --> B{Do distant<br/>components read it?}\n  B -- no --> L[Local:<br/>setState in the component]\n  B -- yes --> C{Domain name?<br/>History relevant?}\n  C -- no --> L\n  C -- yes --> S[Store:<br/>action + reducer]\n```\n\nIn the repository [introduction-react](https://github.com/MikeBild/introduction-react), in which I have been collecting React topics for talks and examples since the spring, the Redux part is deliberately small for exactly this reason: a manageable example app in which the message vocabulary stays limited to a handful of domain events. Not because more wouldn’t be possible – but because the difference between protocol and container is easier to see in a small, clean vocabulary than in a large, noisy one.\n\n## What I take away from this\n\nOver time, I noticed that the teams who are happy with Redux and the ones who curse it aren’t using different libraries at all – they are using different protocols. The former have a vocabulary of domain events that you can read out loud; their action log reads like a running report of the application. The latter have setters in capital letters and wonder why the promised benefit fails to appear: the DevTools show noise, the tests check assignments, and there is nothing to discuss in review, because `SET_VALUE` contains no domain statement anyone could disagree with.\n\nThat’s why I now consider the store an implementation detail and the protocol the real architectural decision. The three questions that make the difference have little to do with the library: Which events exist in this application? What are they called in the language of the domain? And who may trigger them? If you have answered these questions, Redux gives you traceability, testability and a shared language almost for free. If you skip them, you get a global state container with ceremony – and then you really wouldn’t have needed Redux.\n\nShould Redux be replaced by something else at some point, the exercise still remains valuable. A protocol of named, serializable change messages is not an invention of this library – networking has lived on it for decades, and so have event-driven systems on the server. Redux merely carried this discipline to a place where it used to be rare: right into the UI.\n\n## Further reading\n\n- [MikeBild/introduction-react](https://github.com/MikeBild/introduction-react) – repository with React examples, including a Flux/Redux part and an example app\n- [Redux documentation: Motivation](https://redux.js.org/understanding/thinking-in-redux/motivation) – why mutation plus asynchrony is the real problem\n- [Dan Abramov: You Might Not Need Redux](https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367) – the price list for the constraints, from the author himself\n- [React v16.0 release announcement](https://legacy.reactjs.org/blog/2017/09/26/react-v16.0.html) – the fresh Fiber core, which changes nothing about the data flow model"},{"locale":"en","translation_key":"javascript-patterns-module-hof-currying","slug":"javascript-patterns-that-stayed","title":"JavaScript Patterns That Stayed: Modules, Higher-Order Functions, Currying","summary":"Three JavaScript patterns have survived every framework change: the module pattern for clean encapsulation, higher-order functions for functions as values and currying for specialized variants. Why they form the foundation of modern utility libraries.","tags":["Software","Frontend"],"published_at":"2017-09-19T10:00:00+00:00","updated_at":"2026-07-13T13:21:18.680262+00:00","url":"https://www.mikebild.dev/en/blog/javascript-patterns-that-stayed/","audio_url":null,"audio_duration_secs":null,"text":"A pattern is not a library and not a framework feature. It is the shape in which code is arranged – and that sits one level below whatever framework currently sits on top. For us, only a few years lay between jQuery, Backbone, Angular 1, Angular 2 and React. The tools were swapped out; the arrangement underneath stayed remarkably constant.\n\nI pick out three of these arrangements here: the module pattern, higher-order functions and currying or partial application. They build on each other, and once you have taken them apart, you read modern JavaScript code with different eyes. I assume ES2015 as the baseline.\n\nThe three patterns in one sentence each:\n\n- The module pattern encapsulates state and exposes only a deliberately chosen public API.\n- Higher-Order Functions treat functions as values – they take functions as arguments or return them.\n- Currying and partial application turn a generic function into specialized, preconfigured variants.\n\n## Module pattern: two routes, one goal\n\nThe oldest problem in browser JavaScript is the global namespace. In the past, every variable you did not deliberately encapsulate ended up on the `window` object, and two scripts could overwrite each other without noticing. The solution before ES6 was a convention, not a language feature: the Immediately Invoked Function Expression, IIFE for short. You wrap code in a function, call it immediately and use the resulting scope as a private space. What is declared inside stays inside – unless you deliberately return it as an object. This return of the public API is also called the Revealing Module Pattern.\n\n```js\nconst counterModule = (function () {\n  let count = 0; // private, not accessible from outside\n\n  return {\n    increment() {\n      return ++count;\n    },\n    get() {\n      return count;\n    }\n  };\n})();\n\ncounterModule.increment(); // 1\ncounterModule.increment(); // 2\ncounterModule.get();       // 2\ncounterModule.count;       // undefined – deliberately not exposed\n```\n\nThe trick lies in the closure: the returned methods keep access to `count` even though the outer function finished long ago. From the outside, there is no way to set `count` directly. That is exactly what we wanted – encapsulation without language support, purely through scope and closure.\n\nSince ES2015, there are real modules in the language. Every file is its own module scope, nothing leaks to global automatically, and what should be visible from the outside you mark with `export`. Importing happens statically with `import`. The same example as an ES module:\n\n```js\n// counter.js\nlet count = 0; // module-private, only visible in this file\n\nexport function increment() {\n  return ++count;\n}\n\nexport function get() {\n  return count;\n}\n```\n\n```js\n// app.js\nimport { increment, get } from './counter.js';\n\nincrement(); // 1\nincrement(); // 2\nget();       // 2\n```\n\nBoth pursue the same goal: private state and a clearly defined public API. The difference is the semantics. With the IIFE, encapsulation is a runtime construct based on functions and closures. With the ES module, it is part of the module system – tools can analyze the imports before execution and remove unused code. Imported bindings are also live and cannot be reassigned by the importer. Modules run implicitly in strict mode.\n\n```mermaid\ngraph LR\n  A[IIFE + Closure] --> C[Encapsulation<br/>private state<br/>clear public API]\n  B[ES6 import/export] --> C\n```\n\nAn honest word about the state of things in 2017: Node.js does not yet support native ES modules in a stable way. There you still write CommonJS with `require` and `module.exports`; the experimental `--experimental-modules` flag has only just appeared with Node 8.5.0. In browsers, support is fresh – Chrome 61 and Safari 10.1 already handle `type=\"module\"`, Firefox and Edge still behind a flag. In practice, in 2017 we therefore bundle with webpack or Rollup and let Babel translate the `import/export` syntax. That does not change the pattern: we think in modules, even if deployment still goes through a bundler.\n\n## Higher-Order Functions: functions are values\n\nThe second building block is JavaScript’s real strength, and most of us used it long before we had a name for it. In JavaScript, functions are first-class values: you can store them in variables, pass them as arguments and return them from other functions. A function that takes a function as an argument or returns a function is called a higher-order function.\n\nThe best-known examples are the array methods `map`, `filter` and `reduce`. They have been available everywhere since ES5 (2009) and replace imperative loops with declarative transformations. Instead of describing how to iterate, you describe what happens to each element:\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\n\nconst doubled = numbers.map(n => n * 2);        // [2, 4, 6, 8, 10]\nconst evens = numbers.filter(n => n % 2 === 0); // [2, 4]\nconst sum = numbers.reduce((acc, n) => acc + n, 0); // 15\n```\n\nEach of these methods is itself a higher-order function because it takes a callback. `map` calls the callback for each element and collects the return values in a new array. `filter` keeps only the elements for which the callback returns true. `reduce` folds the array into a single value by carrying an accumulator through all elements.\n\nThe other half of the pattern – functions that return functions – is the key to everything that comes after. A function that produces a configured function is sometimes called a function factory:\n\n```js\nconst multiplyBy = factor => n => n * factor;\n\nconst double = multiplyBy(2);\nconst triple = multiplyBy(3);\n\ndouble(5); // 10\ntriple(5); // 15\n\n[1, 2, 3].map(double); // [2, 4, 6]\n```\n\n`multiplyBy(2)` does not return a number but a new function that has remembered `factor` via closure. `double` and `triple` are specialized tools built from a single generic function. And because they are perfectly normal functions, you can pass them directly to `map`. This is exactly where higher-order functions interlock with the next pattern.\n\n## Currying and partial application: from generic to specific\n\nCurrying means turning a function with several arguments into a chain of unary functions. `f(a, b, c)` becomes `f(a)(b)(c)`. Each call takes exactly one argument and returns a function that waits for the next one – until all arguments are there and the result is computed. Again, this is implemented via closures.\n\n```js\nconst add = (a, b) => a + b;          // ordinary, two arguments at once\nconst curriedAdd = a => b => a + b;   // curried, unary chain\n\ncurriedAdd(10)(5); // 15\n\nconst add10 = curriedAdd(10); // specialized function, waits for b\nadd10(5);  // 15\nadd10(90); // 100\n```\n\nClosely related, but not the same, is partial application. Here you fix some arguments of a function and get a new function with fewer parameters. The difference from currying: partial application does not force you into unary chains but simply fixes a few arguments up front. In JavaScript, you can get this without any helpers of your own via `Function.prototype.bind`, which has also been available since ES5:\n\n```js\nconst add = (a, b) => a + b;\n\n// bind fixes this (here null) and the leading arguments\nconst add10 = add.bind(null, 10);\n\nadd10(5);  // 15\nadd10(90); // 100\n```\n\nThe benefit shows as soon as you compose such specialized functions. From a small stock of generic building blocks, you build tailored variants and plug them together. An example that shows how naturally such a building block fits into the array methods – `add10` from the `bind` step goes straight into `map`:\n\n```js\nconst numbers = [1, 2, 3, 4];\n\nconst shifted = numbers.map(add10);                   // [11, 12, 13, 14]\nconst total = shifted.reduce((sum, n) => sum + n, 0); // 50\n```\n\nThe arc from generic to specialized function reads well as a flow:\n\n```mermaid\ngraph LR\n  A[\"add(a, b)<br/>generic, two arguments\"] --> B[\"curriedAdd(10)<br/>or add.bind(null, 10)\"]\n  B --> C[\"add10(n)<br/>specialized, one argument\"]\n```\n\nAnd that is exactly why these patterns have stayed for years: they are the foundation of modern utility libraries. Ramda (since 2013) and `lodash/fp` ship many functions curried and with a “data-last” signature – the data comes last so that you can fix the configuration up front and conveniently compose the resulting building blocks. Once you understand the principle behind `multiplyBy` and `curriedAdd`, you also understand why these libraries are built the way they are.\n\n## Three pitfalls I see again and again\n\nAs elegant as the patterns are, teams reliably stumble over the same spots. I want to name three of them because they get expensive in real codebases.\n\nThe first concerns the `this` binding with higher-order functions. If you pass an object method directly as a callback, the receiver is lost. The method is called without its object, and `this` is then undefined or the global object:\n\n```js\nconst counter = {\n  count: 0,\n  increment() {\n    this.count += 1; // this depends on HOW it is called\n  }\n};\n\n[1, 2, 3].forEach(counter.increment);\n// TypeError, i.e. counter.count stays 0 – this is not counter\n```\n\nThe solution in 2017 is clear-cut. You bind `this` with `bind`, wrap the call in an arrow function that takes its `this` lexically from the surrounding context, or use the `thisArg` parameter that `map`, `filter` and `forEach` offer as a second argument:\n\n```js\n[1, 2, 3].forEach(counter.increment.bind(counter));\n[1, 2, 3].forEach(() => counter.increment());\n[1, 2, 3].forEach(counter.increment, counter); // thisArg\n```\n\nArrow functions are the sharpest tool here because they do not bring their own `this` at all – they inherit it from the surrounding scope. In many cases, that makes this class of error disappear entirely.\n\nThe second pitfall is overusing currying. Deeply nested `f(a)(b)(c)(d)` chains look neat in a blog post, but in team code they cost readability. They are harder to debug, the stack traces become confusing, and whoever reads the code six months later has to unfold the chain in their head again. Currying pays off where specialization or composition brings a concrete advantage. Where it only looks functional, it costs more than it brings.\n\nThe third concerns `reduce` without an initial value. If you leave out the `initialValue` argument, `reduce` takes the first array element as the initial value – and throws a TypeError on an empty array. On top of that, the semantics of the accumulator are then tied to the element type, which quickly leads to subtle bugs:\n\n```js\n[].reduce((sum, n) => sum + n);    // TypeError: Reduce of empty array\n[].reduce((sum, n) => sum + n, 0); // 0 – correct, because initial value set\n```\n\nFor sums, building lists and other folds with a neutral element, I therefore set the initial value explicitly. Where there is no neutral element in domain terms, I prefer to handle the empty case deliberately instead of inventing an artificial initial value.\n\n## Conclusion\n\nWhen I put the three patterns side by side, a common line stands out. The module pattern encapsulates state, whether via IIFE and closure or via ES module – the goal stays the same, only the level moves from convention into the language. Higher-order functions turn functions into values and replace loops with transformations. Currying and partial application build specialized variants from Generic Functions that can be composed. The syntax shifted between ES5 and ES6; the principle behind it did not.\n\nThat is exactly what I have learned over the years: patterns beat syntax. The language features will keep changing – years lie between the first IIFE and today’s `import` – but encapsulation, functions as values and specialization through preconfiguration have stayed stable. If you master this core, you do not have to start from scratch at the next framework change. You recognize the old acquaintances in new clothes, and in the long run that is worth more than any current library version.\n\n## Further reading\n\n- [ES modules guide (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n- [export (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) and [import (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\n- [IIFE (MDN Glossary)](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) and [Closures (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n- [Array.prototype.map (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), [filter (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [reduce (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)\n- [Function.prototype.bind (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) and [Arrow functions (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n- [ECMAScript 2015 (ES6) Specification](https://www.ecma-international.org/ecma-262/6.0/)\n- [Eloquent JavaScript – Higher-Order Functions](https://eloquentjavascript.net/05_higher_order.html)"},{"locale":"en","translation_key":"websockets-nicht-immer-antwort","slug":"websockets-are-not-always-the-answer","title":"WebSockets Are Not Always the Answer","summary":"Why Server-Sent Events are the simpler choice for most real-time requirements and when the price of a real WebSocket connection actually pays off.","tags":["Software","Node.js","Backend"],"published_at":"2017-09-12T10:00:00+00:00","updated_at":"2026-07-14T17:07:20.712151+00:00","url":"https://www.mikebild.dev/en/blog/websockets-are-not-always-the-answer/","audio_url":null,"audio_duration_secs":null,"text":"# WebSockets Are Not Always the Answer\n\nA dashboard that shows new orders. A notification when the build has finished. A progress bar for an import that takes twenty minutes. Three typical “real-time” requirements – and in all three cases, the data flows in one direction only: from the server to the client. Still, the first technical answer is surprisingly often: WebSockets, socket.io, a persistent bidirectional connection.\n\nThe reflex “real-time equals WebSocket” runs deep, and it is understandable. WebSockets are the most prominent tool on the shelf; every other tutorial series builds a chat with them. But a chat is bidirectional. An order dashboard is not. If you fire up the heavy machinery for pure server-to-client push, you pay for capabilities you never use – and the price is not zero.\n\n## What “real-time” really means in the requirements\n\nIf you seriously take the requirement apart, it rarely says “client and server continuously exchange messages in both directions”. It says: the user should see something as soon as it happens, without pressing F5. That is notification, not conversation. The client still talks to the server through ordinary requests – it clicks, it saves, it loads more. The only new thing is that the server may say something on its own.\n\nIncidentally, for some of these cases, simple polling is even enough. A progress bar that sends a GET every two seconds is not an elegant solution, but it is one that everyone on the team understands, that every cache and every proxy knows, and that can be thrown away and replaced in a minute. So the question is not just “WebSocket or not”, but how much machinery the requirement justifies in the first place.\n\nThis became clear to me in a shop project this spring. The team had built socket.io into an order dashboard, and the connection itself was never the problem. The problem was everything around it: after every deployment, clients hung on dead connections until the homegrown reconnect kicked in. The load balancer needed special treatment for the protocol upgrade. And when a browser was offline for thirty seconds, exactly the orders from those thirty seconds were missing – nobody had built resuming from the last known state, simply because the protocol doesn’t provide it.\n\n## The price of a WebSocket connection\n\nA WebSocket starts as an HTTP request, but leaves HTTP after the upgrade handshake and becomes its own protocol (RFC 6455) on a raw TCP connection. From that moment on, none of the infrastructure and semantics that the HTTP world brings along apply anymore. Concretely, you buy into:\n\n- Connection state management on the server: Who is connected, since when, with which session?\n- Your own heartbeats, because dead TCP connections don’t reveal themselves – ping/pong is manual work or a library feature, but always part of your own responsibility.\n- Reconnect logic in the client, including backoff and the question of what was missed during the silence.\n- Special cases in the infrastructure: proxies, load balancers and corporate firewalls that don’t know the upgrade or cut long silent connections.\n\nNone of this is unsolvable. Libraries like socket.io take a lot off your hands; that is exactly why they exist. But it remains complexity that has to be operated, monitored and understood when something goes wrong. For a channel that only sends in one direction, that is a bad trade.\n\n```javascript\nconst WebSocket = require('ws')\nconst server = new WebSocket.Server({ port: 8080 })\n\nserver.on('connection', socket => {\n  socket.isAlive = true\n  socket.on('pong', () => { socket.isAlive = true })\n})\n\n// dead connections are not detected for free – ping/pong is on us\nsetInterval(() => {\n  server.clients.forEach(socket => {\n    if (!socket.isAlive) return socket.terminate()\n    socket.isAlive = false\n    socket.ping()\n  })\n}, 30000)\n```\n\nThat is just the heartbeat. Reconnect, message buffers and resuming after an interruption are a different story – and in most projects I have seen, surprisingly little of that story has been written.\n\n## Server-Sent Events: push over ordinary HTTP\n\nServer-Sent Events are the unspectacular counterpart: a perfectly normal HTTP GET request whose response never ends. The server keeps the connection open and writes events into it as text; the browser consumes them through the `EventSource` API. No protocol switch, no upgrade, no new vocabulary for the infrastructure. An SSE endpoint in Express is a few lines:\n\n```javascript\nconst express = require('express')\nconst app = express()\n\nlet nextEventId = 0\nconst eventLog = []\nconst clients = []\n\napp.get('/events', (req, res) => {\n  res.set({\n    'Content-Type': 'text/event-stream',\n    'Cache-Control': 'no-cache',\n    Connection: 'keep-alive'\n  })\n  res.flushHeaders()\n\n  // replay everything the client missed while it was offline\n  const lastEventId = Number(req.get('Last-Event-ID') || 0)\n  eventLog\n    .filter(event => event.id > lastEventId)\n    .forEach(event => res.write(toMessage(event)))\n\n  clients.push(res)\n  req.on('close', () => clients.splice(clients.indexOf(res), 1))\n})\n\nfunction broadcast(data) {\n  const event = { id: ++nextEventId, data }\n  eventLog.push(event)\n  clients.forEach(res => res.write(toMessage(event)))\n}\n\nfunction toMessage({ id, data }) {\n  return `id: ${id}\\ndata: ${JSON.stringify(data)}\\n\\n`\n}\n\napp.listen(3000)\n```\n\nThe client is even shorter – and that is the real point:\n\n```javascript\nconst source = new EventSource('/events')\n\nsource.onmessage = event => {\n  const order = JSON.parse(event.data)\n  renderOrder(order)\n}\n\n// no reconnect code here: EventSource reconnects on its own\n// and sends the Last-Event-ID header with every new attempt\n```\n\nThe comment in the client code is not a claim but the specification. If the connection drops, `EventSource` reconnects on its own – the server can even set the waiting time via the `retry:` field in the stream. And when reconnecting, the browser automatically sends the `Last-Event-ID` header with the ID of the last event received. The server can use it to continue exactly where the client left off. The very feature that was so painfully missing in the shop project is part of the protocol here.\n\n```mermaid\nsequenceDiagram\n    participant B as Browser (EventSource)\n    participant S as Server (Express)\n    B->>S: GET /events\n    S-->>B: Event 41 (order A-1041)\n    S-->>B: Event 42 (order A-1042)\n    Note over B,S: Connection drops<br/>(deployment, dead zone, proxy timeout)\n    B->>S: GET /events with header Last-Event-ID 42\n    S-->>B: Event 43 (everything since 42 is delivered)\n```\n\nOn top of that comes an advantage you only learn to appreciate in operations: the entire channel is ordinary HTTP. Load balancers route it like any other request, authentication runs over the same headers and cookies as the rest of the application, and debugging needs no special tooling:\n\n```bash\n$ curl -N http://localhost:3000/events\nid: 1\ndata: {\"orderId\":\"A-1041\",\"total\":89.9}\n\nid: 2\ndata: {\"orderId\":\"A-1042\",\"total\":24.5}\n```\n\nIf you have ever tried to go through a WebSocket frame capture together with a colleague from operations, you know what this one curl call is worth. The stream is readable text, every event carries its ID, and the browser sees the same output.\n\n## Where SSE honestly hits its limits\n\nSo that this doesn’t turn into an advertisement: Server-Sent Events have limits, and they belong on the table before the decision is made.\n\nThe channel is strictly unidirectional. If the client wants to say something, it does so through a normal POST – for forms, clicks and commands, that is perfectly fine and the natural way anyway; for a high-frequency back channel, it isn’t. Second: Internet Explorer and Edge still don’t support `EventSource` to this day; there you need a polyfill. The available polyfills work decently, but it is one more building block you have to plan for. Third, under HTTP/1.1, SSE shares the browser limit of roughly six connections per host – if you open several streams per tab, you run into it. Under HTTP/2, this eases considerably, because all streams run over a single multiplexed connection. And finally: buffering proxies occasionally have to be convinced by configuration to pass the stream through immediately instead of collecting it – but that is one line of nginx configuration, not an architecture problem.\n\n## GraphQL subscriptions: the same reflex, one floor up\n\nIt gets interesting when the reflex moves into frameworks. In the Apollo ecosystem, GraphQL subscriptions run over `subscriptions-transport-ws` by default, that is, over WebSockets. Yet subscriptions are the textbook example of unidirectional data flow: the client registers once what it is interested in, and from then on only the server talks. Queries and mutations go over HTTP anyway. The bidirectional capability of the transport is used for a single handshake – after that it lies idle, while its operating costs remain.\n\nThis kept me busy enough this spring to try it out: `subscriptions-transport-sse` is my API-compatible SSE variant of this transport, created in my GitHub organization CodeCommission. On the server side, the `SubscriptionServer` attaches to an Express app and the `SubscriptionManager` from `graphql-subscriptions`; on the client side, the `SubscriptionClient` is attached to Apollo’s network interface as usual:\n\n```javascript\nimport { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-sse'\n\nconst httpClient = createNetworkInterface({ uri: 'https://example.com/graphql' })\nconst sseClient = new SubscriptionClient('https://example.com/subscriptions')\nconst apolloClient = new ApolloClient({\n  networkInterface: addGraphQLSubscriptions(httpClient, sseClient)\n})\n\napolloClient.subscribeToMore({\n  document: gql`\n    subscription onOrderCreated {\n      orderCreated {\n        id\n        total\n      }\n    }`,\n  updateQuery: (prev, { subscriptionData }) => {\n    // merge the new order into the store and return the new state\n  }\n})\n```\n\nFrom the application’s point of view, nothing changes – the same subscription, the same `subscribeToMore`. Only the transport underneath is now ordinary HTTP with everything described above: automatic reconnect, `Last-Event-ID`, curl debugging. As a practical test, I built a small presence list with it in April – who is online right now, React and Apollo in the frontend, Node in the backend, events over SSE. Both are deliberately lean projects, more evidence than product. I wanted to show that “GraphQL subscriptions need WebSockets” is a convention, not a necessity.\n\n## When WebSockets are the right answer\n\nAfter so much counterargument, the other side, because it exists. WebSockets are the right choice when both sides actually send continuously and with low latency:\n\n- Collaborative editing, where keystrokes and operations from both sides converge\n- Cursor positions and presence signals that flow in both directions many times per second\n- Games and simulations in which every round reconciles client input against server state\n- Frontends where the overhead of a separate POST per client message really matters\n\nThe common denominator: the back channel is not an occasional command but a stream. Then the protocol pays off, and then the operational complexity is justified too – after all, you use what you pay for. The deciding question is therefore not “Do we need real-time?” but “Where does the data flow, and how often?”.\n\n```mermaid\nflowchart TD\n    A[Requirement: real-time] --> B{Does data flow continuously<br/>in both directions?}\n    B -- no --> C[Server-Sent Events<br/>plus normal HTTP requests]\n    B -- yes --> D{Is the back channel a stream<br/>with latency requirements?}\n    D -- no --> C\n    D -- yes --> E[WebSockets –<br/>plan for operating costs]\n```\n\nIf you answer these two questions honestly, in my experience you end up on the left side of the diagram in the vast majority of cases. The order dashboard, the build monitor, the import progress, the notification bell in the top right of the application – all cases for SSE. The editor with your colleagues’ live cursors is the rare, genuine case for the right side.\n\n## The bottom line\n\nFrom the shop project and the two SSE experiments, I take away one observation above all: the costs of a technology rarely sit where its strengths are advertised – they sit in operations, in debugging and in the failure cases the protocol doesn’t cover on its own. WebSockets can do something SSE can’t, and if you need that something, they are unrivaled. But “real-time” in the requirements is not yet evidence that you need it. Most of the time, a server just wants to tell you something, and for that, an HTTP request that never ends is enough – with built-in reconnect, built-in resuming and a debugging experience that consists of a single curl call.\n\nThe more boring technology wins here not despite but because of its boredom. It has fewer moving parts – and every moving part you never build in can’t break at three in the morning.\n\n## Further reading\n\n- [subscriptions-transport-sse on GitHub](https://github.com/CodeCommission/subscriptions-transport-sse) – GraphQL subscriptions over Server-Sent Events, API-compatible with subscriptions-transport-ws\n- [graphql-subscriptions-sse-presence-list on GitHub](https://github.com/MikeBild/graphql-subscriptions-sse-presence-list) – presence list example with React, Apollo and SSE\n- [Server-Sent Events in the HTML specification (WHATWG)](https://html.spec.whatwg.org/multipage/server-sent-events.html)\n- [EventSource API on MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)\n- [RFC 6455 – The WebSocket Protocol](https://tools.ietf.org/html/rfc6455)"},{"locale":"en","translation_key":"knockoutjs-observables-computed-vor-signals","slug":"knockoutjs-fine-grained-reactivity-with-observables","title":"KnockoutJS: Fine-Grained Reactivity with Observables and Computed","summary":"How KnockoutJS solves reactivity: observables as get/set functions, computed with automatic dependency tracking and targeted DOM updates instead of a global tree comparison.","tags":["Software","Frontend"],"published_at":"2017-08-22T10:00:00+00:00","updated_at":"2026-07-13T09:59:11.759377+00:00","url":"https://www.mikebild.dev/en/blog/knockoutjs-fine-grained-reactivity-with-observables/","audio_url":null,"audio_duration_secs":null,"text":"Three functions are enough to keep an entire UI reactive in KnockoutJS: `ko.observable`, `ko.observableArray` and `ko.computed`. None of them takes a dependency list. Still, after the first run, Knockout knows which value is attached to which place in the DOM. It reads the dependencies from the actual program flow.\n\n**Editorial note (July 2026):** This post explains KnockoutJS as a historical forerunner of today’s fine-grained reactivity. I am not recommending that you build a new frontend on Knockout in 2026. What has remained interesting is the mechanism: capturing dependencies on read and updating only the affected places.\n\nKnockout declaratively couples the DOM to a ViewModel through bindings such as `text`, `value`, `foreach` and `click`. Here I look one level deeper: How does Knockout notice that something has changed, and how does it figure out which parts of the UI are affected? The core of this mechanism is called observables and computed.\n\n## An observable is a function – not a property\n\nThe first mental leap you have to make with Knockout is this: in KnockoutJS, an observable is not a property but a function. More precisely, a function that is getter and setter at the same time. If I call it without an argument, I read the value. If I call it with an argument, I write the value – and Knockout notifies everyone interested in that value.\n\n```js\nvar name = ko.observable('Bob');\n\nname();          // read  -> 'Bob'\nname('Mary');    // write -> sets the value and notifies subscribers\nname();          // read  -> 'Mary'\n```\n\nThat is the whole trick. No `Object.defineProperty`, no proxy, no compiler magic. Just a function that remembers who read it and who wants to be notified. Writing is chainable, by the way, because the setter returns the ViewModel:\n\n```js\nviewModel.name('Mary').age(50);\n```\n\nFor lists, there is a matching variant. A `ko.observableArray` behaves like an observable on read – `arr()` returns the underlying array – but it also comes with mutation methods that trigger tracking:\n\n```js\nvar todos = ko.observableArray([]);\n\ntodos();                 // read -> the current array\ntodos.push({ title: 'Buy milk' });\ntodos.remove(someItem);\ntodos.removeAll();\n```\n\nThe first pitfall is already lurking here, and I will come back to it later: these `push`, `remove` and `splice` methods are Knockout’s own wrappers. They are what triggers a notification. If you write `todos().push(x)` instead, you bypass them on the raw array, and Knockout notices nothing of the change.\n\n## Computed derives – and automatically tracks what it reads\n\nNow comes the really interesting part. You rarely want to just store a value and output it again. Most of the time you need derived values: the total of a shopping cart, the full name from first and last name, the number of open tasks. That is what `ko.computed` is for.\n\n```js\nvar firstName = ko.observable('Mike');\nvar lastName  = ko.observable('Bild');\n\nvar fullName = ko.computed(function () {\n  return firstName() + ' ' + lastName();\n});\n\nfullName();            // 'Mike Bild'\nfirstName('Michael');\nfullName();            // 'Michael Bild'\n```\n\nAnd here something happens that I looked at twice myself when I first encountered Knockout, because it is the linchpin of the whole model. Nowhere did I tell Knockout that `fullName` depends on `firstName` and `lastName`. I declared no dependency list. Knockout figured that out by itself.\n\nHow? When the evaluator function runs for the first time, Knockout observes which observables are actually read. At that moment, `firstName()` and `lastName()` register themselves, so to speak: “This computed is reading me right now.” Knockout then registers a subscription. The dependency graph thus emerges at runtime, purely through execution – nothing is declared. This is the fine-grained, automatic dependency tracking that defines Knockout.\n\nThe evaluator does not run just once. It is executed once immediately on creation, and after that again every time one of the dependencies it read changes. The second part is important: on every re-evaluation, Knockout determines the dependencies afresh. That allows dynamic dependencies behind conditions:\n\n```js\nvar showFullName = ko.observable(true);\n\nvar displayName = ko.computed(function () {\n  if (showFullName()) {\n    return firstName() + ' ' + lastName();\n  }\n  return firstName();\n});\n```\n\nAs long as `showFullName` is `true`, `displayName` depends on three observables. If it is `false`, `lastName()` is no longer read at all – and Knockout automatically removes this dependency again on the next run. A change to `lastName` then no longer triggers a re-evaluation. That is exactly what “dynamic” means: the graph adapts to the actual control flow.\n\nDrawn as a graph, this relationship looks like this:\n\n```mermaid\ngraph LR\n  A[firstName<br/>observable] --> C[fullName<br/>computed]\n  B[lastName<br/>observable] --> C\n  C --> D[text binding<br/>DOM]\n```\n\nThe arrows mean “is read by and notifies.” If `firstName` changes, the notification travels along the edge to `fullName`, which recalculates, and from there on to the text binding in the DOM. Only this one path becomes active. Nothing else in the tree is touched.\n\nFor the toolbox, this small trio is enough for now:\n\n- `ko.observable(value)` – a single reactive value, read with `obs()`, written with `obs(newValue)`.\n- `ko.observableArray([...])` – a reactive list with mutation methods such as `push`, `remove` and `splice` that notify bindings.\n- `ko.computed(fn)` – a derived value that automatically tracks which observables it reads and recalculates when they change.\n\n## From the ViewModel into the DOM: the todos app\n\nSo this does not stay abstract, here is a small todos application. It shows all three building blocks working together.\n\n```js\nfunction TodoViewModel() {\n  var self = this;\n\n  self.todos = ko.observableArray([]);\n  self.newTodo = ko.observable('');\n\n  self.remaining = ko.computed(function () {\n    return self.todos().filter(function (t) {\n      return !t.done();\n    }).length;\n  });\n\n  self.addTodo = function () {\n    self.todos.push({\n      title: self.newTodo(),\n      done: ko.observable(false)\n    });\n    self.newTodo('');\n  };\n}\n\nko.applyBindings(new TodoViewModel());\n```\n\nA few things here are built this way on purpose. `self.todos` is an `observableArray`, `self.newTodo` a simple observable for the input field. `self.remaining` is a computed that counts the tasks still open. It reads `self.todos()` and, per entry, `t.done()` – which means it depends both on the list and on every single `done` observable. If you add a todo or check one off, `remaining` recalculates by itself.\n\nNotice that every single todo gets its own `done: ko.observable(false)`. Only this way is the done status reactive per entry. A plain `done: false` would be a dead value with nothing to observe.\n\nThe view declaratively couples the ViewModel to the DOM. Here is the relevant excerpt:\n\n```html\n<input data-bind=\"value: newTodo\" />\n<button data-bind=\"click: addTodo\">Add</button>\n\n<ul data-bind=\"foreach: todos\">\n  <li data-bind=\"text: title\"></li>\n</ul>\n\n<span data-bind=\"text: remaining\"></span> remaining\n```\n\n`ko.applyBindings` activates these connections once at startup. From then on, everything runs through tracking: when the user types into the field, the `value` binding updates `newTodo`. A click on the button calls `addTodo`, which changes the list via `push`. This change notifies the `foreach` binding (new list entry) and the computed `remaining` (recalculation), which in turn updates the `text` binding in the `<span>`. Each of these updates hits exactly the place that is affected.\n\n## Why targeted tracking is a different model\n\nAt this point, it pays to draw the distinction that gives the whole thing its shape. There is a second, very widespread approach to the same problem: Virtual DOM diffing, as you know it from React, for example. There, on every change you build a new virtual tree, compare it with the old one and apply the difference to the real DOM. The framework does not know up front which data change affects which place in the DOM – it computes the difference afterward.\n\nKnockout goes the opposite way. Through fine-grained tracking, it knows exactly, per observable, which computed and which bindings depend on it. It does not have to compare anything. When a value changes, Knockout simply follows the registered edges of the dependency graph and updates only the DOM places attached to them. No tree comparison, no re-rendering of subtrees that have not changed at all.\n\nThe sequence of a single change looks like this:\n\n```mermaid\nsequenceDiagram\n  participant U as User\n  participant O as observable\n  participant C as computed\n  participant D as DOM binding\n  U->>O: obs(newValue)\n  O->>C: notify subscriber\n  C->>C: re-evaluate\n  C->>D: targeted text update\n```\n\nBoth models have their place, and I do not want to declare either one the winner. But once you have understood the difference at this point, you also understand why the two worlds feel so different. Knockout’s approach is immediately comprehensible, because you can almost see the graph in the code. The price for that is discipline: you have to work consistently with observables, or the graph breaks at some point.\n\n## Pitfalls from practice\n\nIt is exactly this discipline where the graph tends to break, and at three recurring places. All three have cost me hours in my own projects, because they fail silently.\n\nThe classic is forgotten parentheses. An observable is a function. If you use it without parentheses, you are working with the function itself instead of its value:\n\n```js\n// wrong: todo.done is the function itself, so always truthy\nif (todo.done) {\n  // this branch ALWAYS runs\n}\n\n// correct: todo.done() reads the value\nif (todo.done()) {\n  // ...\n}\n```\n\nThe bug is treacherous because it throws no error. A function is truthy, so the condition simply always comes out the same. You then search for a long time in the wrong place. Reading always takes parentheses, without exception.\n\nThe second pitfall is the native array methods. I hinted at it above:\n\n```js\n// wrong: mutates the raw array without notification\ntodos().push(newItem);\n\n// correct: KO wrapper, notifies dependent bindings\ntodos.push(newItem);\n```\n\n`todos()` returns the underlying JavaScript array. Its native `push` does change the content, but Knockout learns nothing about it – the `foreach` binding stays as it was. The KO wrapper `todos.push`, on the other hand, triggers tracking. The only difference is the parentheses before `.push`, which once again makes the bug unpleasantly subtle.\n\nThe third concerns the `this` context in computed. If the evaluator wants to access the ViewModel, `this` really has to point to the ViewModel:\n\n```js\nfunction ViewModel() {\n  this.price = ko.observable(10);\n  this.count = ko.observable(3);\n\n  // wrong: this does not reliably point to the ViewModel here\n  this.total = ko.computed(function () {\n    return this.price() * this.count();   // this.price is undefined\n  });\n}\n```\n\nKnockout calls the evaluator in a different context, so `this` does not point to the instance. There are two established ways out. Either you pass the context as a second argument:\n\n```js\nthis.total = ko.computed(function () {\n  return this.price() * this.count();\n}, this);   // second argument binds this\n```\n\nOr you use the `self` pattern I already used in the todos example:\n\n```js\nfunction ViewModel() {\n  var self = this;\n  self.price = ko.observable(10);\n  self.count = ko.observable(3);\n  self.total = ko.computed(function () {\n    return self.price() * self.count();\n  });\n}\n```\n\nIn my projects I prefer the `self` pattern, because it works across the board – in event handlers and callbacks too, not just in computed. One pattern for everything is easier to remember than a special rule for each case.\n\nIn passing, it is worth mentioning `ko.pureComputed`, which has been available since KO 3.2. It behaves like a normal computed but “sleeps” as long as nobody subscribes to it, which saves recalculations for pure derivations without side effects. For getting started, `ko.computed` is enough; as soon as you notice that a purely deriving computed recalculates unnecessarily often, `pureComputed` is the obvious improvement.\n\n## Conclusion\n\nOnce you have understood the core of KnockoutJS, you are basically holding just three building blocks: observables as get/set functions, observableArrays for reactive lists and computed for derived values. The real elegance lies between these building blocks: in automatic dependency tracking. Knockout observes at runtime which observables a computed reads, builds a dependency graph from that and, on every change, updates only the affected places – determined afresh on every run, so that dynamic dependencies behind conditions are mapped cleanly too.\n\nThis model deliberately runs counter to Virtual DOM diffing: instead of comparing trees, Knockout follows the edges it registered itself while reading. That makes the behavior immediately comprehensible, but it demands discipline – parentheses for reading, KO wrappers for mutating lists, the right `this` context in computed. Once these three reflexes are internalized, working with Knockout becomes surprisingly calm. You describe what a value depends on, and the framework takes care of the rest. This clarity is exactly why I still consider Knockout’s reactivity model one of the best entry points for understanding what really happens behind reactive UIs.\n\n## Further reading\n\n- [Observables – KnockoutJS Documentation](https://knockoutjs.com/documentation/observables.html)\n- [Computed Observables – KnockoutJS Documentation](https://knockoutjs.com/documentation/computedObservables.html)\n- [How Dependency Tracking Works – KnockoutJS Documentation](https://knockoutjs.com/documentation/computed-dependency-tracking.html)\n- [Observable Arrays – KnockoutJS Documentation](https://knockoutjs.com/documentation/observableArrays.html)\n- [Pure Computed Observables – KnockoutJS Documentation](https://knockoutjs.com/documentation/computed-pure.html)"},{"locale":"en","translation_key":"pwa-weather-offline-feature","slug":"pwa-weather-offline-is-a-feature","title":"PWA Weather: Offline Is a Feature","summary":"A small weather app built as a Progressive Web App shows why offline behavior is a product decision and how honestly a UI should deal with outdated data.","tags":["Software","Architecture"],"published_at":"2017-08-12T10:00:00+00:00","updated_at":"2026-07-14T17:05:39.041102+00:00","url":"https://www.mikebild.dev/en/blog/pwa-weather-offline-is-a-feature/","audio_url":null,"audio_duration_secs":null,"text":"# PWA Weather: Offline Is a Feature\n\nOn the subway between two stations, no signal. The weather app opens, briefly shows a loading spinner and then: nothing. A white screen. And yet this morning’s weather would have been perfectly fine – the question was whether to take the umbrella, not whether it’s 21.3 or 21.4 degrees this minute. The app had even loaded this data before. It just threw it away, because nobody decided that it’s worth anything without a network.\n\nThis white screen is not a technical defect. It is the result of a non-decision. Somewhere in the backlog, “offline support” was probably listed as a technical nice-to-have, behind the next feature and the redesign after that. That is exactly what I consider the mistake in thinking: offline is not an add-on you bolt onto a finished app later. Offline is a feature with product questions – what should work without a network, what explicitly should not, and how honestly the UI shows the state of the data.\n\n## A small demo as a test bench\n\nTo play this through for myself, I created a small repository in April of this year: [pwa-weather-demo](https://github.com/MikeBild/pwa-weather-demo). It is deliberately not a product but a rebuild exercise following Google’s tutorial “Your First Progressive Web App” – one weather card per city, a public weather API behind it, a service worker in front. Locally, the whole thing starts with a simple `http-server`; it needs no more infrastructure than that. The value isn’t in the feature set but in the fact that a manageable example lets you touch every decision one at a time.\n\nAnd there are more decisions than the word “caching” suggests. While working through it, I noticed that the real work isn’t in the service worker code. You can write that in an afternoon. The work lies in the question of what answer the app owes a person without a network connection.\n\n## Offline is a product question, not a cache option\n\nFor the weather app, my answer looks like this:\n\n- The most recently loaded weather for the saved cities is shown – always, immediately, even without a network.\n- The UI itself (layout, icons, fonts, logic) loads completely from the local cache.\n- Searching for new places doesn’t work offline – and says so, instead of letting a spinner turn.\n- Every weather card shown carries a timestamp: “Updated 2 hours ago” instead of silently old data.\n\nThe third point matters to me. It would be technically possible to cache search results too and show something offline. But a place search against a two-day-old cache doesn’t deliver a search; it delivers a dummy. Not everything that can be cached should be cached. The line runs along the question of whether an outdated answer is still an honest answer: this morning’s weather is honest, clearly dated information. A search result from the day before yesterday is not.\n\nThe fourth point is the second half of the same decision. If you show old data without marking it as old, your interface is lying. A small timestamp turns the same record from potential misinformation into useful information. It costs one line of UI and a date – and it’s the difference between “the app shows something” and “the app tells me what it knows and how sure it is.”\n\n## The service worker: a proxy with a lifecycle\n\nTechnically, all of this hinges on the service worker – a script that the browser runs separately from the page and that sits as a programmable proxy between the app and the network. Every request from the page goes through its `fetch` handler, and there, code instead of chance decides whether a response comes from the network, from the cache or from a combination of both.\n\nIf you work with it for the first time, you stumble less over the API than over the lifecycle. A service worker is registered, installed, waits if necessary for the old version to end and only then takes control of the page:\n\n```mermaid\nflowchart LR\n  A[register] --> B[install<br/>precache the app shell]\n  B --> C[waiting<br/>old version still running]\n  C --> D[activate<br/>clean up old caches]\n  D --> E[fetch<br/>control requests]\n```\n\nThe registration itself is unspectacular and belongs at the end of the app startup:\n\n```js\n// app.js\nif ('serviceWorker' in navigator) {\n  navigator.serviceWorker\n    .register('/service-worker.js')\n    .then(function (registration) {\n      console.log('service worker registered, scope:', registration.scope);\n    })\n    .catch(function (error) {\n      console.error('service worker registration failed', error);\n    });\n}\n```\n\nThe `if` is not a formality but part of the architecture: in browsers without service workers, the app simply keeps running as a normal website. More on that later, because in 2017 this case is anything but exotic.\n\nTwo quirks of the lifecycle actually cost me time in the demo. First: by default, an updated service worker only takes over once all tabs of the old version are closed – if you just reload during development and wonder why the new code doesn’t apply, you’re fighting `waiting`, not a bug. Second: the `activate` step is the right place to delete old cache versions. If you skip it, you accumulate another cache with every deployment and wonder months later about the storage usage.\n\n## App shell: the frame always comes from the cache\n\nThe first cache decision concerns the app shell – everything the application needs for display before even a single byte of weather data is there: HTML, CSS, JavaScript, icons. These files only change with a deployment, so they are put into the cache completely once during `install` (precache) and always served from there afterward:\n\n```js\n// service-worker.js\nvar SHELL_CACHE = 'weather-shell-v1';\nvar DATA_CACHE = 'weather-data-v1';\n\nvar SHELL_FILES = [\n  '/',\n  '/index.html',\n  '/styles/app.css',\n  '/scripts/app.js',\n  '/images/icons/icon-192.png'\n];\n\nself.addEventListener('install', function (event) {\n  event.waitUntil(\n    caches.open(SHELL_CACHE).then(function (cache) {\n      return cache.addAll(SHELL_FILES);\n    })\n  );\n});\n\nself.addEventListener('activate', function (event) {\n  event.waitUntil(\n    caches.keys().then(function (keys) {\n      return Promise.all(\n        keys\n          .filter(function (key) {\n            return key !== SHELL_CACHE && key !== DATA_CACHE;\n          })\n          .map(function (key) {\n            return caches.delete(key);\n          })\n      );\n    })\n  );\n});\n```\n\nThe version number in the cache name is the deployment concept in its simplest form: new shell, new name, old caches get thrown out on `activate`. Tools like `sw-precache` generate this part from the build, and Workbox has just been released as a fresh successor that brings the common strategies as a library. For the demo, I deliberately wrote it by hand – not out of principle, but because you should only leave a strategy to a generator with a clear conscience once you’ve formulated it yourself.\n\n## Two kinds of data, two strategies\n\nThe more interesting decision happens in the `fetch` handler, because the app shell and the weather data need opposite strategies. The shell should arrive as fast as possible and may well be one deployment cycle old: cache first. The weather data should be as fresh as possible, and the cache is just the safety net for the subway moment: network first, with the last known response as a fallback.\n\n```mermaid\nflowchart TD\n  R[fetch event] --> Q{Path starts with<br/>/api/weather?}\n  Q -- yes --> N[Network first]\n  N -- response ok --> C1[Copy into weather-data-v1<br/>response to the app]\n  N -- no network --> C2[last known response<br/>from the cache]\n  Q -- no --> S[Cache first:<br/>app shell]\n  S -- hit --> C3[serve immediately]\n  S -- no hit --> C4[pass through to the network]\n```\n\nIn code, this switch looks like this:\n\n```js\nself.addEventListener('fetch', function (event) {\n  var url = new URL(event.request.url);\n\n  if (url.pathname.indexOf('/api/weather') === 0) {\n    // network first, cached data as offline fallback\n    event.respondWith(\n      fetch(event.request)\n        .then(function (response) {\n          var copy = response.clone();\n          caches.open(DATA_CACHE).then(function (cache) {\n            cache.put(event.request, copy);\n          });\n          return response;\n        })\n        .catch(function () {\n          return caches.match(event.request);\n        })\n    );\n    return;\n  }\n\n  // app shell: cache first, network as fallback\n  event.respondWith(\n    caches.match(event.request).then(function (cached) {\n      return cached || fetch(event.request);\n    })\n  );\n});\n```\n\nAn alternative for the data route would be stale-while-revalidate: deliver the cached response immediately and fetch the fresh one in the background in parallel, which is then ready for the next render. For a weather app, that’s a legitimate choice – the display appears instantly, and the update trickles in afterward. In the demo, I still chose network-first, because with weather data the fresh response deserves priority as long as the network is there. The point is not which of the two strategies is “right.” The point is that it’s a choice with visible consequences – and that it’s made per route, not across the board for the whole app. Jake Archibald’s Offline Cookbook spells out these patterns one by one and has been my reference for them for years.\n\n## The age of the data belongs in the UI\n\nSo that “showing old data” doesn’t turn into quietly slipping it in, the app has to know how old a response is. Conveniently, this information is already in the cached response – the `Date` header of the original server response is stored with it:\n\n```js\n// show data age when rendering a cached response\ncaches.match('/api/weather?city=berlin').then(function (cached) {\n  if (!cached) {\n    return;\n  }\n  var fetchedAt = new Date(cached.headers.get('date'));\n  var ageInMinutes = Math.round((Date.now() - fetchedAt.getTime()) / 60000);\n  showLastUpdated(ageInMinutes); // \"Stand: vor 120 Minuten\"\n});\n```\n\nThat’s ten lines, and they change the character of the app. “Why is it showing me sunshine when it’s raining outside” becomes “ah, that’s the state from this morning.” In a project review, I would weigh these ten lines higher than the entire cache logic underneath – the cache logic decides whether something is shown; these lines decide whether you can trust what’s shown.\n\n## Manifest, HTTPS and the home screen\n\nBesides the service worker, two more building blocks belong to a PWA. The web app manifest describes how the app behaves when it lands on the home screen:\n\n```json\n{\n  \"name\": \"PWA Weather\",\n  \"short_name\": \"Weather\",\n  \"start_url\": \"/index.html\",\n  \"display\": \"standalone\",\n  \"background_color\": \"#3f51b5\",\n  \"theme_color\": \"#3f51b5\",\n  \"icons\": [\n    {\n      \"src\": \"images/icons/icon-192.png\",\n      \"sizes\": \"192x192\",\n      \"type\": \"image/png\"\n    }\n  ]\n}\n```\n\nWith a manifest plus a registered service worker plus repeated use, Chrome on Android offers “Add to Home screen” on its own – the app then starts without browser chrome, with its own icon, and feels surprisingly like an installed application. Lighthouse checks whether a page meets the criteria; the PWA audit reliably complains about missing icons, missing offline behavior of the start route or missing HTTPS.\n\nHTTPS is not a recommendation here but a requirement: browsers only register service workers over secure connections (with `localhost` as the development exception). And that’s a good thing – you don’t want to deliver a script that may intercept and answer every request of a domain over a connection that can be tampered with.\n\n## The honest limit: Safari\n\nNow the part that comes up suspiciously quietly in many PWA articles this year: Safari has no service worker. Neither on the Mac nor – and this weighs more – on iOS. Chrome, Firefox and Opera support the API, Microsoft Edge is working on it, and on the WebKit status board the entry has at least recently moved to “In Development.” But as of today, August 2017, a PWA on an iPhone is simply a normal website: no offline cache, no intercepting of requests, no install banner.\n\nThat’s no reason to give up on it – but it absolutely belongs in the product decision, not in a footnote. For the weather demo, this concretely means: the app has to work fully without a service worker, just without the offline comfort. The service worker is an enhancement layer (Progressive Enhancement in the original sense of the term), not a prerequisite. If you build your app so that it breaks without a service worker, you have nothing at all on iOS. If you build it so that the service worker adds behavior instead of carrying it, you have a decent website on iOS and an app on Android that survives the subway moment.\n\nDepending on the target audience, this shifts the calculation considerably. With an audience with a high iOS share, the PWA effort today mainly buys you better load times through the shell cache in Chrome and Firefox – not nothing, but a different promise than “works offline.” This calculation should be openly on the table in the team before anyone writes “offline-capable” on a slide.\n\n## Bottom line\n\nThe technology behind the demo is manageable: a lifecycle, two cache strategies, a manifest, HTTPS. What sticks is something else. The white screen on the subway doesn’t happen because caching is hard – it happens because “offline” was never treated as a feature, with the same questions as any other feature: What exactly should it be able to do? What deliberately not? How does the person in front of it recognize what’s happening right now?\n\nMy answers for the weather app – last known weather yes, place search no, timestamp always – are not universal. A banking app draws the line differently, a news site differently again. The only universal thing is that this line has to be drawn before the first `fetch` handler is written. The service worker carries out a product decision. It doesn’t replace it.\n\n## Further reading\n\n- Repository: [MikeBild/pwa-weather-demo](https://github.com/MikeBild/pwa-weather-demo)\n- Jake Archibald: [The Offline Cookbook](https://jakearchibald.com/2014/offline-cookbook/)\n- MDN: [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)\n- MDN: [Web App Manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest)"},{"locale":"en","translation_key":"tic-tac-toe-minimax-react","slug":"tic-tac-toe-with-minimax-in-react","title":"Tic-Tac-Toe with Minimax in React","summary":"An unbeatable tic-tac-toe opponent in React shows why game logic as a pure function must know nothing about rendering – and why immutable moves fit React’s model.","tags":["Software","Frontend"],"published_at":"2017-06-12T10:00:00+00:00","updated_at":"2026-10-23T14:29:51.128339+00:00","url":"https://www.mikebild.dev/en/blog/tic-tac-toe-with-minimax-in-react/","audio_url":null,"audio_duration_secs":null,"text":"# Tic-Tac-Toe with Minimax in React\n\n```js\nfunction score(board, depth) {\n  if (winnerOf(board) === COMPUTER) return 10 - depth;\n  if (winnerOf(board) === HUMAN) return depth - 10;\n  return 0;\n}\n```\n\nAn unbeatable tic-tac-toe opponent doesn’t need more evaluation than this. A board is worth `10 - depth` if the computer has won, `depth - 10` if the human has won, and zero for a draw. As a bonus, the search depth in the value provides playing style: a win in two moves counts more than one in four, and a loss in four moves is less bad than one in two. So the opponent wins as early as possible and loses as late as possible – if it can lose at all, which never happens with flawless play.\n\nMore striking than what is in the function is what is missing: no React, no DOM, no event handler, no `this`, no `setState`. A board goes in, a number comes out. That is exactly what this article is about. The game itself is trivial; every child learns it in five minutes. What’s interesting is the dividing line: the entire opponent is a set of pure functions over an array, and in the end React only renders state. If you don’t draw this line, you later have neither testable logic nor a replaceable UI.\n\nI built the accompanying repository `react-tic-tac-toe` in October 2016, prompted by Carsten König’s Othello in Elm – a project that impressed me at the time because the same separation was a matter of course there. In Elm, there simply is no other option: game logic is one function, the view another. In JavaScript, you have to decide on it.\n\n## The board is an array, a move is a new board\n\nThe data structure is as small as it sounds: an array with nine fields, each field `'X'`, `'O'` or `null`. The indices 0 to 8 run row by row from top left to bottom right. The winning conditions are eight lines over these indices – three rows, three columns, two diagonals.\n\n```js\nconst HUMAN = 'X';\nconst COMPUTER = 'O';\n\nconst LINES = [\n  [0, 1, 2], [3, 4, 5], [6, 7, 8],\n  [0, 3, 6], [1, 4, 7], [2, 5, 8],\n  [0, 4, 8], [2, 4, 6],\n];\n\nfunction winnerOf(board) {\n  const line = LINES.find(([a, b, c]) =>\n    board[a] && board[a] === board[b] && board[a] === board[c]);\n  return line ? board[line[0]] : null;\n}\n\nfunction movesFor(board) {\n  return board.reduce((moves, field, index) =>\n    field === null ? moves.concat(index) : moves, []);\n}\n\nfunction applyMove(board, index, player) {\n  const next = board.slice();\n  next[index] = player;\n  return next;\n}\n```\n\nThe most important decision is in `applyMove`: a move doesn’t change the board, it creates a new one. `board.slice()` copies the array, then one field is set, and the original stays untouched. For nine elements, that costs nothing, and it pays off twice.\n\nFirst, for the search. Minimax tries moves hypothetically: What if the computer plays field 4 and the human then plays field 0? With mutation, every tried move would have to be taken back after the evaluation – classic do/undo with every opportunity to forget the undo part. With immutable boards, there is nothing to take back. Each branch of the game tree holds its own board, and when the recursion returns, the old board is still exactly the old board.\n\nSecond, for React. `setState` with a fresh array means: if you want to know whether something has changed, you compare references instead of contents. It is no coincidence that the official React tutorial – of all things also a tic-tac-toe – recommends `slice()` at the same spot. Immutable data is the currency React thinks in. That the same decision simplifies the search algorithm and serves the UI model at the same time was the real aha moment of this small project for me.\n\n## Minimax, told recursively\n\nThe algorithm is older than any web framework and can be summed up in one sentence: I choose the move that maximizes my result, assuming that the opponent then chooses the move that minimizes my result – and so on, until the game is decided. Two players, alternating maximum and minimum, hence the name.\n\n```js\nfunction minimax(board, player, depth) {\n  if (winnerOf(board) || movesFor(board).length === 0) {\n    return score(board, depth);\n  }\n\n  const values = movesFor(board).map(index =>\n    minimax(\n      applyMove(board, index, player),\n      player === COMPUTER ? HUMAN : COMPUTER,\n      depth + 1\n    ));\n\n  return player === COMPUTER ? Math.max(...values) : Math.min(...values);\n}\n\nfunction bestMove(board) {\n  const moves = movesFor(board);\n  const values = moves.map(index =>\n    minimax(applyMove(board, index, COMPUTER), HUMAN, 1));\n  return moves[values.indexOf(Math.max(...values))];\n}\n```\n\nThe recursion has three building blocks, and all three are visible in the code:\n\n- The base case: if someone has won or no field is free anymore, `score` returns the value of the end state.\n- The step: for every free field, `applyMove` creates a successor board, which is evaluated with the player swapped and the depth increased by one.\n- The choice: if it is the computer’s turn, the maximum of the child values wins, otherwise the minimum.\n\n`bestMove` is then just the top level of this search, written out: evaluate all of your own moves, return the index of the best one. A small game tree shows why the depth in the evaluation makes the difference between a correct and a smart opponent:\n\n```mermaid\ngraph TD\n  R[\"Board, O to move<br/>takes the maximum\"] --> A[\"Move to field 2 blocks<br/>X to move, takes the minimum\"]\n  R --> B[\"Move to field 5<br/>O wins immediately: value +9\"]\n  A --> A1[\"X later forces the win<br/>value -6\"]\n  A --> A2[\"Draw<br/>value 0\"]\n  A -.-> AV[\"Minimum: -6\"]\n  B -.-> BV[\"Leaf: +9\"]\n```\n\nHere, the computer faces the choice of blocking an opposing line or winning itself. Without the depth bonus, both wins would be worth the same, and the choice would depend on the order of evaluation. With `10 - depth`, the immediate win is strictly better – the opponent doesn’t just play flawlessly, it plays purposefully.\n\nFor a sense of scale: from an empty board, there are around 255,000 possible games, and the tree shrinks drastically with every stone placed. A laptop evaluates that in milliseconds; optimization is computationally unnecessary. The repository still contains a variant with alpha-beta pruning, formulated non-recursively – that was curiosity following the Elm template, because for Othello with its 8×8 board, pruning is no longer a gimmick but a prerequisite. For this article, I deliberately stick with the recursive basic form: it is the version you can derive on a whiteboard, and [simple beats elegant](https://www.mikebild.dev/en/blog/simple-design-can-save-process/) as long as the simple form is measurably enough.\n\n## React only renders state\n\nOnly now does React come into play, and in a decidedly boring role. The entire game state is `state.board`, and the only place where this state changes is the click handler. The handler orchestrates two moves – the human’s, then the computer’s reply – and delegates everything of substance to the pure functions from above.\n\n```jsx\nclass Game extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { board: Array(9).fill(null) };\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick(index) {\n    const afterHuman = applyMove(this.state.board, index, HUMAN);\n    const finished =\n      winnerOf(afterHuman) || movesFor(afterHuman).length === 0;\n    const nextBoard = finished\n      ? afterHuman\n      : applyMove(afterHuman, bestMove(afterHuman), COMPUTER);\n    this.setState({ board: nextBoard });\n  }\n\n  render() {\n    return <Board board={this.state.board} onSquareClick={this.handleClick} />;\n  }\n}\n\nconst Board = ({ board, onSquareClick }) => (\n  <div className=\"board\">\n    {board.map((field, index) => (\n      <button\n        key={index}\n        disabled={field !== null || winnerOf(board) !== null}\n        onClick={() => onSquareClick(index)}\n      >\n        {field}\n      </button>\n    ))}\n  </div>\n);\n```\n\n`Board` is a stateless functional component: board in, nine buttons out. `Game` is a React 15 class with exactly one state field and exactly one handler. The setup around it is an ordinary create-react-app project – `npm install`, `npm start`, running on port 3000. In 2017, you no longer need more tooling than that for something like this, and that is a pleasant development.\n\nThe contrast to the official React tutorial is instructive. There, tic-tac-toe is the vehicle for explaining React: break down components, lift state up, pass props down, and at the end a time history. The opponent is a second human; the game logic is limited to checking for a winner. Here it is exactly the other way around: React is the vehicle, the algorithm is the center. Both perspectives are legitimate – but only the second forces you to draw the boundary between logic and presentation cleanly, because otherwise the logic immediately becomes unwieldy.\n\n```mermaid\nflowchart LR\n  subgraph core[\"Pure functions – no React import\"]\n    score --> minimax\n    winnerOf --> minimax\n    movesFor --> minimax\n    applyMove --> minimax\n    minimax --> bestMove\n  end\n  subgraph ui[\"React 15\"]\n    state[\"state.board\"] --> render[\"render()\"]\n    render --> onclick[\"onClick(index)\"]\n  end\n  onclick -->|\"applyMove + bestMove\"| core\n  core -->|\"new board\"| setState[\"setState\"]\n  setState --> state\n```\n\nThe arrows between the two boxes are the entire coupling: the handler calls functions and writes the result back into the state. No import runs in the opposite direction. You could replace the right box with a console application, with jQuery or, indeed, with Elm – the left box wouldn’t notice.\n\n## Tests without a browser\n\nThis separation isn’t a matter of taste; it is measurable – most directly in the tests. The game logic runs in Node, without a DOM, without jsdom, without a mocked event system. Jest, which comes with create-react-app, runs something like this in milliseconds:\n\n```js\ntest('computer blocks an open line', () => {\n  const board = [\n    HUMAN,    HUMAN, null,\n    COMPUTER, null,  null,\n    null,     null,  null,\n  ];\n  expect(bestMove(board)).toBe(2);\n});\n\ntest('computer prefers the immediate win over the block', () => {\n  const board = [\n    HUMAN,    HUMAN,    null,\n    COMPUTER, COMPUTER, null,\n    null,     null,     null,\n  ];\n  expect(bestMove(board)).toBe(5);\n});\n```\n\nThese aren’t unit tests in the fine-grained sense but game sense as a specification: the opponent must block an open line, and it must prefer its own win to the block. You can take such cases straight from games – every time the opponent behaves oddly while you try it out, the position becomes a test case. For me, it was exactly such a case at the beginning: without the depth component in `score`, the search kept postponing a certain win, because a win in four moves had the same value as one in two. The position from the second test above is the fossil of this bug.\n\nNow the counter-check, and I have seen it in the wild often enough in reviews: the move logic sits in the click handler, the winner check in `render`, the computer’s move in a lifecycle hook such as `componentDidUpdate`. Functionally identical, but now the following applies:\n\n- Every logic test needs a mounted component and simulated clicks – a function call turns into a browser ritual.\n- The position from the bug case can’t be written down directly; it has to be played out through a sequence of clicks.\n- Switching the UI library, or even just a larger restructuring of the component tree, drags the game logic along with it.\n- The algorithm can no longer be read in one piece, because it is spread across handlers, render branches and lifecycle methods.\n\nNone of this is dramatic with three by three fields. But tic-tac-toe is only the lab animal here. Replace “game logic” with “price calculation”, “validation” or “planning rules”, and it is the same decision with the same consequences – except that the entangled version can no longer be untangled in an afternoon.\n\n## What I take away from it\n\nHardly anyone will need minimax itself in everyday project work. What remains is the pattern underneath. The whole opponent is an evaluation function plus a search over immutable values – and because that is so, you can test it like a price formula and render it with whatever happens to be at hand. In this project, React has the role that suits it best in my view: take in state, turn it into a UI, report inputs back. Nothing more.\n\nWhat I find remarkable is how well the parts fit together without being built for each other. Minimax demands immutable boards because otherwise the recursion would need bookkeeping. React rewards immutable state because otherwise comparisons would be expensive. An algorithm from the early days of game theory and a UI library from 2013 meet in the same discipline: no mutation, values instead of changes. That is no coincidence but a sign that this discipline is more fundamental than any single tool.\n\nIf you want to rebuild this: an array with nine fields, five pure functions, one class with one handler. One afternoon – and afterwards a precise sense of where the line between logic and presentation should run in your own, much larger applications. And a game you will never win again.\n\n## Further reading\n\n- Repository `react-tic-tac-toe` (“Tic Tac Toe in React with Minimax-AI”): https://github.com/MikeBild/react-tic-tac-toe\n- Carsten König’s Othello in Elm, the source of inspiration: https://github.com/CarstenKoenig/ElmOthello\n- The official React tutorial (tic-tac-toe, current version): https://react.dev/learn/tutorial-tic-tac-toe\n- Minimax at a glance: https://en.wikipedia.org/wiki/Minimax\n- Alpha-beta pruning: https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning"},{"locale":"en","translation_key":"einfach-schlagen-elegant-statt-prozess","slug":"simple-design-can-save-process","title":"Simple Design Can Save Process","summary":"In many projects, process overhead compensates for a design that is too large or too speculative. Cutting smaller can save coordination; external requirements and real dependencies remain.","tags":["Software","Product"],"published_at":"2017-05-24T10:00:00+00:00","updated_at":"2026-07-13T08:35:56.109624+00:00","url":"https://www.mikebild.dev/en/blog/simple-design-can-save-process/","audio_url":null,"audio_duration_secs":null,"text":"A change board doesn’t measure how risky a change is. It measures how big it was cut. The same goes for the approval round, the design review and the weekly integration meeting: they react to the shape a design gave the work, not to its domain value.\n\nThat’s why the usual proposals against too much process start in the wrong place – one more committee, tighter approvals, a rebuilt ticket board. That manages friction instead of getting rid of it. The question that comes before is more fruitful: why does this one change need three teams, two reviews and an approval meeting in the first place? Very often the answer lies in the design, not in the organization. Not always, but often enough that it’s worth looking there first.\n\n## Overhead is expensive before it becomes visible\n\nBefore I get to design, it’s worth looking at the bill. In his text on YAGNI (“You Aren’t Gonna Need It”), Martin Fowler neatly broke premature, speculative complexity down into types of cost: there’s build cost – building the feature you don’t need today. There’s delay cost – what you didn’t work on in the actual problem during that same time. There’s carry cost – every line of speculative flexibility has to be carried, understood, tested and worked around from now on. And there’s repair cost when the prebuilt assumption turns out to be wrong.\n\nThe point that almost always gets lost in discussions: a large part of these costs is coordination cost. A flexible, configurable design laid out “for later” needs a design review. It needs a config ticket. It crosses team boundaries and therefore needs alignment. That’s why YAGNI isn’t a laziness principle but a design principle – and, incidentally, a process-saving principle. Less prebuilt complexity means less to align on.\n\nA small example I see again and again in variations:\n\n```python\n# Over-engineered: a pluggable strategy, a factory, and a config object\n# for ONE rule that exists today. This needs a design review, a config\n# ticket, and a feature-flag rollout before it ships.\nclass DiscountEngine:\n    def __init__(self, strategy: DiscountStrategy, config: DiscountConfig):\n        self.strategy = strategy\n        self.config = config\n\n    def apply(self, price: Money, customer: Customer) -> Money:\n        return self.strategy.compute(price, customer, self.config)\n\n\n# YAGNI: the one rule you actually have today. One PR, no coordination,\n# no ticket for a config value nobody has asked for yet.\ndef apply_discount(price: Money, is_returning_customer: bool) -> Money:\n    return price * 0.9 if is_returning_customer else price\n```\n\nThe lower variant isn’t “sloppy.” It’s honest. It describes exactly the one rule that exists today. And it costs almost nothing to ship – no round through the committee, no flag, no meeting. If a second discount rule comes along tomorrow, I refactor – then, with real information, instead of today on suspicion.\n\n## The real lever: the size of the cut\n\nThe discount is the small stage. The big one is the question of how large a change is before it goes live. And this is exactly where the connection lies that I most like to draw out in reviews.\n\n```mermaid\nflowchart TB\n    A[\"One large change<br/>crossing three teams\"] --> B[Design Review]\n    B --> C[Cross-team Ticket]\n    C --> D[Merge Conflict]\n    D --> E[Change Board]\n    E --> F[Coordination Meeting]\n    F --> G[Release]\n\n    A2[\"Same value, cut into three<br/>small independent changes\"] --> H[\"Context A<br/>own pipeline\"]\n    A2 --> I[\"Context B<br/>own pipeline\"]\n    A2 --> J[\"Context C<br/>own pipeline\"]\n    H --> K[Release]\n    I --> K\n    J --> K\n```\n\nThe core message of the diagram is simple: coordination effort doesn’t depend on the feature’s value. It depends on the size of the cut and how many team boundaries a cut crosses. A large change that touches three teams creates thick coordination edges – reviews, merge conflicts, change board, alignment rounds. The same domain value, broken down into three small, independent changes, creates almost no cross edges. Each change stays in its own bounded context and goes through its own pipeline.\n\nThis isn’t theory. The State of DevOps reports of recent years – the work around Forsgren, Humble and Kim – show the same empirically. High performers work with few active branches, integrate into trunk at least once a day and have no long integration or freeze phases. They replace merge and coordination overhead with small batches. Trunk-Based Development is exactly that: making the cut so small that the elaborate coordination never arises in the first place.\n\nAnd the part that surprises skeptics: small deployments aren’t riskier but safer. The same data shows that high deployment frequency and short lead time for changes correlate with a lower change fail rate and shorter time to restore. A small cut is easier to understand, easier to review and easier to roll back if something goes wrong. A large cut needs the heavy approval ceremony – because it really has earned it. You build yourself the process that the size forces on you.\n\n## When coordination is just a symptom\n\nA pattern that persists stubbornly in projects: two teams align in a recurring integration meeting because team A provides an endpoint that team B depends on. Every change is discussed in advance, every integration tested together. The process is real – but it only compensates for the fact that nobody made the expectation between the teams explicit.\n\nConsumer-Driven Contracts turn this around. The consumer describes exactly what it needs – no more. The provider verifies this contract in its own pipeline, independently. The alignment meeting disappears because the alignment lives in the code:\n\n```javascript\n// The consumer declares only what it actually needs. No cross-team\n// integration meeting, no shared end-to-end test suite to schedule.\npact\n  .given(\"customer 42 exists\")\n  .uponReceiving(\"a request for the customer name\")\n  .withRequest({ method: \"GET\", path: \"/customers/42\" })\n  .willRespondWith({\n    status: 200,\n    body: { name: like(\"Ada\") },\n  });\n\n// The provider replays this contract in ITS OWN pipeline and fails fast\n// if it ever breaks the expectation — independently, no meeting required.\n```\n\nTools like Pact have made this practical for a few years now. The effect is the same as with the small cut: a piece of coordination that used to exist as a meeting becomes an executable specification – and the process around it is no longer needed.\n\n## Governance without a committee\n\nThe same pattern applies at the architecture level. Many heavyweight governance processes – the architecture committee that signs off on every change – exist because nobody found a more lightweight way to enforce architecture rules. Neal Ford and Rebecca Parsons coined a nice term for the alternative: fitness functions. Instead of designing big once up front and then guarding it through a committee, you formulate the architecture goals as automatically checkable rules in the deployment pipeline.\n\n```yaml\n# Architecture rules as executable guardrails in the pipeline,\n# not as a slide reviewed once a quarter by a committee.\nfitness_functions:\n  - name: modules_stay_decoupled\n    rule: \"no cyclic dependencies between packages\"\n  - name: p95_latency_budget\n    threshold_ms: 300\n  - name: public_api_is_stable\n    rule: \"no breaking change without a new version\"\n```\n\nIf the rule is violated, the build turns red – immediately, traceably, the same for everyone. That doesn’t replace architecture work; it replaces the ritual you otherwise use to enforce it. Related to this are Fowler’s ideas of “Sacrificial Architecture” and “MonolithFirst”: build simply and, if necessary, disposably at first, and only bring in complexity when reality forces it. Evolutionary architecture is the consistent refusal to pay process overhead for a future you don’t know yet.\n\n## Where the thesis reaches its limit\n\nThe counterargument is justified. Three honest caveats, so that a good heuristic doesn’t turn into an ideology.\n\nFirst: simple isn’t the same as simplistic. YAGNI applies to speculative features and premature flexibility – not to internal quality. “We’ll leave out the tests and the design, then we’ll be faster” is the misreading Fowler explicitly writes against. The difference is the one between accidental and essential complexity that Brooks already drew. Less speculative structure: yes. Less care in the core: no. The small discount function from above needs its test just as much as the big engine – just exactly one, for the one rule that exists.\n\nSecond: overhead isn’t always the design’s fault. Compliance requirements are real. Regulatory gates are real. Real dependencies between teams that can’t be cut away are real. That’s why it deliberately says “often” above and not “always.” It’s not about abolishing every process step. It’s about questioning it: are you compensating for a requirement from outside right now – or for a complexity we built ourselves?\n\nThird: a smaller cut can also just shift complexity. Turning one module into two services trades code coupling for distributed coupling and network. That’s sometimes right, but it’s never free. That’s exactly why contract tests are the replacement for the full end-to-end integration circus – and exactly why Fowler’s “MicroservicePremium” is worth remembering: you have to earn distribution; it’s not a default. If you cut small without placing the cut along real domain boundaries, you end up with more coordination, not less.\n\n## How I approach it concretely\n\nThe order that has proven itself doesn’t start with the process.\n\n```mermaid\nflowchart LR\n    A[\"Spot the heavy<br/>process step\"] --> B[\"Ask: what complexity<br/>is it compensating?\"]\n    B --> C[\"Cut the change<br/>smaller\"]\n    C --> D[\"Make the expectation<br/>explicit as a contract\"]\n    D --> E[\"Turn the gate into a<br/>fitness function\"]\n    E --> F[\"Drop the step<br/>that is now redundant\"]\n```\n\nFirst I look for the most expensive process step – the meeting that annoys everyone, the approval that always blocks. Then I don’t ask “how do we make it more efficient” but “what complexity is it absorbing.” Most of the time we find a cut that is too large behind it, an unspoken expectation or governance nobody has automated. Then we cut smaller, make the expectation explicit as a contract, cast the gate into a fitness function – and drop the step that no longer absorbs anything, without replacement.\n\nThe result is rarely spectacular and almost always noticeable: shorter cycles, because less is waiting for approvals. Less friction, because less has to be aligned across team boundaries. Higher quality, because small changes are easier to check and easier to roll back if something goes wrong. Simple and elegant instead of process overhead – that falls out as a by-product of better design and isn’t a cost-cutting measure.\n\n## Conclusion\n\nProcess is expensive, and usually it’s expensive for a good reason: it absorbs friction that really exists. But the more interesting question is almost never how to make the process more efficient. It’s why the friction arises in the first place. Very often the answer is a design that is too large, too speculative or too implicit.\n\nCutting smaller beats coordinating more. Explicit contracts beat recurring alignment. Automated guardrails beat committees. And YAGNI beats any flexibility you build today and work around tomorrow. This isn’t an invitation to sloppiness – internal quality remains non-negotiable. It’s an invitation not to take process overhead as a law of nature but to read it as a symptom. If you make the problem small in the right place, you don’t need the heavy machinery around it in the first place.\n\nWhere the process compensates for self-built complexity, a simpler design can actually make it superfluous. Where regulation, operations or real team dependencies are the cause, that calculation remains open. To me, exactly this distinction matters more than the blanket demand for less process.\n\n## Further reading\n\n- [Martin Fowler – Yagni](https://martinfowler.com/bliki/Yagni.html)\n- [Martin Fowler – Is Design Dead?](https://martinfowler.com/articles/designDead.html)\n- [Sacrificial Architecture (InfoQ, 2014)](https://www.infoq.com/news/2014/11/sacrificial-architecture/)\n- [Building Evolutionary Architectures / Fitness Functions (O’Reilly, 2017)](https://www.oreilly.com/library/view/building-evolutionary-architectures/9781491986356/ch02.html)\n- [Neal Ford – Building Evolutionary Architectures](https://nealford.com/books/buildingevolutionaryarchitectures.html)\n- [Pact – documentation](https://docs.pact.io/)"},{"locale":"en","translation_key":"html5-css3-ecmascript-baseline","slug":"html5-css3-and-ecmascript-as-a-baseline","title":"HTML5, CSS3 and ECMAScript as a Baseline","summary":"In the spring of 2017, CSS Grid, Flexbox, fetch and native ES2015 carry so far that the first architecture question in the frontend deserves to be asked again: How far do I get without a framework?","tags":["Software","Architecture"],"published_at":"2017-05-12T10:00:00+00:00","updated_at":"2026-07-14T17:01:38.042661+00:00","url":"https://www.mikebild.dev/en/blog/html5-css3-and-ecmascript-as-a-baseline/","audio_url":null,"audio_duration_secs":null,"text":"# HTML5, CSS3 and ECMAScript as a Baseline\n\nBaseline means something specific here: the set of HTML, CSS and JavaScript capabilities that runs in all of a project’s browsers without a single dependency. No `npm install`, no framework, no plugin – only what the platform ships out of the box. This set is not a fixed quantity. It depends on which browsers a project actually has to serve, and it shifts with every browser release. If you know it, you can precisely answer a question that otherwise gets answered by reflex: what exactly do I need a dependency for – and what not?\n\nThis question is especially worth asking right now, because over the last few months the baseline has moved further up than it has in a long time.\n\n## An unusual spring\n\nIn March, Chrome 57, Firefox 52 and Safari 10.1 shipped CSS Grid Layout within a few weeks of each other. I’ve never before seen a major layout feature land practically simultaneously and without prefixes in three major browsers. Usually something like this dragged on for years – think of the three different Flexbox syntaxes that coexisted for a long time. Grid is usable in its final syntax from day one.\n\nBut Grid is only the most visible part. If you can limit your target browsers to current versions of Chrome, Firefox, Safari and Edge, here’s what you have in May 2017 without any dependency:\n\n- Flexbox and CSS Grid for layout, plus `@supports` for clean feature queries in the stylesheet\n- CSS custom properties (widely supported since last year, IE11 excepted)\n- Native ES2015: classes, arrow functions, destructuring, template literals, promises\n- `async`/`await` from ES2017 in the current versions of the evergreen browsers\n- `fetch` as a built-in HTTP client, since Safari 10.1 there too\n- Custom Elements v1 and Shadow DOM v1 in Chrome and Safari\n- Service workers in Chrome and Firefox – Safari and Edge are still missing here, and honesty requires saying so\n\nTwo or three years ago, every single item on this list was a reason to install a library. That’s exactly why the question matters to me again. In a code review recently, I went through a frontend that dragged along jQuery, a grid system, an AJAX helper library and a class emulator – well over 100 KB together before the first line of its own code ran. In 2013, there was a good reason for each of these dependencies. In 2017, the platform handles all four tasks itself. Nobody had ever reversed the decision, because nobody had ever looked at it as a decision.\n\n## Layout now belongs to the platform\n\nThe example I use to play this through is deliberately ordinary: a product overview, cards in a grid, data from an HTTP interface. The classic case for which you’d otherwise install Bootstrap along with its jQuery dependency.\n\nThe grid first. With Grid, the layout is a handful of lines, and the fallback for older browsers isn’t a second codebase but a layer underneath:\n\n```css\n/* baseline for every browser: a simple flex wrap */\n.products {\n  display: flex;\n  flex-wrap: wrap;\n}\n\n.product-card {\n  flex: 1 1 240px;\n  margin: 8px;\n}\n\n/* enhancement for browsers with grid support */\n@supports (display: grid) {\n  .products {\n    display: grid;\n    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));\n    grid-gap: 16px;\n  }\n\n  .product-card {\n    margin: 0;\n  }\n}\n```\n\nI find two things about this remarkable. First: `repeat(auto-fill, minmax(240px, 1fr))` replaces what grid systems needed classes like `col-md-4` and a cascade of media queries for over the years – without a single media query. Second: `@supports` turns the browser matrix into a design decision instead of a compatibility hack. IE11 and the current Edge get the Flexbox grid, modern browsers get Grid. The pages don’t look pixel-identical, and that’s fine – the idea that every browser version has to render identically has cost us a lot of unnecessary code for years.\n\nYou have to stay honest about Edge: so far it only supports the old Grid syntax with the `-ms` prefix, which dates back to the IE10 era. If Edge is in your target set, treat it like IE11 for Grid for now and use the fallback. That’s exactly what the `@supports` query is for.\n\n## Loading data without a library\n\nThe second building block is fetching data. What used to require `$.ajax` or your own XHR wrapper is now handled by `fetch` – and with `async`/`await`, the control flow finally reads like synchronous code. How tedious the same task was three years ago with callback chains I recorded back then [in a separate post](https://www.mikebild.dev/en/blog/control-flow-before-async-await/); the distance between these two worlds is surprisingly short.\n\n```js\nasync function loadProducts() {\n  const response = await fetch('/api/products', {\n    headers: { 'Accept': 'application/json' }\n  });\n\n  // fetch resolves on HTTP errors too, so check explicitly\n  if (!response.ok) {\n    throw new Error('Request failed with status ' + response.status);\n  }\n\n  return response.json();\n}\n```\n\nThe comment in the code marks the pitfall I run into most often in reviews: `fetch` doesn’t reject the promise on a 404 or 500, only on network errors. If you come from jQuery, you expect the opposite. You have to learn quirks like this once – but in doing so you learn the platform, not a library’s opinion, and that knowledge goes stale much more slowly.\n\nFor IE11: no `fetch`, no promises, no `async`/`await`. If you have to support it, compile with Babel and load two small polyfills. That’s a build step I otherwise like to avoid – but it’s manageable, targeted and above all temporary. The polyfill goes away as soon as IE11 drops out of the matrix. In my experience, a framework dependency never goes away.\n\n## Components directly in the browser\n\nThe third building block is the most interesting because it comes closest to what you’d otherwise reach for a framework for: reusable components. Custom Elements v1 have arrived in Chrome and Safari, and with them you can define the product list as your own HTML element:\n\n```js\nclass ProductList extends HTMLElement {\n  async connectedCallback() {\n    this.textContent = 'Loading products ...';\n\n    try {\n      const products = await loadProducts();\n      this.render(products);\n    } catch (error) {\n      this.textContent = 'Products are currently unavailable.';\n    }\n  }\n\n  render(products) {\n    this.innerHTML = '<div class=\"products\"></div>';\n    const container = this.querySelector('.products');\n\n    products.forEach(product => {\n      const card = document.createElement('article');\n      card.className = 'product-card';\n      card.textContent = product.name;\n      container.appendChild(card);\n    });\n  }\n}\n\ncustomElements.define('product-list', ProductList);\n```\n\nThe markup then simply contains `<product-list></product-list>`, and the browser calls the lifecycle methods itself. No virtual DOM, no data binding, no render loop – a component of this size needs none of that. Firefox and Edge still need the polyfill from the webcomponents.org project for this, and it isn’t free: it adds noticeable weight and has to be tested across the browser matrix. If you rely on Custom Elements in production today, you should know these costs and not just the Chrome demo.\n\nA note on the side: native ES modules in the browser are also just around the corner – Safari 10.1 already supports `<script type=\"module\">`, the others have it behind flags. For the moment, bundling stays in the build; but this gap is closing too.\n\n## The order of checks\n\nThese building blocks result in an order I now go through for every frontend requirement – not as dogma, but as a path of checks that turns dependencies into justified decisions instead of reflexes:\n\n```mermaid\nflowchart TD\n  A[Requirement in the frontend] --> B{Can the platform do it?<br/>caniuse against the target browsers}\n  B -- yes, in all target browsers --> C[Use the baseline<br/>no dependency]\n  B -- yes, with exceptions --> D{Fallback via @supports<br/>or polyfill acceptable?}\n  D -- yes --> E[Retrofit selectively<br/>polyfill is temporary]\n  D -- no --> F[Library for exactly<br/>this one gap]\n  B -- no --> F\n  F --> G{Do several gaps<br/>form a pattern together?}\n  G -- yes --> H[Framework – with a clear purpose]\n  G -- no --> C\n```\n\nThe decisive point is the last node. A framework isn’t forbidden in this picture – it just comes at the end of the check instead of at the beginning. If you’ve gone through the path, you can name the purpose precisely: “We need React because we have twenty views with shared state and data binding by hand is no longer manageable” is an architecture decision. “We’re using React because that’s how it’s done today” is not.\n\n## The honest other side\n\nSo that this doesn’t sound like a plea for frontend asceticism: there are good reasons to keep installing dependencies in 2017, and they belong on the table.\n\nThe browser matrix is the biggest one. If you build an internal system for a large company where IE11 is set by group policy, you have a different baseline than someone running a website for a tech-savvy audience. For the IE11 world, the platform approach means: Babel, several polyfills, two layout paths, twice the testing. Beyond a certain point, a library that abstracts away these differences is simply the cheaper solution – and that’s exactly why jQuery is still legitimate this year:\n\n- when IE versions are in the target set whose quirks jQuery has reliably smoothed out for years\n- when an existing plugin ecosystem – date pickers, tables, upload widgets – is in production use and a rebuild creates no business value\n- when a team maintains a large, long-grown jQuery codebase and a technology switch would bring more risk than benefit\n\nThe polyfill math has to be honest too. A `fetch` polyfill is small; the Web Components polyfill isn’t. If you retrofit five platform features, you may end up loading more kilobytes than with a compact library that brings everything along – and you carry the testing burden for every combination yourself. The baseline question is not “the platform at any price,” but: what runs everywhere anyway, and what does the rest really cost?\n\nAnd finally: for large, long-lived applications with lots of shared state, the platform doesn’t solve the core problem. HTML, CSS and ECMAScript say nothing about how state and presentation stay consistent when thirty components show the same data. This problem is real, and frameworks rightly address it. But it’s a specific problem – not every website has it, and a product overview with three views almost certainly doesn’t.\n\n## A collection of material as a by-product\n\nWhile sorting out this topic, I created a public collection of material in April: [introduction-html5-css3-ecma](https://github.com/MikeBild/introduction-web-plattform) on GitHub. It gathers the platform’s inventory in sections – HTML5 markup and the APIs from geolocation through canvas, web workers and WebSockets to server-sent events, plus CSS3 selectors and animations, the JavaScript fundamentals around prototypes and closures, and ES2015+ syntax up to promises, `async`/`await` and generators. None of it is exotic; for me, the value lies in having it side by side. Only when the inventory lies written down in front of you do you see how much of it currently exists twice in your own project – once natively in the browser and once as a dependency in the bundle.\n\n## Bottom line\n\nIn 2017, the baseline of HTML5, CSS3 and current ECMAScript is no longer a makeshift compromise but a solid foundation: Grid and Flexbox for layout, `fetch` and `async`/`await` for data, Custom Elements for components on a small scale. If you start with it, you cut three costs at once – fewer dependencies that need maintaining and updating, less build complexity, and a lower barrier to entry for everyone new to the project, who only needs to know web standards at first.\n\nAbove all, though, the baseline changes the quality of the framework decision. It no longer happens at the start of the project out of habit, but later, deliberately, with a purpose you can name. Sometimes the answer is still React or Angular – and that’s perfectly fine, because now it’s clear which problem it solves and which one the platform has long solved itself. More often than I would have thought two years ago, though, the answer is: you don’t need one at all.\n\n## Further reading\n\n- [MikeBild/introduction-html5-css3-ecma](https://github.com/MikeBild/introduction-web-plattform) – the collection of material on HTML5, CSS3 and ECMAScript mentioned above\n- [MDN: CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout) – reference and introduction to the Grid model\n- [MDN: Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) – documentation on `fetch`, Request and Response\n- [Grid by Example](https://gridbyexample.com/) – Rachel Andrew’s collection of CSS Grid examples\n- [Can I use](https://caniuse.com/) – browser support tables for your own target browser matrix"},{"locale":"en","translation_key":"rxjs-push-und-pull","slug":"rxjs-telling-push-and-pull-apart","title":"RxJS: Finally Telling Push and Pull Apart","summary":"Once you name the producer and the consumer, you see right away whether data is pulled or pushed, and you choose between function, iterator, Promise and Observable without guessing.","tags":["Software","Reactive"],"published_at":"2017-04-12T10:00:00+00:00","updated_at":"2026-07-14T20:56:00.987422+00:00","url":"https://www.mikebild.dev/en/blog/rxjs-telling-push-and-pull-apart/","audio_url":null,"audio_duration_secs":null,"text":"# RxJS: Finally Telling Push and Pull Apart\n\nIf you treat a cold Observable like a shared Promise, your HTTP request goes out as many times as someone calls `subscribe`. Three components on the same cold stream mean three requests – no error message, no warning, exactly as defined.\n\nThe reason has less to do with operators at first than with one question: Who decides when a value flows – the producer or the consumer? Before `map`, `switchMap` and `debounceTime`, people usually ask which operator is the right one. That question comes too early. Push and pull provide the basic model that cold, hot and multicasting build on later.\n\n## The one question that sorts everything\n\nYou can describe every data source in JavaScript by its direction. There are only two.\n\nIn a pull system, the consumer actively fetches the values. It calls something and gets an answer. A function is exactly that: you call it, it delivers. An iterator is the same thing in several steps, because `iterator.next()` pulls out the next value. The consumer sets the pace.\n\nIn a push system, this flips. Now the producer decides when to send something, and the consumer doesn’t know in advance when the next value will arrive. A click event, a WebSocket message, a timer: all of these push as soon as they are ready. The consumer only reacts.\n\nThat sounds academic, but it has direct consequences for your code. With synchronous pull, the consumer determines the next fetch and can block while doing so; an asynchronous iterator doesn’t have to. With push, the producer decides when it delivers, and the consumer reacts to it. This is exactly where many migrations from “querying data” to “reacting to data” fail.\n\n## Four producers, two directions\n\nThe official RxJS documentation places the four important producers in a grid. In architecture discussions, it’s the first thing I draw on the whiteboard, because afterwards most questions are already answered.\n\n| Producer | Number of values | Direction | Evaluation |\n| --- | --- | --- | --- |\n| Function | exactly one value | Pull | lazy |\n| Iterator / Generator | zero to many | Pull | lazy |\n| Promise | exactly one value | Push | eager |\n| Observable | zero to many | Push | lazy |\n\nRead the table as two axes. One axis asks: one value or several? The other asks: does the consumer pull or does the producer push? The Observable is the only source that pushes several values and still stays lazy. This combination makes it so powerful and so confusing for newcomers, because it has no direct counterpart in classic JavaScript.\n\nA Promise is its closest relative, but it only covers the neighboring cell: one value, pushed, started immediately. Once you internalize this, you stop treating an Observable like a Promise with more methods.\n\n## An Observable is a function with several outputs\n\nCode makes this clear fastest. My `introduction-rxjs` material deliberately starts with the `Observable` constructor before it shows any operators. It forces you to name the producer and the consumer yourself.\n\n```ts\nimport { Observable } from 'rxjs';\n\n// The producer decides on its own when values flow.\nconst ticks$ = new Observable((observer) => {\n  let n = 0;\n  const id = setInterval(() => observer.next(n++), 1000);\n\n  // Cleanup function: runs on unsubscribe or on complete.\n  return () => clearInterval(id);\n});\n\n// The consumer only reacts, it does not actively pull.\nconst sub = ticks$.subscribe({\n  next: (v) => console.log('value', v),\n  error: (e) => console.error('error', e),\n  complete: () => console.log('done'),\n});\n```\n\nThe block in `subscribe` is the observer with its three channels: `next` for values, `error` for aborting with an error, `complete` for a clean end. That is the complete vocabulary of a push consumer. There is nothing more, and you don’t need anything more.\n\nFor comparison, here is the same idea as a pull source. Nothing happens as long as nobody pulls.\n\n```ts\nfunction* naturals() {\n  let n = 0;\n  while (true) yield n++; // The value is produced only when pulled.\n}\n\nconst it = naturals();\nit.next().value; // 0  – the consumer pulls\nit.next().value; // 1  – and sets the pace\n```\n\nBoth sources deliver an infinite sequence of natural numbers. The only difference is control. With the generator, you decide with every `next()` when the one comes after the zero. With the Observable, the timer decides, and the values are simply delivered to you.\n\n## Lazy means: without subscribe, nothing happens\n\nThe most consequential column of the table is “Evaluation”. The cold Observable built here is lazy. It runs its producer code only when `subscribe` is called, and starts over for every `subscribe`. Hot Observables and shared sources behave differently. A Promise, on the other hand, is eager: it starts its work the moment it is created, without any `then`.\n\nThis difference causes most of the mistakes when people switch over.\n\n```ts\n// eager: the request goes out immediately, even without then.\nconst preise = fetch('/api/preise');\n\n// lazy: nothing happens until someone calls subscribe.\nconst preise$ = new Observable((observer) => {\n  fetch('/api/preise')\n    .then((res) => res.json())\n    .then((data) => {\n      observer.next(data);\n      observer.complete();\n    })\n    .catch((err) => observer.error(err));\n});\n```\n\nThis resolves the case from the beginning. A team rebuilds a search. Before, there was a shared Promise that ran once, and several components shared its result. After the switch to an Observable, three components subscribe to the same stream. Suddenly three HTTP requests go out instead of one. Nobody made a mistake in the classic sense; the Observable behaves exactly as defined: lazy and cold, so each subscription gets its own execution. In 2017, if you wanted the Promise behavior back, you shared the stream with `publishReplay` and `refCount` or put a `Subject` in front of it. `publishReplay` is now deprecated; today `shareReplay({ bufferSize: 1, refCount: true })` expresses the same intent more directly. You still have to decide on multicasting deliberately. Only when you name push, lazy and cold separately do you see why three requests happen here.\n\n## Making time visible with the marble diagram\n\nIn push systems, everything depends on how things unfold over time, and that is exactly what makes them hard to read. A marble diagram draws this time on a line. Each marble is a pushed value, the `|` is `complete`, the `X` would be an `error`.\n\n```text\nsubscribe                         unsubscribe\n   |                                   |\n   v                                   v\nticks$: ---0----1----2----3----4----5--|\n              (the producer pushes every 1000 ms)\n```\n\nThe line makes two things visible right away that get lost in prose. First: the values appear according to the producer’s internal logic, here the interval, and not on demand. Second: there are two edges, the subscription and the unsubscription. The stream exists between these edges, not before and not after. Once you read marble diagrams, you stop thinking about individual values and start thinking about the lifetime of the stream.\n\nFor the direction itself, a small diagram is enough. It shows who drives whom.\n\n```mermaid\nflowchart LR\n  subgraph Pull\n    C1[Consumer] -- pulls next --> P1[Producer]\n  end\n  subgraph Push\n    P2[Producer] -- pushes next --> C2[Consumer]\n  end\n```\n\n## The mistake almost everyone makes once\n\nThe lazy property comes with a duty that has its own chapter in the material: Disposable. If a `subscribe` starts a producer, someone also has to stop it again. With `ticks$` above, this is obvious: the `setInterval` keeps running forever as long as nobody calls `unsubscribe`.\n\n```ts\nconst sub = ticks$.subscribe((v) => console.log(v));\n\n// Without this line the timer ticks forever,\n// even after the component is long gone.\nsub.unsubscribe();\n```\n\nIn a single-page application, this can turn into a real leak. A component subscribes to an event stream, the user navigates away, the component disappears from the DOM, but a subscription that was never ended keeps listeners and referenced objects alive. The next time the view opens, a second subscription is added, then a third. The symptoms are side effects that run twice and growing memory usage. The subscription is the boundary where a stream gets ownership and a lifetime; depending on the source, it ends through `complete`, `error` or a deliberate unsubscribe.\n\n## What remains\n\nPush and pull is not a theoretical detail but the grid on which you hang every decision in RxJS. Do I need one value or several? Does my consumer pull or does my producer push? Does the work start immediately or only on subscribe? And who ends the stream again? These four questions settle most operator discussions before they start.\n\nThe order in my course material – which I also use with partners like [Grossweber](https://grossweber.com/) – follows exactly this logic. First Observable, Observer and Notification, that is, the push vocabulary. Then Scheduler and Disposable, that is, time and lifetime. Operators come last, because they are only tools on top of this foundation. If you start with the list of operators, you learn vocabulary without grammar.\n\n## Further reading\n\n- RxJS documentation, chapter Observable with the push/pull table: https://rxjs.dev/guide/observable\n- [RxJS: `publishReplay` and today’s alternatives](https://rxjs.dev/api/operators/publishReplay)\n- [RxJS: `shareReplay`](https://rxjs.dev/api/index/function/shareReplay)\n- Course material for the training, repository `introduction-rxjs`: https://github.com/MikeBild/introduction-rxjs"},{"locale":"en","translation_key":"nodejs-async-io-architektur","slug":"nodejs-async-io-explains-architecture","title":"Node.js: Async I/O Explains Architecture","summary":"The calculation “one thread times 200 connections” shows which systems fit Node.js and which work belongs in separate processes.","tags":["Software","Node.js","Backend"],"published_at":"2017-03-24T10:00:00+00:00","updated_at":"2026-07-14T20:54:32.790854+00:00","url":"https://www.mikebild.dev/en/blog/nodejs-async-io-explains-architecture/","audio_url":null,"audio_duration_secs":null,"text":"# Node.js: Async I/O Explains Architecture\n\nFifty milliseconds isn’t a conspicuous number. A `JSON.parse` over a few megabytes, a synchronous template render, some hashing – 50 ms of CPU time doesn’t stand out unpleasantly in any profiler. Now the second number: 200 concurrent connections. In Node.js, all JavaScript code runs on a single thread. If each of these 200 requests contains a synchronous 50 ms block, the last response doesn’t wait 50 milliseconds but 200 × 50 ms = 10 seconds. Not because the machine is overloaded – CPU and network are bored – but because all requests share the same thread and have to pass through the same bottleneck one after the other.\n\nThis small calculation is the complete architecture talk on Node.js in one paragraph. Once you have really understood it, you can derive most system decisions around Node: which services belong there, which don’t, and why the scaling answer is “more processes”. The following sections show what that means in detail.\n\n## One thread, many connections\n\nNode answers the question “How do I serve many concurrent connections?” differently than the classic servers. Apache with PHP or a Java servlet container give each request its own thread or process; if one blocks, it hardly bothers the others. Node turns the model around: there is exactly one thread for JavaScript, and it must never wait. Everything that takes time – a network call, a file access, a DNS lookup – is handed off to the operating system or to a small internal thread pool. The JavaScript thread merely registers a callback and turns to the next task.\n\nThis is organized by libuv, the C library Node is built on. It asks the kernel via epoll (Linux), kqueue (macOS) or IOCP (Windows) which of the open operations are done and works through the associated callbacks in a fixed order – that is the event loop. The loop goes through phases: timers, pending callbacks, polling for I/O, `setImmediate`, close callbacks. In between, microtask processing with `process.nextTick` and promise resolutions slips in. File system, DNS and parts of crypto don’t run through the kernel mechanism but through the thread pool mentioned above – four threads by default, configurable via `UV_THREADPOOL_SIZE`.\n\n```mermaid\nflowchart LR\n  subgraph proc[Node process]\n    JS[JavaScript<br/>one single thread] --> Loop[Event loop<br/>libuv]\n  end\n  Loop --> Kernel[Kernel<br/>epoll / kqueue / IOCP]\n  Loop --> Pool[Thread pool<br/>fs, dns, crypto]\n  Kernel -. callback ready .-> JS\n  Pool -. callback ready .-> JS\n```\n\nFor everyday work, two rules of thumb are enough. First: I/O is practically free in Node, because the waiting happens elsewhere – in the kernel or in the thread pool. Second: CPU time in the JavaScript thread is the most expensive resource of the whole system, because it is exclusive. Every millisecond a request spends computing is a millisecond in which all other requests stand still.\n\n## One blocking call blocks everyone\n\nThis first really became clear to me in a production incident, not while reading the documentation. A reporting endpoint accepted JSON documents, normally a few kilobytes. One day, a client started sending exports of around 30 MB. The code looked harmless:\n\n```js\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n  let body = '';\n  req.on('data', chunk => { body += chunk; });\n  req.on('end', () => {\n    // synchronous: the event loop stops while parsing\n    const report = JSON.parse(body);\n    res.end(JSON.stringify({ items: report.items.length }));\n  });\n});\n\nserver.listen(3000);\n```\n\n`JSON.parse` over 30 MB takes several hundred milliseconds. During that time, nothing else happens in the process: no new connections, no ongoing responses, no timers. The health check endpoint stopped answering too, the load balancer took the instance out of rotation, and monitoring reported the service as dead – while the process was running perfectly and simply computing. The incident was understood after an hour, but the lesson was bigger than the incident: in Node, there is no such thing as “one slow request”. There are only slow requests that take all the others down with them.\n\nThat makes the failure model fundamentally different from thread-per-request servers. There, a CPU hog shows up as one slow request in the statistics. In Node, it shows up as a latency spike across the entire system – including for requests that have nothing to do with the culprit.\n\n## Which systems fit – and which don’t\n\nIf you take the model seriously, architecture decisions almost sort themselves. Node is strong when the process mostly waits and computes only briefly:\n\n- API gateways and proxies that check, enrich and forward requests\n- REST APIs in front of databases, where the actual work happens in storage\n- Aggregators that query several backends in parallel and assemble results\n- Push and real-time services with many open, mostly idle connections\n\nAll these systems have the same character: thousands of connections, almost all of which are waiting for something at any given moment. That is exactly what an event loop is built for – the waiting connections cost almost nothing, and one thread is enough for all of them.\n\nConversely, work with serious CPU load doesn’t belong in the request path of a Node process: image processing, PDF generation, encrypting large files, elaborate computations over data sets. Not because V8 is slow – the JIT compiler is astonishingly fast – but because every one of these milliseconds belongs to all requests at the same time.\n\nIn one project, we cut a gateway along this line: Node took over authentication, routing and assembling responses from three backends. Thumbnail generation for uploaded images, initially right in the middle of the upload handler, moved into a separate process with its own queue – started via `child_process.fork` and connected through messages. Upload latency dropped, but the real gain was a different one: the 99th percentile of all other endpoints calmed down, because no image occupied the shared thread anymore. The event loop had dictated the boundary along which to split the system – and it was a good boundary.\n\n## Backpressure: waiting needs organizing, too\n\nAsync I/O doesn’t mean data flows at the right speed on its own. If you load a 2 GB export file with `fs.readFile` to send it to the client, you hold 2 GB in memory – per request. Streams solve this by passing data through in chunks:\n\n```js\nconst fs = require('fs');\nconst zlib = require('zlib');\nconst http = require('http');\n\nhttp.createServer((req, res) => {\n  res.setHeader('Content-Encoding', 'gzip');\n  fs.createReadStream('./export.csv')\n    .pipe(zlib.createGzip())\n    .pipe(res);\n}).listen(3000);\n```\n\nThe interesting thing about `pipe` isn’t the compact notation but the built-in flow control. If the destination can’t keep up – that is, `write()` returns `false` – the reading stream pauses until the `drain` event signals that there is room again. This interplay is called backpressure. Without this brake, the disk reads at a few hundred MB/s while a mobile client receives at a fraction of that – the difference piles up as a buffer in the heap, and the process grows until memory runs out.\n\nBackpressure is thus the second place where the runtime model becomes an architecture question: if you route uploads, exports or event streams through Node, you have to design data flow as something boundable – with streams as the standard tool and `pipe` as the connector, not with “everything into one variable and then send”.\n\n## Scaling means: more processes\n\nA Node process uses one core for JavaScript. On a machine with eight cores, seven lie idle as long as only one process runs. The platform’s answer is the `cluster` module: a master process starts one worker per core, all share the same port, and the master distributes incoming connections round-robin.\n\n```js\nconst cluster = require('cluster');\nconst os = require('os');\n\nif (cluster.isMaster) {\n  os.cpus().forEach(() => cluster.fork());\n  cluster.on('exit', worker => {\n    console.log(`worker ${worker.process.pid} died, forking a new one`);\n    cluster.fork();\n  });\n} else {\n  require('./server');\n}\n```\n\n```mermaid\nflowchart TB\n  In[incoming connections<br/>port 3000] --> M[Master process<br/>round-robin distribution]\n  M --> W1[Worker 1<br/>own event loop]\n  M --> W2[Worker 2<br/>own event loop]\n  M --> W3[Worker N<br/>own event loop]\n```\n\nEach worker has its own event loop and its own heap. That has two pleasant side effects and one inconvenient consequence. Pleasant: a crashed worker only takes itself down, and the master restarts it; and a blocked worker now only blocks an eighth of the system instead of everything. Inconvenient: there is no shared memory. Sessions, caches, counters – everything that used to sit comfortably in a module variable has to move out of the process, for example into Redis or the database. In my view, that isn’t a loss but an early push toward a state you need anyway for horizontal scaling across machines. If you get to eight workers with `cluster`, you later get to eight machines almost without changes.\n\nThe classification matters: `cluster` mitigates the blocking problem, it doesn’t solve it. The 50 ms calculation from the beginning applies unchanged in every worker. For real CPU work, the clean answer remains a separate process with a queue in front of it – `cluster` is load distribution, not a free pass for computation in the request path.\n\n## async/await: new syntax, same model\n\nSince a few weeks ago – Node 7.6, released in February 2017 – `async`/`await` runs without a flag. On Node 6 LTS, which many production systems run, you still need Babel for it. After years of callback pyramids and promise chains, the same flow suddenly reads like synchronous code:\n\n```js\nasync function loadDashboard(userId) {\n  const user = await fetchUser(userId);\n  const orders = await fetchOrders(user.id);\n  return { user, orders };\n}\n\n// independent calls: run them concurrently instead\nasync function loadDashboardFast(userId) {\n  const [user, orders] = await Promise.all([\n    fetchUser(userId),\n    fetchOrders(userId)\n  ]);\n  return { user, orders };\n}\n```\n\nThere is nothing synchronous about it. At every `await`, the function releases the thread; the event loop serves other callbacks and resumes the function as soon as the promise is resolved. That is exactly why two things belong in the same thought. First: two `await` lines one after the other run sequentially, even if they are independent – `Promise.all` remains responsible for parallelism, as in the second example. Second, and I consider this the real trap of the new syntax: `await` makes waiting cooperative, but CPU work between two `await` points blocks exactly as before. A `JSON.parse` over 30 MB doesn’t get more polite because there is an `await` in front of it. If you have moved from callbacks through promises to `async`/`await`, you have much better code – and an unchanged runtime model. The syntax is new; the math stays the same.\n\nI collect runnable examples for all of this – event loop, streams, Express, async patterns from callbacks to streams – in a public repository: [MikeBild/introduction-nodejs](https://github.com/MikeBild/introduction-nodejs). The examples are deliberately kept small; each one shows exactly one of the limits described here.\n\n## The bottom line\n\nThe event loop is a useful architecture test, and a cheap one. For every planned feature, you can ask: Does this code wait, or does it compute? Waiting work – database, HTTP, files, open connections – fits into the Node process in almost any quantity. Computing work belongs in separate processes, behind a queue, with `cluster` and `child_process` as built-in tools. Streams with working backpressure keep memory flat where large amounts of data flow.\n\nI find it remarkable how much architecture follows from a single runtime property. Separating the gateway from image processing, stateless processes, queues in front of CPU work – none of this is in a framework handbook, all of it is in the calculation 200 × 50 ms. Platforms shape their systems, whether you want them to or not. Node’s upbringing is strict, but it points in a direction that pays off beyond Node, too: small processes that mostly wait, keep nothing important in local memory and limit their data flows. Once you have seen the 10 seconds from the beginning in a real dashboard, you won’t forget this direction.\n\n## Further reading\n\n- Example repository “Introduction to NodeJS”: https://github.com/MikeBild/introduction-nodejs\n- The Node.js Event Loop, Timers, and process.nextTick(): https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick\n- Backpressuring in Streams: https://nodejs.org/en/learn/modules/backpressuring-in-streams\n- libuv Design Overview: https://docs.libuv.org/en/v1.x/design.html\n- Cluster module (Node.js documentation): https://nodejs.org/api/cluster.html"},{"locale":"en","translation_key":"babel-node-express-http","slug":"babel-node-express-modern-syntax-old-http","title":"Babel Node Express: Modern Syntax, Old HTTP","summary":"Babel translates syntax, not an execution model – once you keep the two apart, you know why babel-node belongs in the development loop and not in production.","tags":["Software","Node.js","Backend"],"published_at":"2016-12-20T10:00:00+00:00","updated_at":"2026-07-14T17:17:26.234673+00:00","url":"https://www.mikebild.dev/en/blog/babel-node-express-modern-syntax-old-http/","audio_url":null,"audio_duration_secs":null,"text":"# Babel Node Express: Modern Syntax, Old HTTP\n\n```text\n$ node src/server.js\n/app/src/server.js:1\n(function (exports, require, module, __filename, __dirname) { import express from 'express';\n                                                               ^^^^^^\nSyntaxError: Unexpected token import\n    at Object.exports.runInThisContext (vm.js:76:16)\n    at Module._compile (module.js:542:28)\n```\n\nThis is how Node 6 responds to a file that starts with an `import`. The message is short, and the confusion behind it is reliable: the same line appears in what feels like every other tutorial this year, it runs in the frontend build without complaint – only the runtime that is supposed to actually run the server in the end doesn’t know the keyword. ES2015 was approved a year and a half ago, V8 has built in a large part of it, and still startup fails on the first line of the first file.\n\nThe occasion for this post is a small repository I put together in early December: [babel-node-expressjs](https://github.com/MikeBild/babel-node-expressjs), a deliberately simple Express app, written entirely in ES2015+ and made runnable with Babel. A second one came out of the same day, [babel-node-rx-ping-monitor](https://github.com/MikeBild/babel-node-rx-ping-monitor), which pushes RxJS through the same toolchain – but that has a topic of its own and deserves its own text. This post is about the dividing line that became visible during setup and that gets blurred surprisingly often in discussions: Babel changes the language, not the execution model. The syntax became modern in 2016. The HTTP underneath stayed the same.\n\n## What Node 6 and 7 can already do on their own\n\nBefore Babel comes into play, it’s worth taking a sober look at what the platform handles without any tool. Node 6 has been the active LTS line since October, Node 7 the current development line, and through V8 both already ship a substantial part of ES2015 natively:\n\n- Classes including `extends` and `super`\n- `const` and `let` with real block scoping\n- Template literals, arrow functions, default parameters\n- Destructuring for objects and arrays\n- Promises and generators\n\nIf you want to check in detail what your own Node version covers, node.green has a matrix per version and feature. The list is longer than many assume – and that is exactly why the blanket statement “you need Babel for ES2015” is now off the mark. For most of the language, you simply don’t need it anymore.\n\nTwo prominent gaps remain. `async`/`await` exists in Node 7 only experimentally behind the `--harmony-async-await` flag – for code that is supposed to carry a server, that’s not a foundation but a preview. And `import`/`export` is missing entirely: the module syntax is part of the specification, but what a loader in Node should look like and how ES modules work together with the established CommonJS ecosystem is unresolved. A native ES module system is nowhere in sight. If you write `import` in the backend today, you’re writing syntax for a runtime that doesn’t exist in that form yet – and that’s why you need a translator.\n\n## The app: Express 4 in today’s style\n\nThe server in the repository deliberately does little – one JSON route, one route for URL-encoded form data, both demonstrated in the README:\n\n```js\nimport express from 'express';\nimport bodyParser from 'body-parser';\n\nconst app = express();\nconst port = process.env.PORT || 3000;\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: false }));\n\napp.get('/', (req, res) => {\n  res.json({ message: 'hello' });\n});\n\napp.post('/', (req, res) => {\n  const { msg } = req.body;\n  res.json({ received: msg });\n});\n\napp.listen(port, () => {\n  console.log(`server listening on port ${port}`);\n});\n```\n\nWhat’s interesting isn’t what this code does but how it looks: `import` instead of `require`, arrow functions instead of `function`, `const` instead of `var`, destructuring on the request body, a template literal in the log. This is the style that finally won out in the frontend this year, and there’s no good reason to maintain an older language level in the backend than in the rest of the project. Uniform syntax reduces friction when the same people touch React components in the morning and Express routes in the afternoon.\n\nOn the side, you also see a bit of Express 4 history here: body parsing is no longer a built-in function but comes as a separate `body-parser` package and is plugged in as middleware per format. If you come from Express 3, this is exactly where you stumble first – and that has nothing to do with Babel and all the more to do with HTTP.\n\nOn the wire, this changes exactly nothing. A POST to `http://localhost:3000` with a URL-encoded form field – the README has the matching one-liner – sends the same bytes as against any Express app of the last three years, and the answer is the same HTTP response with the same headers. Middleware chain, body parsing, status codes, content negotiation – the complete HTTP behavior is untouched by the syntax question. That sounds trivial. But it’s the core of the topic, because this is exactly where the misunderstandings arise.\n\n## What babel-node does in development mode\n\nFor the file to start at all, you need two things: a translation rule and a tool that applies it. The rule lives in `.babelrc`:\n\n```json\n{\n  \"presets\": [\"es2015\"]\n}\n```\n\nThe `es2015` preset is the established way with Babel 6. Brand new alongside it is `babel-preset-env`, which, via a `targets` field, only transpiles what the target Node version actually can’t do – more on that in a moment. The tool for development is called `babel-node` and ships with `babel-cli`. It starts a normal Node process, hooks into the `require` mechanism and translates every loaded file in memory, right before V8 sees it. No `dist/` folder, no intermediate step; together with nodemon, that makes for a pleasantly short loop:\n\n```json\n{\n  \"scripts\": {\n    \"dev\": \"nodemon --exec babel-node src/server.js\",\n    \"build\": \"babel src --out-dir dist --source-maps\",\n    \"start\": \"node dist/server.js\"\n  }\n}\n```\n\nSave the file, nodemon restarts, babel-node translates, the server runs. For development, that’s exactly right, because the feedback is what counts and the process restarts constantly anyway. The only important thing is to be clear about what’s happening: the translation has been pulled into program startup. Every start pays for it again.\n\nThe same mechanism, by the way, also carries the tests: `babel-register`, hooked into mocha, translates the test files on load following the same principle. That, too, is meant for the development loop and is perfectly fine there – a test run is a short-lived process where a few hundred milliseconds of warm-up don’t matter. So the line doesn’t run between “with Babel” and “without Babel,” but between short-lived tool processes and the one process that has to run for a long time and be back quickly after a crash.\n\n```mermaid\nflowchart LR\n  subgraph DEV[Development]\n    S1[src/server.js<br/>ES2015+] --> BN[babel-node<br/>translates in memory] --> P1[Node process]\n  end\n  subgraph PROD[Production]\n    S2[src/server.js<br/>ES2015+] --> BC[npm run build<br/>babel-cli] --> D[dist/server.js<br/>ES5 + CommonJS] --> P2[node dist/server.js]\n  end\n```\n\n## What the convenient path costs in production\n\nIt’s tempting to simply use `babel-node` in production too – one script fewer, one folder fewer, the same command line everywhere. The Babel documentation itself explicitly advises against it, and the reasons are solid:\n\n- Process startup becomes noticeably slower because every file first has to go through the transpiler on boot – with every deployment, every restart after a crash, every process in the cluster all over again.\n- Memory usage rises because Babel, including parser, presets and cache, keeps running in the server process even though it contributes nothing after startup.\n- Stack traces point to translated code that nobody ever wrote; without properly wired source maps, the line number in the error report points nowhere.\n- The debugger works against the generated code, breakpoints land next to the intended line, and the behavior depends on the Babel version installed on the target machine.\n\nI ran into this point concretely in a project this year: a colleague had deployed a small internal service with `babel-node`, and for weeks nobody noticed. It only came to light when the process restarted under load and the supervisor brought it up several times in a row – each restart several seconds of transpiling, during which the port was open but the service wasn’t responding. The bug wasn’t in any line of application code. It was in the decision to take a development tool into production.\n\n## Build first, then start\n\nThe grown-up variant separates translation from startup. `npm run build` calls `babel-cli`, translates `src/` once into `dist/` and puts source maps next to it. What arrives there is unspectacular ES5 with CommonJS – the `import` at the top of the file becomes exactly what Node has understood for years:\n\n```js\n'use strict';\n\nvar _express = require('express');\n\nvar _express2 = _interopRequireDefault(_express);\n\nfunction _interopRequireDefault(obj) {\n  return obj && obj.__esModule ? obj : { default: obj };\n}\n```\n\nYou don’t have to find this generated code pretty, but you should have read it once. It takes all the magic out of the module syntax: after translation, `import` is a synchronous `require` at program startup, with a small wrapper for the default export. No new loading logic, no different resolution behavior, no difference at runtime.\n\nThe artifact in `dist/` has two pleasant properties. First, the target machine no longer needs Babel – `node dist/server.js` is enough, and the devDependencies stay at home. Second, the startup path is once again the boring one Node has followed for years: start the process, load modules, open the port. The translation happens once per build instead of once per start, and that’s exactly where it belongs. Otherwise, you only notice that there’s a difference between “it runs on my machine with babel-node” and “it runs as a built artifact” at the worst possible moment.\n\nIn practice, this also determines where the build happens: in the pipeline, not on the target machine. You build and test once, ship the result, and an installation without devDependencies leaves Babel and its presets off the server entirely. The order in the repo’s README – build, test, only then run – is therefore not a formality but the short version of this operating model.\n\n## Language on top, execution model below\n\nNow to the actual dividing line. Babel works exclusively at the level of the language: it reads syntax that V8 doesn’t understand yet and rewrites it into syntax that V8 does understand. Everything below remains untouched – the event loop, the module system at runtime, streams, sockets, all of HTTP.\n\n```mermaid\nflowchart TB\n  B[Babel] -->|changes only this layer| L1\n  L1[Language: import, classes,<br/>arrow functions, destructuring] --> L2[Runtime: event loop,<br/>CommonJS require, streams]\n  L2 --> L3[HTTP: connections, headers,<br/>request and response]\n```\n\nThis separation sounds obvious, but it regularly gets blurred as soon as the new syntax looks like more than it is. Three examples from conversations over the last few months. An `import` at the top of the file looks declarative and static – after translation, it’s an ordinary `require` that runs synchronously at startup, in the order of the lines. An arrow function in the route looks lightweight – it runs on the same single thread as everything else, and an expensive JSON serialization inside it blocks the event loop exactly as it did in 2013. And the `async` previews in Node 7 look like concurrency – in fact they’re just a different way of writing promise chains and change nothing about timeouts, error paths or behavior under load. If you run an Express server with modern syntax, you’re running the same server. The questions that matter in production – how long may a request take, what happens with an aborted body, who shuts down the process cleanly – aren’t answered by any preset.\n\nConversely, the separation also helps you save. Because Node 6 runs most of ES2015 natively, Babel no longer has to translate the whole language. This is exactly where the brand-new `babel-preset-env` comes in: you tell it the target environment, and it selects only the transformations that are really missing there.\n\n```json\n{\n  \"presets\": [\n    [\"env\", { \"targets\": { \"node\": 6 } }]\n  ]\n}\n```\n\nFor Node 6, what remains is essentially the module syntax. The generated code stays closer to the original, classes stay real V8 classes instead of ES5 prototype imitations, and the build gets faster. The better the platform gets, the thinner the translation layer can be – until one day it might disappear entirely. When it comes to modules, though, I wouldn’t bet on it yet.\n\n## What I take away from this\n\nThe two small repos were put together in an afternoon, but the dividing line they show reaches further than the code. Babel is a translator for syntax, not a new execution model – and both directions of this statement are useful. In one direction: the modern style costs nothing in production if you pay for it in the build instead of at process startup; `babel-node` belongs in the development loop, `node dist/` in production. In the other direction: the modern style also doesn’t solve anything that needs solving at the HTTP level. Timeouts, error handling, body limits and restart behavior look exactly the same in ES2015 as in ES5, just prettier.\n\nWhen `async`/`await` arrives without a flag next year, the same question will come up again, with the same answers. The syntax will get a bit more modern again. The HTTP underneath stays the old one – and that’s not bad news, because it means twenty years of knowledge about servers doesn’t have to be renewed with every preset.\n\n## Further reading\n\n- Repository: https://github.com/MikeBild/babel-node-expressjs\n- Express documentation: https://expressjs.com/\n- babel-preset-env: https://github.com/babel/babel-preset-env\n- babel-node in the Babel documentation: https://babeljs.io/docs/babel-node"},{"locale":"en","translation_key":"api-denken-vor-framework-denken","slug":"api-thinking-before-framework-thinking","title":"API Thinking Before Framework Thinking","summary":"If you define operations, data and failure cases before choosing a framework, you can swap the frontend almost at will later – the other way around, you get an API that mimics a framework.","tags":["Software","GraphQL","API"],"published_at":"2016-12-12T10:00:00+00:00","updated_at":"2026-07-14T16:37:07.719359+00:00","url":"https://www.mikebild.dev/en/blog/api-thinking-before-framework-thinking/","audio_url":null,"audio_duration_secs":null,"text":"# API Thinking Before Framework Thinking\n\n“Angular or React?” is considered the architecture question for new web projects this year. It isn’t one. It’s a tool question – and it is regularly asked before anyone has answered the question that actually is architecture: what are our operations and our data? This order is backwards, and right now it’s especially tempting. 2016 is the year of framework debates: Angular 2 has been final since September, Vue 2 came out at the end of September, React is at version 15, and the comparison articles fill conference programs, blogs and team meetings.\n\nThe dispute is entertaining, but it hides something simple: the framework only renders what an API provides. If you design the API first – resources or schema, names from the domain language, failure cases, permissions – you can choose the frontend almost freely afterwards and even switch it later. If you choose the framework first, you’ll very likely get an API that mimics exactly this framework’s data flow. And this API stays when the framework has long been replaced.\n\n## What an API defines – and what a framework defines\n\nA frontend framework decides how components are rendered, how state is managed in the client and how the team building the UI organizes itself. That’s not nothing, but it’s replaceable. There are plenty of migration stories from Backbone to Angular or from Angular 1 to React – this year, with the hard break between Angular 1 and Angular 2, more than ever. A framework switch is expensive, but it’s a local event: it affects the client and no one else.\n\nAn API defines something else, and for everyone involved at the same time:\n\n- which operations exist and what they’re called,\n- which data belongs together and which deliberately stays separate,\n- which failure cases are expected in domain terms and what they look like,\n- who may trigger which operation.\n\nThese four points survive every framework fashion. They form the contract between the business side, the backend and all clients – today’s web frontend, next year’s mobile app, the partner system of the day after tomorrow. A contract that changes forces changes on all contract partners. That’s exactly why it belongs at the beginning, not at the end.\n\nThe fourth point deserves a second look, because it’s the one most reliably run over by the framework-first approach. From the UI’s point of view, permissions look like a display matter: the button is hidden, the menu shortened, done. From the API’s point of view, they are an assurance – the statement that a particular caller simply cannot trigger an operation, no matter which client comes knocking. This assurance can only be given in the contract, not in the component. If you leave it out of the design, you add it later under time pressure, usually after the first call has shown up that no button ever triggered.\n\n## The wrong order in everyday project work\n\nI experienced what the backwards order feels like this spring in a project: order management for a retail customer, web UI first, mobile “sometime later.” The first three weeks went into framework evaluation – Angular 2 was still a release candidate, React with Redux the alternative, plus the usual side battles over TypeScript and JSX. The API was on no agenda. “We’ll do that once the frontend is in place,” people said, and they meant it honestly.\n\nOnce the frontend was in place, there was an API too. It had an endpoint `/api/app-state` that filled the complete Redux store on load. It had field names that came from the reducers, not from the domain language. Errors came as HTTP 500 with a text, because the client only showed a red message anyway. Permissions were checked in the frontend because that was more convenient there at the time. None of this was ill will – every single decision was reasonable from the frontend’s point of view. Taken together, the API was an imprint of the Redux data flow.\n\nHalf a year later, the mobile team arrived. It couldn’t do anything with `/api/app-state`, needed smaller slices, different error handling, real authorization on the server. The backend got a second API next to the first, and from then on both were maintained. The framework question, by the way, had been decided in favor of React back then – it would have made no difference to the result if it had been Angular. The expensive decision wasn’t the framework. It was the order.\n\n## Resources first: an example\n\nWhat does the other order look like? It starts with a conversation in which no framework comes up. With the business side at the table, you collect the terms that come up there every day anyway: order, customer, credit limit, cancellation. From these terms, a first resource design emerges – noted here as REST routes:\n\n```http\nGET    /customers/{id}\nGET    /customers/{id}/orders\nPOST   /orders\nGET    /orders/{id}\nPOST   /orders/{id}/cancellation\n```\n\nTwo things about this design are more important than they look. First: `POST /orders/{id}/cancellation` instead of `DELETE /orders/{id}`. In retail, a cancellation is not a deletion but a domain process with its own rules – it can be rejected, it can trigger fees, it shows up in the history. The endpoint carries the name from the domain language, not the one from the HTTP textbook. Second: the failure case is part of the contract. When an order exceeds the credit limit, that’s not a server error but an expected domain response:\n\n```json\n{\n  \"order\": null,\n  \"failure\": {\n    \"code\": \"CREDIT_LIMIT_EXCEEDED\",\n    \"message\": \"Customer credit limit exceeded\",\n    \"creditLimit\": 5000,\n    \"openAmount\": 5240\n  }\n}\n```\n\nYou can print this JSON and discuss it with the business side. “Is the error code right? Is a field missing? Is the field sales team even allowed to see this?” – such questions can be settled on a contract document long before a single line of frontend exists. They can’t be settled on a Redux reducer or an Angular service, because the business side never gets to see it.\n\n## The same thing thought of as a schema\n\nFor a year and a half, there has been a second vocabulary for this contract work: GraphQL, published by Facebook in the summer of 2015 as a specification along with a reference implementation. With Relay, there was a client from the start; since the middle of this year, the Meteor team has been working with Apollo on a second, deliberately framework-neutral client family. What interests me about GraphQL for the design step is less the query mechanism than the schema shorthand notation. It forces you to write down exactly the things that API design is about:\n\n```graphql\ntype Order {\n  id: ID!\n  customer: Customer!\n  items: [OrderItem!]!\n  status: OrderStatus!\n}\n\nenum OrderStatus {\n  PLACED\n  APPROVED\n  REJECTED\n  CANCELLED\n}\n\ntype OrderFailure {\n  code: String!\n  message: String!\n}\n\ntype PlaceOrderResult {\n  order: Order\n  failure: OrderFailure\n}\n\ntype Mutation {\n  placeOrder(input: PlaceOrderInput!): PlaceOrderResult\n  cancelOrder(id: ID!): CancelOrderResult\n}\n```\n\n`placeOrder` and `cancelOrder` are named after the processes the business side talks about. `PlaceOrderResult` makes visible that an order can fail in domain terms without anything being technically broken – the same distinction as in the JSON example above, only this time anchored in the type system. Whether REST resources or a GraphQL schema form the contract in the end is secondary for the order. Both are notations for the same thinking: operations, data, failure cases, permissions – before the framework.\n\n```mermaid\nflowchart TD\n  subgraph FF[\"Framework first\"]\n    F1[Framework choice] --> F2[Data flow of the<br/>framework] --> F3[API mimics the<br/>data flow] --> F4[Every new client<br/>needs a new API]\n  end\n  subgraph AF[\"API first\"]\n    A1[Domain language:<br/>operations and data] --> A2[API contract:<br/>resources or schema] --> A3[Frontend freely chosen:<br/>Angular, React, Vue]\n  end\n```\n\n## How to recognize a framework-shaped API\n\nThe backwards order leaves traces that reliably turn up in code reviews. A few signals I now watch for:\n\n- Endpoints that correspond exactly to one screen (`/api/dashboard`, `/api/app-state`)\n- Field names from the client store instead of from the domain language\n- Errors exclusively as HTTP 500 with free text, because the client only shows a message anyway\n- Permission checks that exist only in the frontend\n- Data formats that assume the internal structure of a particular client library\n\nEach of these signals is harmless on its own and even efficient at the moment it comes about. Together they mean: this API has exactly one legitimate consumer, and that happens to be the framework that’s in the project right now. The second consumer – mobile app, partner integration, batch import – then pays the full price.\n\n## Backend for Frontend as an honest compromise\n\nNow, it would be dishonest to pretend that all clients have the same needs. A web frontend often wants broad, nested responses; a mobile app on a cellular connection wants small, pre-condensed slices. If you force the same generic format on both, you make both slow. For this tension, a pattern with its own name has become established since last year: Backend for Frontend, BFF for short. Sam Newman described it, SoundCloud demonstrated it in its own architecture – one thin layer per client type, dedicated to the respective frontend, with the one domain API behind it.\n\n```mermaid\nflowchart LR\n  Web[Web client<br/>React or Angular] --> BW[BFF Web]\n  Mob[Mobile client<br/>iOS and Android] --> BM[BFF Mobile]\n  BW --> API[Domain API:<br/>Orders, Customers]\n  BM --> API\n```\n\nThe point that makes the pattern honest for me: the coupling to the client isn’t denied but named and fenced in. The BFF may be client-specific, may tailor responses, may even flatter a framework’s data flow – it’s the only place in the system where that’s allowed. The domain API behind it stays clean and framework-free. If you confuse the two levels, you end up back at the `/api/app-state` endpoint, only this time with a clear conscience.\n\nIt also matters who owns such a layer. At SoundCloud, each client team maintains its own BFF – the web team its own, the mobile team its own. That fits the logic of the pattern: whoever needs the tailoring is also responsible for it, and the domain API behind it doesn’t have to negotiate every client whim. If the backend team takes over all the BFFs instead, the compromise quickly turns into a bottleneck again, and the pressure grows to push the tailoring into the domain API after all.\n\n## Contract work is work with the business side\n\nWhether resources or schema: the design is only as good as the conversation it comes from. For REST APIs, Swagger has become established as the description format – officially, since the founding of the OpenAPI Initiative at the end of last year, the specification is called OpenAPI, but in everyday use everyone still says Swagger. The real value isn’t in the tooling but in the fact that there is a document that can sit next to the domain concepts in a review. A GraphQL schema does the same, in a more compact form.\n\nI experimented in this direction myself this year: graphql-pouch, a small open-source project that generates a working API on top of PouchDB from a GraphQL schema notation, including CouchDB synchronization. The approach there is deliberately “frontend first” – get to a typed data model quickly without backend migrations. Interestingly, exactly this experiment confirms the thesis: even when the runtime accommodates the frontend, the first artifact is the schema notation. You write down types and operations before anything renders. The schema is the contract; everything else is output.\n\nThe contract work itself stays uncomfortable, and that’s a good thing. When the business side frowns at the name `cancelOrder` because no one in the company talks about “cancellation” but everyone talks about “reversal,” that’s exactly the discussion you want to have in December – not in June, when three clients have already hard-wired the name.\n\n## The bottom line\n\nThe framework question can be fun, and this year’s answers – Angular 2, React 15, Vue 2 – are all defensible. But it’s the second question. The first is: which operations are there, what are they called in the domain language, which failure cases are expected, who may do what? If you answer this question in a contract document – as a resource design or as a schema – you make the choice of framework almost risk-free and a later switch affordable. If you skip it, you still choose the framework – only then it secretly co-designs the API, and that part of the decision can’t be corrected later with an npm install.\n\n## Further reading\n\n- [graphql-pouch on GitHub](https://github.com/MikeBild/graphql-pouch)\n- [GraphQL – introduction and schema documentation](https://graphql.org/learn/)\n- [Sam Newman: Pattern – Backends For Frontends](https://samnewman.io/patterns/architectural/bff/)\n- [Phil Calçado: The Back-end for Front-end Pattern (BFF) at SoundCloud](https://philcalcado.com/2015/09/18/the_back_end_for_front_end_pattern_bff.html)\n- [OpenAPI Initiative](https://www.openapis.org/)"},{"locale":"en","translation_key":"tyrian-rx-react-ui-datenfluss","slug":"tyrian-rx-react-ui-as-data-flow","title":"Tyrian Rx React: UI as Data Flow","summary":"A rebuild of the Elm Architecture with RxJS and React – actions as a stream, scan() folds the model, side effects stay at the edge – and what this proof of concept reveals about UI architecture that ages well.","tags":["Software","Reactive"],"published_at":"2016-10-12T10:00:00+00:00","updated_at":"2026-07-14T16:35:20.035699+00:00","url":"https://www.mikebild.dev/en/blog/tyrian-rx-react-ui-as-data-flow/","audio_url":null,"audio_duration_secs":null,"text":"# Tyrian Rx React: UI as Data Flow\n\nWhen every component in a UI mutates its own state, the first thing the system loses is its timeline. A click here, a callback there, a `setState` somewhere in between – and three weeks later, nobody can say **when** the state flipped that triggered the bug. The debugger shows the result, but not the history. You see: `count` is 7, although it should be 3. You don’t see which sequence of events turned the 3 into a 7, in which order two responses from the server arrived, whether the user clicked faster than the network responded.\n\nThe Elm Architecture is built precisely against this loss of history. And because you only understand an architecture once you have rebuilt it yourself, that is what I did over the last few weeks: the Elm Architecture with RxJS and React – as a proof of concept, not as a framework. The repository is at [github.com/MikeBild/reactish-elmish](https://github.com/MikeBild/reactish-elmish), and the README already warns in its second line: *Don't use in production!* That warning is meant seriously, and I will come back to it at the end. The value of the experiment lies elsewhere.\n\n## The Elm Architecture, reduced to the skeleton\n\nElm – since version 0.17 from May of this year without signals, but with subscriptions instead – forces every application into the same shape:\n\n- a model that holds the entire state of the application as one value\n- an `update` function that computes a new model from the old model and a message\n- a `view` function that produces the rendering from the model\n- subscriptions for everything that comes in from outside: timers, WebSockets, browser events\n\nNone of this is optional, and none of it has a side exit. The compiler simply doesn’t allow anything else. State doesn’t come into being anywhere on the side; it arises exclusively from `update` processing a message. So the history of the state is identical to the list of messages – and the question “when did this happen?” has an answer again: at message number 34, between 33 and 35.\n\nWhat is remarkable about this shape is how little it has to do with the Elm language. Model, update, view – that is a fold over a sequence of events plus a projection. Both are concepts that exist in every language. The question that wouldn’t let go of me: How much of the clarity remains if you drop the compiler and voluntarily rebuild the shape in JavaScript?\n\n## The rebuild: actions as a stream\n\nThe core of the rebuild fits into a few lines. Every user interaction becomes a value on a stream, and a single `update` function folds this stream into the model. In the repository, this sits behind a small API of `init`, `update`, `view` and `subscriptions` – here is the raw form without the wrapping:\n\n```javascript\nimport Rx from 'rx'\n\n// every user interaction becomes a value on this stream\nconst actions$ = new Rx.Subject()\n\nfunction update (model, action) {\n  switch (action.type) {\n    case 'INCREMENT':\n      return { count: model.count + 1 }\n    case 'DECREMENT':\n      return { count: model.count - 1 }\n    case 'TICK':\n      return { count: model.count + action.step }\n    default:\n      return model\n  }\n}\n\n// fold the action history into the current model\nconst model$ = actions$\n  .startWith({ type: 'INIT' })\n  .scan(update, { count: 0 })\n```\n\nA side note on the choice of library: the prototype uses the classic `rx` package, that is, version 4 with `onNext` and `dispose`. RxJS 5 is available as a release candidate and will align the names with the ES Observable proposals (`next`, `unsubscribe`), but for an experiment I wanted the stable version, whose operator documentation is complete. That changes nothing about the concept – method chains on observables work the same in both worlds.\n\nThe decisive operator is `scan`. If you know `reduce` over arrays, you almost know `scan`: it is the same fold, except that it doesn’t wait for a finished array but emits the intermediate result for every new element. `reduce` folds a closed list into a final value. `scan` folds a list that never ends – and that is exactly what a user interface is: a sequence of events without an end point. The model at a point in time is nothing but the fold of all actions up to that point in time. This one insight is half the article: **state is the left fold over the event history.**\n\n## React only renders\n\nIn this setup, React gets a deliberately boring role: it projects the current model into the DOM and reports interactions back to the action stream. No fetch in `componentDidMount`, no state logic in handlers – the component follows the `model$` stream and nothing else:\n\n```javascript\nimport React from 'react'\n\nclass CounterView extends React.Component {\n  componentDidMount () {\n    // the view follows the model stream, nothing else\n    this.subscription = model$.subscribe(model => this.setState({ model }))\n  }\n\n  componentWillUnmount () {\n    this.subscription.dispose()\n  }\n\n  render () {\n    if (!this.state) return null\n    const { count } = this.state.model\n    return (\n      <div>\n        <span>{count}</span>\n        <button onClick={() => actions$.onNext({ type: 'INCREMENT' })}>+</button>\n        <button onClick={() => actions$.onNext({ type: 'DECREMENT' })}>-</button>\n      </div>\n    )\n  }\n}\n```\n\nThat `setState` still shows up here is not a break in style, but the handover point: somewhere the stream has to flow into React’s render cycle, and in React 15, `setState` simply is the door. What matters is that it is the **only** place where `setState` occurs – as a bridge, not as state management. In the repository, this bridge comes in two variants: once as a higher-order component `withElmish` for composition with stateless functional components, once as a base class `ReactComponent` that you inherit from, overriding `init`, `update` and `view`.\n\nAt this point, by the way, the rebuild deliberately departs from Elm and from Redux: it keeps state per component instead of in a central store. Every “smart” component gets its own small Elm loop, “dumb” components remain stateless functions. Whether that is a good idea depends on how things are cut – for the collection of examples in the repository (counter, form validation, optimistic UI updates, an ordering process as a long-running saga stream), it was pleasant, because each example lives on its own. For a large application, I would ask the question again.\n\n## Side effects as streams at the edge\n\nThe most interesting part is the one counter examples like to leave out: What happens to everything that doesn’t come from a click? Timers, HTTP responses, server push. In Elm, those are subscriptions and tasks. In the rebuild, they are – of course – observables. The `subscriptions` function receives a command from `init` or `update` and responds with a stream whose values end up as messages in `update` again:\n\n```javascript\nconst stop$ = actions$.filter(action => action.type === 'INTERVAL_STOP')\n\nfunction subscriptions (cmd) {\n  switch (cmd) {\n    case 'INTERVAL_START':\n      return Rx.Observable\n        .interval(1000)\n        .map(() => ({ type: 'TICK', step: 1 }))\n        .takeUntil(stop$)\n  }\n}\n```\n\nThe runtime layer subscribes to this stream itself; the component never calls `subscribe`. This keeps side effects where they belong: at the edge, as separate streams that you compose with the same operators as everything else. `takeUntil` ends the timer declaratively, `merge` combines several sources, `filter` splits a stream into substreams. The lifecycle of a side effect is no longer special logic, but a data flow expression.\n\nThis also reveals a real difference from Elm, not a rebuilt one: Elm subscriptions only know *next* – the next message comes, nothing else. Errors and completion pass through `update` as ordinary message content, and for chained asynchronous effects there are tasks with `andThen`. An Rx observable, on the other hand, carries three signals in its contract: *next*, *error*, *complete*. A stream can fail, and a stream can be done – both are part of the type, not convention. For things like AJAX long polling against a CouchDB change feed or EventSource push (both included as examples in the repository), this is the more natural description.\n\nThe entire cycle, as a picture:\n\n```mermaid\nflowchart LR\n  U[User event] --> A[\"actions$ (stream)\"]\n  SUB[\"subscriptions:<br/>interval, HTTP, push\"] --> A\n  A --> S[\"scan(update, initialModel)\"]\n  S --> M[\"model$ (stream)\"]\n  M --> V[\"React view<br/>renders the model\"]\n  V --> U\n```\n\nOne direction, one cycle. Everything that happens happens as a value on a stream – and is therefore observable, filterable, loggable. An `actions$.subscribe(console.log)` in the right place replaces a lot of debugger sessions.\n\n## Redux, Elm, RxJS – the same idea three times\n\nIf you have read this far and know Redux, you saw the punchline long ago: `update` is a reducer. `(model, action) => model` and `(state, action) => state` are the same signature with different names. That is no coincidence – Dan Abramov has never hidden the fact that Redux distills the Elm Architecture for JavaScript. The difference lies in what each variant of the idea enforces and what it merely recommends.\n\nRedux does the fold with less math and more convention: a store instead of a model stream, `dispatch` instead of `onNext`, middleware instead of operator chains. That reducers stay pure and side effects stay outside is written in the documentation – nobody can enforce it. In return, you get an ecosystem: DevTools with time travel, bindings, conventions that a team can adopt without discussion. Interestingly, redux-observable is growing into a middleware right now that brings Rx streams back into Redux as a side effect layer – actions in, actions out, observable operators in between. So the two worlds are converging anyway.\n\nElm enforces the shape in the compiler. There is no way to sneak state past `update`, no forgotten mutation, no unhandled message variant – the type check finds them. That is the hardest variant, but also the most unforgiving one: you only get the guarantees together with the language.\n\nAnd RxJS? RxJS makes explicit something that stays implicit in both of the others: **time**. An observable is a sequence of values on a timeline, and the operators talk about it openly – `debounce` negotiates intervals, `takeUntil` an end, `scan` history. In Redux, time is a side effect of the dispatch order; in Elm, the runtime hides it. In the Rx rebuild, it is in the code. Once you have seen that “state” is just the current result of a fold over the timeline, you read Redux code differently afterward too. CycleJS, by the way, takes the same thought even further: there, the entire application is a function from streams to streams, replacing React including rendering. And if you want to see the opposite school, you will find it in MobX, which doesn’t ban mutation but makes it observable – a different contract, a different discussion.\n\n## What building it yourself teaches – and what it doesn’t\n\nAfter a few weeks with the prototype and its sixteen examples, my verdict is split in two. I learned more than from any blog article about Redux, and specifically things that apply regardless of the library:\n\n- Understanding state as a fold makes failure patterns explainable: not “the state is wrong”, but “this sequence of actions produces this model” – a verifiable statement.\n- A single direction in the data flow is not aesthetics, but the reason you can still read the system once it has grown.\n- Side effects are manageable when they have an explicit lifecycle – whether that is called a task, a subscription or an observable.\n- `update` as a pure function is trivially testable; the test for the delayed counter in the repository needs neither a DOM nor a browser.\n\nWhat building it yourself is **not**: a production replacement. The warning in the README is there out of conviction. Everything that makes an architecture hold up in everyday work is missing – well-thought-out error handling across component boundaries, tools, documentation beyond a README, and above all: other people who know the code. A framework that one person built over a few evenings is a learning machine, not a foundation. If you want the Elm Architecture in JavaScript in production, take Redux and get conventions and a community along with it; if you want the guarantees, take Elm and pay with the language switch. The rebuild in between has exactly one purpose: understanding why both work.\n\nAdd to that an observation from the building itself: the temptation to turn the proof of concept into a real framework “just quickly” is enormous. Every example suggests another abstraction, every abstraction another configuration point. I deliberately pushed back – minimally invasive, React rendering plus Rx composition, not one layer more than necessary. That is a lesson too: the distance between “instructive prototype” and “bad framework” is about two weekends.\n\n## The bottom line\n\nWhy does this shape age so well? Because it makes almost no assumptions about its environment. Model, update, view – that requires neither a language nor a library nor a rendering technique. React 15 can be replaced by something else tomorrow, `rx` version 4 by version 5, and the architecture stays the same, because it consists of two ingredients that are older than the web: a fold and a projection. In this field, frameworks come and go fast enough that I don’t mean this as a platitude, but as a selection criterion.\n\nAnd the question from the beginning – when did this happen? – always has an answer in this shape. The event history is not a by-product you reconstruct with logging, but the primary data structure of the application. Everything else, the model included, is derived from it. When, in future reviews, I sit in front of a UI whose state nobody can explain anymore, this will be my first suggestion: not more tools, but one direction.\n\n## Further reading\n\n- The repository discussed: [github.com/MikeBild/reactish-elmish](https://github.com/MikeBild/reactish-elmish)\n- The Elm Architecture in the official guide: [guide.elm-lang.org/architecture](https://guide.elm-lang.org/architecture/)\n- The `scan` operator as an interactive marble diagram: [rxmarbles.com/#scan](https://rxmarbles.com/#scan)\n- Redux documentation: [redux.js.org](https://redux.js.org/)\n- redux-observable, Rx streams as Redux middleware: [redux-observable.js.org](https://redux-observable.js.org/)"},{"locale":"en","translation_key":"graphql-pouch-lokale-daten","slug":"graphql-pouch-local-data-with-a-schema","title":"GraphQL-Pouch: Local Data with a Schema","summary":"An open-source experiment from the summer of 2016: a GraphQL runtime that generates a complete CRUD API on top of PouchDB from a schema shorthand – including synchronization via the CouchDB replication protocol.","tags":["Software","GraphQL","API"],"published_at":"2016-07-26T10:00:00+00:00","updated_at":"2026-07-14T16:33:18.446465+00:00","url":"https://www.mikebild.dev/en/blog/graphql-pouch-local-data-with-a-schema/","audio_url":null,"audio_duration_secs":null,"text":"# GraphQL-Pouch: Local Data with a Schema\n\n```graphql\ntype Post implements Node {\n  id: ID!\n  rev: String\n  title: String\n  body: String\n  published: Boolean\n}\n```\n\nFive fields, one interface, not a single line of resolver code. This file is the complete backend of a small blog system – data storage, HTTP endpoint and searchable API documentation included. You pass it to `graphql-pouch`, and a few seconds later a running GraphQL API with generated queries and mutations answers at `http://127.0.0.1:3000/graphql/blog`: `post`, `allPosts`, `upsertPost`, `deletePost`. Data isn’t stored on a remote database server but locally in PouchDB – and if you want, the process synchronizes its documents with other nodes via the CouchDB replication protocol.\n\nThat’s the short version of GraphQL-Pouch, an open-source project I published on GitHub and npm this month. It is explicitly an experiment. I didn’t want to know GraphQL only from blog posts but from the inside – and for years, my best way to get to know a technology from the inside has been the same: build something small and real with it and use it until the uncomfortable spots become visible.\n\n## One year of GraphQL, many open questions\n\nFor context: the GraphQL specification has been public for just one year. Facebook released it in July 2015 together with `graphql-js` as the reference implementation; internally, the technology has been running there since 2012. The tooling around it is still modest: Relay as a client framework, GraphiQL as an interactive UI for exploring an API, `express-graphql` as the HTTP binding for Node.js. If you build a GraphQL server today, you write type definitions and resolvers by hand against `graphql-js` – one function per field that says where the data comes from.\n\nBy the third resolver I wrote myself, I noticed how mechanical this work is for simple cases. A `Post` type with five fields, a document database behind it: read by key, list all documents, write, delete. It’s always the same pattern, and patterns that are always the same can be generated by a machine. The really interesting work lies in the schema – in the question of which types, fields and relationships the application needs. That became the thesis of the experiment: if the schema is the only source, how far does a runtime get that generates the rest?\n\nThe second thread came from a different direction. In several frontend projects, I’ve seen backend development become the bottleneck: the team waits for endpoints, for database migrations, for deployments – and in the meantime builds mock-ups that later have to be painstakingly removed. A backend that emerges from a schema file and runs locally without infrastructure reverses this order. The frontend team defines the data contract itself, works against a real API immediately and negotiates later what a “real” backend has to take over.\n\n## From shorthand to a running API\n\nGraphQL-Pouch reads the schema shorthand – the same terse notation the GraphQL documentation uses for its examples – and builds a complete, executable schema from it at runtime with `graphql-js`. For every type, this produces generated root fields including resolvers against PouchDB. The parser for this goes back to Matthew Mueller’s project `graph.ql`, whose groundwork saved me a lot of time.\n\nThe Relay conventions are active by default: a `Node` interface with global IDs, connections with `edges` and `node` for lists, `clientMutationId` in the mutation payloads. That was a deliberate decision, because Relay is currently the most demanding GraphQL client, and if you meet its conventions, you meet the simpler cases along the way. If you don’t want them, you turn them off with `--no-relay` and get plain lists.\n\nA query against the generated blog schema looks like this:\n\n```graphql\nquery BlogFrontpage {\n  allPosts {\n    edges {\n      node {\n        id\n        rev\n        title\n        published\n      }\n    }\n  }\n}\n\nmutation PublishPost {\n  upsertPost(input: {\n    id: \"hello-graphql\",\n    title: \"GraphQL over local data\",\n    published: true,\n    clientMutationId: \"1\"\n  }) {\n    post {\n      id\n      rev\n    }\n  }\n}\n```\n\nIn development mode (`graphql-pouch --development`), the server automatically serves GraphiQL at the endpoint. That sounds like a sideshow, but in day-to-day work it was the single biggest gain: the API can be explored interactively from the first minute, with autocompletion and built-in documentation from the schema comments. No Postman, no fiddling with cURL – type in a query, see the result.\n\nBeyond that, the runtime brings a few things that turned the experiment, almost unnoticed, into a usable tool:\n\n- several schemas in parallel under their own URL paths (`/graphql/blog`, `/graphql/cms`)\n- JWT authentication via a startup parameter, including a CLI command for signing tokens\n- serving static files, so a React application can live right next to it\n- migrating schema files, custom functions and static content via the command line\n\n## Why PouchDB sits underneath\n\nThe choice of database was the real architecture decision of the project. PouchDB is a JavaScript implementation of the CouchDB ideas: document-oriented, revision-based, and – this is the crucial point – with the CouchDB replication protocol as a built-in synchronization mechanism. In the Node.js process, PouchDB stores data directly in the file system via LevelDB. There is no database server, no connection string, no migrations. `npm install -g graphql-pouch`, start, done – the state lives as files next to the process.\n\nFor a tool meant to decouple frontend development from the backend, this self-sufficiency is not a convenience feature but the core. Every infrastructure dependency a developer first has to install is a hurdle before the first query.\n\nIt gets interesting as soon as more than one node is involved. With `graphql-pouch --remote http://user:pass@couch.example.com`, the local PouchDB replicates against a remote CouchDB – in both directions. Several instances behind a load balancer share the same data this way, without any of them being the “master.” The price is known and well documented in the CouchDB world: there is no single source of truth, only eventual consistency. Every node is available at all times, but not every node sees the same state at all times.\n\n```mermaid\nflowchart LR\n  SDL[Schema file<br/>shorthand] --> RT[graphql-pouch<br/>runtime]\n  RT --> GEN[Generated fields<br/>allPosts, upsertPost, deletePost]\n  UI[GraphiQL /<br/>Relay client] --> GEN\n  GEN --> P[(PouchDB<br/>LevelDB in the file system)]\n  P <-->|CouchDB<br/>replication protocol| C[(CouchDB<br/>remote node)]\n```\n\nThat I treat this property not as a flaw but as a feature has to do with the target audience: frontends. A UI that waits for confirmation from a remote server feels sluggish. With its optimistic updates, Relay already comes with a model that shows changes immediately and reconciles them with the server response later. Eventual consistency at the data level and optimistic updates at the client level are two expressions of the same idea – the architecture of GraphQL-Pouch takes this idea seriously instead of hiding it.\n\n## The revision is in the schema – on purpose\n\nIf you read the `Post` example above carefully, you’ll stumble over the `rev` field. That’s the document revision from the CouchDB world, and you can ask with good reason whether such a storage detail should be visible in an API. I decided it should, after a concrete failed attempt: in an early version, I handled the revision internally and simply passed writes through. That works exactly as long as nobody writes at the same time. As soon as two clients change the same document – or a replicated node plays back an older version – the last one silently overwrites the first. The lost state only gets noticed when a user misses it, and by then it can no longer be reconstructed.\n\nWith a visible revision, this flips around. An `upsertPost` with an outdated revision fails in a controlled way, because PouchDB detects the conflict:\n\n```mermaid\nsequenceDiagram\n  participant A as Client A\n  participant B as Client B\n  participant API as graphql-pouch\n  participant DB as PouchDB\n  A->>API: upsertPost(id, rev: \"1-abc\", ...)\n  API->>DB: put(document)\n  DB-->>API: ok, rev: \"2-def\"\n  B->>API: upsertPost(id, rev: \"1-abc\", ...)\n  API->>DB: put(document)\n  DB-->>API: 409 conflict\n  API-->>B: error instead of silent overwrite\n```\n\nThe client then has to read again and decide what happens to the competing changes. That’s less convenient than a schema without `rev`, but the inconvenience is honest: it shows a problem at the place where it arises instead of pushing it into the future. With local, replicated data, the write conflict is not an edge case you can abstract away – it’s the normal case that just rarely happens.\n\n## When generated CRUD is no longer enough\n\nGenerated endpoints get you surprisingly far, but not arbitrarily far. At some point, an application needs a query with domain logic, validation before writing or data from an external source. For these cases, GraphQL-Pouch has an escape hatch: custom functions in JavaScript that register under the name of a schema field and replace the generated resolver. Combined with use as an npm module, this can be embedded directly into an existing Express application – the companion repository `graphql-pouch-as-library` shows exactly this setup:\n\n```javascript\nconst express = require('express');\nconst expressGraphQL = require('express-graphql');\nconst graphqlPouch = require('graphql-pouch');\n\nconst schemaDefinition = `\ntype Post implements Node {\n  id: ID!\n  rev: String\n  title: String\n  body: String\n  published: Boolean\n}\n\ntype Query {\n  postsByAuthor(author: String!): [Post]\n}\n`;\n\n// custom resolver replaces the generated CRUD implementation\nconst customFunctions = {\n  postsByAuthor: (ctx, input) => {\n    legacyBlogService\n      .fetchPostsByAuthor(input.author)\n      .then(posts => ctx.success(posts));\n  },\n};\n\nconst mySchema = graphqlPouch.schema('blog', schemaDefinition, true, customFunctions);\n\nconst app = express();\napp.use('/graphql', expressGraphQL({\n  schema: mySchema.schema,\n  graphiql: true,\n}));\napp.listen(3000);\n```\n\nThis pattern turned out to be the most important finding of the experiment. Generation covers the mechanical part, and the custom functions take over the domain part – without having to change the foundation. GraphQL shows its strength as a facade here: behind the same schema, a generated PouchDB access, a call to an existing REST service and a hand-written calculation can exist side by side, and no client notices the difference.\n\n## What the experiment can’t do\n\nBeing honest about an experiment includes the list of loose ends, and for GraphQL-Pouch it isn’t short:\n\n- Events are missing. PouchDB provides a changes feed that could drive notifications to clients – that’s on the roadmap but not built.\n- A batching and caching mechanism for resolvers is missing too; nested queries cause more database accesses than necessary.\n- The JWT support authenticates but doesn’t authorize – there are no roles or field permissions.\n- Generated CRUD stays generic: `upsertPost` says nothing about whether a post is being published, withdrawn or edited. A good domain API needs named operations, and those still have to be designed by a person.\n\nThe last point is the most important. Generation takes the typing work off your hands, not the design work. A schema that consists only of types with CRUD is a database with a prettier protocol – useful for prototypes, demos and the early frontend phase, but no substitute for a well-thought-out interface.\n\n## What I take away from this\n\nAfter a few weeks with my own tool, three observations remain. First: the approach of writing the schema first and deriving everything else from it changes conversations. You can negotiate concretely with frontend colleagues over a schema file with comments long before any server exists – the schema becomes the contract, not documentation after the fact. Second: local data with synchronization shifts complexity; it doesn’t eliminate it. What you save in infrastructure comes back as thinking about revisions and conflicts in the data model, and it’s better if the API makes that explicit. Third: a weekend experiment that you seriously build to the end – with a CLI, tests, documentation and publication on npm – teaches you more about a technology than any introduction, because it forces you to touch the edges too: error messages, authentication, operation with several nodes.\n\nIn the summer of 2016, I can’t judge whether GraphQL will catch on. But the idea of putting a typed data contract between client and server and aligning both sides with it seems more viable to me than much of what I’ve negotiated with REST conventions in ten years of API development. For that reason alone, the experiment was worth it.\n\n## Further reading\n\n- GraphQL-Pouch on GitHub: https://github.com/MikeBild/graphql-pouch\n- Example of embedding it as a library: https://github.com/MikeBild/graphql-pouch-as-library\n- Official GraphQL introduction: https://graphql.org/learn/\n- PouchDB replication guide: https://pouchdb.com/guides/replication.html\n- CouchDB replication overview: https://docs.couchdb.org/en/stable/replication/intro.html"},{"locale":"en","translation_key":"definition-of-done-als-qualitaets-gate","slug":"definition-of-done-as-a-quality-gate","title":"Definition of Done as a Quality Gate, Not Bureaucracy","summary":"The automatable core of a Definition of Done belongs in a green gate of lint, build and test. Business acceptance and other judgments remain shared quality work.","tags":["Software","Delivery"],"published_at":"2016-06-24T10:00:00+00:00","updated_at":"2026-07-13T08:35:40.529374+00:00","url":"https://www.mikebild.dev/en/blog/definition-of-done-as-a-quality-gate/","audio_url":null,"audio_duration_secs":null,"text":"```console\n$ make verify\nlint    ✓  0 warnings\nbuild   ✓\ntest    ✗  2 failing, coverage 61 % (threshold 80 %)\n\nDefinition of Done: rot\n```\n\nThis red is not up for negotiation. Nobody can tick it off, nobody has to interpret it in the review, and everyone on the team reproduces it in seconds on their own machine. The printed twelve-point list next to the board can’t do that. If it says “all tests green” and someone puts a check mark next to it, that doesn’t mean the tests are green – only that someone believes or claims it.\n\nEverything else hinges on this difference. Whatever in a Definition of Done can be expressed as a command belongs in a gate that blocks the merge as long as it is red. Whatever needs human judgment stays honestly named as such, small and visible – and isn’t treated as if it were code.\n\nAt first, this sounds like a purely technical shift. In fact, it reaches all the way to the business result: shorter cycles, less friction in the team, higher and above all more reliable quality. If you tie quality to an automated gate, you no longer argue in the review about whether something is done. The pipeline says so.\n\n## Why the ritual fails\n\nThe classic Definition of Done as a checklist has a structural problem: it checks at the latest possible moment and with the least reliable checking instrument we have – a tired human at the end of the sprint. If one item says “all tests green”, ticking it off doesn’t mean the tests are green. It means that someone believes they are, or at least claims so.\n\nThis is exactly where the ticket battle begins. Because the checklist isn’t binding, the dispute moves into the social realm. Is this “done” or “done done”? Does the refactoring count, too? Has the product owner already accepted it? Each of these questions costs time, creates friction and – worst of all – conveys a certainty that doesn’t exist. A ticked item feels like a guarantee but is only a declaration of intent.\n\nMartin Fowler described the technical counter-design long before. Self-testing code and Continuous Integration form a foundation in which every commit triggers an automatic build and test run. A red build is a stop – “stop the line”. That isn’t a suggestion you can discuss. It is a state. That is exactly the property I want for the Definition of Done: it should be a state, not a consensus.\n\n## The Definition of Done as the commit stage\n\nThe decisive conceptual step came for me through the deployment pipeline of Jez Humble and David Farley. Their model turns quality into an automated run. The first stage, the commit stage, compiles the code, runs unit tests and runs linters and static analysis. Only when this stage is green do later stages start at all. Everything else is blocked.\n\nIf I take that seriously, a Definition of Done can be mapped almost one to one onto this commit stage. What was on the checklist becomes steps in the pipeline:\n\n```yaml\ncommit_stage:\n  fail_fast: true            # any red step blocks the merge\n  steps:\n    - name: compile\n    - name: lint             # static analysis, style rules\n    - name: unit_test\n    - name: coverage_check    # fail below an agreed threshold\n    - name: contract_test     # verify integration boundaries\ngate:\n  rule: merge_blocked_unless(commit_stage == \"green\")\n```\n\nThe interesting thing about this representation is what it enforces. An item that I can’t express as a step doesn’t belong in the automated part of the Definition of Done. I can execute “code compiles”. I can execute “no lint errors”. I can execute “coverage above threshold”. I can’t execute “the code is elegant” – that is a human judgment and stays in the review, where it belongs.\n\nThis sharp separation is the real gain. The Definition of Done splits into two cleanly separated parts: a hard, executable gate and a small, honestly named remainder of human checks. No more mixing, no more false precision.\n\n## One command, locally and in CI\n\nFor the gate to hold up in everyday work, it needs a property that is often overlooked: developers must be able to run it locally exactly as CI does. If the pipeline checks different things than what I can run before pushing, I lose the fast feedback loop and only get red builds after the push. That is friction, and it is avoidable.\n\nThat’s why I bundle the executable core of the Definition of Done in exactly one target. The name is secondary; the idea is what counts:\n\n```makefile\n# One command is the executable Definition of Done.\n# Developers run it before push; CI runs the exact same target.\nverify: lint build test\n\t@echo \"Definition of Done: green\"\n\nlint:\n\teslint . --max-warnings 0\n\nbuild:\n\tnpm run build\n\ntest:\n\tnpm test -- --coverage\n```\n\nThe merge gate in CI doesn’t call a script of its own. It calls the same `verify`. So: what is green locally is also green in CI, and vice versa. In one sentence: the automatable part of the Definition of Done is a command; the complete agreement remains more than this command.\n\nAs a Git hook, this becomes a light safety net that makes the slow detour through CI unnecessary in the first place:\n\n```bash\n#!/usr/bin/env sh\n# .git/hooks/pre-push\n# Run the executable DoD before anything leaves the machine.\nif ! make verify; then\n  echo \"Push blocked: Definition of Done is red.\"\n  exit 1\nfi\n```\n\nYou can immediately see why this shortens the cycles. The developer gets the red in seconds on their own machine, not minutes later from the pipeline, and certainly not days later in the sprint review. Errors are caught where they are cheapest to fix: right after they come into being.\n\n## The path through the gate\n\nSide by side, the difference jumps out. On one side the ritual, on the other the gate:\n\n```mermaid\nflowchart TD\n    A[Commit] --> B{Ritual or gate?}\n    B -->|Ritual| C[12-point checklist]\n    C --> D[manual ticking off]\n    D --> E[Review meeting]\n    E --> F[Merge<br/>hope, no proof]\n    B -->|Gate| G[Commit stage:<br/>lint, build, test, contract]\n    G --> H{all green?}\n    H -->|yes| I[Merge]\n    H -->|no| J[blocked<br/>back to the developer]\n```\n\nThe left path ends in hope. The right one ends in proof or in a clear block. And the block isn’t an accusation against a person but factual feedback from the system. That also takes enormous pressure off the team dynamics – it isn’t a colleague saying “this isn’t done”, it’s the gate, reproducibly and the same for everyone.\n\nEmpirically, this stance is backed by the State of DevOps Reports from 2014 and 2015, on which Nicole Forsgren, Gene Kim and Jez Humble, among others, worked. Their findings refute the widespread reflex that speed comes at the expense of quality. High performers combine high deploy frequency with a low change fail rate. Speed and quality aren’t a trade-off – provided the checks run automatically instead of manually. That is exactly the business case for the executable gate: it makes fast and safe possible at the same time.\n\n## Boundaries can be checked as a gate, too\n\nA common objection: unit tests only check your own unit, but the really expensive bugs arise at the integration boundaries between services. True. And there is an executable way for that, too, instead of an acceptance meeting. Consumer-driven contracts, as Fowler and Ian Robinson described them and as Pact makes them manageable, turn the question “do our interfaces fit together?” into a signal that is green or red.\n\n```javascript\n// A consumer-driven contract turns an integration\n// boundary into an executable check.\nprovider\n  .given(\"an order with id 42 exists\")\n  .uponReceiving(\"a request for order 42\")\n  .withRequest({ method: \"GET\", path: \"/orders/42\" })\n  .willRespondWith({\n    status: 200,\n    body: { id: 42, status: \"shipped\" }\n  });\n```\n\nThe contract test becomes part of the same commit stage. That moves another check that used to happen in meetings and coordination chains into the pipeline. Fewer appointments, more proof. The lever lies wherever coordination is only necessary because nobody can execute the agreement – such coordination can be replaced by executable agreements.\n\n## Staying honest: what the gate can’t do\n\nAt this point, I have to argue against my own argument, otherwise it becomes dishonest. A green gate isn’t the same as quality. It is evidence that the agreed checks were executed and passed – not evidence that these checks are meaningful. High coverage with weak assertions is green and still worthless. Tests that don’t really assert anything give a false sense of security that is more dangerous than openly admitted uncertainty.\n\nSo the gate measures the execution of checks, not their quality. The quality of the checks themselves remains a human, domain responsibility. If you confuse the two, you only replace the old checklist ritual with a coverage ritual.\n\nJust as honestly: not every item of a Definition of Done can be automated. “Documentation updated”, “accepted by the product owner”, “accessibility checked manually” – that stays human. The mistake would be to pretend that everything turns into code. The right way to handle it is separation: make the automatable core gate hard and blocking, and leave the manual remainder small, visible and consciously standing as a human decision.\n\nAnd one more distinction that saves a lot of friction in practice: the Definition of Done isn’t the same as acceptance criteria. The Definition of Done is project-wide and stable, a quality standard that applies to every story. Acceptance criteria are per story; they describe what the business wants from this one requirement. If you mix the two, you get back exactly the bloated, constantly renegotiated lists this article is written against.\n\n## Conclusion\n\nThe Definition of Done is a good idea that fails in many teams because of its form. Ticked off purely mechanically as a checklist at the latest point, it creates friction and a false sense of security instead of quality. Its automatable core therefore belongs in a gate that checks the same thing locally and in CI. Shared quality criteria and business acceptance don’t disappear as a result; they just aren’t passed off as automatic proof.\n\nThe way there is conceptually simple, and that is exactly why it is elegant. Map the automatable core of the Definition of Done onto the commit stage of a pipeline. Bundle it in one `verify` command. Block the merge as long as it is red. Separate this hard core cleanly from the small manual remainder, and don’t pretend everything is code. And stay honest about the fact that green means “checked”, not “good”.\n\nThe business result of this shift is real and measurable. Shorter feedback cycles, fewer meetings about the state of the code, less social friction in the team and a quality that doesn’t rest on hope but on a reproducible state. The Definition of Done turns from a bureaucratic ritual into a quiet, reliable bouncer. And the best bouncer is the one nobody has to talk about anymore.\n\n## Further reading\n\n- Martin Fowler: *Continuous Integration* and *SelfTestingCode*, martinfowler.com\n- Jez Humble, David Farley: *Continuous Delivery*, 2010 – deployment pipeline and commit stage\n- Puppet Labs: *State of DevOps Report* 2014 and 2015 (Forsgren, Kim, Humble)\n- Ken Schwaber, Jeff Sutherland: *The Scrum Guide* – Definition of Done\n- Martin Fowler, Ian Robinson: *Consumer-Driven Contracts*, martinfowler.com; tool: Pact\n- Michael Nygard: *Release It!*, 2007 – stability patterns as non-functional check targets"},{"locale":"en","translation_key":"react-komponenten-als-schnittstellen","slug":"react-components-as-interfaces","title":"React: Components as Interfaces","summary":"Why props are the public contract of a React component – and what changes when you design them like an API instead of a parameter list.","tags":["Software","Frontend"],"published_at":"2016-03-12T10:00:00+00:00","updated_at":"2026-08-17T11:32:14.2772+00:00","url":"https://www.mikebild.dev/en/blog/react-components-as-interfaces/","audio_url":null,"audio_duration_secs":null,"text":"# React: Components as Interfaces\n\nA React component is not a template that someone mixed some logic into. This reading is widespread because at first glance JSX looks like a template language – and it produces exactly the components that no one wants to touch half a year later: markup with conditions sprinkled in, fifteen props without any recognizable order, and somewhere deep inside an Ajax call. A component is an interface. Props are its public contract, state is a private implementation detail, and the render result is the fulfillment of the contract. If you design props the way you design a good API – minimal, named in the language of the domain, without internals passed through – you get components that survive staff changes and fashions.\n\nSince React 0.14, this is no longer just an interpretation; the framework itself speaks this language: a component may be a plain function that takes props and returns elements. No `createClass`, no class, no lifecycle – a function signature. It’s hard to express “interface” more clearly.\n\n## Props are the contract, state is a detail\n\nIn a billing project I’m currently working on, we render a list of open invoices. The smallest unit is a row, and it is deliberately a stateless functional component:\n\n```jsx\n// InvoiceRow.js - a stateless functional component (React 0.14)\nconst InvoiceRow = ({ invoice, isSelected, onSelect }) => (\n  <tr className={isSelected ? 'selected' : ''}\n      onClick={() => onSelect(invoice.id)}>\n    <td>{invoice.number}</td>\n    <td>{invoice.customer}</td>\n    <td className=\"amount\">{formatAmount(invoice.total)}</td>\n  </tr>\n);\n```\n\nFrom the caller’s perspective, the contract reads: give me an invoice, tell me whether it’s selected, and give me a callback for the selection. Nothing more. The component knows nothing about REST endpoints, nothing about a store, nothing about the logged-in user’s session. That’s exactly why it can be used equally in the detail view, the search results and the month-end closing – and exactly why a test can call it without a server and without browser contortions.\n\nThe counterpart of the contract is state. The official docs contain a checklist for this that I now quote almost word for word in code reviews. A value only belongs in state if all three questions are answered with no:\n\n- Does the value come in through props?\n- Does it stay unchanged over time?\n- Can it be derived from other props or state values?\n\nI’ve noticed that most React problems I see in reviews aren’t render problems but contract problems: props are copied into state on mount and drift apart afterwards, derived values are stored instead of computed, and suddenly there are two truths for the same invoice. If you consistently treat state as a private detail and express everything contractual in props, you don’t get this class of bugs in the first place.\n\n## propTypes: the contract lives in the code\n\nA contract that exists only in the author’s head isn’t one. React ships `propTypes` for this – since 0.14 directly in the `react` package, whether you work with `React.createClass` or with ES2015 classes:\n\n```jsx\nInvoiceRow.propTypes = {\n  invoice: React.PropTypes.shape({\n    id: React.PropTypes.string.isRequired,\n    number: React.PropTypes.string.isRequired,\n    customer: React.PropTypes.string.isRequired,\n    total: React.PropTypes.number.isRequired\n  }).isRequired,\n  isSelected: React.PropTypes.bool,\n  onSelect: React.PropTypes.func.isRequired\n};\n\nInvoiceRow.defaultProps = {\n  isSelected: false\n};\n```\n\nTechnically, these are just warnings in the development environment – no compiler, no guarantee at runtime in production. Still, I consider `propTypes` one of the most underrated tools in the current React ecosystem, for a reason that has little to do with type checking: they are documentation that can’t go stale unnoticed. When a colleague opens `InvoiceRow` for the first time, she reads the contract before she sees a single line of implementation. And when someone breaks the contract, the console complains on the next development run.\n\nAlong the way, `propTypes` also defuse a team problem that affects many codebases right now: the coexistence of `React.createClass` and ES2015 classes. We write new code with Babel and classes or as stateless functions, but older parts of the application are still in the `createClass` style – and that will stay that way for a while, because no one rewrites a running application just over a question of syntax. As long as every component declares its contract as `propTypes`, that matters surprisingly little. The caller sees the same interface in both cases, and migrating a single component from one style to the other breaks nothing the contract wouldn’t report immediately.\n\nIt gets interesting when you use `propTypes` as a design tool instead of as a chore after the fact. In the billing project, we now write the `propTypes` first, before the component gets any markup. That feels cumbersome at first, but it forces the one question that matters: what does the caller really have to provide? A component whose `propTypes` block is longer than its render code is almost always a sign that two or three components are hiding in one.\n\n## Breaking things down as in “Thinking in React”\n\nWith “Thinking in React,” the official docs contain a text that describes exactly this design attitude as a method – and that, in my opinion, is skipped far too often because it sounds like beginner reading. The method is simple: draw rectangles over the UI mock, give each rectangle a single responsibility, first build a static version without any state, then identify the minimal state and place it in the nearest common ancestor.\n\nTranslated into the interface view, this means: every rectangle gets a contract, and the static version is the proof that the contract holds before anything dynamic happens. The step “find the minimal state” is then not a React trick but what you also do when designing a data model – every redundancy you allow now, you have to keep in sync by hand later.\n\nThis is not a new idea. If you have ever cut a module interface or negotiated a service contract, you’ll recognize the pattern immediately. What’s new is that React makes this discipline affordable down to the smallest UI unit: a function with three props is cheap enough to throw away and re-cut if the split isn’t right.\n\n## Separating container and presentation\n\nThe data has to come from somewhere, though. Last year, Dan Abramov wrote down the distinction between container and presentational components for this, and it quickly caught on in our project: presentational components know only their props; containers know the data source and pass results on as props.\n\n```jsx\n// InvoiceListContainer.js - knows where the data comes from\nclass InvoiceListContainer extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { invoices: [], isLoading: true, selectedId: null };\n    this.handleSelect = this.handleSelect.bind(this);\n  }\n\n  componentDidMount() {\n    fetchInvoices().then(invoices =>\n      this.setState({ invoices, isLoading: false })\n    );\n  }\n\n  handleSelect(invoiceId) {\n    this.setState({ selectedId: invoiceId });\n  }\n\n  render() {\n    const { invoices, isLoading, selectedId } = this.state;\n    if (isLoading) return <LoadingHint />;\n    return (\n      <InvoiceList\n        invoices={invoices}\n        selectedId={selectedId}\n        onSelect={this.handleSelect}\n      />\n    );\n  }\n}\n```\n\nThe container is deliberately boring: it loads, it holds the selection state, it passes things on. `InvoiceList` and `InvoiceRow` stay pure functions of their props. The data flow can thus be read at every point – data flows down as props, events travel up as callbacks:\n\n```mermaid\nflowchart TD\n  C[InvoiceListContainer<br/>State: invoices, isLoading, selectedId] -->|Props: invoices, selectedId, onSelect| L[InvoiceList]\n  L -->|Props: invoice, isSelected, onSelect| R1[InvoiceRow]\n  L -->|Props: invoice, isSelected, onSelect| R2[InvoiceRow]\n  R1 -.->|onSelect with invoice.id| C\n```\n\nIf you use Redux – and the rise of Redux is in full swing right now – you already know this pattern: `connect` creates nothing other than containers. But the point is independent of the library. The separation pays off even in an application without any store, because it separates the expensive components (the ones with data access) from the cheap ones (the ones with pure presentation). The cheap ones are the ones you reuse, show in the style guide and test in five minutes.\n\n## Composition via children instead of inheritance\n\nThe second place where interface thinking becomes concrete is reuse of frames and layout. The reflex from the object-oriented world would be inheritance: a `BasePanel` class that special cases inherit from. In React, I haven’t needed that in a single case yet. Instead, the contract gets a placeholder – `children`:\n\n```jsx\n// Panel.js - a layout component with a slot for arbitrary content\nconst Panel = ({ title, children }) => (\n  <div className=\"panel\">\n    <h2 className=\"panel-title\">{title}</h2>\n    <div className=\"panel-body\">{children}</div>\n  </div>\n);\n\n// usage\n<Panel title=\"Open invoices\">\n  <InvoiceList invoices={invoices} selectedId={selectedId} onSelect={handleSelect} />\n</Panel>\n```\n\n`Panel` knows nothing about invoices, `InvoiceList` knows nothing about panels. Both contracts stay minimal, and every combination is visible at the call site instead of being hidden in an inheritance hierarchy. If a panel needs several slots – say, a toolbar next to the title – that’s just another prop that takes an element. Elements are ordinary values in React, and contracts that exchange values are easier to understand than contracts that require inheritance.\n\n## The honest limit: props across many levels\n\nSo much for the places where the interface view holds up. There is one place where it hurts at the moment, and I don’t want to hide it: props that have to be passed through many levels.\n\nThe classic example is the logged-in user. The user menu at the very bottom of the tree needs it, so it travels as a prop through components that don’t use it themselves:\n\n```mermaid\nflowchart LR\n  App -->|currentUser| Page\n  Page -->|currentUser| Toolbar\n  Toolbar -->|currentUser| UserMenu\n```\n\n`Page` and `Toolbar` don’t have `currentUser` in their domain contract – they merely transport it. Every intermediate level that passes a foreign prop through dilutes exactly the minimality I argued for above. And in early 2016, there is no truly satisfying standard answer to this. There is relief:\n\n- restructure the tree and use composition – `App` renders the `UserMenu` itself and passes the finished element down instead of the data\n- place additional containers deeper in the tree that get their data themselves, with Redux for example via `connect`\n- put application-wide data in a store as a rule and carry only local contracts via props\n\nReact does have a context mechanism meant to address exactly this problem – but the docs literally say the feature is experimental and the API is likely to be unstable. I don’t build an application that’s supposed to outlive the warning on something like that. In the project, we tolerate passing through two or three levels, restructure the tree beyond that, and rely on the store for truly global things. That’s a compromise, not a state of affairs I’m happy with. Here the ecosystem simply isn’t finished yet.\n\n## What I take away from this\n\nThe quality of a component isn’t decided in its render code but at the call site. That’s why, in reviews, I now ask questions about the props list first, not about the implementation: do I understand the contract without opening the file? Do the names speak the language of the domain – `invoice`, `onSelect` – or the language of the technology behind it? Is there a prop in there that only exists because a deeper child needs it? Could a second, completely different caller use this component without it noticing?\n\nTemplates answer none of these questions; interfaces do. React prescribes surprisingly little for this – a function, props, `children`, plus `propTypes` as a readable contract – and exactly this sparseness is the value. The library beneath the component will keep turning; in the last year and a half alone, build tools, language standard and state libraries have turned over completely once. A cleanly cut contract of three props has a good chance of surviving all that. A template with some logic doesn’t.\n\n## Further reading\n\n- Thinking in React (official React documentation): [react.dev/learn/thinking-in-react](https://react.dev/learn/thinking-in-react)\n- React v0.14 – release announcement with stateless functional components: [legacy.reactjs.org/blog/2015/10/07/react-v0.14.html](https://legacy.reactjs.org/blog/2015/10/07/react-v0.14.html)\n- Dan Abramov: Presentational and Container Components (2015): [medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0)"},{"locale":"en","translation_key":"graphql-als-frage-an-das-system","slug":"graphql-as-a-question-to-the-system","title":"GraphQL as a Question to the System","summary":"Half a year after the specification, this post sorts out what is really new about GraphQL – and which questions nobody had answered yet in early 2016.","tags":["Software","GraphQL","API"],"published_at":"2016-01-12T10:00:00+00:00","updated_at":"2026-07-14T16:06:16.162736+00:00","url":"https://www.mikebild.dev/en/blog/graphql-as-a-question-to-the-system/","audio_url":null,"audio_duration_secs":null,"text":"# GraphQL as a Question to the System\n\n“A query language for APIs” – that is how Facebook describes GraphQL in the specification, which has been public as a working draft since July 2015. The term quickly leads you astray. If you hear “query language,” you think of SQL and assume a query language for databases, somehow extended to the web: the client sends a SELECT, the server passes it through. That is not it, and the misunderstanding is dangerous, because it makes GraphQL seem either too powerful (arbitrary queries against my data) or too trivial (yet another ORM over the network).\n\nGraphQL does not query tables, knows nothing about joins and has no opinion about where data lives. What gets queried is something else: a type system that the server publishes. The client phrases its question in the terms of this type system, the server answers exactly that question – and where the data comes from, whether from a database, from three internal services or from a file on disk, remains entirely the server’s business. Half a year after the release, it is worth taking a sorting look: what of this is really new, and what is just new syntax for old ideas?\n\n## Who is actually asking the question here?\n\nThe core fits in one sentence: REST answers questions the server asked itself – GraphQL lets the client ask the question.\n\nThat sounds more polemical than it is meant. A well-thought-out REST design is a collection of answers: `GET /posts/42` returns what the developer of the endpoint considered relevant for an article. When the endpoint was designed, someone guessed which fields a client would probably need – and, when in doubt, packed in a few more. This answer is frozen. If a view comes along later that only needs the title and author names of the last ten articles, it has two options: call the fat endpoint and throw most of it away, or request a new, tailor-made endpoint. Both happen constantly in real projects, and both create costs – once in the network, once in coordination between teams.\n\nGraphQL reverses the direction. The server no longer says “these are my answers,” but “these are the terms in which you may ask.” The concrete question – which fields, how deeply nested, in which combination – is phrased by the client itself, per view, per release, without checking back with the server team. That is the real shift, and it is at least as interesting organizationally as technically.\n\n## The schema as contract and domain language\n\nFor the client to ask, the server has to disclose its vocabulary. That happens in the schema, and for me this is where the underestimated quality of GraphQL lies: the schema is not just a contract about data shapes, it is a domain language. Types name things in the domain, not rows in a table. In the compact schema notation that has become common in examples and talks, it looks roughly like this:\n\n```graphql\ntype Author {\n  id: ID!\n  name: String!\n  posts: [Post]\n}\n\ntype Post {\n  id: ID!\n  title: String!\n  body: String!\n  author: Author!\n  comments: [Comment]\n}\n\ntype Comment {\n  id: ID!\n  text: String!\n  author: Author!\n}\n\ntype Query {\n  post(id: ID!): Post\n  latestPosts(count: Int): [Post]\n}\n```\n\nYou can show this schema to an editor and discuss whether a comment really always has an author. The exclamation point is not a formality but a domain statement: `author: Author!` claims that there are no orphaned comments. Whether that is true is known not by the client developer, but by whoever knows the legacy data. I have rarely had such discussions about database schemas – around the GraphQL schema they arise almost by themselves, because it sits exactly on the boundary between the teams and both sides can read it.\n\nThe `Query` type stands out: it does not describe a thing but the entry points – the questions the system allows at all. That, too, is a design decision of the server. GraphQL does not open up all data indiscriminately; it opens exactly the roots that are in the schema, and from there the edges that the types define.\n\n## The query: the shape of the answer is the shape of the question\n\nThe second property that stands out immediately in daily work: a GraphQL query is declarative, and the answer has exactly the shape of the question.\n\n```graphql\n{\n  post(id: \"42\") {\n    title\n    author {\n      name\n    }\n    comments {\n      text\n      author {\n        name\n      }\n    }\n  }\n}\n```\n\nThe answer to it:\n\n```json\n{\n  \"data\": {\n    \"post\": {\n      \"title\": \"GraphQL as a question\",\n      \"author\": { \"name\": \"Ada\" },\n      \"comments\": [\n        { \"text\": \"Nice read!\", \"author\": { \"name\": \"Grace\" } }\n      ]\n    }\n  }\n}\n```\n\nNot one field too many, not one too few, and the nesting of the answer mirrors the nesting of the question. At first this looks like a convenience, but it has practical depth: the client code that processes the answer sits right next to the query that describes it. If you change the view, you change the query, and the data shape follows. Facebook’s Relay, available as open source since August 2015, takes exactly this idea to the extreme and lets every component declare its own data requirements. You do not have to use Relay to benefit from the idea – the query alone already forces a clarity that never emerges with “we just take whatever the endpoint returns.”\n\n## Resolvers: where the truth lives\n\nThat leaves the question of how a declarative question turns into a concrete answer. The reference implementation graphql-js answers it with a simple principle: every field has a resolver function. It receives the parent object and the arguments and returns the value of the field – synchronously or as a promise.\n\n```js\nimport {\n  GraphQLObjectType,\n  GraphQLID,\n  GraphQLString,\n  GraphQLList,\n  GraphQLNonNull\n} from 'graphql';\n\nconst postType = new GraphQLObjectType({\n  name: 'Post',\n  fields: () => ({\n    id: { type: new GraphQLNonNull(GraphQLID) },\n    title: { type: new GraphQLNonNull(GraphQLString) },\n    author: {\n      type: authorType,\n      resolve: (post) => db.findAuthorById(post.authorId)\n    },\n    comments: {\n      type: new GraphQLList(commentType),\n      resolve: (post) => db.findCommentsByPostId(post.id)\n    }\n  })\n});\n\nconst queryType = new GraphQLObjectType({\n  name: 'Query',\n  fields: {\n    post: {\n      type: postType,\n      args: { id: { type: new GraphQLNonNull(GraphQLID) } },\n      resolve: (root, args) => db.findPostById(args.id)\n    }\n  }\n});\n```\n\nIn graphql-js, you currently build the schema programmatically from such type objects; the compact schema notation from above mainly serves communication. More important than the API details is the place where truth emerges here: in the resolver. Whether `author` comes from the same database as the post, from another service or from a cache – that is decided by this one function, and only by it. The schema promises the shape, the resolver delivers the content. This separation makes GraphQL a facade: you can clean up behind it, merge services or split them apart without any client noticing, as long as the schema holds.\n\nIn a project at the end of last year, I put a small prototype with graphql-js in front of two existing internal services – nothing in production, an experiment over the holidays. The surprising experience was not the query language, but how quickly the discussion in the team shifted from endpoints to terms. Instead of “which endpoint returns this field,” the question suddenly became “does this field belong on this type.” That is a better question.\n\n## Overfetching and underfetching: the problem actually solved\n\nIf you ask soberly which concrete problem GraphQL solves, I keep ending up with two that share the same root. Overfetching: the endpoint returns more than the view needs, and mobile clients pay for it with data volume and battery life. Underfetching: the endpoint returns less than the view needs, and the client works its way through further endpoints one after another – each round a full network latency, on mobile networks often three-digit milliseconds.\n\n```mermaid\nflowchart LR\n  subgraph REST[\"REST – three rounds for one view\"]\n    C1[Client] --> E1[\"GET /posts/42\"]\n    C1 --> E2[\"GET /posts/42/comments\"]\n    C1 --> E3[\"GET /authors/7\"]\n  end\n  subgraph GQL[\"GraphQL – one question\"]\n    C2[Client] --> Q[\"POST /graphql<br/>one query, one round trip\"]\n    Q --> R[\"Resolver\"]\n    R --> S1[(\"Database\")]\n    R --> S2[\"internal service\"]\n  end\n```\n\nBoth problems disappear because the question lies entirely with the client: it asks for everything it needs and nothing beyond that, in a single round trip. The rounds between the data sources still take place – but on the server side, in the data center, where latency is cheap. That is exactly why Facebook built GraphQL for its mobile applications, and exactly why the benefit is greatest where clients talk over poor networks. If you build an internal API between two servers in the same rack, GraphQL solves a problem you may not have at all.\n\n## GraphiQL: the window into the system\n\nOne aspect is often left out in discussions about the language and the type system: GraphQL servers are introspectable. The schema can be queried at runtime – with a GraphQL query about the schema itself. GraphiQL builds on this: the browser-based explorer that Facebook published together with the reference implementation. You point it at an endpoint and get:\n\n- autocompletion for fields and arguments, straight from the schema\n- inline documentation for every type and every field\n- validation of the query as you type, before the first request\n- a window for trying things out, without a line of client code\n\nThat changes how you get to know an unfamiliar API. Instead of reading documentation wikis that nobody has maintained for three versions, you explore the system itself – and the information cannot go stale, because it comes from the running server. While playing around, I noticed that GraphiQL disciplines schema quality along the way: when every field name is immediately visible and autocompleted, bad naming visibly hurts.\n\n## What is open in early 2016\n\nSo much for the praise. To be honest, a stock-taking also has to include what the specification and the young community have not answered yet. Four points occupy me at the moment:\n\n- Caching without URLs\n- the N+1 problem in resolvers\n- permissions per field\n- versioning – the promise of the “versionless API”\n\nWith caching, GraphQL initially loses something that REST gets for free. HTTP caching lives on the URL as the cache key: browser, proxy and CDN can cache `GET /posts/42` without understanding the content. A GraphQL request is a POST against a single endpoint – to the HTTP infrastructure, all requests look the same. Relay answers this on the client side with a normalized cache over object IDs, which is elegant but only helps in the client. For the intermediate layers, there is no convincing answer as of today.\n\nThe N+1 problem arises directly from the resolver model. The query `latestPosts(count: 10)` with the field `author` calls the author resolver ten times – in the naive case ten individual database queries for a list that a single query could deliver:\n\n```mermaid\nflowchart TD\n  Q[\"latestPosts(count: 10)<br/>with field author\"] --> P[\"Resolver latestPosts<br/>1 query\"]\n  P --> A1[\"Resolver author<br/>Post 1\"]\n  P --> A2[\"Resolver author<br/>Post 2\"]\n  P --> An[\"Resolver author<br/>Post 10\"]\n  A1 --> DB[(\"10 individual queries<br/>instead of one\")]\n  A2 --> DB\n  An --> DB\n```\n\nFor this, Facebook released DataLoader in the fall, a small, fresh project that collects load operations per request, deduplicates them and executes them in batches. The approach looks viable, but it is not an established pattern yet – you have to know it and build it in deliberately, otherwise the most elegant schema produces a miserable database load.\n\nPermissions are the question I respect the most. With REST, you authorize per endpoint, and the model is well understood. In a graph, potentially every type is reachable from every other type via edges: if `Comment` has a field `author` and `Author` has a field `posts`, you get from the most harmless comment to the complete list of works. The consequence is uncomfortable: authorization has to be thought of per field, sensibly in the resolvers – and a widespread, proven pattern for it simply does not exist yet.\n\nThat leaves versioning. Facebook advertises GraphQL as a “versionless API”: instead of building `/v2/`, you extend the schema, mark old fields as deprecated – the specification explicitly provides for deprecation – and watch which clients still query them. Because every query names its fields explicitly, the server knows for the first time exactly what is actually used. On paper this convinces me; whether it sustains the discipline over years, nobody can prove in early 2016. I note it as a promise, not as a property.\n\n## The bottom line\n\nWhat is really new about GraphQL is not in the syntax and not in the word “graph.” What is new is the distribution of responsibility: the server defines the domain language and is responsible for the truth in the resolvers, the client phrases its question itself – completely, type-checked, answerable in one round trip. Overfetching and underfetching, the two chronic points of friction between API teams and client teams, disappear almost as a side effect.\n\nThe open questions are real: caching, N+1, field permissions, the unproven versioning promise. None of them looks unsolvable, but if you use GraphQL in production today, you answer them yourself and carry the risk for it. For me that means: keep working with prototypes, take the schema seriously as a basis for conversations with domain experts, and keep the server side small. I consider the idea that a client asks the system a question instead of fetching prefabricated answers to be right regardless of the tool – and if GraphQL does not catch on, the next technology will have to pick up exactly this idea again.\n\n## Further reading\n\n- GraphQL specification (working draft): https://spec.graphql.org/\n- GraphQL Learn – official introduction: https://graphql.org/learn/\n- graphql-js, the reference implementation: https://github.com/graphql/graphql-js\n- GraphiQL, the schema explorer: https://github.com/graphql/graphiql\n- DataLoader for batched loading: https://github.com/graphql/dataloader"},{"locale":"en","translation_key":"build-skripte-als-produktcode","slug":"build-scripts-as-product-code","title":"Build Scripts as Product Code","summary":"Build scripts deserve the care of product code, because they determine how reproducible a system actually is.","tags":["Software","Tooling"],"published_at":"2015-10-12T10:00:00+00:00","updated_at":"2026-07-13T08:35:25.355094+00:00","url":"https://www.mikebild.dev/en/blog/build-scripts-as-product-code/","audio_url":null,"audio_duration_secs":null,"text":"# Build Scripts as Product Code\n\nA build script is not a collection of convenient command-line shortcuts. It is the description of all the inputs from which a deliverable artifact is created: sources, dependencies in concrete versions, toolchain, environment. Whatever isn’t written there is silently borrowed from the machine the build happens to run on.\n\nNevertheless, these scripts tend to end up in a gray zone between code and infrastructure: rarely reviewed, almost never tested, usually maintained by a single person. This gray zone is exactly why releases hurt.\n\n## The thesis\n\nA feature is only done when a second person can build, test and ship it from an empty directory – without me sitting next to them. The path there is not a by-product. It is the product. If `git clone` plus one command isn’t enough to produce the same artifact file as on my machine, then the system really only exists locally on my machine – and is therefore not shipped, just demonstrated.\n\nThat’s why I treat the build script with the same care as product code: it has a clear contract, it is versioned, it is read, and it has a defined failure path. That doesn’t make it as runtime-critical in every respect as the shipped service. What I mean is the level of responsibility: others have to be able to rely on its result.\n\n## Why this is an architecture question\n\n“Build” sounds like craftsmanship, like a side issue. In fact, the build decides two properties that are otherwise expensive to retrofit: reproducibility and cycle time.\n\nReproducibility means that the same inputs produce the same outputs – regardless of machine, time of day and the mood of the network. A build that is green on my laptop and red on the CI server doesn’t have a test problem. It has a state problem: somewhere, undeclared state flows in – a globally installed CLI, an environment variable, a version that resolves to “latest”.\n\nCycle time means how long it takes to get from a change to a reliable statement. This time multiplies with every person and every day on the team. A build that takes ten minutes and fails every other run is not a comfort issue. It is a productivity leak you can measure in hours per week.\n\nBoth are architectural properties, not tool details. That’s why the tool question comes last. Before it comes clarification: which inputs go into the build? Which of them are declared and which are implicit? What is the expected artifact? Only after that is it decided whether this becomes an `npm` script, a Gulpfile or a Makefile.\n\n## A small, unspectacular example\n\nThe most common mistake is not the wrong tool but undeclared state. A typical frontend setup from this period often looks like this:\n\n```json\n{\n  \"scripts\": {\n    \"start\": \"webpack-dev-server --hot\",\n    \"build\": \"webpack -p\"\n  }\n}\n```\n\nThat reads harmlessly. But the hidden contract isn’t in the script at all: it assumes that `webpack` is installed globally, that the right Node version is running, that `NODE_ENV` is set. None of this is part of the repository. On their first day, the new colleague gets a different build than I do – and nobody broke the contract, because there never was one.\n\nThe fix is cheap and takes effect immediately: bind dependencies locally, reduce the entry point to one command, make the one environment decision explicit.\n\n```json\n{\n  \"scripts\": {\n    \"start\": \"webpack-dev-server --hot --config webpack.dev.js\",\n    \"build\": \"NODE_ENV=production webpack --config webpack.prod.js\",\n    \"test\": \"mocha --recursive\",\n    \"verify\": \"npm run test && npm run build\"\n  }\n}\n```\n\nThe gain is not elegance. The gain is that `npm run verify` is now a verifiable statement: if it is green, an artifact exists, and the tests that sign off on it have run along with it. I haven’t replaced a build server. I have only brought the contract into the repository, where it can be reviewed.\n\n## Determinism is not a luxury\n\nThe most expensive break in reproducibility is versions that are decided at install time. `^1.2.0` in the `package.json` means: today’s build and next week’s may install different code without a single line in the repository having changed. For an experiment, that doesn’t matter. For a product, it is an open flank.\n\n```bash\n# freeze the exact dependency tree, then commit the lockfile\nnpm shrinkwrap\ngit add npm-shrinkwrap.json\n```\n\nFrom here on, the dependency tree is an artifact like any other: versioned, diffable, visible in review. If an update breaks something, I see it as a change to a file – and not as a ghost that only appears on the CI server. That is the core of the whole thing: state that used to seep invisibly through the cracks becomes something you can read and reject.\n\nWhere the language ecosystem isn’t enough for me, I draw the line one level deeper. A slim image that contains exactly the toolchain turns the environment itself into a versioned artifact.\n\n```makefile\nIMAGE = myapp-build:1.0\n\nbuild:\n\tdocker build -t $(IMAGE) .\n\tdocker run --rm -v $(PWD):/src $(IMAGE) npm run verify\n```\n\nI’m not using Docker here as a deployment strategy and certainly not as an end in itself – I deliberately leave out the topic of clusters and orchestration. I use it as a reproducibility tool: the question “which Node version, which `make`, which system library?” now has an answer that lives in the repository.\n\n## One command per intention\n\nA build script is an interface before it is an implementation. That’s why I care about the vocabulary first, not the content. If every project in the company understands the same four verbs – `install`, `verify`, `build`, `clean` – then nobody has to read the README anymore to contribute. The intention is in the name; the mechanics behind it may differ from project to project.\n\nThat sounds like cosmetics, but it is an architecture decision with reach. Once the vocabulary is stable, I can swap the tools behind it without anything changing for the team. The switch from Grunt to Gulp, from Gulp to plain `npm run`, from one test runner to another – all of that stays hidden behind `npm run verify`. The line I draw separates intention from mechanics. Exactly this separation keeps the build maintainable while the toolchain moves beneath it.\n\nThe other effect is that the script becomes documentation. A newcomer doesn’t need to know that the build internally runs Babel, bundling and an Uglify step. They need to know `npm run build`. The shifted knowledge is the point: it now lives in the code and no longer in people’s heads – and so it isn’t lost when someone leaves the team.\n\n## The build belongs in the pipeline, not on my laptop\n\nA contract that only I keep is not a contract. So the logical next step is to run the same entry point on a neutral server – on every push, without exception.\n\n```yaml\nlanguage: node_js\nnode_js:\n  - \"4\"\ninstall:\n  - npm install\nscript:\n  - npm run verify\n```\n\nThis is deliberately boring. The CI calls exactly the same command I use locally – not a parallel truth of its own. That makes the server not a second build system that can drift apart but an incorruptible witness to the same contract. As soon as a colleague introduces an undeclared assumption, the pipeline turns red before the code reaches the main branch. The expensive mistake – environment drift that only shows up at release – becomes a cheap mistake that shows up in the pull request.\n\nThis is exactly where the metrics from the next layer become measurable in the first place: time to a green build, share of red runs, time until the artifact is reproduced. Without the pipeline, these are anecdotes. With it, they are numbers you can use to prove an improvement.\n\n## The failure path, not the happy path\n\nAn idea about the build is only robust once the failure path is described. This is exactly where demo and operations part ways.\n\nThe first question is idempotence. What happens on the second run? A build that fills a `dist/` directory without emptying it first produces ghost files after a few weeks: old bundles that nobody references anymore but that get shipped anyway. A clean build starts with `clean`, not out of love of order, but so that the tenth run produces the same result as the first.\n\nThe second question is failure itself. A script that chains several steps with `&&` has to abort at the first error – and end with a non-zero exit code. Otherwise the CI reports green even though the test step silently went missing. I have traced more broken releases back to swallowed exit codes than to wrong logic.\n\nThe third question is reversibility. Can I recreate last week’s artifact exactly when a bug shows up in production? If the build isn’t deterministic, the answer is no – and then a rollback is no longer a decision but a guessing game.\n\n## The operational consequence\n\nI can tell whether the work is having an effect from simple things: how long does a new colleague need until the first local build? How often does the CI fail because of an assumption that only held on one machine? Can the artifact of an old release be recreated from the inputs of that time? A declared build improves exactly these cases. How big the effect is, the team has to measure against its own run times and failures.\n\n## Typical mistakes\n\nThe first mistake is confusing the tool with the solution. Gulp is not reproducibility. A Makefile is not a guarantee of determinism. These tools can express a clean contract, but they don’t create it on their own. I have seen Gulpfiles that assumed just as much hidden knowledge as the broken `npm` script before them.\n\nThe second mistake is considering the build done as soon as it was green once. A build is living code. It rots with every undeclared assumption that creeps in – the one environment variable that is set “only on our machines”, the tool that “everyone has installed anyway”. That’s why the build script belongs in the same review as the feature, not in a separate, unsupervised folder.\n\nThe third mistake is trading speed for trust. A build that skips tests to turn green faster sells future cycle time for today’s convenience. The loan is always called in, usually at the worst possible moment.\n\n## What I check in review\n\nThree questions are usually enough for me to judge whether a build deserves to be called product code. Can a person who doesn’t know the project produce an artifact from an empty directory with one command? Is every input that affects the result visible in the repository – versions, environment, toolchain? Does the build abort visibly on an error instead of silently reporting green?\n\nIf one of these questions is answered with no, it’s not a tool that’s missing. A part of the architecture is missing. And that part is usually cheaper to close than the team thinks – as long as you treat the build as what it is: product code that determines whether a system reproducibly exists or was only demonstrated.\n\n## Conclusion\n\nIn the end there is a practical test: can a new machine build the same artifact from the versioned inputs, does an error abort visibly, and can a release be rolled back? If so, the build script meets its responsibility. Whether Gulp, Grunt or a shell script runs underneath is secondary."},{"locale":"en","translation_key":"es6-memory-ui-state","slug":"es6-memory-understanding-ui-state","title":"ES6 Memory: Understanding UI State","summary":"A memory game in fresh ES2015, built without a framework, makes visible which states a UI really has, where they should live and who may change them.","tags":["Software","Frontend"],"published_at":"2015-09-24T10:00:00+00:00","updated_at":"2026-07-14T16:53:05.755017+00:00","url":"https://www.mikebild.dev/en/blog/es6-memory-understanding-ui-state/","audio_url":null,"audio_duration_secs":null,"text":"# ES6 Memory: Understanding UI State\n\nA single memory card has four distinguishable states: hidden, revealed, matched – and locked while two open cards are being compared. Usually exactly two of them end up in the DOM, as CSS classes such as `flipped` and `matched`. The third state hides implicitly in a running `setTimeout`, the fourth follows from the absence of the others. So two of four states are written down nowhere explicitly – and it is exactly these two that produce the bugs you reliably find in small UIs: the third card that can be revealed in the middle of a comparison, and the pair that stays open for good after a hasty double click.\n\nThe fact that I only really noticed this ratio – four states, two of them visibly recorded – when I built a game says a lot about how casually we otherwise treat UI state.\n\n## A game as a test bench\n\nECMAScript 2015 has been final since June. Classes, modules, `const` and `let`, arrow functions, template literals – that is all in the standard now, but it still feels unfamiliar, like a foreign language with familiar vocabulary. I did not want to work through the new syntax with slide examples but with something real: small enough for a few evenings, big enough that real state questions come up. A memory game fits exactly into this gap. Sixteen cards, eight pairs, a move counter – no more domain is needed.\n\nThe result is on GitHub as [es6-memory](https://github.com/MikeBild/es6-memory). Deliberately without a framework: no jQuery, no React. Not out of dogmatism, but because I wanted to know what remains of the state problems when no tool hides them or takes them off your hands. The build is still up to date: jspm resolves the dependencies, SystemJS loads the ES2015 modules, Babel translates the new syntax for browsers that are not there yet – and a small `node build` bundles everything into a `memory.min.js` that you can hook into any existing page with a single `div`. Fitting for the week in which the repository was created: at the beginning of September, Node 4.0 was released, the first version after the reunification with io.js, with a V8 tailwind for part of the new language features. ES2015 is just moving from paper into the tools, and exactly at this moment a project that uses the language in its pure form is worthwhile.\n\n## Which states really exist\n\nThe first gain came before the first line of code: listing the states. For a card there are three, not four – that was the first correction to my own picture of the game:\n\n- hidden: the back is visible, the card reacts to clicks\n- revealed: the motif is visible, the card waits for the comparison\n- matched: the motif stays visible, the card never reacts again\n\nAnd the fourth state from the introduction? “Locked” is not a card state at all. It is a state of the game: as long as two revealed cards are being compared – and, if they do not match, stay visible briefly so that you can memorize them – no further card may be turned over. Add to that the move counter and the derived question of whether the game is over. This separation between card state and game state does not occur to you as long as you think in CSS classes. It occurs to you immediately when you have to write the state down as a data structure.\n\n```mermaid\nflowchart LR\n  H[hidden] -->|flipCard| R[revealed]\n  R -->|second card<br/>matches| M[matched]\n  R -->|no match<br/>after 800 ms| H\n  M --> E[game over<br/>when all matched]\n```\n\nIn ES2015, the model reads pleasantly directly. A class for the card, a factory for the game – and for the first time without the usual tangle of prototypes:\n\n```js\n// card.js\nexport class Card {\n  constructor(id, motif) {\n    this.id = id;\n    this.motif = motif;\n    this.state = 'hidden'; // 'hidden' | 'revealed' | 'matched'\n  }\n}\n\n// game.js\nimport { Card } from './card.js';\n\nexport function createGame(motifs) {\n  const pairs = motifs.concat(motifs);\n  const cards = shuffle(pairs).map((motif, id) => new Card(id, motif));\n  return { cards, locked: false, moves: 0 };\n}\n```\n\nThat is the complete state of the game: an array of cards, each with a `state` field, a `locked` flag, a counter. No `data-` attribute, no class list, no hidden timeout that carries truth on the side.\n\n## Where the state lives – and where it does not\n\nI know the obvious alternative from enough jQuery codebases of recent years, including my own: the DOM is the state store. Whether a card is revealed is decided by `classList.contains('flipped')`. How many cards are open is determined by a selector. That works surprisingly long – and then tips over at always the same spot: as soon as timing comes into play, there are moments when the display lags behind the truth. The animation is not finished yet, the class not yet set, the selector counts wrong. The bug is then not deterministic but depends on how fast someone clicks.\n\nThe deeper point: a DOM node mixes two things that belong apart – what is the case and how it currently looks. As long as both are identical, you do not notice the difference. It gets interesting exactly when the two diverge, and they do with every `setTimeout`, every transition, every server round trip. If, on the other hand, the state lives in the model, it is unambiguous at any point in time, regardless of what the browser is currently drawing. And it is testable without a browser: `createGame`, `flipCard` twice, an assertion on `state` – that runs in Node in milliseconds, without any DOM mock.\n\n## One transition function instead of scattered toggles\n\nThe second decision follows from the first: if the state lives in one place, it should also be changed in only one place. Not three event handlers that each do a bit of class logic, but a single function that knows all the rules of the game:\n\n```js\n// game.js\nexport function flipCard(game, cardId, onSettled) {\n  const card = game.cards.find(c => c.id === cardId);\n  if (game.locked || !card || card.state !== 'hidden') return;\n\n  card.state = 'revealed';\n  const revealed = game.cards.filter(c => c.state === 'revealed');\n  if (revealed.length < 2) return;\n\n  game.locked = true;\n  game.moves += 1;\n  const [first, second] = revealed;\n  const isMatch = first.motif === second.motif;\n\n  setTimeout(() => {\n    first.state = second.state = isMatch ? 'matched' : 'hidden';\n    game.locked = false;\n    onSettled();\n  }, isMatch ? 300 : 800);\n}\n```\n\nThe first line after the `find` is the actual payoff of the whole rework. `game.locked || card.state !== 'hidden'` takes care of both bugs from the introduction in one expression: the third card during the comparison bounces off `locked`, the double click on the same card off the card state. In the DOM variant, these were two separate symptoms in two places in the code, each with its own workaround. In the model, they are two facets of the same rule: revealing is only allowed when the game is open and the card is hidden.\n\nWhile writing this function, I noticed something else: it is the place where you talk about the game. When a colleague asked in the review whether a revealed pair should lock in immediately or with a delay, I could point to two lines. The question “Who may change this state?” deserves the same answer in the small as in the large: ideally exactly one function, and it carries a name from the domain language.\n\n## Rendering in one direction\n\nThat leaves the third question: how does the state get onto the screen? The answer that proved sustainable while building is almost uncomfortably simple – after every change, the complete board is redrawn:\n\n```js\n// render.js\nexport function render(game, root) {\n  root.innerHTML = `\n    <p class=\"moves\">Moves: ${game.moves}</p>\n    <ul class=\"board\">\n      ${game.cards.map(card => `\n        <li class=\"card ${card.state}\" data-id=\"${card.id}\">\n          ${card.state === 'hidden' ? '' : card.motif}\n        </li>`).join('')}\n    </ul>`;\n}\n```\n\nTemplate literals make this kind of rendering pleasant for the first time. Before ES2015, this meant string concatenation over twenty lines or a template library as a dependency; now it is a multi-line expression with interpolation, right in the language. The wiring for it is a single delegated listener:\n\n```js\n// main.js\nimport { createGame, flipCard } from './game.js';\nimport { render } from './render.js';\n\nconst root = document.querySelector('.memory');\nconst game = createGame(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']);\n\nconst update = () => render(game, root);\n\nroot.addEventListener('click', event => {\n  if (!event.target.classList.contains('card')) return;\n  flipCard(game, Number(event.target.dataset.id), update);\n  update();\n});\n\nupdate();\n```\n\nWith that, everything flows in one direction: a click is only a message to the transition function, the transition function changes the model, the model is rendered. No handler ever touches the DOM, no renderer ever changes the state.\n\n```mermaid\nflowchart LR\n  E[Click event] --> T[flipCard<br/>transition function]\n  T --> S[(Game state<br/>in the model)]\n  S --> R[render]\n  R --> D[DOM]\n  D -. only reports events,<br/>holds no state .-> E\n```\n\nThe reflexive objection is: isn’t re-rendering everything wasteful? I measured it instead of believing it. Replacing seventeen elements via `innerHTML` costs well under a millisecond in Chrome – for an interaction that happens at most twice per second. The limit exists, but it lies far away from sixteen cards: with hundreds of nodes, form focus or scroll positions that do not survive the rebuild, the approach no longer holds. This is exactly the limit React addresses, which is getting a lot of attention with version 0.13 right now: it keeps the principle “state in, display out” and only makes the write path into the DOM smart by computing differences instead of replacing everything. If you have built the memory game by hand, you read the React documentation differently – as an optimization of a model you already understand rather than as magic.\n\n## What a framework takes off your hands – and what it does not\n\nFor me, this is the real insight from the project, and it has only marginally to do with ES2015. A framework takes a lot off your hands:\n\n- efficiently updating the DOM when redrawing becomes too expensive\n- breaking the UI down into composable, reusable parts\n- wiring events, templates and data without homegrown conventions\n\nWhat no framework takes off your hands are the three questions this small game forced: which states exist at all – and which of them belong to the card, which to the game? Where do they live – in the model or smeared across class lists and timeouts? And who may change them – a named transition function or every handler a little? If you do not answer these questions, you get the same bugs with a framework as without one, just better packaged. Duplicated state between component and DOM looks tidier in JSX than in jQuery, but it remains duplicated state. As an aside: since the summer, a library experiment called Redux has come out of the React community that declares exactly this transition function the central building block – a sign that the idea does not end with the toy example.\n\n## What I take away from this\n\nThe game itself is an afternoon’s fun, a prototype with eight motifs and a move counter. The value lies in what it forced. First: list the states before code is written – the inventory alone corrected my picture, because “locked” had been assumed on the wrong level. Second: the state belongs in the model; the DOM is a projection of it and is no good as storage as soon as timing comes into play. Third: one transition function that knows all the rules instead of toggles spread across handlers – that is where reviews happen, where the domain language lives, where two bugs disappear in one guard line. And the new language? ES2015 did not make the whole thing possible, but it made it pleasant: classes for the model, modules for the boundaries, template literals for rendering. Babel and jspm make sure it already runs in real browsers today. I will probably not build the next larger frontend without a framework – but I will know more precisely which part of the work the framework really takes over and which part has to happen in my own head beforehand.\n\n## Further reading\n\n- Repository es6-memory: https://github.com/MikeBild/es6-memory\n- MDN: Classes (JavaScript reference): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\n- MDN: Template literals: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\n- Babel, the JavaScript compiler for ES2015: https://babeljs.io/\n\nThe links help you look up the language features – the decision of where state lives and who changes it, they do not make for you."},{"locale":"en","translation_key":"web-messaging-mit-rxjs","slug":"web-messaging-with-rxjs","title":"Web Messaging with RxJS","summary":"If you hide incoming messages behind an observable, the transport between browser and server becomes interchangeable – and you notice along the way how far plain HTTP gets you.","tags":["Software","Reactive"],"published_at":"2015-07-24T10:00:00+00:00","updated_at":"2026-07-14T16:51:17.40526+00:00","url":"https://www.mikebild.dev/en/blog/web-messaging-with-rxjs/","audio_url":null,"audio_duration_secs":null,"text":"# Web Messaging with RxJS\n\n```js\nvar incoming = Rx.Observable.create(function (observer) {\n  var source = new EventSource('/subscribe/green');\n\n  source.onmessage = function (event) {\n    observer.onNext(JSON.parse(event.data));\n  };\n  source.onerror = function (error) {\n    observer.onError(error);\n  };\n\n  return function () {\n    source.close();\n  };\n});\n\nincoming\n  .map(function (message) { return message.green; })\n  .distinctUntilChanged()\n  .subscribe(function (count) {\n    render(count);\n  });\n```\n\nThe interesting thing about this piece of client code is the part that’s missing. The consuming side – the three lines starting at `incoming.map(...)` – knows nothing about `EventSource`, nothing about HTTP, nothing about connections. It subscribes to a stream of incoming messages and processes it with the same operators it would use for an array or a sequence of mouse clicks. How the messages technically arrive is locked inside the `create` callback. This very separation is the core of what I’ve been trying out over the last few weeks: thinking of messages between browser and server not as a connection problem but as a stream – with RxJS as the shared language on both sides.\n\n## Why not go straight to WebSockets?\n\nAs soon as someone in a project says “real-time,” reaching for WebSockets is the obvious move – usually in the form of socket.io, which kindly wraps up the connection details. That is often the right choice, but it comes at a price that tends to show up only later. WebSockets are a protocol of their own with their own handshake. Older proxies swallow the upgrade, some corporate firewalls cut long-lived connections without comment, load balancers need special treatment, and the familiar HTTP toolbox – caching, auth headers, access logs, curl for debugging – only partly applies. socket.io answers some of this with fallbacks, but in return pulls a whole library layer into the project on client and server.\n\nYet the business requirement is often more modest than the word “real-time” suggests: the server should inform the browser about events, mostly in one direction, and a latency of a fraction of a second is perfectly fine. For this profile, HTTP has had answers for years that work without switching protocols: long polling, chunked responses, server-sent events. All of them run through any infrastructure that speaks HTTP – which is practically everything.\n\nSo the real architecture question is not “WebSockets or not?” but: How do I write the application code so that this decision can be revised later?\n\n## An experiment: everything is a stream\n\nA little under two weeks ago, I published a small repository on this, [web-messaging](https://github.com/MikeBild/web-messaging). The README line describes its scope honestly: “Message routing and Complex-Event-Streams via HTTP (Transfer-Encoding: chunked)”. It’s an experiment, not a product – a single `server.js`, an `index.html`, no Express, not even a routing framework, but a hand-written mini router made of regular expressions. This very simplicity makes it visible what it’s all about.\n\nThe server models everything that produces messages as an observable. A simulated source ticks every two seconds and rolls a random group; a `Subject` serves as the entry point for messages from outside. Both flow into a shared stream:\n\n```js\nvar rx = require('rx');\n\nvar publishChannel = new rx.Subject();\n\nvar simulated = rx.Observable.interval(2000)\n  .map(function (tick) {\n    return { sequence: tick, group: randomGroup() };\n  });\n\nvar events = simulated\n  .merge(publishChannel)\n  .publish()\n  .refCount();\n\nvar totals = events\n  .scan({}, function (acc, message) {\n    acc[message.group] = (acc[message.group] || 0) + 1;\n    return acc;\n  })\n  .publish()\n  .refCount();\n```\n\nTwo things in it turned out to be load-bearing. First, `merge`: the fact that a simulated time source and a Subject fed by HTTP POSTs can be combined into one stream without anyone noticing is not a gimmick – it means that “where does the message come from?” stays a local decision. Second, `publish().refCount()`: without these two calls, the stream would be cold, and every subscriber would get its own simulation with its own counter. This way, all connections share the same hot source, and `scan` keeps exactly one count across all groups – state as a stream, not as a variable that many places write to.\n\nThe `publishChannel` is fed by the POST route, and that may be the prettiest line in the experiment: an ordinary HTTP request becomes an event in the stream.\n\n```js\nroute.post(/\\/publish\\/([a-z]*)/, function (req, res) {\n  publishChannel.onNext({ group: req.params[0] });\n  res.end();\n});\n```\n\n## The response as an Observer\n\nMore exciting than the producing side is the delivery. How does a server stream get into a browser without WebSockets? The experiment’s answer: the HTTP response simply stays open. With `Transfer-Encoding: chunked`, a server may write in small pieces for as long as it likes – and that turns `res` into an Observer that receives messages from the stream:\n\n```js\nroute.get(/\\/subscribe\\/([a-z]*)/, function (req, res) {\n  res.setHeader('Content-Type', 'application/json');\n  res.setHeader('Transfer-Encoding', 'chunked');\n\n  var subscription = totals\n    .map(function (data) {\n      var group = req.params[0];\n      if (!group) return data;\n      var result = {};\n      result[group] = data[group];\n      return result;\n    })\n    .subscribe(function (data) {\n      res.write(JSON.stringify(data) + '\\n\\n');\n    });\n\n  req.on('close', function () {\n    subscription.dispose();\n  });\n});\n```\n\nEvery connection is a subscription. That sounds trivial, but along the way it takes care of the problem that regularly leads to memory leaks in hand-rolled publish-subscribe servers: lifetime. When the browser closes the connection – tab closed, network gone, page reloaded – `req.on('close')` fires, the subscription ends with `dispose()`, and because `refCount` keeps count, the source stops working as soon as the last subscriber is gone. Cleanup is no longer special logic but the natural flip side of subscribing. In a project a few years earlier, we maintained a dedicated registry with timeout heuristics for exactly this cleanup – here it’s two lines.\n\nA side effect of this setup that I wouldn’t want to give up anymore: you can observe the stream with built-in tools. A `curl http://localhost:8765/subscribe/green` in the terminal, and the messages trickle in line by line – no special tool, no browser plugin, no protocol inspection. The repository even has a dedicated `/log` route for this, which delivers the unfiltered raw stream before aggregation. While developing, I always had two terminals open: one on `/log` for the raw events, one on `/subscribe/...` for what a client actually sees. With a WebSocket setup, the same visibility already requires building your own tools, or at least the frame view of the browser developer tools.\n\nThe flow at a glance:\n\n```mermaid\nflowchart LR\n  POST[HTTP POST<br/>/publish/:group] --> SUBJ[Subject<br/>publishChannel]\n  SIM[Interval<br/>Simulation] --> MERGE[merge]\n  SUBJ --> MERGE\n  MERGE --> SCAN[scan<br/>count per group]\n  SCAN --> SUBA[Subscription<br/>connection A]\n  SCAN --> SUBB[Subscription<br/>connection B]\n  SUBA --> RESA[chunked Response A<br/>res.write]\n  SUBB --> RESB[chunked Response B<br/>res.write]\n```\n\nOn the client side, by the way, I’m less consistent in the repository: the `index.html` is a small AngularJS 1.4 application that still picks the chunks out of an `XMLHttpRequest` by hand – at `readyState === 3`, cut the `responseText` at the double line breaks and parse the last complete line. That works, but it’s exactly the kind of transport detail that has no place in application code. The `Rx.Observable.create` wrapper from the beginning is the consequence: written once, it hides this fiddling, and everything behind it only speaks Observable. If you use server-sent events instead of raw chunks – the same pattern, just formalized as `text/event-stream` – `EventSource` even gives you parsing and reconnecting from the browser for free.\n\n## Reconnect and backpressure as stream problems\n\nTwo topics decide whether a setup like this stays a weekend experiment or holds up in operation. Both can be phrased as stream problems, and that is the second reason RxJS pays off here.\n\nFirst, re-establishing the connection. Network connections break – the question is not whether, but how often. With `EventSource`, the browser reconnects on its own and even sends `Last-Event-ID` to say where it left off, as long as the server assigns IDs. With the raw XHR approach, you build this yourself – and instead of a loop with state variables, it becomes an operator on the stream:\n\n```js\nvar resilient = incoming.retryWhen(function (errors) {\n  return errors.delay(3000);\n});\n```\n\nThe error case is no longer a special path with its own code but part of the same declaration as the success case. If you want smarter behavior – growing wait times, giving up after n attempts – you compose it from the same building blocks instead of maintaining a state machine.\n\nSecond, backpressure. The server in the experiment writes into the response as fast as the stream delivers. What if the receiver can’t keep up – a mobile device in a dead zone, an overloaded tab? In Node, `res.write` honestly returns `false` when the kernel buffer is full; the experiment generously ignores this, and that’s exactly where the fun stops. The clean answer is again a stream answer, because RxJS comes with the tools to shape the rate before it hits the wire:\n\n- `sample` sends only the most recent state at fixed intervals – ideal for aggregations like the count here, because nobody cares about outdated intermediate states.\n- `bufferWithTime` collects messages and sends them in batches – when nothing may be lost but the frequency should drop.\n- `pausableBuffered` holds the stream until the receiver has room again – real pausing instead of dropping, for example coupled to the response’s `drain` event.\n\nWhat matters is less which of the three paths you choose than that the question has an answer in the model at all. In the callback world, “producer faster than consumer” is a cross-cutting problem that runs through the whole code. In the stream, it’s one line in the right place.\n\n## The transport becomes interchangeable\n\nNow to the real architectural gain. If the consuming side only sees an Observable, the transport is an implementation of this interface – and implementations can be swapped. The same application, tomorrow over WebSockets:\n\n```js\nvar incoming = Rx.Observable.create(function (observer) {\n  var socket = new WebSocket('ws://localhost:8765/subscribe/green');\n\n  socket.onmessage = function (event) {\n    observer.onNext(JSON.parse(event.data));\n  };\n  socket.onerror = function (error) {\n    observer.onError(error);\n  };\n\n  return function () {\n    socket.close();\n  };\n});\n```\n\nThe lines from `incoming.map(...)` on stay unchanged, as does `retryWhen` and everything built on it. Long polling fits into the same frame: a request that responds when a message arrives, chained into an endless stream with `flatMap` and repetition. Switching the transport is then a local change in one file – not open-heart surgery on the application.\n\n```mermaid\nflowchart LR\n  LP[Long polling] --> OBS[Observable<br/>shared interface]\n  SSE[Server-Sent Events] --> OBS\n  CH[chunked HTTP] --> OBS\n  WS[WebSocket] --> OBS\n  OBS --> APP[Application code<br/>map / filter / scan / retryWhen]\n```\n\nAt this point I noticed that the “WebSockets vs. HTTP” discussion in teams is often so tough because it’s treated as a one-way street – as if the decision had to hold forever. Once the transport sits behind an observable, it loses that weight. You can start with the least demanding transport that meets the requirement and move later when measurements call for it.\n\n## When plain HTTP is enough\n\nThat leaves the honest trade-off. After this experiment, I would choose ordinary HTTP – chunked or as server-sent events – wherever three conditions come together:\n\n- The messages flow overwhelmingly from the server to the browser; the other direction consists of occasional commands, for which a POST is perfectly sufficient.\n- Latencies of a few hundred milliseconds don’t bother anyone – dashboards, notifications, progress indicators, feeds.\n- The existing HTTP infrastructure – proxies, auth, logging, debugging with curl – should keep working without detours.\n\nWebSockets earn their place where these conditions break down: real bidirectional traffic with many small messages in both directions, collaborative editing, games, anything with a noticeable latency requirement. Then one POST per message no longer holds up, and switching protocols pays off. One drawback on the HTTP side belongs on the table too: browsers cap the number of concurrent connections per host, six is common – if you open many streams in parallel, you have to multiplex them into one on the server side. HTTP/2 has been an approved RFC since May and will ease exactly this problem, but in everyday browser use it isn’t yet something you can plan with today.\n\nAnd of course the experiment remains an experiment: no authentication, no persistence, no message IDs for gap-free catching up after a reconnect, and a message space that exists exactly as long as the one Node process. If you need more, you attach a real source to the Subject – a queue, a log – and that’s exactly what that spot is already prepared for.\n\n## Bottom line\n\nThe value of this small server doesn’t lie in the transport trick with chunked responses – that existed long before RxJS. It lies in both sides speaking the same abstraction. On the server, the simulation, the POST input and the aggregation are observables that can be composed with `merge` and `scan`; in the browser, the incoming message stream is an observable that `map`, `distinctUntilChanged` and `retryWhen` work on. Connection loss, retries, rate limiting, cleanup – everything that lies scattered across the file as special cases in callback code has a named place in the stream.\n\nES2015 was approved a few weeks ago, and much of the code above will get prettier with arrow functions. That doesn’t change the core: the decision to model incoming messages as a stream and hide the transport behind it is independent of syntax and, by the way, of RxJS itself – it would work with any Observable implementation. So what I take away from the experiment is less a library recommendation than an order of steps: first define the message model as a stream, then choose the least demanding transport that meets the requirement – and keep the freedom to switch it when reality calls for it.\n\n## Further reading\n\n- [MikeBild/web-messaging](https://github.com/MikeBild/web-messaging) – the experiment discussed here: message routing and event streams over HTTP with chunked transfer encoding\n- [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) – the Reactive Extensions for JavaScript with documentation of all operators\n- [Server-sent events (MDN)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) – `EventSource` and the `text/event-stream` format\n- [ReactiveX: Introduction](https://reactivex.io/intro.html) – the Observable model and the idea of operators explained across languages"},{"locale":"en","translation_key":"funktionale-stile-im-alltag","slug":"functional-styles-in-everyday-code","title":"Functional Styles in Everyday Code","summary":"Why functional style in everyday team work in 2015 does not mean Haskell, but the discipline of separating pure functions from I/O – and how ES2015 finally makes that convenient.","tags":["Software","Architecture"],"published_at":"2015-07-12T10:00:00+00:00","updated_at":"2026-07-14T16:49:16.61261+00:00","url":"https://www.mikebild.dev/en/blog/functional-styles-in-everyday-code/","audio_url":null,"audio_duration_secs":null,"text":"# Functional Styles in Everyday Code\n\nWhen business logic and side effects sit unseparated in the same function body, there is a very concrete consequence: every test needs a database. If you want to check whether an invoice counts as overdue, you first have to load test data, replace a mailer with a stand-in and clean everything up afterwards. The test suite runs for minutes instead of seconds, so it runs less often, so nobody dares to touch exactly the places that most urgently need a change. That is not a tooling problem and not a framework problem – it is a style problem.\n\nMany colleagues still regard functional programming as an academic affair: Haskell, monads, type theory. What I mean by it in everyday project work is much more modest and at the same time more effective: pure functions as the standard building block, data flow instead of state mutation, `map`/`filter`/`reduce` instead of loop bodies with side effects. No new language, no new runtime – a discipline in the language that is already in use.\n\n## Pure functions as the standard building block\n\nA pure function is quickly explained: same input, same output, no observable side effect. It does not read the clock, does not write to the database, does not change any variables outside its body. That sounds trivial, but in code that has grown over time it is the exception. More typical is a function that loads data, filters it, converts it, saves it and sends an email on the side – five responsibilities in thirty lines.\n\nAt the beginning of the year, I forked Crista Lopes’ collection [exercises-in-programming-style](https://github.com/MikeBild/exercises-in-programming-style): the same small task – a word frequency analysis – in dozens of programming styles, each style its own folder with program and description. While working through it, I noticed something that had not been that clear to me before: style is a decision, not a language feature. The same task can be written in Python monolithically, object-oriented or as a pipeline of pure functions. The language prevents none of it and enforces none of it. The same is true for JavaScript and C#.\n\nThe discipline lies in making the pure function the normal case. Not: “Where could I sprinkle in something functional?” but the other way around: every function is pure until there is a reason against it. And the reasons against it – I/O, time, randomness, DOM, database – then gather in a few named places instead of everywhere.\n\n## What ES2015 changes about this\n\nECMAScript 2015 has been ratified since June – the [specification](https://262.ecma-international.org/6.0/) is final, and Babel 5 already compiles the new standard down to ES5 today. Node 0.12 and io.js support parts of it natively; for the rest, the transpiler stays in the build. For the functional style this is more than cosmetics, because three new features lower exactly the writing costs this style used to founder on:\n\n- Arrow functions make small functions so cheap that you actually write them – `x => x.amount` instead of a four-line `function` block with `return`.\n- `const` documents in the code that a binding is not reassigned – the reading direction flips: mutation becomes the marked exception.\n- Destructuring takes data structures apart without helper variables, which is what makes functions over plain objects pleasant in the first place.\n\nThe transpiler is an honest extra cost item: the build gets one step longer, source maps have to be right, and if you debug in the browser, you occasionally look at generated ES5 code instead of what you wrote. In our case it was worth the trade – but it belongs on the table before the team agrees, not after.\n\nBefore, functional style in JavaScript was possible but syntactically expensive. A `function (invoice) { return !invoice.paid; }` at every filter call is tiring, and what is tiring does not get done. With arrow functions the balance tips: the compact form is now also the disciplined form. In an ongoing project, I saw how the switch to Babel alone multiplied the number of small helper functions in the team – not because anyone ordered it, but because it was suddenly the most convenient way.\n\n## From loop body to data pipeline\n\nThe difference becomes concrete in a piece of code like the one found in every back-office system: from a list of invoices, find the overdue ones, create reminders and calculate the open amount. The common form looks like this:\n\n```js\nfunction processInvoices(invoices, db, mailer) {\n  let total = 0;\n  for (let i = 0; i < invoices.length; i++) {\n    const invoice = invoices[i];\n    if (!invoice.paid && invoice.dueDate < Date.now()) {\n      total += invoice.amount;\n      db.markAsOverdue(invoice.id);\n      mailer.sendReminder(invoice.customerEmail, invoice.amount);\n    }\n  }\n  return total;\n}\n```\n\nThe code works, and that is exactly what makes it long-lived – nobody touches a function that has been quietly doing its job for two years. Still, the loop body mixes four things: the business rule (when is an invoice overdue?), the aggregation (sum), the database access and the mail delivery. On top of that, the function secretly reads the clock with `Date.now()` – the same call returns a different result at midnight than at 23:59. It can only be tested with a real database, a real mailer replacement and frozen time.\n\nThe same logic as a data flow, with ES2015:\n\n```js\nconst isOverdue = (today) => (invoice) =>\n  !invoice.paid && invoice.dueDate < today;\n\nconst toReminder = (invoice) => ({\n  invoiceId: invoice.id,\n  email: invoice.customerEmail,\n  amount: invoice.amount\n});\n\nconst totalAmount = (invoices) =>\n  invoices.reduce((sum, { amount }) => sum + amount, 0);\n\nconst overdueReminders = (today, invoices) => {\n  const overdue = invoices.filter(isOverdue(today));\n  return {\n    reminders: overdue.map(toReminder),\n    total: totalAmount(overdue)\n  };\n};\n```\n\nFour pure functions. Time comes in as a parameter instead of from the clock, the business rule stands isolated in `isOverdue`, and `overdueReminders` only describes what should become of the data – not how a loop variable gets incremented. The test for it is an array literal and an equality check, no database anywhere in sight. And whoever reads the code in half a year sees the rule at a glance instead of dissecting it out of a loop body.\n\n## The impure edge\n\nThe honest limit belongs here too: `db.markAsOverdue` and `mailer.sendReminder` have not disappeared. I/O, DOM and database stay impure – an application that reads nothing and writes nothing is useless. The point is not to forbid side effects, but to push them to the edge, where they are visible and thin.\n\n```mermaid\nflowchart LR\n  DB[(Database)] -->|load invoices| Edge[Impure edge<br/>I/O, clock, mailer]\n  Edge -->|data in| Core[Pure core<br/>isOverdue, toReminder,<br/>totalAmount]\n  Core -->|result out| Edge\n  Edge -->|send reminders| Mail[Mail server]\n```\n\nAt the edge, the code then looks like this – with ES2015, promises are part of the language:\n\n```js\nconst today = Date.now();\n\ndb.loadInvoices()\n  .then((invoices) => overdueReminders(today, invoices))\n  .then(({ reminders, total }) => {\n    reminders.forEach((reminder) => mailer.sendReminder(reminder));\n    log.info(`sent ${reminders.length} reminders, open amount: ${total}`);\n  });\n```\n\nThis edge is deliberately boring: load, call the pure function, write the result away. It is hardly ever tested on its own because it contains hardly any logic – the logic lives in the core, and the core knows neither database nor mailer. In one project, after exactly this split, we cut the integration tests down from half an hour to a handful of edge cases; everything domain-related ran as a plain unit test in seconds.\n\n## The view from the .NET world\n\nIf this looks like a JavaScript fad to you, a look at the .NET world, where I also come from, helps. There, the same idea has been called LINQ for years and no longer upsets anyone:\n\n```csharp\nvar overdue = invoices\n    .Where(invoice => !invoice.Paid && invoice.DueDate < today)\n    .ToList();\n\nvar reminders = overdue.Select(invoice => new Reminder\n{\n    InvoiceId = invoice.Id,\n    Email = invoice.CustomerEmail,\n    Amount = invoice.Amount\n});\n\nvar total = overdue.Sum(invoice => invoice.Amount);\n```\n\n`Where`, `Select`, `Sum` – those are `filter`, `map` and a specialized `reduce`. In C# teams, everyone has been writing this for years without calling it functional programming; it is simply the normal way to work with collections. If you bring a `foreach` loop with a running total into a review there, you get asked why it is not LINQ. This observation takes the ideology out of the topic: it is not about a camp, but about a form of expression that established itself long ago in a very pragmatic environment – JavaScript is catching up with ES2015 right now.\n\n## Underscore, Lodash, Ramda\n\nFor the gaps in the standard library, there are toolboxes. Underscore was the default for years, and Lodash has practically replaced it with version 3 – same idea, more functions, and since Lodash 3 chained calls are evaluated lazily, so long chains do not have to create an intermediate array at every step. [Ramda](https://ramdajs.com/) has gone one step further for a good year now: all functions are automatically curried, and the data comes as the last argument, so processing steps can be plugged together into new functions:\n\n```js\nconst openAmountOf = R.pipe(\n  R.filter(isOverdue(today)),\n  R.map(R.prop('amount')),\n  R.sum\n);\n\nconst total = openAmountOf(invoices);\n```\n\n`openAmountOf` is a named, reusable pipeline – not a call but a definition. That is elegant, and this is exactly where the friction begins.\n\n## Where it chafes in the team\n\nThe functional style has real costs in everyday team work, and if you keep quiet about them, you rightly lose the skeptics. Three points come up for me regularly:\n\n- Debugging chains is more tedious than debugging a loop. In a `for` body you set a breakpoint and see all local variables; in a `pipe` chain of anonymous functions, the stack trace shows cryptic names, and to look at intermediate values you have to break up the chain or insert a `tap` function.\n- Point-free style quickly tips over into an end in itself. A trained eye reads `R.pipe(R.filter(...), R.map(R.prop('amount')), R.sum)` fluently – three more levels of composition later nobody can read it anymore, not even the author. In reviews, one simple question has proven itself for us: can the colleague at the next desk read the line aloud without explanation and say what it does?\n- The performance argument comes reliably and is mostly a myth. Yes, `filter` and `map` create intermediate arrays, and a hand-written loop is faster on a million elements. But very few places in the code process a million elements – they process thirty invoices, and the real bottleneck is the database call next to them. Measure first, then optimize; the two hot paths that are really affected can happily stay a commented loop.\n\nThere is also a social component: a team in which two people love Ramda and five cannot read it has gained nothing from the style. The common denominator – `map`, `filter`, `reduce`, pure functions, a thin edge – carries further than perfect composition. The library is negotiable, the discipline is not.\n\n## Outlook: streams\n\nOnce you have internalized the separation of core and edge, you find the next step almost by yourself. [RxJS](https://github.com/Reactive-Extensions/RxJS) treats events – clicks, WebSocket messages, timers – as collections over time, with the same vocabulary: `map`, `filter`, `reduce` or `scan` on streams instead of arrays. The pure functions from the core can be used unchanged; only the impure edge then speaks observables instead of promises. For UIs with many concurrent event sources that is a noticeable gain – but that is a separate article.\n\n## The bottom line\n\nTo me, functional programming in the everyday work of 2015 does not mean switching languages or putting category theory on the team. It means cultivating three habits: functions are pure until there is a reason against it. Data flows through `map`, `filter` and `reduce` instead of being mutated in loop bodies. And everything impure – clock, database, DOM, network – is gathered at a thin, boring edge. ES2015 makes these habits truly convenient for the first time, LINQ has shown for years that they are fit for the mainstream, and the test suite thanks you right away: the part of the system where bugs hurt suddenly no longer needs a database. Nobody has to learn Haskell for that – you just have to stay consistent when the next loop with a running total shows up in a review.\n\n## Further reading\n\n- [exercises-in-programming-style](https://github.com/MikeBild/exercises-in-programming-style) – my fork of Crista Lopes’ style collection: one task, dozens of styles\n- [ECMAScript 2015 Language Specification](https://262.ecma-international.org/6.0/) – the freshly ratified standard\n- [Array.prototype.reduce (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) – the most underrated of the three core functions\n- [Ramda](https://ramdajs.com/) – functional library with currying and a data-last convention\n- [RxJS](https://github.com/Reactive-Extensions/RxJS) – Reactive Extensions for JavaScript, the same style on event streams"},{"locale":"en","translation_key":"container-sind-keine-architektur","slug":"containers-are-not-architecture","title":"Containers Are Not Architecture","summary":"Docker makes system boundaries visible and portable – you still have to draw them by hand, and a monolith remains a monolith inside a container.","tags":["Software","Platform"],"published_at":"2015-06-12T10:00:00+00:00","updated_at":"2026-07-14T16:47:25.291379+00:00","url":"https://www.mikebild.dev/en/blog/containers-are-not-architecture/","audio_url":null,"audio_duration_secs":null,"text":"# Containers Are Not Architecture\n\nA badly cut monolith doesn’t get better when you put it in a container. It stays the same monolith – the same tangled dependencies, the same shared database, the same deployment where everything goes out at once. The only new thing is the Dockerfile on top. Still, the same equation is being heard everywhere right now, at conferences as well as in project meetings: we’re introducing Docker, so now we’re doing microservices. At first, the one has nothing to do with the other. Docker packages software. It doesn’t design it.\n\nThe mix-up isn’t a coincidence, and it isn’t stupid either. It has a reason, and that reason is worth a look – just like the question of what containers actually do. Because that’s quite a lot. It’s just something other than architecture.\n\n## Why the equation works so well\n\nBoth topics grew big at the same time. Docker is at version 1.6, 1.7 is in the works, DockerCon in San Francisco starts in a week and a half, and after the months-long public dispute between Docker and CoreOS over the “right” container format, an initiative for an open, vendor-neutral standard is taking shape right now. Orchestration is a jungle: Mesos on one side, Docker’s own Swarm on the other, and Google is working on Kubernetes, which hasn’t reached version 1.0 yet. At the same time, the text by James Lewis and Martin Fowler about microservices has been the reference point of every architecture discussion for a good year.\n\nBoth waves carry the same vocabulary before them: small, independent units, isolated, individually deployable. But if you put the texts side by side, you see the gap immediately. Lewis and Fowler talk about domain boundaries, about teams, about data ownership. The Docker documentation talks about images, layers and processes. That a container is an “independent unit” holds true for the process and its file system – not for the domain logic inside it. A container doesn’t know whether a cleanly cut service runs inside it or a mountain of twelve years of organically grown code. It doesn’t care either.\n\nThe equation works because it’s convenient. You can write a Dockerfile in an afternoon. You don’t get a module split that two teams no longer argue about in an afternoon – that takes weeks of conversations about data, responsibilities and interfaces, and at the end there is no tool to show off, just a system that is easier to change. When both sail under the same buzzword, the afternoon wins. After all, only one of the two is something you can show off.\n\n## What a container really does\n\nAt the beginning of the year, I packaged a small .NET API in a container: Nancy as the web framework, self-hosted, LiteDB as a file database, the whole thing on Mono so it runs on Linux. Not a customer project, an experiment – I wanted to know whether the path from Windows-centric .NET code to a Linux container can be walked without major contortions. It can. The Dockerfile was sobering in how unspectacular it was:\n\n```dockerfile\nFROM mono:3.12\n\nCOPY . /app\nWORKDIR /app\n\nRUN nuget restore shop-api.sln && \\\n    xbuild /p:Configuration=Release shop-api.sln\n\nEXPOSE 8080\nCMD [\"mono\", \"src/ShopApi/bin/Release/ShopApi.exe\"]\n```\n\nExactly this lack of spectacle is the point. Everything the service needs to run is in thirteen lines: the runtime including its version, the build path, the port, the one command that starts the process. Before, this knowledge was scattered across a wiki page (“Set up the development environment, 14 steps”), the heads of two colleagues and the configuration of a build server that nobody wanted to touch anymore. Now it’s in the repository, versioned with the code and read in reviews.\n\nThat’s the honest benefit of containers, and it’s considerable:\n\n- The same environment on the laptop, in CI and on the server – “works on my machine” loses its terror.\n- An explicit entry point: exactly one command starts the process, and nothing depends on a logged-in user or a terminal session.\n- Dependencies live in the image instead of the wiki – if you want to know what the service needs, you read the Dockerfile, not the memory of the most senior colleague.\n- An artifact that can be moved unchanged from environment to environment instead of being rebuilt on every machine.\n\nNote what doesn’t appear in this list: domain boundaries, data ownership, independent releases. The Dockerfile above doesn’t reveal whether `ShopApi.exe` is a focused service or a colossus. It builds both without complaint.\n\n## The monolith just moves house\n\nHow little the packaging changes the content becomes clear as soon as you containerize a real monolith. Let’s take a shop of the kind that exists countless times: orders, invoices and catalog in one solution, a shared database, one deployment. With Docker Compose, the local environment for it is quickly described:\n\n```yaml\nshop-api:\n  build: .\n  ports:\n    - \"8080:8080\"\n  links:\n    - shop-db\nshop-db:\n  image: postgres:9.4\n  environment:\n    POSTGRES_DB: shop\n```\n\nThis file is useful – everyone on the team starts the current state with one command. But above all, it’s one thing: honest. It documents in black and white that there is exactly one deployable unit and one database that all parts write into. If you change a line in the billing code, you still build and deploy the entire shop. If you migrate the order schema, you still hold your breath, because the catalog sits on the same tables. The release cadence, the coupling, the fear of the migration – all unchanged.\n\n```mermaid\nflowchart LR\n  subgraph before[\"Before\"]\n    M1[\"Monolith<br/>Orders + Billing + Catalog\"] --> D1[(\"one database\")]\n  end\n  subgraph after[\"After – with Docker\"]\n    M2[\"Container<br/>Monolith<br/>Orders + Billing + Catalog\"] --> D2[(\"one database\")]\n  end\n  before -. \"docker build\" .-> after\n```\n\nThe diagram is deliberately boring. The same system stands on the left and on the right. The container has made the structure visible and portable – it hasn’t created a new one. And visibility is no small thing. But it’s often confused with change, the way a moving box is confused with tidying up. Only when you pack it do you see what has piled up. Nothing has been thrown away yet.\n\n## Making boundaries visible isn’t drawing boundaries\n\nThe actual work is called the module split, and it happens before any Dockerfile. Three questions decide whether a split holds. Who owns which data – who may change the order tables, and who only gets to see them through an interface? What does the contract between the parts look like – which calls are allowed, and how stable do they stay when something changes inside? And: what can be shipped independently without two teams having to align their calendars?\n\nNone of this needs Docker. A clean split can be drawn in the middle of the monolith, in the same solution, in the same process. Between the orders module and the billing module there is then a deliberately narrow contract:\n\n```csharp\n// the only allowed path from Orders into Billing –\n// no shared tables, no reaching into internals\npublic interface IBillingService\n{\n    Invoice CreateInvoice(OrderId orderId, Money total);\n}\n```\n\nThe more uncomfortable half belongs to it as well: `Orders` writes exclusively into its own tables, `Billing` into its own. No join across the module boundary, not even “just for the report.” Once this discipline has held for a while, the rest is mechanics. Then – and only then – the module becomes its own container if needed, and the Compose file suddenly looks like what Lewis and Fowler describe:\n\n```yaml\norders:\n  build: ./orders\n  ports:\n    - \"8080:8080\"\n  links:\n    - orders-db\n    - billing\norders-db:\n  image: postgres:9.4\nbilling:\n  build: ./billing\n  links:\n    - billing-db\nbilling-db:\n  image: postgres:9.4\n```\n\nThe crux: this file is the result of the design work, not a replacement for it. If you write it down without having carried out the split in the code and in the data first, you get two containers reaching into each other’s database – the same monolith, now with network latency in between. That’s the most expensive variant of a monolith I know: distributed but not decoupled. Every orchestration tool, whether Mesos, Swarm or soon Kubernetes, only multiplies this state. It distributes what you give it. If you give it a tangled split, it distributes tangles.\n\n```mermaid\nflowchart LR\n  subgraph om[\"Orders module\"]\n    O[\"orders\"] --> ODB[(\"orders-db\")]\n  end\n  subgraph bm[\"Billing module\"]\n    B[\"billing\"] --> BDB[(\"billing-db\")]\n  end\n  O -- \"Contract:<br/>CreateInvoice(orderId, total)\" --> B\n```\n\nThis picture is the difference. The boxes aren’t what’s interesting, but the arrows that are missing: no arrow from `orders` to `billing-db`, no back channel bypassing the interface. No tool draws these missing arrows for you. You have to earn them, against the resistance of day-to-day business, which always has a good reason for that one small shortcut.\n\n## The container as a touchstone\n\nIf containers help with design at all, then as a touchstone. In the Mono experiment, I noticed that the most unpleasant question wasn’t “How do I build the image?” but “What goes into it?” The service pulled configuration from three sources, expected a network drive and wrote logs to a hard-wired path. None of this had been a problem before, because the machine it ran on silently provided all of it. The container provides nothing silently. It forces you to either write every assumption into the image or bring it to the surface as an environment variable. Each of these assumptions was essentially an invisible coupling – to a machine, to a department, to a piece of operations folklore that was written down nowhere.\n\nThat’s the same kind of pressure a good module split exerts, just one level deeper. If you can’t say for a service what belongs in its image and what comes from outside, you don’t know the boundaries of that service – and shouldn’t be talking about microservices yet. In that sense, containerizing the monolith is a perfectly good first step: not because it’s architecture, but because it forces the inventory without which no later split succeeds. You learn more about your system along the way than you’d like.\n\nYou should just treat the step as what it is. A containerized monolith is a completely legitimate state – built reproducibly, started the same way everywhere, with documented dependencies. For many systems, that’s enough for years to come. If, on the other hand, you sell it as “microservices migration, phase one,” you have put a promise out into the world that the packaging can’t keep.\n\n## What I take away from this\n\nFor me, an order has emerged that holds up in discussions: first containerize the monolith and take the operational benefits – the same environment everywhere, an explicit process entry point, dependencies in the image. In parallel, draw the boundaries in the code where they cost nothing: modules, separate tables, narrow contracts like the `IBillingService` example above. And only when a boundary has stayed stable over several releases and there is a concrete reason – a different release cadence, a different load, a different team – does the module become its own service with its own container.\n\nAlong this path, Docker does two things excellently: it transports the units you have cut, and it ruthlessly exposes where you haven’t cut at all yet. Both are valuable. Neither of them is design. The standardization now emerging around the container format will make packaging even more of a given – which makes it all the more important not to confuse it with the content. A Dockerfile answers the question of how a process starts. If you want to answer the question of where one system ends and the next begins, you’re still sitting in front of a whiteboard, not a YAML file.\n\n## Further reading\n\n- [MikeBild/dotnet-docker on GitHub](https://github.com/MikeBild/dotnet-docker) – the experiment mentioned above: Nancy, self-hosting and LiteDB on Mono in a container\n- [Microservices – James Lewis and Martin Fowler](https://martinfowler.com/articles/microservices.html) – the reference text on domain boundaries, data ownership and independent delivery\n- [Dockerfile reference](https://docs.docker.com/reference/dockerfile/) – the official description of all build instructions\n- [Docker Compose documentation](https://docs.docker.com/compose/) – basics of describing several services in one file"},{"locale":"en","translation_key":"programming-styles-architekturvergleich","slug":"programming-styles-as-an-architecture-comparison","title":"Programming Styles as an Architecture Comparison","summary":"The same small task solved in dozens of programming styles is the most compact architecture comparison I know – because every style is a deliberately chosen set of constraints.","tags":["Software","Architecture"],"published_at":"2015-05-24T10:00:00+00:00","updated_at":"2026-07-14T16:44:07.688862+00:00","url":"https://www.mikebild.dev/en/blog/programming-styles-as-an-architecture-comparison/","audio_url":null,"audio_duration_secs":null,"text":"# Programming Styles as an Architecture Comparison\n\nA programming style is not a matter of taste. At least not in the sense that Cristina Videira Lopes gives the word in her book “Exercises in Programming Style” (2014): there, a style is a set of rules that determine which means are allowed and which are forbidden. No global variables. Only functions that leave their input unchanged. No direct calls between components. When you write in a style, you submit to a set of constraints – and it is exactly these constraints that produce the properties of the program, not a personal preference for indentation or naming.\n\nThe book takes this idea to the extreme with a device that Lopes borrowed from Raymond Queneau. In “Exercices de style” (1947), Queneau tells the same trivial everyday scene in 99 different ways. Lopes does the same with a program: in the first edition, a single, deliberately mundane task is solved in 33 styles. The task is word frequency counting – term frequency:\n\n- read a text file (in the repo: “Pride and Prejudice”)\n- normalize the text, that is, lowercase it and remove punctuation\n- filter out stop words such as “the” and “of”\n- count the frequency of each word\n- print the 25 most frequent words\n\nEach solution is a short Python script, all of them produce the same output, all of them run with the same command. I forked the accompanying repository in early May and worked through it style by style – not reading, but typing, changing, breaking and repairing. In doing so, I noticed something that goes beyond the book: this is not a cabinet of curiosities. It is the most compact architecture comparison I have ever come across. Because the task is trivial and constant, structure remains the only variable. You see architectural decisions in pure form, each on a single screen.\n\nI want to pick out a few of the styles and set them against each other.\n\n## Good Old Times: the absence of structure\n\nThe first style in the book simulates the conditions of early computers: barely any memory, no named abstractions, no functions – the program is a single sequence of statements that has to keep intermediate results on a simulated “hard disk”. The result is tedious to read and even more tedious to change. The related monolithic style relaxes the memory limit but still forbids any abstraction: one long procedure, nested loops, flags.\n\nWhat’s interesting about it is not the nostalgia but the honesty. The monolith is the zero point: this is what code looks like when no constraint shapes it. And it is by no means extinct – in 2014 I took over an organically grown import script in a project that followed exactly this style, only with 1,800 instead of 80 lines. It worked. It was just impossible to test, because there was no place where you could have touched it without touching everything.\n\n## Pipeline: data flow instead of a sequence of steps\n\nThe pipeline style allows only functions that take their input and return a result. No shared state, no side effects between the steps. My rebuild looks like this (Python 2.7, as in the book):\n\n```python\nimport re\nimport operator\n\ndef read_text(path):\n    with open(path) as f:\n        return f.read()\n\ndef normalize(text):\n    return re.sub('[^a-z]', ' ', text.lower())\n\ndef tokenize(text):\n    return text.split()\n\ndef remove_stop_words(words):\n    with open('stop_words.txt') as f:\n        stop_words = set(f.read().split(','))\n    return [w for w in words if w not in stop_words and len(w) > 1]\n\ndef count_frequencies(words):\n    counts = {}\n    for w in words:\n        counts[w] = counts.get(w, 0) + 1\n    return counts\n\ndef top_25(counts):\n    ordered = sorted(counts.items(), key=operator.itemgetter(1), reverse=True)\n    return ordered[:25]\n\nfor word, count in top_25(count_frequencies(remove_stop_words(\n        tokenize(normalize(read_text('pride-and-prejudice.txt')))))):\n    print word, '-', count\n```\n\nThe last line reads like a mathematical formula: the program is the composition of its steps. Each function can be tested on its own, each can be swapped out as long as the shape of the data fits. That is the architecture of every batch and ETL pipeline and every Unix pipe – except that there the functions are called processes and the return values are files or streams. The constraint “no shared state” buys testability and parallelizability and pays with the ban on remembering anything along the way.\n\n## Things: state behind doors\n\nThe “Things” style is the object-oriented answer: the problem is broken down into things – a `DataStorageManager`, a `StopWordManager`, a `WordFrequencyManager` – and each thing encapsulates its state. From outside, only methods are visible; nobody reaches into another thing’s data. The constraint is: state exists, but only behind a door, and the door has a name.\n\nOn 60 lines, this seems almost excessively solemn. But the analogy at the system level is obvious: it is the basic idea of modular systems and clean service boundaries. The question “who owns this state, and who may change it?” is the most productive question of all in every architecture review I have experienced – and this style forces you to answer it for every piece of data.\n\n## Hollywood: Don’t call us, we’ll call you\n\nFrom here on, the direction of control flips. In the Hollywood style, the program no longer calls its building blocks – a framework calls back whatever registered beforehand:\n\n```python\nclass WordFrequencyFramework:\n    def __init__(self):\n        self._load_handlers = []\n        self._work_handlers = []\n        self._end_handlers = []\n\n    def register_for_load(self, handler):\n        self._load_handlers.append(handler)\n\n    def register_for_work(self, handler):\n        self._work_handlers.append(handler)\n\n    def register_for_end(self, handler):\n        self._end_handlers.append(handler)\n\n    def run(self, path):\n        for handler in self._load_handlers:\n            handler(path)\n        for handler in self._work_handlers:\n            handler()\n        for handler in self._end_handlers:\n            handler()\n```\n\nThe domain parts – reading, filtering, counting – register with the framework and wait. The flow belongs to the framework, no longer to the application. This is Inversion of Control in its barest form, and it is the construction principle of practically every web framework and every plugin architecture: you no longer write a main loop; you fill gaps that someone else has provided.\n\nIf you write a lot of JavaScript, you know this feeling from every Node program – there, the callback is not a style exercise but everyday life, with all the consequences for the readability of the control flow. I once wrote down [how to tame control flow before async/await](https://www.mikebild.dev/en/blog/control-flow-before-async-await/). The style exercise makes visible what you trade in the process: flexibility for the framework, traceability for the reader. If you want to know when `count_frequencies` runs, you have to understand the framework, not the domain logic.\n\n## Bulletin Board: the notice board\n\nThe bulletin board style decouples one level further. Components no longer call each other at all, not even through registration with the framework – they publish events to a notice board, and whoever has signed up for an event type gets notified:\n\n```python\nclass EventManager:\n    def __init__(self):\n        self._subscriptions = {}\n\n    def subscribe(self, event_type, handler):\n        self._subscriptions.setdefault(event_type, []).append(handler)\n\n    def publish(self, event):\n        event_type = event[0]\n        for handler in self._subscriptions.get(event_type, []):\n            handler(event)\n```\n\nThe counter subscribes to `word`, the filter subscribes to `valid_word`, the output subscribes to `print` – and nobody knows anybody. That is publish/subscribe in 15 lines, the pattern behind every message broker and every event-driven integration. The constraint “no direct calls” buys maximum decoupling: you can add participants without changing existing ones. The price is losing the visible flow. While working through the exercises, this style was the first for which I needed the debugger – with 80 lines. You have exactly the same experience later at large scale, when you chase a message through an event-driven system.\n\n## The One: the value in a container\n\nThe style with the nicest name is a monad light: a value is put into a container, and the container knows how to apply functions to its content one after another.\n\n```python\nclass TheOne:\n    def __init__(self, value):\n        self._value = value\n\n    def bind(self, func):\n        self._value = func(self._value)\n        return self\n\nTheOne('pride-and-prejudice.txt') \\\n    .bind(read_text) \\\n    .bind(normalize) \\\n    .bind(tokenize) \\\n    .bind(remove_stop_words) \\\n    .bind(count_frequencies) \\\n    .bind(top_25) \\\n    .bind(print_all)\n```\n\nIn terms of content, this is the same chain as in the pipeline style – but the chaining itself is now a building block you can extend: with logging at every step, with error handling, with deferred execution. If you have worked with promise libraries in ES5 JavaScript, you recognize the pattern immediately: `then` is a `bind` that also encapsulates asynchrony along the way. The constraint “everything flows through a container” buys a place where cross-cutting concerns are allowed to live.\n\n## Six styles, six architectures\n\nLaid side by side, the exercises yield a mapping that I have kept in my head ever since:\n\n```mermaid\nflowchart LR\n    A[Monolith<br/>no abstraction allowed] --> A2[grown scripts,<br/>legacy procedures]\n    B[Pipeline<br/>only pure functions] --> B2[batch, ETL,<br/>Unix pipes]\n    C[Things<br/>state only behind methods] --> C2[modules,<br/>service boundaries]\n    D[Hollywood<br/>framework calls back] --> D2[frameworks,<br/>plugin systems]\n    E[Bulletin Board<br/>only events, no calls] --> E2[message brokers,<br/>integration]\n    F[The One<br/>everything through one container] --> F2[fluent APIs,<br/>promise chains]\n```\n\nEach of these architectures at large scale is a programming style at small scale – the same set of constraints, only at the process level instead of the function level. And at both scales, the properties you want come from what you forbid yourself. Testability comes from forbidding shared state. Extensibility comes from forbidding direct calls. Traceability comes from forbidding hidden control flows. None of this comes for free; every constraint has its price, and the exercises make you feel the price on a single screen instead of presenting it only after two years in production.\n\n## The unconscious mix of styles\n\nThe most important insight for me, though, didn’t come from any of the styles but from the contrast with my own everyday code. Like most code out there, presumably, it is a mix of styles: a bit object-oriented, because the language suggests it; a few pure functions where it was convenient; a global cache, because it had to be quick; callbacks, because the framework demands them. None of this is wrong in itself. The problem is that the mix arises unconsciously. Nobody decided that this module follows the pipeline idea and that one the notice board – it just happened, commit by commit.\n\nFor me, this is exactly the difference between code that has structure and code that only looks structured. Architecture is the art of choosing constraints deliberately – and then sticking to them even where they are inconvenient at the moment. A constraint you give up as soon as it pinches never was one; it was a habit. Since working through the exercises, I occasionally ask a new question in code reviews: which style are we actually in here? Not as a trick question, but because the answer immediately shows whether a rule the team set for itself was broken – or whether the rule never existed and we should make up for it now.\n\nThe view also helps in the opposite direction. When a module is hard to test, the question is not “which test tool is missing?” but “which constraint is missing?”. Usually it is the same one that the pipeline style enforces and organically grown code ignores.\n\n## What I take away from this\n\nCounting word frequencies is the most boring task in the world, and that is exactly what makes it the ideal test bench: if the task stays constant, everything that differs between two solutions is structure – and therefore comparable. You can discuss architectural styles by dissecting systems with years of history. Or you compare 33 scripts of 80 lines each that all do the same thing, and see the same forces at work, only without the fog.\n\nThere are a few concrete things I take away:\n\n- Judge styles not by sympathy but by the question of which property their constraints buy and what they cost.\n- When reading someone else’s code, identify the style first – afterwards, much of what previously looked arbitrary explains itself.\n- Occasionally make your own mix of styles explicit: which rules apply in this module, and are they written down anywhere?\n\nIf you don’t have the book at hand: the repository alone already gets you far. Fork it, rebuild one style per evening, deliberately violate the constraints along the way and watch what breaks. I have learned more about architecture from these evenings than from many a thick design patterns tome – precisely because not a single UML diagram appeared, only the question: what do you forbid yourself, and what do you get in return?\n\n## Further reading\n\n- My fork with the exercises I worked through: https://github.com/MikeBild/exercises-in-programming-style\n- The original repository by Cristina Videira Lopes: https://github.com/crista/exercises-in-programming-style\n- Raymond Queneau’s literary model “Exercises in Style”: https://en.wikipedia.org/wiki/Exercises_in_Style\n- Python 2 documentation on `collections` (including `Counter` for frequency counting): https://docs.python.org/2/library/collections.html"},{"locale":"en","translation_key":"docker-fuer-dotnet","slug":"docker-for-dotnet-before-it-was-normal","title":"Docker for .NET, Before It Was Normal","summary":"Packing a small Nancy API under Mono into a Docker container was a detour via Linux in the spring of 2015 – and it taught me more about .NET deployment than any IIS manual.","tags":["Software","Platform"],"published_at":"2015-04-24T10:00:00+00:00","updated_at":"2026-07-14T17:05:06.200176+00:00","url":"https://www.mikebild.dev/en/blog/docker-for-dotnet-before-it-was-normal/","audio_url":null,"audio_duration_secs":null,"text":"# Docker for .NET, Before It Was Normal\n\nA good 400 megabytes. That is what `docker images` reports for an image whose actual application is a single compiled file of a few kilobytes – a small HTTP API written in C#. The number seems absurd, and it is. But the more interesting measurement is a different one: `docker start demo1` takes under a second, and then the service responds. A comparable deployment on a Windows server with IIS regularly cost me half an afternoon in projects – check the framework version, create an app pool, set permissions, copy files, pray.\n\nThese two numbers side by side – 400 megabytes of space versus one second to start – describe pretty precisely what you get into when you put .NET code into a Docker container in the spring of 2015. You trade disk space for repeatability. I think that is a good trade, and I want to explain why.\n\n## Spring 2015: .NET officially means Windows\n\nWhoever says “.NET” today practically always means Windows, IIS and the Microsoft stack from top to bottom. Docker, on the other hand, is a Linux topic: Docker 1.6 has just been released, on the Mac the Docker daemon runs in a small VirtualBox VM called boot2docker, and Compose has only just emerged from Fig. The two worlds barely touch.\n\nThe picture isn’t entirely accurate anymore, though. In November, Microsoft announced that it would develop .NET Core as open source; since February, the CoreCLR has been on GitHub, and the upcoming ASP.NET 5 is explicitly meant to run on Linux and OS X as well. That is a remarkable turn – but in April 2015, it is an announcement with early betas, not a foundation. If you want to run .NET code in a Linux container today, you end up with Mono, the free runtime that has existed for more than ten years and now covers a surprising amount of the .NET Framework.\n\nThat is exactly what I wanted to try. Not because a project demanded it, but because the question wouldn’t let go of me: How much of the usual .NET deployment ritual is actually necessary – and how much of it is just habit tied to IIS? One weekend, one repository, a deliberately small service. If the experiment fails, little is lost; if it holds up, I know something that no blog article by others can replace.\n\n## The attempt: a Nancy API in a container\n\nThe result is a repository called `dotnet-docker` on GitHub: a small HTTP API with the Nancy framework, self-hosted via `Nancy.Hosting.Self`, with LiteDB as an embedded database. No IIS, no Windows service, no installation – a process that opens a port. The README calls it a “Docker + DotNet Microservice”, and it is as small as that sounds: one module, two serious endpoints, one database file.\n\nThe heart of it is the Dockerfile. It describes completely what this application needs to run – in a way that leaves no silent assumption behind:\n\n```dockerfile\nFROM mono:3.10\n\n# Update SSL certs\nRUN mozroots --import --sync\n\n# Copy source files\nADD src ./src\nWORKDIR /src\n\n# Install dependencies via NuGet\nRUN mono /src/NuGet.exe install Nancy\nRUN cp /src/Nancy.1.1/lib/net40/Nancy.dll /src\n\nRUN mono /src/NuGet.exe install Nancy.Hosting.Self\nRUN cp /src/Nancy.Hosting.Self.1.1/lib/net40/Nancy.Hosting.Self.dll /src\n\nRUN mono /src/NuGet.exe install LiteDB\nRUN cp /src/LiteDB.1.0.0/lib/net40/LiteDB.dll /src\n\n# Compile the web service\nRUN mcs nancy.cs modules/webhooks.cs \\\n    -reference:Nancy.dll \\\n    -reference:Nancy.Hosting.Self.dll \\\n    -reference:LiteDB.dll\nEXPOSE 8080\n\n# Run the web service\nCMD [\"mono\", \"/src/nancy.exe\"]\n```\n\nYou can tell the era from the Dockerfile, and that is intentional. There is no official Microsoft image, so everything starts on `mono:3.10`. There is no built-in package management in the build, so `NuGet.exe` sits in the repository and is called via `mono`. And because NuGet puts the packages into version folders, the DLLs are then copied by hand to the place where the compiler expects them. Compilation happens with `mcs`, the Mono C# compiler, directly in the image – no Visual Studio, no MSBuild project file, just source files and references.\n\nThat is uncomfortable. But each of these lines replaces an assumption that would otherwise sit invisibly somewhere on a server: which runtime, which package versions, which certificates, which port. While writing it, I noticed how many of these assumptions I had never written down in Windows projects, but had only ever known.\n\n```mermaid\nflowchart LR\n  A[mono:3.10<br/>base image] --> B[mozroots<br/>SSL certificates]\n  B --> C[NuGet.exe install<br/>Nancy + LiteDB]\n  C --> D[mcs<br/>compiles nancy.exe]\n  D --> E[Image dotnet<br/>approx. 400 MB]\n  E --> F[docker run demo1<br/>mono nancy.exe]\n```\n\n## The code: a process that opens a port\n\nThe application itself is deliberately plain. The entry point starts a `NancyHost` and keeps the process alive:\n\n```csharp\nusing System;\nusing Nancy;\nusing Nancy.Hosting.Self;\n\nclass Program\n{\n    static void Main()\n    {\n        using (var host = new NancyHost(new Uri(\"http://localhost:8080\")))\n        {\n            host.Start();\n            Console.WriteLine(\"Nancy host (http://localhost:8080) started.\");\n            Console.ReadLine();\n        }\n    }\n}\n```\n\nPlus a Nancy module that stores webhooks in LiteDB – a database that sits next to the application as a single file and needs no server:\n\n```csharp\npublic class WebHookModule : NancyModule\n{\n    public WebHookModule() : base(\"/webhooks\")\n    {\n        Get[\"/\"] = _ =>\n        {\n            using (var db = new LiteDatabase(@\"MyData.db\"))\n            {\n                return db.GetCollection<WebHook>(\"webhooks\")\n                    .FindAll()\n                    .ToArray();\n            }\n        };\n\n        Post[\"/\"] = _ =>\n        {\n            using (var db = new LiteDatabase(@\"MyData.db\"))\n            {\n                db.GetCollection<WebHook>(\"webhooks\").Insert(new WebHook());\n                return HttpStatusCode.Created;\n            }\n        };\n    }\n}\n```\n\nBuilding and starting takes three commands, exactly as they appear in the README:\n\n```bash\ndocker build -t dotnet .\ndocker run --name demo1 -p 8080:8080 -i -t dotnet\ndocker start demo1\n```\n\n## Where it got stuck\n\nIt didn’t go smoothly, and the stumbling blocks are more instructive than the happy path. The first start ended with a container that exited immediately. The reason is right there in the code above: `Console.ReadLine()` only keeps the process alive as long as there is a stdin. Without the `-i -t` flags, Docker doesn’t provide one, `ReadLine` returns immediately, `Main` runs out, the container is dead. That is why the two flags are in the README – not out of diligence, but as a scar. The real lesson: a container lives exactly as long as its process. There is no IIS holding on to the application in the background; the application itself is responsible for not finishing.\n\nThe second stumbling block was reachability. On the Mac, the Docker daemon runs in the boot2docker VM, so the service doesn’t answer on `localhost` but on the VM’s IP – `boot2docker ip` reveals it. And the fact that the binding to `http://localhost:8080` in the container is reachable from outside at all is thanks to a quirk of Nancy’s self-hosting: the `HostConfiguration` has an option `RewriteLocalhost` that is enabled by default and turns `localhost` into a wildcard binding. I only understood that after reading the Nancy source code. If you bind strictly to `127.0.0.1`, you see from outside: nothing.\n\nThe rest was small stuff that adds up:\n\n- Fresh Mono images don’t know any SSL root certificates; without `mozroots --import --sync`, even NuGet’s access to HTTPS sources fails.\n- The packages have to be available as net40 assemblies so that Mono 3.10 loads them cleanly – no problem with Nancy 1.1 and LiteDB 1.0, but quite possibly with more exotic packages.\n- Every `RUN` creates an image layer; if you build often while experimenting, you learn to love the build cache and to respect the order of the lines.\n- The 400 megabytes stay. A base image with a complete Mono installation is not a lean foundation, and there is currently no leaner one for .NET code.\n\n## What the detour taught: process instead of IIS\n\nThe real gain of the experiment is not in the container, but in what the container enforces. A .NET application running under IIS is not an application but a guest: the web server owns the process, the configuration system, the lifecycle. The IIS XML configuration file describes not so much the application as its relationship to the host. In the container, this flips. The application is an ordinary process that opens a port, writes to standard output and can be terminated without anything to clean up.\n\nThis also changes where configuration belongs. An image that has to be rebuilt for every environment because the settings are compiled in misses the point. Configuration has to come from outside, and the natural way to do that is environment variables – `docker run -e` then provides both the capability and the discipline. In the next iteration of the entry point, it looked like this:\n\n```csharp\nstatic void Main()\n{\n    var port = Environment.GetEnvironmentVariable(\"PORT\") ?? \"8080\";\n    var uri = new Uri(\"http://localhost:\" + port);\n\n    using (var host = new NancyHost(uri))\n    {\n        host.Start();\n        Console.WriteLine(\"Nancy host ({0}) started.\", uri);\n        Console.ReadLine();\n    }\n}\n```\n\nThat seems trivial, but it is a break with years of IIS configuration transformations and registry entries. Interestingly, Heroku’s Twelve-Factor list – public since 2011 – describes exactly this way of thinking: configuration in the environment, stateless processes, logs as an event stream to standard output, explicitly declared dependencies. I had read the manifesto and taken it for a Heroku marketing document. Only the container showed me that it describes what remains when you take the host away from an application.\n\n```mermaid\nflowchart TD\n  subgraph W[Familiar Windows path]\n    W1[Prepare server<br/>with IIS] --> W2[Configure framework<br/>+ app pool]\n    W2 --> W3[Transform XML<br/>configuration]\n    W3 --> W4[Copy files<br/>and hope]\n  end\n  subgraph C[Container path]\n    C1[Dockerfile<br/>describes everything] --> C2[docker build<br/>reproducible]\n    C2 --> C3[docker run -e PORT=8080<br/>configuration from outside]\n  end\n```\n\nThen there is repeatability. The image built on my machine is, bit for bit, what runs on any other Docker host. “Works on my machine” stops being an argument, because “my machine” is now a file you can pass on. For someone who has known .NET deployments as a series of manual steps on carefully tended servers, that is the real culture shock – not the technology, but losing the excuses.\n\n## An honest assessment\n\nStill, you have to stay sober. Mono is not the .NET Framework. For Nancy, LiteDB and a manageable API, it holds up without problems; if you bring WCF legacy, WPF or deep Windows dependencies, you won’t get far. If you ship to Windows servers in operations, a Mono container also means testing a different runtime than the production one – that is something you need to know and price in. And the toolchain is noticeably second-tier: no debugging in the container, package management by hand, error messages that assume basic Linux knowledge.\n\nThat is why I wouldn’t take this setup into a customer project today. There is too much manual work involved, and a team that has run Windows servers for years doesn’t change its operating model because of one successful prototype. As a learning vehicle, on the other hand, it is hard to beat: every step the Dockerfile makes visible is a step that IIS used to hide.\n\nThe direction is right, though. Microsoft apparently means the opening seriously: CoreCLR and the compiler are publicly on GitHub, ASP.NET 5 is explicitly being developed for Linux, and the early betas already run on Mono today. If that delivers on its promise, the Mono detour is a transitional path – but a viable one, today, not someday. I suspect that the skills from this experiment will transfer one to one: writing Dockerfiles, thinking in processes instead of hosts, passing configuration through the environment. The runtime underneath is interchangeable; the way of thinking is not.\n\n## What stuck\n\nThe repository is a throwaway experiment, and that is how I treat it. Still, it has permanently shifted my view of .NET deployment, in three places:\n\n- A Dockerfile is the complete, executable list of all of an application’s runtime assumptions – whatever isn’t in it is silently borrowed from the host.\n- An application that can run as a plain process is the more flexible application – any host, from IIS to a container, can be put on top of it; the reverse is not true.\n- Configuration belongs in the environment, not in the artifact – one build, many deployments.\n\nNone of this requires Docker. But Docker forced me to write it down instead of just knowing it, and written-down assumptions can be discussed, checked and passed on. I gladly pay the 400 megabytes for that – disk space is cheap, lost afternoons in front of IIS Manager are not.\n\n## Further reading\n\n- The repository for this article: [MikeBild/dotnet-docker](https://github.com/MikeBild/dotnet-docker)\n- Microsoft’s announcement: [.NET Core is Open Source](https://devblogs.microsoft.com/dotnet/net-core-is-open-source/)\n- The official [Mono image on Docker Hub](https://hub.docker.com/_/mono)\n- The [Nancy framework on GitHub](https://github.com/NancyFx/Nancy)\n- [The Twelve-Factor App](https://12factor.net/) – the way of thinking behind process, environment and logs"},{"locale":"en","translation_key":"tests-bevor-produkt","slug":"tests-before-there-is-a-product","title":"Tests Before There Is a Product","summary":"Early tests help you grasp a problem, even if the code is later replaced entirely.","tags":["Software","Testing"],"published_at":"2014-12-12T10:00:00+00:00","updated_at":"2026-07-13T06:06:03.52876+00:00","url":"https://www.mikebild.dev/en/blog/tests-before-there-is-a-product/","audio_url":null,"audio_duration_secs":null,"text":"# Tests Before There Is a Product\n\nA test case needs two things: an input and the expectation of what should come out of it. Nothing more is needed to pin down a problem for which not a single line of code exists yet.\n\nThe reflex with something new goes in a different direction: build right away. An endpoint, a screen, a data model – something visible you can show. If you slow down by one step at this point and write the test first, you aren’t securing any code – it doesn’t even exist yet. The test forces you to name the problem in a single, verifiable sentence. And this sentence almost always outlives the implementation I write afterward and throw away a few days later. The test only becomes quality assurance later; at the beginning, it is a thinking tool.\n\n## Katas: practicing without building a product\n\nThe concrete occasion for this text is katas. A kata is a small, clearly defined programming task that you don’t solve to get rid of it, but to practice on – the String Calculator kata, the Bowling Game kata, Roman numerals, FizzBuzz. You often already know the solution. You still do it again, in a coding dojo with the team or alone on a quiet morning, because it isn’t about the result, but about the path to it.\n\nThe interesting thing about a kata is that, deliberately, there is no product at the end. There is no customer, no deadline, no deployment. What remains is the experience of how a problem feels when you untangle it test step by test step. That is exactly the attitude I take into real projects. In the early phase of a feature, I often don’t know yet what the solution looks like. I only know which behavior has to be observable in the end. And that can be phrased as a test before a single line of production code exists.\n\nTake the String Calculator kata. The task sounds trivial: a function that takes a string of numbers and returns their sum. The first test is as boring as it gets – and still the most important line of the day.\n\n```js\ndescribe(\"String Calculator\", () => {\n  it(\"returns 0 for an empty string\", () => {\n    expect(add(\"\")).to.equal(0);\n  });\n\n  it(\"sums two comma-separated numbers\", () => {\n    expect(add(\"1,2\")).to.equal(3);\n  });\n});\n```\n\nBefore I write `add`, I have made two decisions that were unspoken before: the empty case is not undefined, it returns the number 0. And the separator is, for now, the comma. Two small examples – and a discussion becomes possible that would otherwise only have come up in the code review or, worse, in production.\n\n## The test as a thinking tool\n\nIn *Test-Driven Development by Example*, Kent Beck boiled this down to a simple loop: write a test that fails, get it green with the smallest possible step, then clean up. Red, green, refactor.\n\n```mermaid\nflowchart LR\n  Red[Write a test,<br/>it fails] --> Green[smallest step<br/>to green]\n  Green --> Refactor[clean up<br/>without changing behavior]\n  Refactor --> Red\n```\n\nThe decisive effect is not test coverage. It is the feedback on the design. If, for a single test case, I have to set up three objects, provide four dependencies and mock half a database, then the test is telling me something about my design, not about my diligence in testing: the boundary is in the wrong place. A test that is hard to write is almost always a sign of a coupling that I haven’t paid for yet but have already taken on.\n\nThat is why I write the test first, even when I know the code underneath is a throwaway piece. The test is the question; the code is only the first attempt at an answer. The question is what’s valuable. If I completely replace the first attempt at an answer after two days – because by then I understand the problem better – the question stays and checks the new answer just as strictly as the old one.\n\n## Specification by Example\n\nThe second building block that, for me, belongs inseparably to this is Specification by Example, as Gojko Adzic describes it. The idea: instead of phrasing a requirement abstractly (“the discount applies to new customers”), you write it down as a concrete example that is domain language, expectation and automatable check all at once.\n\n```gherkin\nScenario: A new customer gets the welcome discount\n  Given a customer with no previous orders\n  When the customer places an order of 100 EUR\n  Then the invoice total is 90 EUR\n```\n\nThis small scenario achieves more than it seems. It is written in a language a domain expert can read and correct. It pins the expectation down to a number you can argue about – is it really 90, or does the discount apply before or after VAT? And it can be bound to execution, so the description doesn’t go stale next to the code but runs along with it.\n\nIn practice, the example is often the moment a misunderstanding comes to light. For development, “new customer” meant “no order yet”, but for sales it meant “no order in twelve months”. As long as the requirement stayed abstract, everyone agreed. Only the concrete example with the 100 EUR made the two interpretations visible. That is exactly why I write examples early: not to test code, but to test assumptions nobody has voiced yet.\n\n## The boundary is the real decision\n\nWhen I phrase a test, I implicitly make an architecture decision: I define the boundary at which I check. And this boundary determines what I can change freely later and what I can’t.\n\nIf I check too deep – individual method calls, internal ordering, private helper structures – the test sticks to the implementation. Every restructuring that doesn’t even change the behavior turns it red. Such tests punish refactoring instead of protecting it, and the team quickly learns to avoid them or adjust them blindly. If, on the other hand, I check at a sensible boundary – the observable behavior of the unit, what another part of the system actually sees of it – then everything inside may change, as long as the promise holds on the outside.\n\nThis is the point where testing stops being purely a question of craft and becomes a design question. The boundary at which I test is the same boundary at which I can later cut open, swap out or replace the system. A well-placed test describes a seam in the system. A poorly placed test cements a detail that is nobody’s business from the outside. That is why, before the tool question – Mocha or Jasmine, Sinon or handwritten stubs – the question of substance pays off: Which behavior do I want to pin down, and which do I want to deliberately leave open?\n\n## When this pays off – and when it doesn’t\n\nI don’t want to claim that every line has to start with a test. A spike with which I only find out whether a library is any good at all doesn’t need a test – it is the experiment itself and gets deleted afterward. Neither does a pure end-to-end slice to see a layout.\n\nThe trade-off hinges on a single question: How well do I already understand the problem? If the task is clear and just needs typing, test-first costs more than it brings. If, on the other hand, I am not sure what “correct” even means – and in the early product phase, that is the normal case – then the test is the cheapest tool available to force clarity. Precisely because I know the code is throwaway, I want to capture the little I learn in a form that outlives the code.\n\nSeen this way, test-first in the exploration phase doesn’t contradict throwing things away. It is the method with which I still extract lasting knowledge from a throwaway prototype: the one line that pins down the expected behavior stays, even when everything else goes.\n\n## The error path decides whether you can release\n\nThere is a leap between “runs in the demo” and “runs in production”, and early tests make exactly this leap visible. In demo mode, almost every system looks clean, because you show the flow in which everything goes well: valid input, reachable service, exactly one run. It gets interesting next to that.\n\nWhen I build an import, the exciting question isn’t whether it reads a correct file, but what happens with the half-broken one. If the run is repeated, do duplicates appear, or is it idempotent? What happens on a timeout in the middle of processing – does it abort cleanly, or does the system stay in a half-finished state? Which log line helps me at three in the morning to understand the error instead of just noticing it? These questions seem dry, but they are the real difference between a prototype and something you give to a customer.\n\nThat is why I write at least one test for the unpleasant case early on, not just for the pretty one. A test that checks that duplicate processing does not create two invoices says more about how well the design holds up than ten tests for the expected result. And it says so at a point when the change is still cheap.\n\n## What this measurably brings\n\nAll of this would be folklore if it only produced a good feeling. The benefit is more concrete. Misunderstandings become visible in the example, not only at acceptance – that shortens the most expensive of all cycles, the one between “misunderstood” and “noticed that it was misunderstood”. Refactoring gets cheaper, because tests at the right boundary protect the behavior instead of freezing the implementation; the team dares to clean up instead of working around code. And handover gets easier, because an example in domain language is better documentation than any prose that goes stale next to the code.\n\nIf I had to pick out one effect, it would be this one: shorter feedback. An example that checks an assumption turns a discussion that would otherwise be held weeks later in production into a five-minute discussion at the whiteboard. That is not a soft improvement. It is the difference between a team that works on the problem and one that works on its misunderstandings.\n\n## What remains when the code goes\n\nBack to the beginning. The reason I write tests before there is a product is neither discipline nor completeness. It is that the test holds on to the one thing I want to keep while everything else is still in flux: the expected behavior, named at a boundary you can argue about.\n\nThe code of the first week is almost always wrong, and that’s fine – it was never meant as an answer, but as a question in executable form. When I throw it away and rewrite it, the same test checks the new version just as strictly. That is exactly why we practice on katas without ever building a product: what carries weight is not the result, but the judgment about which behavior counts. And this judgment is the only thing a team can really take with it when the first draft has long been deleted."},{"locale":"en","translation_key":"flood-it-architektur-lupe","slug":"flood-it-a-game-as-an-architecture-lens","title":"Flood-It: A Game as an Architecture Lens","summary":"A board of numbers, a move as a pure function and a greedy solver show on a small scale what gets blurry in large systems: the separation of core logic, strategy and presentation.","tags":["Software","Learning"],"published_at":"2014-10-24T10:00:00+00:00","updated_at":"2026-07-14T16:38:17.99207+00:00","url":"https://www.mikebild.dev/en/blog/flood-it-a-game-as-an-architecture-lens/","audio_url":null,"audio_duration_secs":null,"text":"# Flood-It: A Game as an Architecture Lens\n\n```js\nvar board = [\n  [2, 1, 1, 3],\n  [1, 2, 3, 0],\n  [0, 1, 2, 2],\n  [3, 3, 0, 1]\n];\n\nfunction flood(board, color) {\n  // returns a new board where the top-left region\n  // has captured all adjacent cells of the picked color\n}\n```\n\nFlood-It does not need more of a model than that. The game is quickly explained: a board of colored cells, with a region in the top left that initially consists of a single cell. Each move, you pick a color. The region takes on that color and swallows all orthogonally adjacent cells that already have it. The goal is a single-colored board – in as few moves as possible.\n\nA good two weeks ago, I created the repository `kata-flood-it` for this, a fresh kata in JavaScript. So far the README consists of a single line, and I do not promise more here either: not a finished product, but a small experiment. The appeal is not in the game itself anyway – Flood-It has long been on every smartphone. The appeal is that such a tiny program works like a lens. There is no database, no framework, no network layer behind which bad splits could hide. What remains are exactly three things: a model, a strategy and a presentation. And the question of where the boundaries between them run.\n\n## The board is a decision\n\nThe first decision is made before a single line of game logic exists: what is the board? My answer is at the top – a two-dimensional array of numbers. That looks trivial, but it is not. You see the obvious alternative in many small browser games: the board exists only as a collection of `div` elements, and the truth about the game state is hidden in CSS class names. If you want to know which color a cell has, you ask the DOM. The presentation has thereby become the model, and all logic has to go through it.\n\nThe second, smaller decision: numbers instead of color names. In the model there is no `\"red\"` and no `\"#ff0000\"`, only `0` to `5`. Which number corresponds to which shade is a question of presentation – on the console perhaps a letter, in the browser a CSS class, on a canvas a fill style. The model knows nothing about it, and that is exactly what makes it hold up.\n\nWhile writing, I noticed how much material for discussion is in these two lines alone. In a review of a large system we talk about the same questions – where does the leading state live, who may read it, who may change it – just spread across dozens of files. Here the whole question fits on one screen.\n\n## The move as a function\n\nThe core of the game is a flood fill: starting from the top left, all connected cells of the old color are collected and recolored. Classically, you solve this recursively (depth-first search) or with a queue (breadth-first search). I chose breadth-first search because it gets by without deep call stacks – on large boards, naive recursion in JavaScript eventually topples over with a stack overflow.\n\n```js\nfunction flood(board, color) {\n  var next = board.map(function (row) { return row.slice(); });\n  var target = next[0][0];\n  if (target === color) return next;\n\n  var queue = [[0, 0]];\n  while (queue.length > 0) {\n    var cell = queue.shift();\n    var row = cell[0];\n    var col = cell[1];\n    if (row < 0 || col < 0 || row >= next.length || col >= next[0].length) continue;\n    if (next[row][col] !== target) continue;\n\n    next[row][col] = color;\n    queue.push([row - 1, col], [row + 1, col], [row, col - 1], [row, col + 1]);\n  }\n  return next;\n}\n```\n\nThe most important property is in the first line: `flood` does not change the board it is given but returns a new one. That costs a few copies, and `queue.shift()` is not the fastest operation in the world on long arrays either – for a 14×14 board, neither matters at all. What I get in return is considerable: a move is a value. The game history is simply an array of boards, undo is an index that jumps back by one, and a replay is a loop. I did not have to build any of this separately.\n\nOn top of that comes a second pure function that detects the end of the game:\n\n```js\nfunction isSolved(board) {\n  return board.every(function (row) {\n    return row.every(function (cell) {\n      return cell === board[0][0];\n    });\n  });\n}\n```\n\nNeither function knows about move limits, buttons or scores. Each answers exactly one question about the board. Everything else – how many moves are allowed, whether the game is lost, what happens next – belongs somewhere else.\n\n## Tests against the logic, not against the DOM\n\nTesting browser UIs is tedious in 2014: you need a real or headless browser, the runs are slow, and the tests break as soon as a CSS class changes. The kata shows the way out on a small scale: if the core logic consists of pure functions in CommonJS modules, the tests run with Mocha directly on Node – in milliseconds, without a browser. For delivery, Browserify then bundles the same modules for the browser. One module format, two runtimes.\n\n```js\nvar assert = require('assert');\nvar flood = require('./flood');\n\ndescribe('flood', function () {\n  it('captures adjacent cells of the picked color', function () {\n    var board = [\n      [0, 1],\n      [1, 1]\n    ];\n    assert.deepEqual(flood(board, 1), [\n      [1, 1],\n      [1, 1]\n    ]);\n  });\n\n  it('does not mutate the given board', function () {\n    var board = [\n      [0, 1],\n      [1, 1]\n    ];\n    flood(board, 1);\n    assert.deepEqual(board, [\n      [0, 1],\n      [1, 1]\n    ]);\n  });\n});\n```\n\nThe second example matters more to me than the first. Whether a function changes its input is a question of contract, and contracts belong in tests – not in comments. In a larger project, I once spent two days chasing a bug that came from exactly this: a helper function that sorted an array passed to it and thereby silently rearranged the caller’s state. The test above costs six lines and rules out this entire class of bugs.\n\nWhat is also striking is what does not appear in the tests: no `document`, no selector, no simulated click. If the tests for the game rules need a browser, that is not a testing problem but an architectural finding – it means logic is stuck in the presentation.\n\n## The strategy is a layer of its own\n\nBesides the rules, Flood-It has a second domain level: how do you play well? The obvious heuristic is greedy – try every color, count how large the region would be afterwards, and take the color with the largest gain.\n\n```js\nfunction countCaptured(board) {\n  var marked = flood(board, -1);\n  var count = 0;\n  marked.forEach(function (row) {\n    row.forEach(function (cell) {\n      if (cell === -1) count += 1;\n    });\n  });\n  return count;\n}\n\nfunction bestMove(board, colors) {\n  var best = { color: null, captured: -1 };\n  colors.forEach(function (color) {\n    if (color === board[0][0]) return;\n    var captured = countCaptured(flood(board, color));\n    if (captured > best.captured) {\n      best = { color: color, captured: captured };\n    }\n  });\n  return best.color;\n}\n```\n\nTwo observations. First: `countCaptured` does not invent its own traversal, but misuses `flood` with a color that does not occur in the game and counts the markings. That only works because `flood` is pure – I can safely call it “on trial” as often as I like. Exactly this trial run is prohibitively expensive in systems with scattered, mutable state: if you want to ask a what-if question there, you need mocks, transaction rollbacks or a staging environment.\n\nSecond: the greedy strategy is measurably not optimal, and that is not sloppiness on my part. Clifford, Jalsenius, Montanaro and Sach showed in 2010 that Flood-It is NP-hard from three colors on – so an efficient optimal strategy is not to be expected. For the architecture, that means: the strategy will change. Greedy today, perhaps with two moves of lookahead tomorrow. That is why it is a layer of its own that talks to the core only through `flood`, `countCaptured` and `isSolved`. The move counter and the move limit belong here too, not in the rules and not in the UI – they are game mode, not game law.\n\n## The presentation as an exchangeable skin\n\nThe presentation sits on the very outside. It reads the board and draws it – nothing more:\n\n```js\nfunction render(board, element) {\n  element.innerHTML = '';\n  board.forEach(function (row) {\n    var line = document.createElement('div');\n    row.forEach(function (cell) {\n      var field = document.createElement('span');\n      field.className = 'cell color-' + cell;\n      line.appendChild(field);\n    });\n    element.appendChild(line);\n  });\n}\n```\n\nThe click handler on the color buttons translates a DOM event into a call to the core logic and re-renders the result. The presentation never tinkers with the board itself; it is a skin you can peel off and replace. A canvas instead of the `div` soup? Only `render` changes. A console version with letters instead of colors to play through the kata in Node? Again only `render`. I did not even bring in jQuery – for twenty lines of DOM work it contributes nothing, and the temptation to park state in `data` attributes stays outside.\n\n```mermaid\nflowchart TB\n  subgraph ui[\"Presentation\"]\n    H[Click handler] --> R[render]\n  end\n  subgraph strategy[\"Strategy / game mode\"]\n    G[bestMove] --> Z[Move counter +<br/>move limit]\n  end\n  subgraph core[\"Core logic (pure functions)\"]\n    F[flood] --> I[isSolved]\n    F --> C[countCaptured]\n  end\n  ui --> strategy\n  strategy --> core\n  ui --> core\n```\n\nThe arrows all point inward. The core logic knows nobody, the strategy knows only the core, the presentation may use both. There is no way back – `flood` cannot even know whether it was just called by a test, by the greedy solver or by a click.\n\n## What gets blurry at scale\n\nNothing about this split is new. Layers, pure core logic, thin edges – that has been in every architecture book for years. What is interesting is why it still blurs so often at scale and stays so clear on a small scale. My observation: in large systems there is always a convenient reason for the small boundary violation. Validation ends up in the controller because the request object is already lying around there. The discount is calculated in the template because the number is only needed there. Every single shortcut is understandable, and in sum, after two years, nobody can say anymore where the business rules actually live.\n\nThe kata does not have these excuses. If I build a move counter into `flood`, I see the foreign body immediately, because the function used to have seven lines. That is exactly what I mean by a lens: the small program does not magnify the solution, but the violation.\n\nI take a few questions from the game straight into project work:\n\n- What is our “board” – the one data structure that holds the leading state – and how many places may change it?\n- Which operation is our “move,” and is it tangible as a value – traceable, repeatable, reversible?\n- Can we work through a decision “on trial” without touching real state?\n- Do the tests for the rules run without a browser, without a database, without a network?\n\nIf you cannot answer these questions for a large system, you do not have a tooling problem. What is missing is the boundary that is four function names wide in the kata.\n\n## The bottom line\n\nThe kata has deliberately stayed small, and the repository will not become a library either – it is a finger exercise with a finding. The finding: the separation of core logic, strategy and presentation is not a question of system size and not a question of framework. It is just as present or absent in eighty lines of ES5 as in an application with eighty thousand lines. The only difference is that in eighty lines you cannot overlook it.\n\nThat is why such a game is worth it precisely when you do not really need it. Not as algorithm training – the flood fill is written in an evening. But as a test bench for your own habits: where do I put state when nobody gives me a structure? Do I write the UI first or the contract first? The answers you give yourself in a color flood game are the same ones you give later under deadline pressure – just more honest.\n\n## Further reading\n\n- Repository for the kata: https://github.com/MikeBild/kata-flood-it\n- Flood fill (algorithm overview): https://en.wikipedia.org/wiki/Flood_fill\n- Clifford, Jalsenius, Montanaro, Sach: “The Complexity of Flood Filling Games” (2010): https://arxiv.org/abs/1001.4420\n- Mocha (test framework): https://mochajs.org/\n- Browserify: http://browserify.org/"},{"locale":"en","translation_key":"mathparser-parser-als-denkwerkzeug","slug":"mathparser-parsers-as-a-thinking-tool","title":"MathParser: Parsers as a Thinking Tool","summary":"A look back at a parser demo of my own from 2010 shows why a handwritten expression parser teaches more about layers, structure and the boundary between syntax and semantics in a few lines than many a large project.","tags":["Software","Architecture"],"published_at":"2014-10-12T10:00:00+00:00","updated_at":"2026-07-14T16:36:34.264841+00:00","url":"https://www.mikebild.dev/en/blog/mathparser-parsers-as-a-thinking-tool/","audio_url":null,"audio_duration_secs":null,"text":"# MathParser: Parsers as a Thinking Tool\n\nAbout 200 lines of C#. That’s all a complete parser for arithmetic expressions needs – tokenizer, recursive descent, evaluation, parentheses, operator precedence, useful error messages with positions. An average controller in a business system reaches the same length and teaches almost nothing about software design along the way. The 200 parser lines, on the other hand, contain three cleanly separated layers, a grammar as an explicit structural model and a boundary between form and meaning that you’ll pinch your fingers on at least once while writing. Measured in insight per line, I know little that is denser – and it fits into an afternoon.\n\n## A four-year-old demo project, reread\n\nThe occasion for this text is a repository of my own: [MathParser](https://github.com/MikeBild/MathParser), a C# demo project from 2010. A Visual Studio solution containing a parser project, a second variant called `ClassicMathParser` and a test project. Not a product, not a library for others – a demo, written to have worked through the subject myself once.\n\nFour years later I opened it again, really just to clean up. What caught me was something else: the code asks questions I didn’t see at all in 2010. Why are there two variants side by side? Why does the parser evaluate right away instead of building a structure first? Why does the handling of the minus sign sit exactly where it sits? Old projects of your own are uncomfortably honest in this respect: you’re arguing with a former self who can no longer talk their way out.\n\nThat’s exactly why the look back is worth an article. Not because the repository is special – but because the topic ages better as a thinking tool than most frameworks of that time.\n\n## Why a regular expression isn’t enough here\n\nThe first reflex for “parse an arithmetic expression” is the same again and again in code reviews: a regular expression, maybe two, plus a `Split` on operators. For `2+3*4` this even looks good for a moment. For `(1+2)*(3-(4/2))` it collapses, and not because of sloppy craftsmanship but fundamentally: regular expressions can’t count. Nested parentheses require a memory of the nesting depth, and that’s exactly what a regular expression can’t provide by its very model. You can justify this theoretically – regular versus context-free languages – but in practice a look at the parentheses is enough: if you read `(((`, you have to remember that `)))` still has to follow three times.\n\nIn 2010 I noticed for the first time that the choice of tool is a statement about the structure of the problem. A regular expression claims: “This input is flat.” A parser with recursion claims: “This input is a tree.” Arithmetic expressions are trees – `1+2*3` has an inner structure you can’t see in the string. If you claim the wrong thing, you pay for it later with special cases.\n\n## Three layers, three contracts\n\nAn expression parser falls apart into three layers almost by itself, and each one has a clear contract:\n\n- The tokenizer turns a string into a stream of symbols: numbers, operators, parentheses. It knows characters, but no structure.\n- The parser checks whether the symbol sequence matches the grammar and builds the structure from it. It knows structure, but no meaning.\n- Evaluation gives the structure a meaning: it computes. Only here do concepts like “result” or “division by zero” exist.\n\n```mermaid\nflowchart LR\n  A[\"Input<br/>(1+2)*3\"] --> B[\"Tokenizer<br/>characters to symbols\"]\n  B --> C[\"Token stream<br/>( 1 + 2 ) * 3\"]\n  C --> D[\"Parser<br/>recursive descent\"]\n  D --> E[\"Structure<br/>tree or direct value\"]\n  E --> F[\"Evaluation<br/>meaning, result\"]\n```\n\nThat sounds like a textbook, but it has a very practical point: you can test, replace and explain each layer on its own. That’s exactly why the solution has its own test project, and the tests for the tokenizer know nothing about grammar – they only check that `\"12.5+\"` becomes the symbols `12.5` and `+`. This kind of separation is preached constantly in large systems; in the parser it isn’t a resolution but the only convenient way to build it. That’s the first reason I call the topic a thinking tool: it lets you experience an architectural principle instead of just claiming it.\n\n## The grammar forces you to think about structure\n\nBefore the actual parser comes the grammar – back then, for me, as an EBNF sketch on a piece of paper, in this form:\n\n```text\nExpression := Term   { (\"+\" | \"-\") Term }\nTerm       := Factor { (\"*\" | \"/\") Factor }\nFactor     := Number | \"(\" Expression \")\" | \"-\" Factor\n```\n\nThree lines, and the most interesting property isn’t stated explicitly anywhere: operator precedence. Multiplication before addition isn’t a rule checked with an `if` somewhere – it lives in the layering of the grammar. `Expression` consists of `Term` building blocks, `Term` of `Factor` building blocks. Because `*` and `/` are bound one level deeper than `+` and `-`, they automatically bind more tightly. The parenthesis, in turn, jumps from the very bottom back to the very top: a `Factor` may contain a complete `Expression`. That’s the recursion the regular expression failed at earlier, here in a single line.\n\nRereading it in 2014, I still find this remarkable: precedence as structure instead of as a condition. Terence Parr covers exactly this way of thinking in depth in “Language Implementation Patterns” from 2010, and Douglas Crockford shows an alternative path in his essay “Top Down Operator Precedence” from 2007, where precedence is attached as binding power to the operators themselves. Both paths get you there; if you’ve rebuilt both once, you understand better afterward what “expressing structure” even means.\n\n## Recursive descent in C#\n\nThe grammar translates into code almost mechanically – one method per rule. First the tokenizer, deliberately kept simple here:\n\n```csharp\npublic enum TokenType { Number, Plus, Minus, Star, Slash, LeftParen, RightParen, End }\n\npublic sealed class Tokenizer\n{\n    private readonly string _input;\n    private int _position;\n\n    public Tokenizer(string input) { _input = input; }\n\n    public Token Next()\n    {\n        while (_position < _input.Length && char.IsWhiteSpace(_input[_position]))\n            _position++;\n\n        if (_position >= _input.Length)\n            return new Token(TokenType.End, 0, _position);\n\n        char current = _input[_position];\n\n        if (char.IsDigit(current))\n        {\n            int start = _position;\n            while (_position < _input.Length &&\n                   (char.IsDigit(_input[_position]) || _input[_position] == '.'))\n                _position++;\n\n            double value = double.Parse(\n                _input.Substring(start, _position - start),\n                CultureInfo.InvariantCulture);\n\n            return new Token(TokenType.Number, value, start);\n        }\n\n        _position++;\n        switch (current)\n        {\n            case '+': return new Token(TokenType.Plus, 0, _position - 1);\n            case '-': return new Token(TokenType.Minus, 0, _position - 1);\n            case '*': return new Token(TokenType.Star, 0, _position - 1);\n            case '/': return new Token(TokenType.Slash, 0, _position - 1);\n            case '(': return new Token(TokenType.LeftParen, 0, _position - 1);\n            case ')': return new Token(TokenType.RightParen, 0, _position - 1);\n        }\n\n        throw new FormatException(\n            string.Format(\"Unexpected character '{0}' at position {1}.\", current, _position - 1));\n    }\n}\n```\n\nTwo small things with a big effect: `CultureInfo.InvariantCulture`, because otherwise `double.Parse` expects a comma on a German machine and silently turns `1.5` into `15` – a bug I haven’t hunted in the parser demo, but more than once in real systems. And the position in the token, because without it no later layer can produce an error message that shows the user where the problem is.\n\nThe parser itself follows the grammar line by line:\n\n```csharp\npublic sealed class Parser\n{\n    private readonly Tokenizer _tokenizer;\n    private Token _current;\n\n    public Parser(string input)\n    {\n        _tokenizer = new Tokenizer(input);\n        _current = _tokenizer.Next();\n    }\n\n    public double Parse()\n    {\n        double result = ParseExpression();\n        Expect(TokenType.End);\n        return result;\n    }\n\n    // Expression := Term { (\"+\" | \"-\") Term }\n    private double ParseExpression()\n    {\n        double left = ParseTerm();\n        while (_current.Type == TokenType.Plus || _current.Type == TokenType.Minus)\n        {\n            TokenType op = _current.Type;\n            Advance();\n            double right = ParseTerm();\n            left = op == TokenType.Plus ? left + right : left - right;\n        }\n        return left;\n    }\n\n    // Term := Factor { (\"*\" | \"/\") Factor }\n    private double ParseTerm()\n    {\n        double left = ParseFactor();\n        while (_current.Type == TokenType.Star || _current.Type == TokenType.Slash)\n        {\n            TokenType op = _current.Type;\n            Advance();\n            double right = ParseFactor();\n            left = op == TokenType.Star ? left * right : left / right;\n        }\n        return left;\n    }\n\n    // Factor := Number | \"(\" Expression \")\" | \"-\" Factor\n    private double ParseFactor()\n    {\n        if (_current.Type == TokenType.Number)\n        {\n            double value = _current.Value;\n            Advance();\n            return value;\n        }\n\n        if (_current.Type == TokenType.LeftParen)\n        {\n            Advance();\n            double inner = ParseExpression();\n            Expect(TokenType.RightParen);\n            return inner;\n        }\n\n        if (_current.Type == TokenType.Minus)\n        {\n            Advance();\n            return -ParseFactor();\n        }\n\n        throw new FormatException(\n            string.Format(\"Unexpected token at position {0}.\", _current.Position));\n    }\n\n    private void Advance() { _current = _tokenizer.Next(); }\n\n    private void Expect(TokenType type)\n    {\n        if (_current.Type != type)\n            throw new FormatException(\n                string.Format(\"Expected {0} at position {1}.\", type, _current.Position));\n        Advance();\n    }\n}\n```\n\nThis is recursive descent in its purest form: `ParseExpression` calls `ParseTerm`, `ParseTerm` calls `ParseFactor`, and `ParseFactor` calls `ParseExpression` again on a parenthesis. The runtime’s call stack takes over the parenthesis counting that the regular expression lacked. You can have tools like ANTLR generate such methods from a grammar – for serious languages, I would do that too. For understanding, nothing replaces doing it by hand.\n\n## AST or direct evaluation – the question I skipped in 2010\n\nThe parser shown computes right away: `ParseTerm` returns a `double`, not a node. That’s the shortest variant, and perfectly fine for a demo. Rereading it, though, I notice what this shortcut costs: parser and evaluation, a moment ago two layers with their own contracts, are fused into one here. If you want to compute the same expression twice with different variable values, you have to parse twice. If you want to print the expression nicely formatted, simplify it or translate it into another language, you can’t – the structure was never captured, it only existed fleetingly in the call stack.\n\nThe alternative is an abstract syntax tree: `ParseTerm` then returns a `Node`, say `BinaryNode(Star, NumberNode(2), NumberNode(3))`, and a separate `Evaluate` method walks the tree. More code, more allocations – but the structure becomes a value of its own that you can keep working with. In my solution, two project variants still sit side by side to this day, and I strongly suspect the difference revolved around exactly this question; after four years I can no longer say for sure, and that in itself is a lesson about demo projects without notes.\n\nThe general form of the question has come up constantly since then: do I evaluate right away, or do I build a model first? An import that writes line by line directly into the database is direct evaluation. An import that first builds a validated intermediate model and then applies it is the tree. Both are legitimate – but it should be a decision, not an accident.\n\n## The same in ES5, as a test\n\nTo check whether the structure holds or is just a C# idiom, I redid the core in JavaScript – same pattern, same names:\n\n```javascript\n// Expression := Term { (\"+\" | \"-\") Term }\nfunction parseExpression(state) {\n  var left = parseTerm(state);\n  while (state.current.type === 'Plus' || state.current.type === 'Minus') {\n    var op = state.current.type;\n    advance(state);\n    var right = parseTerm(state);\n    left = op === 'Plus' ? left + right : left - right;\n  }\n  return left;\n}\n```\n\nNo type system, no classes, and yet it’s recognizably the same parser. That’s no accident: the grammar is the design document, the code merely its translation. Crockford’s essay takes this even further in JavaScript and uses it to build a parser for JavaScript itself – if you want to know what `JSON.parse` or an expression field in a form does inside, you’ll find the answer there in surprisingly little code.\n\n## The boundary between syntax and semantics becomes physical\n\nThe moment that stuck with me most from that afternoon in 2010 hinges on the minus sign. `3-2` and `-2` contain the same character, but two different things: once a binary operator, once a sign. The tokenizer can’t know the difference – it only sees a character. The decision is made in the parser, based on context: a minus at a position where a `Factor` is expected is a sign; a minus after a completed `Term` is a subtraction. The meaning “negate” comes even later, in evaluation.\n\nThe same goes for errors. `2+*3` fails in the parser – a syntax error, the input is already invalid as a form. `2/0`, on the other hand, passes the parser without complaint and only fails in evaluation – a semantic error, the form was correct, the meaning isn’t. If you handle both errors in the same layer, you’ve blurred the boundary; if you separate them, you get two precise error messages almost for free. I’ve carried this distinction – what is well-formed, what is valid, what makes sense – through every interface discussion since, from validating an XML document to the question of whether a web service should return a 400 or a 422.\n\n## What I take away from it\n\nAll in all, rereading the old demo made three things clear to me. First: small, self-contained problems make the better teaching pieces, because you can understand them completely – in a parser there’s no place where you’d have to point to magic. Second: the three layers and the grammar layering aren’t specialist parser knowledge but architecture in miniature; the questions “who may know what” and “where does the structure live” are exactly the same as in any larger system. Third: reading your own old projects with four years of distance is an underrated exercise – the open questions of back then are visible today, and today’s answers wouldn’t exist without that afternoon back then.\n\nIf you’ve never written a parser: one afternoon, an empty project, the three EBNF lines from above. No generator, no library, no peeking at other people’s code. The 200 lines that come out of it are probably the densest piece of software design you can learn in that time.\n\n## Further reading\n\n- My demo repository: [github.com/MikeBild/MathParser](https://github.com/MikeBild/MathParser)\n- Douglas Crockford: [Top Down Operator Precedence](https://crockford.com/javascript/tdop/tdop.html) (2007)\n- Terence Parr: [Language Implementation Patterns](https://pragprog.com/titles/tpdsl/language-implementation-patterns/) (Pragmatic Bookshelf, 2010)\n- [ANTLR](http://www.antlr.org/) – parser generator, in case it really should become a proper grammar"},{"locale":"en","translation_key":"state-mutation-auf-streams","slug":"state-mutation-on-streams","title":"State Mutation on Streams","summary":"If you compute state as a fold over a stream of events instead of changing it directly, you get undo, replay and traceability almost for free.","tags":["Software","Reactive"],"published_at":"2014-07-12T10:00:00+00:00","updated_at":"2026-07-14T16:34:37.713652+00:00","url":"https://www.mikebild.dev/en/blog/state-mutation-on-streams/","audio_url":null,"audio_duration_secs":null,"text":"# State Mutation on Streams\n\n```javascript\nvar events = [\n  { type: 'ItemAdded', sku: 'A-100', qty: 1 },\n  { type: 'ItemAdded', sku: 'B-200', qty: 2 },\n  { type: 'QuantityChanged', sku: 'B-200', qty: 3 },\n  { type: 'ItemRemoved', sku: 'A-100' }\n];\n\nfunction applyEvent(state, event) {\n  var items = {};\n  Object.keys(state.items).forEach(function (sku) {\n    items[sku] = state.items[sku];\n  });\n\n  if (event.type === 'ItemAdded') { items[event.sku] = event.qty; }\n  if (event.type === 'QuantityChanged') { items[event.sku] = event.qty; }\n  if (event.type === 'ItemRemoved') { delete items[event.sku]; }\n\n  return { items: items };\n}\n\nvar cart = events.reduce(applyEvent, { items: {} });\n// -> { items: { 'B-200': 3 } }\n```\n\nFour events, one function, one call to `Array.prototype.reduce` – and at the end you have the current state of a shopping cart. What’s remarkable is everything this code lacks: no `cart.addItem()`, no setter, no place where someone touches an object and changes it. The cart isn’t maintained, it’s computed. The list of events is the actual truth; the state is just its summary.\n\nAt first that sounds like sleight of hand, because of course memory gets mutated somewhere. But the perspective flips, and for a while now I’ve found this very flip more exciting than any new framework: state here is not a thing with a life story but the result of a fold over everything that has happened so far.\n\n## A fold, not a setter\n\nIn the functional world, this pattern is called `foldl` – a left fold. You take an initial value, walk over a sequence from left to right and, in each step, combine the current intermediate result with the next element. `reduce` in JavaScript is exactly that, part of the language standard since ES5 and available in every current browser in 2014; only the remaining IE8 installations still need an es5-shim.\n\nThe signature of the step function is the interesting part:\n\n```javascript\n// (state, event) -> state\nfunction applyEvent(state, event) { /* ... */ }\n```\n\nTwo properties make this function valuable. First, it’s deterministic: the same sequence of events and the same initial value always produce the same state. Second, it’s complete: there is no second way for the state to change, no method that reaches into the object past the fold. If you want to know why the cart looks the way it does, you read the events. Period.\n\nWhether `applyEvent` builds a fresh object internally or writes to the state passed in directly is, by contrast, almost a matter of taste. In the example above, I copy the items because I’ll need intermediate states later. In a tight loop over a hundred thousand events, the function may mutate too – as long as the mutation stays locked inside the fold and only the result is visible from the outside. The discipline isn’t in the immutability of the objects but in the one single door that changes go through.\n\n```mermaid\nflowchart LR\n  S0[Initial state<br/>empty shopping cart] --> F1((applyEvent))\n  E1[ItemAdded<br/>A-100] --> F1\n  F1 --> F2((applyEvent))\n  E2[ItemAdded<br/>B-200] --> F2\n  F2 --> F3((applyEvent))\n  E3[QuantityChanged<br/>B-200] --> F3\n  F3 --> F4((applyEvent))\n  E4[ItemRemoved<br/>A-100] --> F4\n  F4 --> S[current state<br/>as a projection]\n```\n\n## A small experiment from 2012\n\nI didn’t come up with the idea on the drawing board. In October 2012, I created a tiny repository called [statemutatejs](https://github.com/MikeBild/statemutatejs). The README consists of a single line: “simple projection functions, alias foldl, that mutate state on a stream of elements”. The thing never aimed for more – an experiment that grew out of the question of what projection functions feel like when you consistently write them as a fold over a stream instead of as methods on an object.\n\nI’m not mentioning this because it turned into a library anyone should use. But because, while tinkering, I noticed something I only half understood back then: as soon as the step function is separated from the container, what you fold over becomes interchangeable. An array, a Node stream, an observable sequence – the projection function stays literally the same. In hindsight, the one word “foldl” in the README was the whole point of the experiment.\n\nTwo years later, I see the same pattern in more and more places, and it’s worth laying the variants side by side.\n\n## The same pattern on Node streams\n\nSince Node 0.10, there has been the revised stream interface – streams2 – and with it `objectMode`, in which a stream carries arbitrary objects instead of buffers. This frees the fold from the array: the events no longer have to be fully in memory; they can arrive whenever they like.\n\n```javascript\nvar stream = require('stream');\nvar util = require('util');\n\nfunction StateFold(applyFn, initialState) {\n  stream.Writable.call(this, { objectMode: true });\n  this.state = initialState;\n  this.applyFn = applyFn;\n}\nutil.inherits(StateFold, stream.Writable);\n\nStateFold.prototype._write = function (event, encoding, done) {\n  this.state = this.applyFn(this.state, event);\n  done();\n};\n\n// same projection function as before, no changes needed\nvar fold = new StateFold(applyEvent, { items: {} });\neventSource.pipe(fold);\n\nfold.on('finish', function () {\n  console.log(fold.state); // -> { items: { 'B-200': 3 } }\n});\n```\n\nThis is deliberately unspectacular: a `Writable` in object mode that calls the step function once per event and keeps the intermediate result. `applyEvent` is unchanged from the first example. Whether `eventSource` is a file with line-by-line serialized JSON events, a TCP socket or a parser that turns log lines into objects makes no difference to the fold. Along the way, the backpressure mechanics of streams2 ensure that a slow consumer slows down the source instead of piling up events in memory.\n\nIn a project earlier this year, we built exactly this kind of evaluation over several gigabytes of log data: read events from files, fold them through a handful of projection functions, done. No cache, no database for the evaluation itself – just streams and folds. The code was so small that the discussion in the review took longer than writing it.\n\n## scan() makes the intermediate states visible\n\n`reduce` delivers exactly one value at the end. On an endless stream – user input, sensor data, price data – there is no end, and therefore no single result. The Reactive Extensions for JavaScript, currently in version 2.x, have the `scan` operator for this: the same fold, except that every intermediate state is passed on as an element of a new stream.\n\n```javascript\nvar cartStates = cartEvents\n  .scan({ items: {} }, applyEvent);\n\ncartStates.subscribe(function (state) {\n  renderCart(state); // every intermediate state, as it happens\n});\n```\n\nAgain the same projection function, not a single character changed. Bacon.js offers the same operator with `scan` if the Rx style isn’t your thing. It gets interesting in the browser: if every user interaction is an event and the application state is a `scan` over it, then the UI is at any point in time a function of the event stream so far. I tried this in a prototype for a dashboard, and the most unfamiliar experience wasn’t the code at all. It was debugging: instead of searching the debugger for the object that was breaking, I printed the last twenty events and found the bug in the projection function. The broken state was no longer a mystery but the traceable result of a concrete sequence of events.\n\n## Undo, replay, traceability – by-products\n\nAnd that brings me to the real reason this pattern won’t let go of me. In classic mutating code, certain requirements are expensive because the old state is destroyed when it changes. If you want undo, you have to take snapshots or maintain inverse operations. If you want to know how a state came about, you need logging that someone has to have built in beforehand. In the world of folds, these requirements simply fall out:\n\n```javascript\nfunction stateAt(events, count) {\n  return events.slice(0, count).reduce(applyEvent, { items: {} });\n}\n\nvar current = stateAt(events, events.length);     // state now\nvar undone = stateAt(events, events.length - 1);  // state before the last event\nvar initial = stateAt(events, 0);                 // start over\n```\n\nUndo is a fold over all events except the last one. Replay is the same fold once more, also step by step as a time lapse if you like. And traceability lives in the event list itself – it is the log you’d otherwise have to painstakingly retrofit.\n\n```mermaid\nflowchart TB\n  L[Event list<br/>e1, e2, e3, e4] --> A[Fold over all<br/>= current state]\n  L --> B[Fold over e1 to e3<br/>= undo]\n  L --> C[Fold step by step<br/>= replay / time travel]\n  L --> D[Read the list itself<br/>= audit log]\n```\n\nA few things you get practically for free this way:\n\n- undo and redo without writing inverse operations\n- reproducing bugs by folding the recorded event sequence again\n- new views on old data through a second projection function over the same events\n- tests that consist of nothing but an event list and an expected end state\n\nThe last point is the most underrated in everyday work. A test for `applyEvent` needs no mock, no database, no setup – event list in, compare the end state, done.\n\n## From toy to architecture question\n\nThe idea isn’t new, of course. Martin Fowler described the pattern back in 2005 under the name Event Sourcing: the application state isn’t stored directly but reconstructed from a sequence of events. Greg Young took it further in his work on CQRS – separating the write side, which produces events, from the read side, which builds projections over them. What my small JavaScript experiment showed me above all is how short the path is from the `reduce` one-liner to this architecture question: as soon as you treat events as the truth and state as a projection, you’ve already built Event Sourcing on a small scale – just in memory instead of in a database.\n\nI don’t want to make the idea bigger than it is. If you turn the fold into a system architecture, you buy yourself real problems. The event list grows without bound, so at some point you need snapshots so that not every startup folds through millions of events. The structure of the events changes with the application, but old events have to stay readable – this schema evolution stays with you permanently and is anything but a footnote. And for a simple admin dialog whose history nobody cares about, a direct update is simply the more honest tool. Keeping events pays off where the history means something in the domain: orders, accounts, contracts, measurement series.\n\nThat’s why, for now, my approach is: consistent in the small, cautious in the large. Folding events within a module costs almost nothing and forces a clean separation of “what happened” and “what follows from it.” Whether that should become a persistent event store for the whole system is a much bigger decision that you don’t make on the side during a refactoring.\n\n## What I take away from this\n\nThe README of statemutatejs was one line long, and yet the experiment taught me more than many a framework manual. The lesson is inconspicuous: when changes exist as values – as events you can keep, look at and replay – then the current state is just one of many possible evaluations. `reduce` over an array, a `Writable` in object mode, `scan` in RxJS or Bacon.js: four times the same fold, four times the same projection function.\n\nSince then, I ask one question more often in code reviews than I used to: where does this state come from, and could we record the changes as events instead? Most of the time the answer is “not worth it here,” and that’s fine. But in the cases where someone is building an undo function, an audit log or a reconciliation of two data sets by hand, the question almost always points to the same way out: the properties you want are already in the events. You just have to fold them.\n\n## Further reading\n\n- [MikeBild/statemutatejs](https://github.com/MikeBild/statemutatejs) – the experiment from October 2012 mentioned above\n- [Martin Fowler: Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html) – the pattern description from 2005\n- [Node.js 0.10 stream API](https://nodejs.org/docs/latest-v0.10.x/api/stream.html) – streams2 including objectMode\n- [MDN: Array.prototype.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) – the fold in the language standard\n- [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) – RxJS with the scan operator"},{"locale":"en","translation_key":"http-apis-klein-stabil-lesbar","slug":"http-apis-small-stable-readable","title":"HTTP APIs: Small, Stable, Readable","summary":"What the Heroku HTTP API Design Guide is worth when you hold it up against your own APIs – and why a few resources, a versioning promise and self-explanatory errors achieve more than any framework.","tags":["Software","Architecture"],"published_at":"2014-06-24T10:00:00+00:00","updated_at":"2026-07-14T16:07:55.065953+00:00","url":"https://www.mikebild.dev/en/blog/http-apis-small-stable-readable/","audio_url":null,"audio_duration_secs":null,"text":"# HTTP APIs: Small, Stable, Readable\n\nAn HTTP API that changes its shape every few weeks trains its clients – unfortunately in the wrong direction. After the second break, every client team builds a defensive layer: a mapper that renames fields before the rest of the code gets to see them. A try/catch around every date parser, because the time format has already changed twice. Checks for missing fields, for three different error formats, for status codes that sometimes mean one thing and sometimes another. After half a year, half of the client consists of code that doesn’t model the domain but distrust. And because every team invents this layer for itself, in the end it exists four times, in four variants, with four different bugs.\n\nSo the costs don’t arise where the API is built, but spread across everyone who uses it. That is what makes them so easy to overlook.\n\nIn May, Heroku published its HTTP API Design Guide – a slim document on GitHub, distilled from the work on the Heroku Platform API. I forked the repository at the end of May and have since held it up, point by point, against APIs that I maintain myself or see in reviews. I wouldn’t sign off on all of it. But the basic attitude matches pretty closely what I have found to hold up in my own projects: a good HTTP API is small, stable and readable. Everything else is accessories.\n\n## Small: a resource has to earn its place\n\nThe guide doesn’t say it literally, but it is between all the lines: few resources, with consistent conventions. Resource names in the plural (`/orders`, not `/order` and certainly not `/getOrders`), paths as flat as possible, IDs as lowercase UUIDs, `created_at` and `updated_at` on every resource – without anyone having to ask for them.\n\nThat sounds trivial, but it isn’t. In a project at the beginning of the year, we took over an API that had more than sixty endpoints – for a domain that was fully described by about ten resources. The rest were convenience endpoints: `/orders/search`, `/orders/latest`, `/ordersWithCustomer`, each created because a client team needed a particular view and the fastest route was a new endpoint. Each of these endpoints had its own response format, its own idea of pagination and its own lifespan. None of them could be removed, because nobody knew who was still calling it.\n\nSince then, my rule is: an endpoint is a liability, not a feature. Every resource I publish, I have to carry for years. So before every new path, I first ask whether the use case can be expressed through an existing resource plus query parameters. Most of the time the answer is yes – and the API stays small enough for a new developer to understand it in a morning.\n\nThis is the normal case that everything else should relate to:\n\n```http\nGET /orders/01234567-89ab-cdef-0123-456789abcdef HTTP/1.1\nHost: api.example.com\nAccept: application/json\n\nHTTP/1.1 200 OK\nContent-Type: application/json; charset=utf-8\n\n{\n  \"id\": \"01234567-89ab-cdef-0123-456789abcdef\",\n  \"state\": \"confirmed\",\n  \"total\": 4990,\n  \"currency\": \"EUR\",\n  \"created_at\": \"2014-06-20T08:30:00Z\",\n  \"updated_at\": \"2014-06-21T10:15:00Z\"\n}\n```\n\nNothing about it is spectacular. That is exactly the point: once you have seen this one response, you can guess the shape of every other resource in the API. This predictability is the actual product.\n\n## Readable: the error explains itself\n\nThe part of the guide I adopted immediately is the error format. Heroku proposes the same body for every error: a machine-readable `id`, a human-readable `message` and a `url` that points to further documentation.\n\n```json\n{\n  \"id\": \"rate_limit\",\n  \"message\": \"Account reached its API rate limit.\",\n  \"url\": \"https://docs.example.com/rate-limits\"\n}\n```\n\nWhy this convinces me: it serves both readers at once. The client code branches on the `id` without parsing strings. The person reading the log at two in the morning understands the `message` without opening the docs. And the `url` ends the guesswork when they do have to open them.\n\nThe contrast with practice is stark. In reviews, I have come across the same collection again and again: sometimes an HTML error text from the proxy, sometimes `{\"error\": true}`, sometimes a stack trace in plain text, sometimes status 200 with an error message in the body. Each of these variants forces the client to bolt another special case onto its defensive layer – which brings us back to the beginning.\n\nWith Express 4, which has been out since April, a uniform error format can be enforced with very little code. The core is a small factory for error objects and exactly one central error handler, registered as the last middleware:\n\n```javascript\n// errors.js - one error shape for the whole API\nfunction apiError(status, id, message, url) {\n  var err = new Error(message);\n  err.status = status;\n  err.id = id;\n  err.url = url;\n  return err;\n}\n\napp.get('/orders/:id', function (req, res, next) {\n  store.findOrder(req.params.id, function (err, order) {\n    if (err) { return next(err); }\n    if (!order) {\n      return next(apiError(404, 'order_not_found',\n        'No order exists with the given id.',\n        'https://docs.example.com/errors#order_not_found'));\n    }\n    res.json(order);\n  });\n});\n\n// registered last, catches everything\napp.use(function (err, req, res, next) {\n  res.status(err.status || 500).json({\n    id: err.id || 'internal_error',\n    message: err.message || 'An unexpected error occurred.',\n    url: err.url || 'https://docs.example.com/errors'\n  });\n});\n```\n\nThe side effect I hadn’t expected: the list of error IDs becomes a catalog of the domain. When it contains `order_not_found`, `order_already_shipped` and `payment_declined`, it reads like a summary of the domain. An API whose errors read like this needs much less prose documentation – the URL tells the domain story for the good cases, the error ID tells it for the bad ones.\n\n## Stable: versioning is a promise, not a header\n\nOn versioning, I only half agree with the guide. Heroku recommends requesting the version via the Accept header – `Accept: application/vnd.heroku+json; version=3` – and rejecting requests without an explicit version. That is the cleanest form: the URL identifies the resource, the header negotiates the representation. That is how HTTP was meant to be.\n\nBut in the projects I know, the version in the URL almost always wins, that is, `/v1/orders`. And not out of ignorance, but for solid reasons. A curl call to reproduce a bug doesn’t need an extra header. The access log shows at a glance which version a client is using – important when you want to know whether `/v1` can finally be switched off. Proxies and routers can split by path prefix without inspecting headers. And in the browser, you can look at a GET response without any tool. The Accept header is more elegant; the URL is more honest about the everyday reality of operations and debugging. I use both and wouldn’t push the header variant on any team that loves its logs today.\n\nMore important than how the version number travels is something else anyway: what the version promises. A version number is the commitment that nothing breaks within that version. In concrete terms, for me that means:\n\n- New fields and new resources can be added at any time – clients have to ignore what they don’t know.\n- Existing fields change neither name nor type nor meaning.\n- Error IDs and status codes for existing cases stay as they are.\n- If any of these is violated, there is a new version – and the old one keeps running until it can be shown that nobody calls it anymore.\n\nThis decision logic is small enough for a diagram, and by now I actually put it up on the wall when a team is discussing a change:\n\n```mermaid\nflowchart TD\n  A[Change to the API] --> B{Only additive?<br/>New fields, new resources}\n  B -- yes --> C[Same version<br/>clients keep running unchanged]\n  B -- no --> D{Does the name, type or<br/>meaning of something existing change?}\n  D -- no --> C\n  D -- yes --> E[New version<br/>old version keeps running<br/>until the logs declare it dead]\n```\n\nThe uncomfortable part is in the last box. Announcing a new version is cheap; keeping the old one alive is the real work. If you don’t want to keep the promise, you’d better not hand out a version number at all – a `/v1` that still breaks every two months is worse than none, because it signals a reliability that doesn’t exist.\n\n## Timestamps and pagination – the underestimated details\n\nTwo points in the guide look like footnotes at first glance, but have saved me more hours of debugging than some architecture decisions.\n\nFirst: times exclusively as ISO 8601 in UTC, that is, `2014-06-20T08:30:00Z`. In a legacy system, I once had three time formats in the same API – Unix timestamps in seconds, Unix timestamps in milliseconds and a German date format with dots. The bug that resulted was a classic: a client interpreted seconds as milliseconds, and suddenly all orders were in January 1970. Since everything has consistently been ISO 8601 with a `Z` at the end, this entire class of bugs has disappeared. The format is sortable, unambiguous, and every parser in the world knows it.\n\nSecond: pagination. The guide refers to Heroku’s Range header – the client requests a slice with `Range`, the server responds with `206 Partial Content` and names the key for the next page in the `Next-Range` header:\n\n```bash\ncurl -i https://api.example.com/orders \\\n  -H \"Range: id 01234567-89ab-cdef-0123-456789abcdef..; max=200\"\n\n# HTTP/1.1 206 Partial Content\n# Content-Range: id 01234567-...;\n# Next-Range: id 89abcdef-...; max=200\n```\n\nTechnically, I like one thing about it above all: it is cursor pagination. The client pages forward from a key, not from an offset – and therefore gets no duplicates or gaps when new records are created between two pages. The classic `?page=3` has exactly this problem, and it only shows up in production when the data changes fast enough.\n\nStill, on the transport, I am again more pragmatic than the guide. Range headers for something other than bytes are unusual, many HTTP libraries make access to response headers more awkward than necessary, and in the team you have to explain the convention to everyone anew. In my own APIs, I have ended up with cursor pagination via query parameters – `?limit=200&after=<id>` – with a `next` link in the body. The same property, more ordinary mechanics. I adopt the guide’s idea, not its syntax.\n\nThat, by the way, is exactly my relationship with the document as a whole. It is a collection of decisions that a team made for its platform and justified publicly – not a standard, not a law. Its value lies in forcing you, while reading, to take a stand for each of your own APIs: adopt, deviate, but never again “we never thought about that”.\n\n## What I take away\n\nIf you build an HTTP API in 2014, the format problem is basically solved – JSON has won, the verbs are in the RFC, and with HAL and JSON Schema there are lively discussions about how much hypermedia an API should take. The real problem is a social one: an API is a promise to people whose code you will never see. Small, stable and readable are the three properties that make this promise keepable. Small, so you can keep track of it. Stable, so you can trust it. Readable, so you can understand it without an interpreter.\n\nThe Heroku guide is the best checklist for this that I have come across so far – precisely because it is so short and because a real platform is clearly behind every point. My fork has been in my GitHub account since the end of May, and the most useful exercise wasn’t reading it, but mirroring it: putting each of my own APIs next to it and noting, point by point, where it deviates and whether there is a reason for it. For me, two deliberate deviations remained – version in the URL, pagination via query parameters – and an uncomfortably long list of places where the deviation was simply sloppiness. I am working through that list right now. The clients won’t notice, and that is exactly how you know it is the right work.\n\n## Further reading\n\n- HTTP API Design Guide (original by interagent/Heroku): https://github.com/interagent/http-api-design\n- My fork of the guide: https://github.com/MikeBild/http-api-design\n- Heroku Platform API Reference (the API the guide came from): https://devcenter.heroku.com/articles/platform-api-reference\n- RFC 2616 – Hypertext Transfer Protocol HTTP/1.1: https://datatracker.ietf.org/doc/html/rfc2616\n- Express: http://expressjs.com/"},{"locale":"en","translation_key":"was-ich-an-elixir-gesucht-habe","slug":"what-i-was-looking-for-in-elixir","title":"What I Was Looking for in Elixir","summary":"It wasn’t the syntax that brought me to Elixir but the execution model of the Erlang VM – processes, messages and supervisors, seen through JavaScript and C# eyes.","tags":["Software","Architecture"],"published_at":"2014-05-12T10:00:00+00:00","updated_at":"2026-07-14T16:06:01.869581+00:00","url":"https://www.mikebild.dev/en/blog/what-i-was-looking-for-in-elixir/","audio_url":null,"audio_duration_secs":null,"text":"# What I Was Looking for in Elixir\n\nYou try out a new programming language because you like its syntax – that’s the usual reasoning. Shorter notation, more elegant lambdas, less ceremony. I think this reasoning is backwards. You get used to syntax in two weeks; it is the most interchangeable part of a language. Things get interesting where a language *executes* differently: how it organizes concurrency, who owns state and what happens when something breaks.\n\nThat is exactly why a small Elixir repository has been sitting in my GitHub account since last fall. Not because I liked the Ruby-like dress of the language – at first I almost didn’t care about that – but because the Erlang VM is at work under this dress. And it answers the three questions above radically differently from what I know from my daily work with JavaScript and C#: processes instead of threads, messages instead of shared state, “let it crash” instead of defensive try/catch at every corner.\n\n## A look over the fence, with a period flavor\n\nThe timing for this look over the fence is good. In February, Facebook bought WhatsApp for a sum everyone is still talking about – and suddenly even the management floor is interested in the fact that a surprisingly small team there serves several hundred million users. The backend: Erlang. The numbers that have been circulating from this corner for years – millions of concurrent connections on a single machine – sounded like folklore to me for a long time. Now people are taking a closer look, and so am I.\n\nElixir builds on exactly this machine. José Valim, known to many from the Rails world, is building a language with it that runs on the Erlang VM, can call Erlang modules directly and inherits the platform’s tools. The language is still young: currently version 0.13, on the way to 1.0, with occasional breaking changes between releases. Dave Thomas is writing “Programming Elixir” for the Pragmatic Programmers, available as a beta so far. So if you touch Elixir today, you are deliberately touching something unfinished – the platform underneath, by contrast, has been proven in production for more than twenty years.\n\n## A repository full of questions\n\nMy entry point was not a project but a collection of small experiments: [github.com/MikeBild/tryelixir](https://github.com/MikeBild/tryelixir), started in October, grown in evening hours. No README, no architecture, just folders – each folder a question I wanted to ask the language:\n\n- `actors` – what do `spawn` and `receive`, the tools of the trade for processes, feel like?\n- `bankAccount` – can a single process manage the state of an account on its own, without any lock?\n- `cowboy` – how do you speak HTTP on the Erlang VM, with the Cowboy web server?\n- `kataTennis` and `kataTennisFSM` – the well-known tennis kata, once in the classic way, once as a finite state machine\n- `leveldb` – how do you bind a library like LevelDB?\n\nI don’t claim more about the repository, because it isn’t more: a box of experiments. But the account exercise in it works well to show what grabbed me about the execution model.\n\n## Processes instead of threads\n\nFirst, the starting point. In my daily C# work, a bank account with concurrent access looks roughly like this – shared state, protected by a lock:\n\n```csharp\npublic class BankAccount\n{\n    private readonly object _sync = new object();\n    private decimal _balance;\n\n    public void Withdraw(decimal amount)\n    {\n        lock (_sync)\n        {\n            if (_balance < amount)\n                throw new InvalidOperationException(\"insufficient funds\");\n            _balance -= amount;\n        }\n    }\n}\n```\n\nThat works – as long as every access goes through the same lock, nobody takes two locks in different orders and no exception leaves the state half-changed. In code reviews, these are exactly the places where I get stuck the longest, and the bugs that slip through there only show up under load. In JavaScript, the question arises differently, but not better: a single thread with callbacks does protect against race conditions in memory, but in exchange a single expensive computation blocks everything else, and an uncaught error takes the whole Node process down with it.\n\nThe Erlang VM organizes the problem in a fundamentally different way. Its processes are not operating system threads but tiny units managed by the VM: a few kilobytes at startup, each with its own heap and its own garbage collection, preemptively scheduled. Hundreds of thousands of them on one machine are normal, not heroic. Above all, though: there is no shared memory between them. What a process knows, only it knows.\n\nThe same account in Elixir is a process that carries its balance along as the argument of an endless loop:\n\n```elixir\ndefmodule BankAccount do\n  def start(initial_balance) do\n    spawn(fn -> loop(initial_balance) end)\n  end\n\n  defp loop(balance) do\n    receive do\n      {:deposit, amount} ->\n        loop(balance + amount)\n      {:withdraw, amount, caller} when amount <= balance ->\n        send(caller, {:ok, balance - amount})\n        loop(balance - amount)\n      {:withdraw, _amount, caller} ->\n        send(caller, {:error, :insufficient_funds})\n        loop(balance)\n      {:balance, caller} ->\n        send(caller, {:balance, balance})\n        loop(balance)\n    end\n  end\nend\n```\n\nNo lock, no `synchronized`, no pondering over `volatile`. The balance can’t be changed from two sides at the same time, because only a single process owns it and works through the messages in its mailbox one after another. Concurrency doesn’t come from more threads on the same memory but from more processes, each with its own state – one process per account, not one lock per account.\n\n```mermaid\ngraph LR\n  subgraph SHARED[\"Threads and shared state\"]\n    T1[\"Thread 1\"] --> L[\"Lock\"]\n    T2[\"Thread 2\"] --> L\n    L --> MEM[\"shared memory<br/>balance\"]\n  end\n  subgraph MSG[\"Processes and messages\"]\n    P1[\"Process A\"] -- \"{:withdraw, 30}\" --> MB[\"Mailbox\"]\n    P2[\"Process B\"] -- \"{:deposit, 50}\" --> MB\n    MB --> ACC[\"BankAccount process<br/>own state: balance\"]\n  end\n```\n\n## Messages instead of calls\n\nSeen from outside, such an account is not an object with methods but an address to which you send messages:\n\n```elixir\naccount = BankAccount.start(100)\n\nsend(account, {:deposit, 50})\nsend(account, {:withdraw, 200, self()})\n\nreceive do\n  {:ok, new_balance} ->\n    IO.puts \"withdrawal ok, new balance: #{new_balance}\"\n  {:error, reason} ->\n    IO.puts \"withdrawal failed: #{reason}\"\nend\n```\n\nThe difference from a method call is bigger than it looks. A call is synchronous, free to think about and expensive in its consequences: the caller depends on the callee succeeding and shares stack and fate with it. A message is asynchronous and decoupled – whether and when an answer comes is a separate decision that becomes visible in the code. When you switch, this feels cumbersome at first. But it made me notice how many design decisions a method call silently makes that I had never thought about before.\n\nIf you don’t want to knit every protocol by hand, you reach for the platform’s OTP library: `gen_server` pours exactly this pattern – state in a loop, synchronous and asynchronous messages, orderly start and stop semantics – into a reusable form with callbacks. Writing the account exercise by hand was still the right way: only once you have built the `receive` loop yourself do you understand what OTP takes off your hands.\n\n## “Let it crash” – and who cleans up then?\n\nThe part that challenges my thinking the most is how errors are handled. My learned reflex from years with C# and JavaScript: errors must not happen, so I defend myself – null checks, try/catch around every layer, fallback values, logging and muddling on. I know the result from quite a few codebases, my own included: the error doesn’t get fixed, it gets smeared. Somewhere a catch block catches too much, the program keeps running with half-broken state, and the real bang comes hours later at a place that no longer has anything to do with the cause.\n\nThe Erlang world draws a conclusion from this that sounds reckless at first: let the process crash. No defensive catching inside the process itself – if a message doesn’t match the expected pattern or a computation fails, the process dies. This is only possible because of isolation: a dying process doesn’t drag any shared memory down with it; there is no half-changed state it could leave behind. Cleanup happens elsewhere – by a supervisor, a process whose only job is to watch other processes and restart them after a crash with fresh, defined state. Supervisors also watch other supervisors, and this produces trees:\n\n```mermaid\ngraph TD\n  APP[\"Application\"] --> SUP[\"Supervisor<br/>strategy: one_for_one\"]\n  SUP --> A1[\"BankAccount process<br/>account 1001\"]\n  SUP --> A2[\"BankAccount process<br/>account 1002\"]\n  SUP --> A3[\"BankAccount process<br/>account 1003\"]\n  A2 -. \"crashes\" .-> SUP\n  SUP -. \"restarts,<br/>fresh state\" .-> A2\n```\n\nThis turns error handling from a question of coding style into a question of architecture. No longer: where do I catch the exception? But: which unit may die, and who restarts it in which state? The answer isn’t scattered across a thousand catch blocks but sits in one place in the supervision tree. Joe Armstrong spelled out this idea in his dissertation – reliable systems *despite* faulty software, not through error-free software. While reading it, I kept thinking of production incidents where exactly this was missing: not fewer errors, but a defined way back to a known state.\n\n## The syntax as a bonus\n\nAnd in the end I do like the syntax after all – but as a bonus, not as the reason. Three things stand out.\n\nPattern matching is already visible above: the `receive` branches are not an if cascade over a message type but patterns with conditions, and the structure of the data documents itself exactly where it is processed. That `=` in Elixir is not an assignment but a match operator tripped me up at first and then convinced me.\n\nData is immutable. There is no `balance -= amount`; there is only a new value that moves into the next loop iteration. What remains a question of discipline in C# – please don’t modify shared objects – simply can’t be expressed here. Entire classes of bugs from my reviews don’t exist in this language.\n\nFinally, the pipe operator `|>` makes transformation chains readable, without intermediate variables and without calls nested from the inside out:\n\n```elixir\n\"transactions.csv\"\n|> File.read!\n|> String.split(\"\\n\")\n|> Enum.map(&String.strip/1)\n|> Enum.reject(&(&1 == \"\"))\n|> Enum.map(&String.split(&1, \";\"))\n```\n\nEach line a stage, the data flows from top to bottom. I have been writing the ES5 equivalent with a `for` loop and helper arrays for years without thinking about it – only the side-by-side comparison showed me how much noise is in it.\n\n## What makes its way back into my daily work\n\nElixir won’t become my production language in the foreseeable future. The projects I’m involved in are .NET and Node landscapes, and I won’t drag a pre-1.0 language into them. Still, the experiment wasn’t an end in itself, because I take some patterns of thinking back over the fence with me:\n\n- Small units that are ready to crash. A Node service that starts in seconds and that a process watchdog simply brings back up after a crash is superior to the big process that has to survive every error. A fast restart with fresh state beats heroically running on.\n- Messages instead of calls at the boundaries. Where two parts of a system should live and die independently of each other, a queue belongs in between, not a direct synchronous call – the decoupling that Erlang processes get out of the box is something I have to buy there with infrastructure.\n- State has an owner. Even without Erlang processes, a module can be the only place where a piece of state is changed, while everyone else talks to it only through defined messages or commands.\n- Immutable data wherever the language allows it – even if only as a team convention.\n\nJust as important is what does *not* come along. Rebuilding a supervisor in C# or JavaScript is tempting and leads you astray: without isolated processes with their own heap, “let it crash” is not a strategy but recklessness – the crashing thread does leave shared state behind after all, and the restart doesn’t start from zero. The model holds as a whole or not at all. Imitating OTP in another runtime would mean copying the facade without the foundation.\n\n## Bottom line\n\nWhat I was looking for in Elixir was not a prettier language but a different relationship to the two things that cause me the most work in projects: state and errors. What I found is an execution model that doesn’t solve both problems better but frames them differently – state has exactly one owner, and errors have a defined area in which they are allowed to die. That a pleasant, young language sits on top makes experimenting easier; everything is carried by the Erlang VM underneath.\n\nThe little repository stays where it is and keeps growing when the next question comes up. And I’m watching Elixir itself on its way to 1.0 – not because I’m going to build an account system on it tomorrow, but because this look over the fence has taught me more about my own tools than many a framework release on this side of it.\n\n## Further reading\n\n- [github.com/MikeBild/tryelixir](https://github.com/MikeBild/tryelixir) – my Elixir experiments\n- [elixir-lang.org: Getting Started](https://elixir-lang.org/getting-started/introduction.html) – the official introduction to the language\n- [Erlang/OTP Design Principles](https://www.erlang.org/doc/design_principles/des_princ.html) – supervision trees and behaviours in the official Erlang documentation\n- [Joe Armstrong: Making reliable distributed systems in the presence of software errors](https://erlang.org/download/armstrong_thesis_2003.pdf) – the dissertation behind “let it crash”"},{"locale":"en","translation_key":"control-flow-vor-async-await","slug":"control-flow-before-async-await","title":"Control Flow Before `async/await`","summary":"A look at the tiny library cflow shows how Node developers wired asynchronous steps into a chain by hand, and why the missing error channel is the real lesson.","tags":["Software","Node.js","Backend"],"published_at":"2014-03-12T10:00:00+00:00","updated_at":"2026-07-13T07:27:27.832717+00:00","url":"https://www.mikebild.dev/en/blog/control-flow-before-async-await/","audio_url":null,"audio_duration_secs":null,"text":"# Control Flow Before `async/await`\n\nNode 0.10 knows functions, callbacks and an event loop. What it does not know is a statement that says: “Do this, wait for the result, then do the next thing.” You have to establish this order yourself, step by step, by hand. And as soon as three or four steps build on each other, it becomes visible that “waiting” in a single-threaded environment is not a language feature but a design task.\n\nFor this I built myself a small library, `cflow`. It is so small that you can read it in one go, and that is exactly why it exposes the difference: between a nested callback chain and a pipeline whose transitions you have modeled once.\n\n## The problem: building order out of callbacks\n\nAn asynchronous operation in Node follows a convention. It takes a callback as its last argument, and this callback receives a possible error as its first argument. This is called an error-first or node-style callback:\n\n```js\nfs.readFile(\"config.json\", function (err, data) {\n  if (err) return handle(err);\n  // continue with data\n});\n```\n\nFor one step that is unremarkable. It gets unpleasant as soon as the next step needs the result of the previous one. Then the second call ends up in the callback of the first, the third in the callback of the second, and so on:\n\n```js\nloadUser(id, function (err, user) {\n  if (err) return done(err);\n  loadAccount(user.accountId, function (err, account) {\n    if (err) return done(err);\n    loadInvoices(account.id, function (err, invoices) {\n      if (err) return done(err);\n      done(null, summarize(user, account, invoices));\n    });\n  });\n});\n```\n\nThis shape has earned a fixed name: the pyramid of doom, sometimes also callback hell. The code wanders to the right, the closing brackets pile up, and the actual intent – load three things one after the other and summarize them – disappears behind the mechanics. That is not just a visual annoyance. Every level repeats the same error handling, and that is exactly where mistakes creep in.\n\n## The error case almost everyone hits at some point\n\nThe error-first convention demands a discipline that the language itself does not enforce: after `if (err)` there has to be a `return`. If it is missing, the function keeps running:\n\n```js\nloadUser(id, function (err, user) {\n  if (err) done(err);            // Careful: no return\n  loadAccount(user.accountId, function (err, account) {\n    // ...\n  });\n});\n```\n\nIn the error case, two things happen here at the same time. `done(err)` is called, so the caller considers the work finished and reports an error. In the same breath, `user.accountId` accesses a `user` that is `undefined`, because there was an error after all. That throws a second, completely different exception, or `done` is called a second time – this time with a misleading result. A callback that fires twice is especially nasty, because the order of the messages is no longer guaranteed. Sometimes the real error comes first, sometimes the follow-up error. Such bugs are hard to read in the log, because cause and effect fall apart in time.\n\nThat does not mean callbacks are bad. The finding is a different one: if every step writes its error check and its transition to the next step by hand, then every one of these places is an opportunity to get it wrong. What is missing is one place that models the control flow once, instead of reinventing it at every level of nesting.\n\n## Libraries that take over the flow\n\nIn 2014 you are not alone with this. Caolan McMahon’s `async` is the established toolbox and offers named functions for exactly these patterns. `async.series` runs tasks one after the other, `async.parallel` at the same time, and `async.waterfall` passes the result of each step on to the next:\n\n```js\nasync.waterfall([\n  function (next) { loadUser(id, next); },\n  function (user, next) { loadAccount(user.accountId, next); },\n  function (account, next) { loadInvoices(account.id, next); }\n], function (err, invoices) {\n  if (err) return handle(err);\n  // done\n});\n```\n\nThat is flat instead of nested, and there is only one error exit. In parallel, a second approach is maturing: promises. The Promises/A+ specification has caught on, libraries like Q, when.js and bluebird are widespread, and you can write chains with `.then(...)`. A built-in `Promise`, however, is not reliably available yet in the stable Node version 0.10; that only comes with the V8 update of the 0.11 line. If you want promises today, you add them as a dependency.\n\n## cflow: control flow reduced to the bare minimum\n\n`cflow` takes the waterfall route, but radically small. The entire library is a single function:\n\n```js\nvar Flow = function () {\n  this.args = Array.prototype.slice.call(arguments);\n  var next = function () {\n    if (this.args.length > 0) {\n      this.args.shift();\n      this.args[0].apply(next, Array.prototype.slice.call(arguments));\n    }\n  }.bind(this);\n  this.args[0].apply(next);\n};\n```\n\nThe trick is in two lines. `Flow` receives a list of functions. Each of these functions is called with `this` bound to `next` – that is, to the continuation. At the end of its work, a step simply calls `this(...)`. That discards the current step (`shift`) and calls the next one with exactly the arguments passed to `this`. The values thus flow on from step to step.\n\nIn use, this looks like a straight list of phases instead of a pyramid:\n\n```js\nvar Flow = require(\"cflow\");\n\nnew Flow(\n  function () {\n    slow(\"A\", this);                 // this is the continuation\n  },\n  function (data) {\n    slow2(data + \"B\", \"!!!\", this);  // data is \"A\"\n  },\n  function (data, data2) {\n    slow(data + \"C\" + data2, this);  // data is \"AB\", data2 is \"!!!\"\n  },\n  function (data) {\n    console.log(data);               // \"ABC!!!\"\n  }\n);\n\nfunction slow(value, callback) {\n  setTimeout(function () { callback(value); }, 200);\n}\nfunction slow2(value, value2, callback) {\n  setTimeout(function () { callback(value, value2); }, 300);\n}\n```\n\nEach step passes `this` as the callback to its asynchronous operation. As soon as that is done, the next step becomes active, and the intermediate result is available directly as an argument. Notably, a step can also pass on several values – `slow2` returns two, and the following step accepts two. That is exactly the waterfall pattern, just without an array, without options, without dependencies. The `package.json` simply lists nothing under `dependencies`.\n\n## Chain versus pipeline\n\nThe difference between the two styles is easy to put side by side. The callback chain nests state and error handling deeper with every level. The pipeline lays the steps out next to each other and turns the transitions into a separate, named mechanism.\n\n```mermaid\nflowchart TB\n  subgraph Kette[\"Callback chain (nested)\"]\n    direction TB\n    a1[\"Step 1\"] --> a2[\"  Step 2\"]\n    a2 --> a3[\"    Step 3\"]\n    a3 --> a4[\"      Result\"]\n  end\n  subgraph Pipeline[\"Pipeline (modeled)\"]\n    direction LR\n    b1[\"Step 1\"] --> b2[\"Step 2\"]\n    b2 --> b3[\"Step 3\"]\n    b3 --> b4[\"Result\"]\n  end\n```\n\nVisually, the pipeline is calmer. More important, though, is what changes structurally. In the pipeline, the transition from step to step exists in only one place, namely in the library. If you want to improve something there – logging, a timeout, a central error switch – you have exactly one place for it. In the nested chain, you would have to repeat the same change at every level.\n\n## Where `cflow` reaches its limit\n\nAnd this is where the most honest lesson of this small piece of code lies. `cflow` models the order cleanly, but it does not model errors. There is no error-first channel, no abort, no `try`. If a step throws an exception or calls `this` with an error object, `Flow` does not handle it – the error is simply passed on as the next argument or falls through. Exactly what the callback convention at least provides for with its `err` argument is missing here entirely.\n\nThat is intentional, the consequence of “as simple as possible.” For a demonstration of control flow it is enough. For a service running under load it is not. With that, the library itself names the limit at which you have to keep thinking: a control flow is only complete once the error path is part of the model too. If you build your own flow function, you should therefore design the next step so that an error aborts the chain and is routed to a single endpoint instead of blindly running on. `async.waterfall` shows how, by jumping straight to the final callback when there is an error in the first argument.\n\n## Looking back from a later time\n\n**Editorial note (July 2026):** The following retrospective was added later. The main part of the article describes the state of 2014; the references to ES2015 and ES2017 do not belong to the original time perspective.\n\nIf you read this text years later, you know how it resolved. ES2015 brought generators, which together with libraries like `co` allowed asynchronous code that looked synchronous. And with ES2017, `async/await` became part of the language. With that, the question that carries this article almost completely disappears from everyday work: you write the order from top to bottom again, the error path is a normal `try/catch`, and waiting is a keyword.\n\nThat does not make the old exercise worthless, though. On the contrary. An `await` looks harmless and synchronous, but behind it there is still a non-blocking call that can hold resources. The things you had to make clear to yourself by hand in 2014 – where the order is enforced, where an error aborts the chain, where a timeout is missing, what happens with continuations that fire twice – are all still there. They are just hidden under a convenient syntax. If you have built explicit control flow yourself once, you still recognize these limits when the language no longer puts them in front of your eyes.\n\n## Further reading\n\n- Repository cflow: https://github.com/MikeBild/cflow\n- caolan/async, documentation of the control flow functions: https://github.com/caolan/async\n- Promises/A+ specification: https://promisesaplus.com/"},{"locale":"en","translation_key":"warum-katas-mehr-sind","slug":"why-katas-are-more-than-finger-exercises","title":"Why Katas Are More Than Finger Exercises","summary":"A kata is an architecture lab in miniature – because the task stays constant, it reveals what otherwise only the design knows.","tags":["Software","Testing"],"published_at":"2014-01-12T10:00:00+00:00","updated_at":"2026-07-14T16:02:12.984451+00:00","url":"https://www.mikebild.dev/en/blog/why-katas-are-more-than-finger-exercises/","audio_url":null,"audio_duration_secs":null,"text":"# Why Katas Are More Than Finger Exercises\n\nIn martial arts, a kata is a fixed sequence of movements that you repeat until it runs without thinking. Dave Thomas brought the term into programming a good ten years ago: small, sharply defined tasks that you don’t solve once but again and again – FizzBuzz, the bowling score, Roy Osherove’s String Calculator. codekata.com has a whole collection of them.\n\nThe comparison with martial arts hits one point very precisely and clearly misses another. Where it hits: a kata takes place without anything at stake. No customer is waiting, no deadline is pressing, no legacy system is interfering. You can pick a single thing and give it your full attention. Where it falls short: in martial arts, the goal of repetition is for the movement to become ever more identical. In programming, that would be pointless. Typing isn’t the bottleneck, and if you write down the bowling score identically for the fifth time, you have learned nothing the fifth time.\n\nThe repetition pays off for a different reason. Because the task stays constant, the design can vary – and that is exactly how design decisions become visible that stay invisible in everyday project work. A kata isn’t typing practice. It is an architecture lab in miniature.\n\n## A lab needs a constant\n\nIf you seriously want to compare two designs, you have to hold everything else fixed. In a project, that is practically never possible. There, the problem always changes between two approaches too: new requirements, different colleagues, shifted priorities. If the second solution looks better than the first, nobody knows whether the design was better or just the circumstances more favorable. That is why you can rarely read cleanly from a project what a single design decision really cost or brought.\n\nThe kata turns this around. The problem is small, completely known, and stays exactly the same. The requirements are fixed before the first line is written. What varies between two runs is exclusively the design: where does the state live? What is a function, what is an object? Which boundary separates logic from input and output? If run three is easier to test than run one, it isn’t because of the task. It is because of a decision I made – and that I can now name.\n\nThat sounds trivial, but it isn’t. Only through repetitions like these did I notice how many of my design habits were simply habits: things I did because I always did them that way, not because they served the task. In a project, something like that goes unnoticed, because nobody ever solves the same task a second time in a different way. In a kata, it is noticed immediately.\n\n## Two shelves full of attempts\n\nMy GitHub account holds two such collections from recent years. The older repository is simply called Katas, dates from 2010, and contains C# exercises: a tennis kata and a FizzBuzz variant that I built with the Reactive Extensions back then – not because FizzBuzz needs that, but because I wanted to know how the same trivial task feels when you think of it as a stream of events instead of a loop. There is no README; the repository is a personal practice archive and doesn’t want to be anything else.\n\nThe younger one is called AppKatas, dates from 2013, and is written in JavaScript. Among other things, it contains a calculator kata and a TicTacToe kata, both deliberately implemented as pure JavaScript with Event Sourcing; the modules run in the browser and under Node.js, and the tests run on Travis. TicTacToe exists there in two stages: as a pure browser application and as a client-server variant with a small Node server.\n\nThe value of these repositories doesn’t lie in the code. Today, I would write it differently in many places. The value lies in the fact that the same tasks, solved several times and in different ways, sit side by side there. You can compare the designs because the task stayed constant. That is exactly what I mean by a lab.\n\n## Testability is design pressure\n\nThe tennis kata looks harmless: count the points of a tennis game and output the score – Love, Fifteen, Thirty, Forty, Deuce, Advantage. In the first run in 2010, I built it as a class with two counters and one big method that assembles the score as text. The first NUnit test for it looked roughly like this:\n\n```csharp\n[TestFixture]\npublic class TennisGameTests\n{\n    [Test]\n    public void Score_AfterDeuce_ReturnsAdvantage()\n    {\n        var game = new TennisGame();\n        for (var i = 0; i < 3; i++)\n        {\n            game.WinPoint(Player.One);\n            game.WinPoint(Player.Two);\n        }\n        game.WinPoint(Player.One);\n\n        Assert.AreEqual(\"Advantage Player One\", game.Score());\n    }\n}\n```\n\nThe test works, but it gives something away: to check a single score, I have to play seven points in the right order. The state is locked inside the object, and the only way in goes through the history. With deuce, that is still bearable. With a task that has more state, exactly this pattern becomes torture – every test begins with a long setup that has nothing to do with the actual assertion.\n\nThat is the moment when testability becomes design pressure. The test that is hard to write isn’t a testing problem; it is a symptom. It shows that the design doesn’t allow direct access to the state that matters for the domain. In the second run, I modeled the score as a value you can construct directly, and the transition logic as a function from state to state. The tests shrank to three lines, and along the way, the big text method had fallen apart into small, nameable cases.\n\nIn a project, I would never have done this second run. After all, the first version worked. Nobody rebuilds a working piece of software just to see whether the design could also be different. In a kata, that is exactly the purpose of the exercise.\n\n## The same task, two designs\n\nI saw the lab effect most clearly with TicTacToe in AppKatas. The obvious first version in JavaScript looks the way most people would probably write it – a game object that holds a board and changes it with every move:\n\n```javascript\nfunction Game() {\n  this.board = [null, null, null, null, null, null, null, null, null];\n  this.currentPlayer = \"X\";\n}\n\nGame.prototype.move = function (field) {\n  if (this.board[field] !== null) {\n    throw new Error(\"field already taken\");\n  }\n  this.board[field] = this.currentPlayer;\n  this.currentPlayer = this.currentPlayer === \"X\" ? \"O\" : \"X\";\n};\n```\n\nThat is perfectly fine and easily carries a small game. It gets interesting in the second run with a different fundamental decision: the game doesn’t store a board, only the list of moves. The board is derived from the events when needed:\n\n```javascript\nfunction replay(events) {\n  var board = [null, null, null, null, null, null, null, null, null];\n  events.forEach(function (event) {\n    board[event.field] = event.player;\n  });\n  return board;\n}\n\nfunction move(events, field) {\n  var board = replay(events);\n  if (board[field] !== null) {\n    throw new Error(\"field already taken\");\n  }\n  var player = events.length % 2 === 0 ? \"X\" : \"O\";\n  return events.concat([{ player: player, field: field }]);\n}\n```\n\nNo `this`, no mutation, no constructor. `move` takes a list and returns a new list. The consequences of this one decision practically fall into your lap: a test is now a list in, a list out – you can write down any game state directly without having to play moves. Undo means leaving out the last element. And the client-server variant became almost trivial, because a list of moves can be sent as JSON, whereas an object with methods and internal state falls apart at the process boundary.\n\n```mermaid\nflowchart TD\n  A[Same task:<br/>TicTacToe] --> B[Design 1:<br/>state is mutated]\n  A --> C[Design 2:<br/>list of moves, board derived]\n  B --> D[Test needs<br/>move history as setup]\n  C --> E[Test is<br/>list in, list out]\n  D --> F[Difference is attributable<br/>to the design, because the<br/>problem stayed constant]\n  E --> F\n```\n\nThe point isn’t that event lists are better than mutable state. For a TicTacToe in the browser, the first version is simply appropriate, and running `replay` completely on every move clearly doesn’t scale to large numbers of events. The point is that I can hold both designs side by side against the same task. Only that lets me see what the decision costs and what it buys. In a project, I only ever get to see one of the two branches – the one we chose. The other remains speculation.\n\nAlong the way, the second version forces a clean boundary that tends to blur in the first: the game logic knows nothing about the DOM. `replay` and `move` run unchanged under Node and in the browser; the rendering is a thin edge that receives events and draws a board. I didn’t draw this boundary because a principle demands it, but because the design pushed it on me. Boundaries that get pushed on you like this stick better than preached ones.\n\n## The luxury of throwing away\n\nA kata includes a step that is unthinkable in a project: at the end, the code is deleted. Not archived, not kept as the basis for the next run – deleted. Next time, you start from scratch.\n\nAt first, that struck me as wasteful. By now, I consider it the most important part. As long as code lives on, you defend it. You build on it, work around its weaknesses, get used to its shape. Only when it is certain that it will disappear do you become honest with it. Then you try out the decision you would never risk in a project, because there every decision immediately gets grandfathered in.\n\nThat is exactly the difference between practicing and working. In a project, code is a capital good, and every alternative competes with what is already there. In a kata, code is experimental material. You may think an idea through to the end, find that it doesn’t hold, and bury it at no cost. The insight survives; the code doesn’t. That is the right order.\n\n## What a round looks like for me\n\nOver time, a simple format has settled in for me, without any supporting program – one hour, one editor, one task:\n\n- Choose a familiar task, not a new one. Your curiosity should go to the design, not the problem.\n- Before the first test, fix a single design decision that turns out differently this time than last time.\n- Write the tests first, and read every sluggish test as a hint about the design, not as a testing problem.\n- At the end, jot down two or three sentences: what was easier, what was harder, and why?\n- Delete the code.\n\nThe notes are inconspicuous, but they are the actual result. After a few rounds with the same task, they add up to a small, self-made set of index cards about design decisions – backed by code you wrote yourself instead of taken on faith from a book.\n\n## What sticks\n\nFinger exercise is the wrong word, because it describes the goal wrongly. What gets trained isn’t the hand; it is judgment. A kata holds the problem fixed so that the design can vary, and thereby reveals what a design decision really does: which tests it makes easy or sluggish, which boundaries it forces, what it costs at a process boundary. These are exactly the questions that echo for years in large systems – except that there, you can never observe them in isolation.\n\nThat is why I don’t consider the half hour with FizzBuzz, tennis, or TicTacToe wasted time, even though nothing comes out of it that anyone uses. Something else comes out of it: the experience of having seen the same task with two designs. Once you have that, you no longer argue from preferences in the next architecture discussion but from observations. That is more than a finger exercise could ever deliver.\n\n## Further reading\n\n- https://github.com/MikeBild/AppKatas – my JavaScript katas (calculator, TicTacToe with Event Sourcing)\n- https://github.com/MikeBild/Katas – my older C# katas (tennis, FizzBuzz with Rx)\n- http://codekata.com/ – Dave Thomas’ kata collection, which coined the term\n- https://osherove.com/tdd-kata-1 – Roy Osherove’s String Calculator kata"}],"decks":[{"id":"introduction-javascript-typescript","title":"JavaScript & TypeScript: Von Werten zu Verträgen","summary":"Von Werten und Funktionen über ESM und Async bis zu Generics, Runtime Validation und Library Design.","topics":["JavaScript","TypeScript"],"url":"https://slides.mikebild.dev/introduction-javascript-typescript.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.pdf?v=c6f94b1ce22b","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.mp4?v=c6f94b1ce22b","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.png?v=c6f94b1ce22b","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.de.vtt?v=c6f94b1ce22b","repository":"https://github.com/MikeBild/introduction-javascript","articles":[],"slide_count":124,"slides":[{"no":1,"title":"JavaScript und TypeScript von Grund auf","section":true},{"no":2,"title":"Werte, Funktionen, Objekte, Prototypen","section":true},{"no":3,"title":"Warum überrascht JavaScript manchmal?"},{"no":4,"title":"Primitives nach Wert, Objects nach Reference"},{"no":5,"title":"Strict Equality statt Loose Equality"},{"no":6,"title":"Wie behandelst du fehlende Werte?"},{"no":7,"title":"Jetzt du: Ein Rabatt von null bleibt null"},{"no":8,"title":"Funktionen sind Werte"},{"no":9,"title":"Closures merken sich ihren Scope"},{"no":10,"title":"Higher-Order Functions bauen Funktionen"},{"no":11,"title":"Wo Loops und this überraschen"},{"no":12,"title":"Jetzt du: Eine Closure merkt sich den Gruß"},{"no":13,"title":"Geteilte References ändern still mit"},{"no":14,"title":"Spread baut neu, Destructuring liest heraus"},{"no":15,"title":"Spread kopiert nur die oberste Ebene"},{"no":16,"title":"toSorted und with lassen das Original stehen"},{"no":17,"title":"Jetzt du: Eine Bestellung ohne Mutation ändern"},{"no":18,"title":"Jedes Objekt zeigt auf einen Prototyp"},{"no":19,"title":"class ist Syntax über Prototypen"},{"no":20,"title":"Eine Methode als Callback verliert this"},{"no":21,"title":"Komposition schlägt Mixins"},{"no":22,"title":"Prototype Pollution trifft jedes Objekt"},{"no":23,"title":"Jetzt du: Ein Merge ohne Prototype Pollution"},{"no":24,"title":"Arrays, Modules, Async, Fehler","section":true},{"no":25,"title":"Loops mischen Was und Wie"},{"no":26,"title":"filter wählt, map wandelt, reduce fasst zusammen"},{"no":27,"title":"find, some und groupBy ersetzen Suchschleifen"},{"no":28,"title":"Wo Array-Methoden überraschen"},{"no":29,"title":"Jetzt du: Die Summe der offenen Bestellungen"},{"no":30,"title":"Warum Modules?"},{"no":31,"title":"Named Exports machen Dependencies sichtbar"},{"no":32,"title":"Node braucht type module und Dateiendungen"},{"no":33,"title":"Was beim Umstieg auf ES Modules hakt"},{"no":34,"title":"Jetzt du: Ein Module, eine Aufgabe"},{"no":35,"title":"Warten, ohne zu blockieren"},{"no":36,"title":"then hängt Schritte zu einer Chain"},{"no":37,"title":"async/await liest sich wie synchroner Code"},{"no":38,"title":"Parallel statt nacheinander"},{"no":39,"title":"Wo await fehlt oder nicht wartet"},{"no":40,"title":"Jetzt du: Bestellung und Kunde parallel laden"},{"no":41,"title":"Fehler sind unsichtbar"},{"no":42,"title":"Wann Result, wann Exception?"},{"no":43,"title":"Wirf nur Error-Objekte"},{"no":44,"title":"Ein Result-Objekt macht Fehler sichtbar"},{"no":45,"title":"Wo gehen async Errors verloren?"},{"no":46,"title":"Jetzt du: Eine Menge als Result prüfen"},{"no":47,"title":"Erste Types, Setup, Unions, Narrowing","section":true},{"no":48,"title":"Warum TypeScript?"},{"no":49,"title":"Grenzen annotieren"},{"no":50,"title":"Type Inference erledigt den Rest"},{"no":51,"title":"unknown statt any"},{"no":52,"title":"Was Types zur Laufzeit nicht leisten"},{"no":53,"title":"Jetzt du: Eine Funktion an ihren Grenzen typisieren"},{"no":54,"title":"Drei Checks, ein Befehl"},{"no":55,"title":"strict ist erst die Untergrenze"},{"no":56,"title":"Ein check-Script für lokal und CI"},{"no":57,"title":"Was der Compiler allein nicht findet"},{"no":58,"title":"Jetzt du: Eine alte tsconfig modernisieren"},{"no":59,"title":"Object Types beschreiben Daten"},{"no":60,"title":"Literal Types ersetzen Magic Strings"},{"no":61,"title":"Werte und Types aus einer Quelle"},{"no":62,"title":"Die Form zählt, nicht der Name"},{"no":63,"title":"Jetzt du: Bestellstatus aus einer Quelle"},{"no":64,"title":"Unions brauchen Type Checks"},{"no":65,"title":"Ein Discriminator trennt die Varianten"},{"no":66,"title":"Exhaustiveness Check erzwingen"},{"no":67,"title":"Type Guards glauben dir ungeprüft"},{"no":68,"title":"Jetzt du: Ein neuer State für LoadState"},{"no":69,"title":"Generics, Utility Types, Functional","section":true},{"no":70,"title":"any verliert Information"},{"no":71,"title":"Type Parameter verbinden Ein- und Ausgabe"},{"no":72,"title":"extends und keyof setzen Grenzen"},{"no":73,"title":"Auch Types haben Parameter"},{"no":74,"title":"Jetzt du: Eine Generic Function last"},{"no":75,"title":"Kopierte Types driften auseinander"},{"no":76,"title":"Pick und Omit leiten Varianten ab"},{"no":77,"title":"Record erzwingt vollständige Lookup Tables"},{"no":78,"title":"Types aus Funktionen ableiten"},{"no":79,"title":"Wo Utility Types weniger prüfen als gedacht"},{"no":80,"title":"Jetzt du: Einen Patch für Bestellungen ableiten"},{"no":81,"title":"Versteckte Dependencies machen Code unvorhersagbar"},{"no":82,"title":"pipe setzt kleine Schritte zusammen"},{"no":83,"title":"Predicates und Comparators wiederverwenden"},{"no":84,"title":"Side Effects gehören an den Rand"},{"no":85,"title":"Wann funktionaler Stil schadet"},{"no":86,"title":"Jetzt du: Eine Bestellsumme ohne versteckte Dependencies"},{"no":87,"title":"Tests, Iterators, Async für Profis","section":true},{"no":88,"title":"Warum Tests sich lohnen"},{"no":89,"title":"Ein Test beschreibt ein Behavior"},{"no":90,"title":"Dependencies als Parameter machen Tests einfach"},{"no":91,"title":"Tabellen und Fake Timers sparen Tests und Zeit"},{"no":92,"title":"Jetzt du: Den Fehlerfall von parsePort testen"},{"no":93,"title":"for...of fragt einen Iterator ab"},{"no":94,"title":"Generators pausieren bei yield"},{"no":95,"title":"Iterator Helpers arbeiten lazy"},{"no":96,"title":"for await holt Pages nacheinander ab"},{"no":97,"title":"Was du bei Generators beachten musst"},{"no":98,"title":"Jetzt du: Eine unendliche Sequence lazy auswerten"},{"no":99,"title":"Was geht in Produktion schief?"},{"no":100,"title":"Jeder Request braucht ein AbortSignal"},{"no":101,"title":"Ein Pool begrenzt die Concurrency"},{"no":102,"title":"Große Daten fließen als Stream"},{"no":103,"title":"Wo Abbrechen nicht wirklich abbricht"},{"no":104,"title":"Jetzt du: Eine Bestellung mit Timeout laden"},{"no":105,"title":"Advanced Types, Validation, Branded Types","section":true},{"no":106,"title":"Types aus Types berechnen"},{"no":107,"title":"Conditional Types unterscheiden Fälle"},{"no":108,"title":"Mapped Types laufen über Keys"},{"no":109,"title":"Template Literal Types bauen Strings"},{"no":110,"title":"Wann lohnen sich berechnete Types nicht?"},{"no":111,"title":"Jetzt du: Event-Namen aus Unions berechnen"},{"no":112,"title":"Types verschwinden zur Runtime"},{"no":113,"title":"Schema und Type aus einer Quelle"},{"no":114,"title":"parse wirft, safeParse liefert ein Result"},{"no":115,"title":"Konfiguration scheitert früh beim Start"},{"no":116,"title":"Wo zod anders arbeitet als erwartet"},{"no":117,"title":"Jetzt du: Ein Schema für deine Domain"},{"no":118,"title":"Alles ist ein string"},{"no":119,"title":"Ein Brand macht Types unterscheidbar"},{"no":120,"title":"Erzeugen nur mit Prüfung"},{"no":121,"title":"Mehr als IDs"},{"no":122,"title":"Wo Brands ihren Schutz verlieren"},{"no":123,"title":"Jetzt du: Cent-Beträge nur mit Prüfung"},{"no":124,"title":"Fragen?","section":true}],"languages":{"de":{"title":"JavaScript und TypeScript von Grund auf","summary":"Du schreibst modernes JavaScript und typisierst es mit TypeScript so, dass der Compiler deine Fehler vor dem Deployment findet.","url":"https://slides.mikebild.dev/introduction-javascript-typescript.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.pdf?v=c6f94b1ce22b","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.mp4?v=c6f94b1ce22b","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.png?v=c6f94b1ce22b","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.de.vtt?v=c6f94b1ce22b","slide_count":124,"slides":[{"no":1,"title":"JavaScript und TypeScript von Grund auf","section":true},{"no":2,"title":"Werte, Funktionen, Objekte, Prototypen","section":true},{"no":3,"title":"Warum überrascht JavaScript manchmal?"},{"no":4,"title":"Primitives nach Wert, Objects nach Reference"},{"no":5,"title":"Strict Equality statt Loose Equality"},{"no":6,"title":"Wie behandelst du fehlende Werte?"},{"no":7,"title":"Jetzt du: Ein Rabatt von null bleibt null"},{"no":8,"title":"Funktionen sind Werte"},{"no":9,"title":"Closures merken sich ihren Scope"},{"no":10,"title":"Higher-Order Functions bauen Funktionen"},{"no":11,"title":"Wo Loops und this überraschen"},{"no":12,"title":"Jetzt du: Eine Closure merkt sich den Gruß"},{"no":13,"title":"Geteilte References ändern still mit"},{"no":14,"title":"Spread baut neu, Destructuring liest heraus"},{"no":15,"title":"Spread kopiert nur die oberste Ebene"},{"no":16,"title":"toSorted und with lassen das Original stehen"},{"no":17,"title":"Jetzt du: Eine Bestellung ohne Mutation ändern"},{"no":18,"title":"Jedes Objekt zeigt auf einen Prototyp"},{"no":19,"title":"class ist Syntax über Prototypen"},{"no":20,"title":"Eine Methode als Callback verliert this"},{"no":21,"title":"Komposition schlägt Mixins"},{"no":22,"title":"Prototype Pollution trifft jedes Objekt"},{"no":23,"title":"Jetzt du: Ein Merge ohne Prototype Pollution"},{"no":24,"title":"Arrays, Modules, Async, Fehler","section":true},{"no":25,"title":"Loops mischen Was und Wie"},{"no":26,"title":"filter wählt, map wandelt, reduce fasst zusammen"},{"no":27,"title":"find, some und groupBy ersetzen Suchschleifen"},{"no":28,"title":"Wo Array-Methoden überraschen"},{"no":29,"title":"Jetzt du: Die Summe der offenen Bestellungen"},{"no":30,"title":"Warum Modules?"},{"no":31,"title":"Named Exports machen Dependencies sichtbar"},{"no":32,"title":"Node braucht type module und Dateiendungen"},{"no":33,"title":"Was beim Umstieg auf ES Modules hakt"},{"no":34,"title":"Jetzt du: Ein Module, eine Aufgabe"},{"no":35,"title":"Warten, ohne zu blockieren"},{"no":36,"title":"then hängt Schritte zu einer Chain"},{"no":37,"title":"async/await liest sich wie synchroner Code"},{"no":38,"title":"Parallel statt nacheinander"},{"no":39,"title":"Wo await fehlt oder nicht wartet"},{"no":40,"title":"Jetzt du: Bestellung und Kunde parallel laden"},{"no":41,"title":"Fehler sind unsichtbar"},{"no":42,"title":"Wann Result, wann Exception?"},{"no":43,"title":"Wirf nur Error-Objekte"},{"no":44,"title":"Ein Result-Objekt macht Fehler sichtbar"},{"no":45,"title":"Wo gehen async Errors verloren?"},{"no":46,"title":"Jetzt du: Eine Menge als Result prüfen"},{"no":47,"title":"Erste Types, Setup, Unions, Narrowing","section":true},{"no":48,"title":"Warum TypeScript?"},{"no":49,"title":"Grenzen annotieren"},{"no":50,"title":"Type Inference erledigt den Rest"},{"no":51,"title":"unknown statt any"},{"no":52,"title":"Was Types zur Laufzeit nicht leisten"},{"no":53,"title":"Jetzt du: Eine Funktion an ihren Grenzen typisieren"},{"no":54,"title":"Drei Checks, ein Befehl"},{"no":55,"title":"strict ist erst die Untergrenze"},{"no":56,"title":"Ein check-Script für lokal und CI"},{"no":57,"title":"Was der Compiler allein nicht findet"},{"no":58,"title":"Jetzt du: Eine alte tsconfig modernisieren"},{"no":59,"title":"Object Types beschreiben Daten"},{"no":60,"title":"Literal Types ersetzen Magic Strings"},{"no":61,"title":"Werte und Types aus einer Quelle"},{"no":62,"title":"Die Form zählt, nicht der Name"},{"no":63,"title":"Jetzt du: Bestellstatus aus einer Quelle"},{"no":64,"title":"Unions brauchen Type Checks"},{"no":65,"title":"Ein Discriminator trennt die Varianten"},{"no":66,"title":"Exhaustiveness Check erzwingen"},{"no":67,"title":"Type Guards glauben dir ungeprüft"},{"no":68,"title":"Jetzt du: Ein neuer State für LoadState"},{"no":69,"title":"Generics, Utility Types, Functional","section":true},{"no":70,"title":"any verliert Information"},{"no":71,"title":"Type Parameter verbinden Ein- und Ausgabe"},{"no":72,"title":"extends und keyof setzen Grenzen"},{"no":73,"title":"Auch Types haben Parameter"},{"no":74,"title":"Jetzt du: Eine Generic Function last"},{"no":75,"title":"Kopierte Types driften auseinander"},{"no":76,"title":"Pick und Omit leiten Varianten ab"},{"no":77,"title":"Record erzwingt vollständige Lookup Tables"},{"no":78,"title":"Types aus Funktionen ableiten"},{"no":79,"title":"Wo Utility Types weniger prüfen als gedacht"},{"no":80,"title":"Jetzt du: Einen Patch für Bestellungen ableiten"},{"no":81,"title":"Versteckte Dependencies machen Code unvorhersagbar"},{"no":82,"title":"pipe setzt kleine Schritte zusammen"},{"no":83,"title":"Predicates und Comparators wiederverwenden"},{"no":84,"title":"Side Effects gehören an den Rand"},{"no":85,"title":"Wann funktionaler Stil schadet"},{"no":86,"title":"Jetzt du: Eine Bestellsumme ohne versteckte Dependencies"},{"no":87,"title":"Tests, Iterators, Async für Profis","section":true},{"no":88,"title":"Warum Tests sich lohnen"},{"no":89,"title":"Ein Test beschreibt ein Behavior"},{"no":90,"title":"Dependencies als Parameter machen Tests einfach"},{"no":91,"title":"Tabellen und Fake Timers sparen Tests und Zeit"},{"no":92,"title":"Jetzt du: Den Fehlerfall von parsePort testen"},{"no":93,"title":"for...of fragt einen Iterator ab"},{"no":94,"title":"Generators pausieren bei yield"},{"no":95,"title":"Iterator Helpers arbeiten lazy"},{"no":96,"title":"for await holt Pages nacheinander ab"},{"no":97,"title":"Was du bei Generators beachten musst"},{"no":98,"title":"Jetzt du: Eine unendliche Sequence lazy auswerten"},{"no":99,"title":"Was geht in Produktion schief?"},{"no":100,"title":"Jeder Request braucht ein AbortSignal"},{"no":101,"title":"Ein Pool begrenzt die Concurrency"},{"no":102,"title":"Große Daten fließen als Stream"},{"no":103,"title":"Wo Abbrechen nicht wirklich abbricht"},{"no":104,"title":"Jetzt du: Eine Bestellung mit Timeout laden"},{"no":105,"title":"Advanced Types, Validation, Branded Types","section":true},{"no":106,"title":"Types aus Types berechnen"},{"no":107,"title":"Conditional Types unterscheiden Fälle"},{"no":108,"title":"Mapped Types laufen über Keys"},{"no":109,"title":"Template Literal Types bauen Strings"},{"no":110,"title":"Wann lohnen sich berechnete Types nicht?"},{"no":111,"title":"Jetzt du: Event-Namen aus Unions berechnen"},{"no":112,"title":"Types verschwinden zur Runtime"},{"no":113,"title":"Schema und Type aus einer Quelle"},{"no":114,"title":"parse wirft, safeParse liefert ein Result"},{"no":115,"title":"Konfiguration scheitert früh beim Start"},{"no":116,"title":"Wo zod anders arbeitet als erwartet"},{"no":117,"title":"Jetzt du: Ein Schema für deine Domain"},{"no":118,"title":"Alles ist ein string"},{"no":119,"title":"Ein Brand macht Types unterscheidbar"},{"no":120,"title":"Erzeugen nur mit Prüfung"},{"no":121,"title":"Mehr als IDs"},{"no":122,"title":"Wo Brands ihren Schutz verlieren"},{"no":123,"title":"Jetzt du: Cent-Beträge nur mit Prüfung"},{"no":124,"title":"Fragen?","section":true}],"articles":[]},"en":{"title":"JavaScript and TypeScript from scratch","summary":"You write modern JavaScript and type it with TypeScript so the compiler finds your mistakes before deployment.","url":"https://slides.mikebild.dev/introduction-javascript-typescript.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.en.pdf?v=7c3d048ab16c","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.en.mp4?v=7c3d048ab16c","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.en.png?v=7c3d048ab16c","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-javascript-typescript/introduction-javascript-typescript.en.vtt?v=7c3d048ab16c","slide_count":124,"slides":[{"no":1,"title":"JavaScript and TypeScript from scratch","section":true},{"no":2,"title":"values, functions, objects, prototypes","section":true},{"no":3,"title":"Why does JavaScript sometimes surprise you?"},{"no":4,"title":"Primitives by value, objects by reference"},{"no":5,"title":"Strict equality instead of loose equality"},{"no":6,"title":"How do you handle missing values?"},{"no":7,"title":"Your turn: A discount of zero stays zero"},{"no":8,"title":"Functions are values"},{"no":9,"title":"Closures remember their scope"},{"no":10,"title":"Higher-Order Functions build functions"},{"no":11,"title":"Where loops and this surprise you"},{"no":12,"title":"Your turn: A closure remembers the greeting"},{"no":13,"title":"Shared references change quietly too"},{"no":14,"title":"Spread builds anew, Destructuring reads out"},{"no":15,"title":"Spread copies only the top level"},{"no":16,"title":"toSorted and with leave the original as is"},{"no":17,"title":"Your turn: Change an order without mutation"},{"no":18,"title":"Every object points to a prototype"},{"no":19,"title":"class is syntax over prototypes"},{"no":20,"title":"A method used as a callback loses this"},{"no":21,"title":"Composition beats mixins"},{"no":22,"title":"Prototype pollution affects every object"},{"no":23,"title":"Your turn: A merge without prototype pollution"},{"no":24,"title":"arrays, modules, async, errors","section":true},{"no":25,"title":"Loops mix the what and the how"},{"no":26,"title":"filter selects, map transforms, reduce combines"},{"no":27,"title":"find, some, and groupBy replace search loops"},{"no":28,"title":"Where array methods surprise you"},{"no":29,"title":"Your turn: The total of open orders"},{"no":30,"title":"Why modules?"},{"no":31,"title":"Named exports make dependencies visible"},{"no":32,"title":"Node needs type module and file extensions"},{"no":33,"title":"What trips you up when moving to ES modules"},{"no":34,"title":"Your turn: One module, one task"},{"no":35,"title":"Wait without blocking"},{"no":36,"title":"then links steps into a chain"},{"no":37,"title":"async/await reads like synchronous code"},{"no":38,"title":"Parallel instead of sequential"},{"no":39,"title":"Where await is missing or does not wait"},{"no":40,"title":"Your turn: load order and customer in parallel"},{"no":41,"title":"Errors are invisible"},{"no":42,"title":"When result, when Exception?"},{"no":43,"title":"Throw only Error objects"},{"no":44,"title":"A Result object makes errors visible"},{"no":45,"title":"Where do async errors get lost?"},{"no":46,"title":"Your turn: Check a quantity as a Result"},{"no":47,"title":"first types, setup, unions, narrowing","section":true},{"no":48,"title":"Why TypeScript?"},{"no":49,"title":"Annotate boundaries"},{"no":50,"title":"Type Inference handles the rest"},{"no":51,"title":"unknown instead of any"},{"no":52,"title":"What types cannot do at runtime"},{"no":53,"title":"Your turn: Type a function at its boundaries"},{"no":54,"title":"Three checks, one command"},{"no":55,"title":"strict is only the lower bound"},{"no":56,"title":"One check script for local use and CI"},{"no":57,"title":"What the compiler does not find by itself"},{"no":58,"title":"Your turn: Modernize an old tsconfig"},{"no":59,"title":"Object Types describe data"},{"no":60,"title":"Literal Types replace magic strings"},{"no":61,"title":"Values and types from one source"},{"no":62,"title":"The shape counts, not the name"},{"no":63,"title":"Your turn: order status from one source"},{"no":64,"title":"Unions need type checks"},{"no":65,"title":"A discriminator separates the variants"},{"no":66,"title":"Force an Exhaustiveness Check"},{"no":67,"title":"Type Guards believe you without checking"},{"no":68,"title":"Your turn: A new state for LoadState"},{"no":69,"title":"generics, utility types, functional","section":true},{"no":70,"title":"any loses information"},{"no":71,"title":"Type parameters connect input and output"},{"no":72,"title":"extends and keyof set limits"},{"no":73,"title":"Types have parameters too"},{"no":74,"title":"Your turn: A generic function last"},{"no":75,"title":"Copied types drift apart"},{"no":76,"title":"Pick and Omit derive variants"},{"no":77,"title":"Record enforces complete lookup tables"},{"no":78,"title":"Derive types from functions"},{"no":79,"title":"Where utility types check less than you expect"},{"no":80,"title":"Your turn: derive a patch for orders"},{"no":81,"title":"Hidden dependencies make code unpredictable"},{"no":82,"title":"pipe composes small steps"},{"no":83,"title":"Reuse predicates and comparators"},{"no":84,"title":"Side effects belong at the edge"},{"no":85,"title":"When functional style hurts"},{"no":86,"title":"Your turn: An order total without hidden dependencies"},{"no":87,"title":"tests, iterators, async for pros","section":true},{"no":88,"title":"Why tests pay off"},{"no":89,"title":"A test describes a behavior"},{"no":90,"title":"Dependencies as parameters make tests simple"},{"no":91,"title":"Tables and Fake Timers save tests and time"},{"no":92,"title":"Your turn: Test the parsePort error case"},{"no":93,"title":"for...of queries an iterator"},{"no":94,"title":"Generators pause at yield"},{"no":95,"title":"Iterator Helpers work lazily"},{"no":96,"title":"for await fetches pages one by one"},{"no":97,"title":"What you need to watch with Generators"},{"no":98,"title":"Your turn: evaluate an infinite sequence lazily"},{"no":99,"title":"What goes wrong in production?"},{"no":100,"title":"Every request needs an AbortSignal"},{"no":101,"title":"A pool limits concurrency"},{"no":102,"title":"Large data flows as a stream"},{"no":103,"title":"Where canceling does not really cancel"},{"no":104,"title":"Your turn: Load an order with a timeout"},{"no":105,"title":"advanced types, validation, branded types","section":true},{"no":106,"title":"Compute types from types"},{"no":107,"title":"Conditional types distinguish cases"},{"no":108,"title":"Mapped types loop over keys"},{"no":109,"title":"Template Literal Types build strings"},{"no":110,"title":"When are computed types not worth it?"},{"no":111,"title":"Your turn: compute event names from unions"},{"no":112,"title":"Types disappear at runtime"},{"no":113,"title":"Schema and type from one source"},{"no":114,"title":"parse throws, safeParse returns a result"},{"no":115,"title":"Configuration fails early at startup"},{"no":116,"title":"Where zod behaves differently than expected"},{"no":117,"title":"Your turn: a schema for your domain"},{"no":118,"title":"Everything is a string"},{"no":119,"title":"A Brand makes types distinguishable"},{"no":120,"title":"Create them only with validation"},{"no":121,"title":"More than IDs"},{"no":122,"title":"Where Brands lose their protection"},{"no":123,"title":"Your turn: cent amounts only with validation"},{"no":124,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-python","title":"Python für Entwickler mit uv, pytest und Flask","summary":"Daten einlesen und analysieren, Web-APIs mit Flask und ihre Tests, funktionale Muster und fortgeschrittenes Python.","topics":["Python","Flask","Pandas"],"url":"https://slides.mikebild.dev/introduction-python.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.pdf?v=187505d0ac21","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.mp4?v=187505d0ac21","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.png?v=187505d0ac21","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.de.vtt?v=187505d0ac21","repository":"https://github.com/MikeBild/introduction-python","articles":["https://www.mikebild.dev/de/blog/datenanalyse-mit-pandas/","https://www.mikebild.dev/de/blog/python-daten-einlesen/","https://www.mikebild.dev/de/blog/flask-apps-testen/","https://www.mikebild.dev/de/blog/web-apis-mit-flask/","https://www.mikebild.dev/de/blog/funktionale-muster-in-python/","https://www.mikebild.dev/de/blog/python-advanced-decorators-generatoren/"],"slide_count":42,"slides":[{"no":1,"title":"Python für Entwickler mit uv, pytest und Flask","section":true},{"no":2,"title":"Werte, Funktionen, Collections","section":true},{"no":3,"title":"Ein Name hat keinen Typ, der Wert schon"},{"no":4,"title":"Geld rechnest du in ganzen Cent"},{"no":5,"title":"Gleich oder dasselbe?"},{"no":6,"title":"Was zählt als falsch?"},{"no":7,"title":"Eine Funktion mit Vertrag"},{"no":8,"title":"Der geteilte Default"},{"no":9,"title":"Funktionen sind Werte"},{"no":10,"title":"Vier Collections, vier Zugriffe"},{"no":11,"title":"Durchlaufen und auspacken"},{"no":12,"title":"Zählen, entdoppeln, einfrieren"},{"no":13,"title":"Comprehensions, Projekt mit uv, Dataclasses","section":true},{"no":14,"title":"Was entsteht, nicht wie"},{"no":15,"title":"Summen ohne Zwischenliste"},{"no":16,"title":"Flach machen und Grenzen kennen"},{"no":17,"title":"Ein Tool für alles"},{"no":18,"title":"pyproject.toml ist der Vertrag"},{"no":19,"title":"Module und Pakete"},{"no":20,"title":"Imports erst bei Bedarf laden"},{"no":21,"title":"Eine Klasse von Hand"},{"no":22,"title":"Die Dataclass schreibt den Rest"},{"no":23,"title":"Regeln gehören ins Objekt"},{"no":24,"title":"Fehler, Dateien, Type Hints","section":true},{"no":25,"title":"Fragen statt prüfen"},{"no":26,"title":"Eigene Fehler mit Bedeutung"},{"no":27,"title":"Gezielt fangen, Ursache behalten"},{"no":28,"title":"Pfade sind Objekte"},{"no":29,"title":"JSON schreiben, ohne Daten zu verlieren"},{"no":30,"title":"CSV für die Tabellenkalkulation"},{"no":31,"title":"Hinweise für Tools, nicht für Python"},{"no":32,"title":"Typen, die die Domäne beschreiben"},{"no":33,"title":"Generisch und strukturell"},{"no":34,"title":"Testen und HTTP-API für den Werkstatt-Shop","section":true},{"no":35,"title":"Ein Test ist eine Funktion mit assert"},{"no":36,"title":"Fixtures liefern frische Daten"},{"no":37,"title":"Viele Fälle, ein Test"},{"no":38,"title":"Warum Flask?"},{"no":39,"title":"Den Body prüfen, dann bestellen"},{"no":40,"title":"Fehler zentral übersetzen"},{"no":41,"title":"Testen mit dem Test Client"},{"no":42,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Python für Entwickler mit uv, pytest und Flask","summary":"Du lernst modernes Python mit uv, Type Hints und pytest und baust für den Werkstatt-Shop eine getestete HTTP-API mit Flask.","url":"https://slides.mikebild.dev/introduction-python.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.pdf?v=187505d0ac21","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.mp4?v=187505d0ac21","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.png?v=187505d0ac21","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.de.vtt?v=187505d0ac21","slide_count":42,"slides":[{"no":1,"title":"Python für Entwickler mit uv, pytest und Flask","section":true},{"no":2,"title":"Werte, Funktionen, Collections","section":true},{"no":3,"title":"Ein Name hat keinen Typ, der Wert schon"},{"no":4,"title":"Geld rechnest du in ganzen Cent"},{"no":5,"title":"Gleich oder dasselbe?"},{"no":6,"title":"Was zählt als falsch?"},{"no":7,"title":"Eine Funktion mit Vertrag"},{"no":8,"title":"Der geteilte Default"},{"no":9,"title":"Funktionen sind Werte"},{"no":10,"title":"Vier Collections, vier Zugriffe"},{"no":11,"title":"Durchlaufen und auspacken"},{"no":12,"title":"Zählen, entdoppeln, einfrieren"},{"no":13,"title":"Comprehensions, Projekt mit uv, Dataclasses","section":true},{"no":14,"title":"Was entsteht, nicht wie"},{"no":15,"title":"Summen ohne Zwischenliste"},{"no":16,"title":"Flach machen und Grenzen kennen"},{"no":17,"title":"Ein Tool für alles"},{"no":18,"title":"pyproject.toml ist der Vertrag"},{"no":19,"title":"Module und Pakete"},{"no":20,"title":"Imports erst bei Bedarf laden"},{"no":21,"title":"Eine Klasse von Hand"},{"no":22,"title":"Die Dataclass schreibt den Rest"},{"no":23,"title":"Regeln gehören ins Objekt"},{"no":24,"title":"Fehler, Dateien, Type Hints","section":true},{"no":25,"title":"Fragen statt prüfen"},{"no":26,"title":"Eigene Fehler mit Bedeutung"},{"no":27,"title":"Gezielt fangen, Ursache behalten"},{"no":28,"title":"Pfade sind Objekte"},{"no":29,"title":"JSON schreiben, ohne Daten zu verlieren"},{"no":30,"title":"CSV für die Tabellenkalkulation"},{"no":31,"title":"Hinweise für Tools, nicht für Python"},{"no":32,"title":"Typen, die die Domäne beschreiben"},{"no":33,"title":"Generisch und strukturell"},{"no":34,"title":"Testen und HTTP-API für den Werkstatt-Shop","section":true},{"no":35,"title":"Ein Test ist eine Funktion mit assert"},{"no":36,"title":"Fixtures liefern frische Daten"},{"no":37,"title":"Viele Fälle, ein Test"},{"no":38,"title":"Warum Flask?"},{"no":39,"title":"Den Body prüfen, dann bestellen"},{"no":40,"title":"Fehler zentral übersetzen"},{"no":41,"title":"Testen mit dem Test Client"},{"no":42,"title":"Fragen?","section":true}],"articles":["https://www.mikebild.dev/de/blog/datenanalyse-mit-pandas/","https://www.mikebild.dev/de/blog/python-daten-einlesen/","https://www.mikebild.dev/de/blog/flask-apps-testen/","https://www.mikebild.dev/de/blog/web-apis-mit-flask/","https://www.mikebild.dev/de/blog/funktionale-muster-in-python/","https://www.mikebild.dev/de/blog/python-advanced-decorators-generatoren/"]},"en":{"title":"Python for developers with uv, pytest, and Flask","summary":"You learn modern Python with uv, type hints, and pytest, and build a tested HTTP API with Flask for the workshop shop.","url":"https://slides.mikebild.dev/introduction-python.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.en.pdf?v=a9426e4ffd37","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.en.mp4?v=a9426e4ffd37","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.en.png?v=a9426e4ffd37","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-python/introduction-python.en.vtt?v=a9426e4ffd37","slide_count":42,"slides":[{"no":1,"title":"Python for developers with uv, pytest, and Flask","section":true},{"no":2,"title":"Values, functions, collections","section":true},{"no":3,"title":"A name does not have a type, the value does"},{"no":4,"title":"Calculate money in whole cents"},{"no":5,"title":"Equal or the same?"},{"no":6,"title":"What counts as false?"},{"no":7,"title":"A function with a contract"},{"no":8,"title":"The shared default"},{"no":9,"title":"Functions are values"},{"no":10,"title":"Four collections, four access patterns"},{"no":11,"title":"Loop and unpack"},{"no":12,"title":"Count, deduplicate, freeze"},{"no":13,"title":"Comprehensions, project with uv, dataclasses","section":true},{"no":14,"title":"What is created, not how"},{"no":15,"title":"Sums without an intermediate list"},{"no":16,"title":"Flatten and know the limits"},{"no":17,"title":"One tool for everything"},{"no":18,"title":"pyproject.toml is the contract"},{"no":19,"title":"Modules and packages"},{"no":20,"title":"Load imports only when needed"},{"no":21,"title":"A class by hand"},{"no":22,"title":"The dataclass writes the rest"},{"no":23,"title":"Rules belong in the object"},{"no":24,"title":"Errors, files, type hints","section":true},{"no":25,"title":"Ask instead of checking"},{"no":26,"title":"Custom errors with meaning"},{"no":27,"title":"Catch deliberately, keep the cause"},{"no":28,"title":"Paths are objects"},{"no":29,"title":"Write JSON without losing data"},{"no":30,"title":"CSV for the spreadsheet"},{"no":31,"title":"Hints for tools, not for Python"},{"no":32,"title":"Types that describe the domain"},{"no":33,"title":"Generic and structural"},{"no":34,"title":"Testing and an HTTP API for the workshop shop","section":true},{"no":35,"title":"A test is a function with assert"},{"no":36,"title":"Fixtures provide fresh data"},{"no":37,"title":"Many cases, one test"},{"no":38,"title":"Why Flask?"},{"no":39,"title":"Validate the body, then place the order"},{"no":40,"title":"Translate errors centrally"},{"no":41,"title":"Test with the test client"},{"no":42,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-web-plattform","title":"Moderne Web-Plattform ohne Framework","summary":"Semantisches HTML, Accessibility, modernes CSS, Formulare, ES Modules ohne Build, fetch, Web Components, View Transitions und Offline.","topics":["HTML","CSS","Web-APIs"],"url":"https://slides.mikebild.dev/introduction-web-plattform.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.pdf?v=a232e20fe8ed","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.mp4?v=a232e20fe8ed","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.png?v=a232e20fe8ed","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.de.vtt?v=a232e20fe8ed","repository":"https://github.com/MikeBild/introduction-web-plattform","articles":[],"slide_count":74,"slides":[{"no":1,"title":"Moderne Web-Plattform ohne Framework","section":true},{"no":2,"title":"HTML, Accessibility und Formulare","section":true},{"no":3,"title":"Was sieht ein Screenreader von deiner Seite?"},{"no":4,"title":"Landmarks geben der Seite eine Karte"},{"no":5,"title":"Die Produktliste ist eine Liste"},{"no":6,"title":"Ein button kann mehr als ein div"},{"no":7,"title":"Erst HTML, dann ARIA"},{"no":8,"title":"Wer bedient deinen Shop ohne Maus?"},{"no":9,"title":"Der Focus ist immer sichtbar"},{"no":10,"title":"dialog nimmt dir den Focus ab"},{"no":11,"title":"Änderungen ansagen, ohne den Focus zu stehlen"},{"no":12,"title":"Tools finden viel, aber nicht alles"},{"no":13,"title":"Was kann ein Formular ohne JavaScript?"},{"no":14,"title":"Attribute beschreiben die Regeln"},{"no":15,"title":"Fachregeln meldest du mit setCustomValidity"},{"no":16,"title":"FormData liest das ganze Formular"},{"no":17,"title":"Der Server prüft trotzdem"},{"no":18,"title":"Modernes CSS","section":true},{"no":19,"title":"Warum gewinnt die falsche Regel?"},{"no":20,"title":"Layer entscheiden vor der Specificity"},{"no":21,"title":"Custom Properties sind Variablen zur Laufzeit"},{"no":22,"title":"Nesting hält eine Komponente zusammen"},{"no":23,"title":"Fremd-CSS kommt in einen eigenen Layer"},{"no":24,"title":"Eine Richtung oder zwei?"},{"no":25,"title":"Ein Raster ohne Media Queries"},{"no":26,"title":"Die Warenkorbzeile ist eine Flexbox"},{"no":27,"title":"Subgrid lässt Karten fluchten"},{"no":28,"title":"Logical Properties denken in Schreibrichtung"},{"no":29,"title":"Der Viewport sagt nichts über die Karte"},{"no":30,"title":"Erst den Container, dann die Query"},{"no":31,"title":":has() schaut nach unten"},{"no":32,"title":"Formular-Feedback erst nach der Eingabe"},{"no":33,"title":"Wann bleibt die Media Query?"},{"no":34,"title":"Module und Daten aus dem Netz","section":true},{"no":35,"title":"Braucht jede Seite einen Bundler?"},{"no":36,"title":"Ein Modul-Skript startet den Graphen"},{"no":37,"title":"Eine Import Map ersetzt Pfad-Aliase"},{"no":38,"title":"modulepreload verkürzt den Wasserfall"},{"no":39,"title":"Wann lohnt sich doch ein Build?"},{"no":40,"title":"fetch wirft seltener, als du denkst"},{"no":41,"title":"Ohne Timeout wartet fetch beliebig lange"},{"no":42,"title":"Die neue Suche bricht die alte ab"},{"no":43,"title":"Ein Abbruch ist kein Fehler"},{"no":44,"title":"Warten, bis alles da ist, kostet Zeit"},{"no":45,"title":"NDJSON ist JSON pro Zeile"},{"no":46,"title":"Ein Zeilenpuffer setzt die Chunks zusammen"},{"no":47,"title":"for await rendert jedes Produkt sofort"},{"no":48,"title":"Web Components und View Transitions","section":true},{"no":49,"title":"Eigene HTML-Elemente für den Shop"},{"no":50,"title":"Attribute sind die Eingänge"},{"no":51,"title":"Events sind die Ausgänge"},{"no":52,"title":"Aufräumen gehört zum Lifecycle"},{"no":53,"title":"Wann lohnt sich ein Custom Element?"},{"no":54,"title":"Warum zerlegt das Seiten-CSS meine Karte?"},{"no":55,"title":"template und Shadow Root"},{"no":56,"title":"Slots holen den Inhalt herein"},{"no":57,"title":"Parts und Custom Properties sind die Design-API"},{"no":58,"title":"Declarative Shadow DOM rendert ohne JavaScript"},{"no":59,"title":"Ein Sprung verwirrt, eine Bewegung erklärt"},{"no":60,"title":"startViewTransition macht Vorher und Nachher"},{"no":61,"title":"view-transition-name verbindet zwei Elemente"},{"no":62,"title":"Zwischen Seiten nur als Zusatz"},{"no":63,"title":"Offline und Performance","section":true},{"no":64,"title":"Welcher Speicher für welche Daten?"},{"no":65,"title":"Gespeicherte Daten können kaputt sein"},{"no":66,"title":"Ein Service Worker steht zwischen Seite und Netz"},{"no":67,"title":"Zwei Strategien decken den Shop ab"},{"no":68,"title":"Registrieren, aktualisieren, aufräumen"},{"no":69,"title":"Drei Zahlen für das Gefühl von Tempo"},{"no":70,"title":"Gut heißt: 75 Prozent der Besuche"},{"no":71,"title":"Messen im Feld mit PerformanceObserver"},{"no":72,"title":"Bilder entscheiden über LCP und CLS"},{"no":73,"title":"Schnelle Antworten brauchen kurze Tasks"},{"no":74,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Moderne Web-Plattform ohne Framework","summary":"Du baust den Werkstatt-Shop nur mit HTML, CSS und JavaScript des Browsers: barrierearm, mit Web Components, offline-fähig und schnell.","url":"https://slides.mikebild.dev/introduction-web-plattform.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.pdf?v=a232e20fe8ed","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.mp4?v=a232e20fe8ed","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.png?v=a232e20fe8ed","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.de.vtt?v=a232e20fe8ed","slide_count":74,"slides":[{"no":1,"title":"Moderne Web-Plattform ohne Framework","section":true},{"no":2,"title":"HTML, Accessibility und Formulare","section":true},{"no":3,"title":"Was sieht ein Screenreader von deiner Seite?"},{"no":4,"title":"Landmarks geben der Seite eine Karte"},{"no":5,"title":"Die Produktliste ist eine Liste"},{"no":6,"title":"Ein button kann mehr als ein div"},{"no":7,"title":"Erst HTML, dann ARIA"},{"no":8,"title":"Wer bedient deinen Shop ohne Maus?"},{"no":9,"title":"Der Focus ist immer sichtbar"},{"no":10,"title":"dialog nimmt dir den Focus ab"},{"no":11,"title":"Änderungen ansagen, ohne den Focus zu stehlen"},{"no":12,"title":"Tools finden viel, aber nicht alles"},{"no":13,"title":"Was kann ein Formular ohne JavaScript?"},{"no":14,"title":"Attribute beschreiben die Regeln"},{"no":15,"title":"Fachregeln meldest du mit setCustomValidity"},{"no":16,"title":"FormData liest das ganze Formular"},{"no":17,"title":"Der Server prüft trotzdem"},{"no":18,"title":"Modernes CSS","section":true},{"no":19,"title":"Warum gewinnt die falsche Regel?"},{"no":20,"title":"Layer entscheiden vor der Specificity"},{"no":21,"title":"Custom Properties sind Variablen zur Laufzeit"},{"no":22,"title":"Nesting hält eine Komponente zusammen"},{"no":23,"title":"Fremd-CSS kommt in einen eigenen Layer"},{"no":24,"title":"Eine Richtung oder zwei?"},{"no":25,"title":"Ein Raster ohne Media Queries"},{"no":26,"title":"Die Warenkorbzeile ist eine Flexbox"},{"no":27,"title":"Subgrid lässt Karten fluchten"},{"no":28,"title":"Logical Properties denken in Schreibrichtung"},{"no":29,"title":"Der Viewport sagt nichts über die Karte"},{"no":30,"title":"Erst den Container, dann die Query"},{"no":31,"title":":has() schaut nach unten"},{"no":32,"title":"Formular-Feedback erst nach der Eingabe"},{"no":33,"title":"Wann bleibt die Media Query?"},{"no":34,"title":"Module und Daten aus dem Netz","section":true},{"no":35,"title":"Braucht jede Seite einen Bundler?"},{"no":36,"title":"Ein Modul-Skript startet den Graphen"},{"no":37,"title":"Eine Import Map ersetzt Pfad-Aliase"},{"no":38,"title":"modulepreload verkürzt den Wasserfall"},{"no":39,"title":"Wann lohnt sich doch ein Build?"},{"no":40,"title":"fetch wirft seltener, als du denkst"},{"no":41,"title":"Ohne Timeout wartet fetch beliebig lange"},{"no":42,"title":"Die neue Suche bricht die alte ab"},{"no":43,"title":"Ein Abbruch ist kein Fehler"},{"no":44,"title":"Warten, bis alles da ist, kostet Zeit"},{"no":45,"title":"NDJSON ist JSON pro Zeile"},{"no":46,"title":"Ein Zeilenpuffer setzt die Chunks zusammen"},{"no":47,"title":"for await rendert jedes Produkt sofort"},{"no":48,"title":"Web Components und View Transitions","section":true},{"no":49,"title":"Eigene HTML-Elemente für den Shop"},{"no":50,"title":"Attribute sind die Eingänge"},{"no":51,"title":"Events sind die Ausgänge"},{"no":52,"title":"Aufräumen gehört zum Lifecycle"},{"no":53,"title":"Wann lohnt sich ein Custom Element?"},{"no":54,"title":"Warum zerlegt das Seiten-CSS meine Karte?"},{"no":55,"title":"template und Shadow Root"},{"no":56,"title":"Slots holen den Inhalt herein"},{"no":57,"title":"Parts und Custom Properties sind die Design-API"},{"no":58,"title":"Declarative Shadow DOM rendert ohne JavaScript"},{"no":59,"title":"Ein Sprung verwirrt, eine Bewegung erklärt"},{"no":60,"title":"startViewTransition macht Vorher und Nachher"},{"no":61,"title":"view-transition-name verbindet zwei Elemente"},{"no":62,"title":"Zwischen Seiten nur als Zusatz"},{"no":63,"title":"Offline und Performance","section":true},{"no":64,"title":"Welcher Speicher für welche Daten?"},{"no":65,"title":"Gespeicherte Daten können kaputt sein"},{"no":66,"title":"Ein Service Worker steht zwischen Seite und Netz"},{"no":67,"title":"Zwei Strategien decken den Shop ab"},{"no":68,"title":"Registrieren, aktualisieren, aufräumen"},{"no":69,"title":"Drei Zahlen für das Gefühl von Tempo"},{"no":70,"title":"Gut heißt: 75 Prozent der Besuche"},{"no":71,"title":"Messen im Feld mit PerformanceObserver"},{"no":72,"title":"Bilder entscheiden über LCP und CLS"},{"no":73,"title":"Schnelle Antworten brauchen kurze Tasks"},{"no":74,"title":"Fragen?","section":true}],"articles":[]},"en":{"title":"Modern web platform without a framework","summary":"You build the workshop shop using only the browser’s HTML, CSS, and JavaScript: accessible, fast, offline-capable, and with Web Components.","url":"https://slides.mikebild.dev/introduction-web-plattform.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.en.pdf?v=a8018c5e80c1","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.en.mp4?v=a8018c5e80c1","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.en.png?v=a8018c5e80c1","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-web-plattform/introduction-web-plattform.en.vtt?v=a8018c5e80c1","slide_count":74,"slides":[{"no":1,"title":"Modern web platform without a framework","section":true},{"no":2,"title":"HTML, accessibility, and forms","section":true},{"no":3,"title":"What does a screen reader see on your page?"},{"no":4,"title":"Landmarks give the page a map"},{"no":5,"title":"The product list is a list"},{"no":6,"title":"A button can do more than a div"},{"no":7,"title":"HTML first, then ARIA"},{"no":8,"title":"Who uses your shop without a mouse?"},{"no":9,"title":"Focus is always visible"},{"no":10,"title":"dialog handles focus for you"},{"no":11,"title":"Announce changes without stealing focus"},{"no":12,"title":"Tools find a lot, but not everything"},{"no":13,"title":"What can a form do without JavaScript?"},{"no":14,"title":"Attributes describe the rules"},{"no":15,"title":"You report business rules with setCustomValidity"},{"no":16,"title":"FormData reads the whole form"},{"no":17,"title":"The server still validates"},{"no":18,"title":"Modern CSS","section":true},{"no":19,"title":"Why does the wrong rule win?"},{"no":20,"title":"Layers are decided before specificity"},{"no":21,"title":"Custom properties are runtime variables"},{"no":22,"title":"Nesting keeps a component together"},{"no":23,"title":"Third-party CSS goes in its own layer"},{"no":24,"title":"One direction or two?"},{"no":25,"title":"A grid without media queries"},{"no":26,"title":"The cart row is a Flexbox"},{"no":27,"title":"Subgrid keeps cards aligned"},{"no":28,"title":"Logical properties follow writing direction"},{"no":29,"title":"The viewport says nothing about the card"},{"no":30,"title":"First the container, then the query"},{"no":31,"title":":has() looks down"},{"no":32,"title":"Form feedback only after input"},{"no":33,"title":"When does the media query stay?"},{"no":34,"title":"Modules and data from the network","section":true},{"no":35,"title":"Does every page need a bundler?"},{"no":36,"title":"A module script starts the graph"},{"no":37,"title":"An import map replaces path aliases"},{"no":38,"title":"modulepreload shortens the waterfall"},{"no":39,"title":"When is a build still worth it?"},{"no":40,"title":"fetch throws less often than you think"},{"no":41,"title":"Without a timeout, fetch waits indefinitely"},{"no":42,"title":"The new search aborts the old one"},{"no":43,"title":"An abort is not an error"},{"no":44,"title":"Waiting until everything is there costs time"},{"no":45,"title":"NDJSON is JSON per line"},{"no":46,"title":"A line buffer puts the chunks together"},{"no":47,"title":"for await renders each product right away"},{"no":48,"title":"Web Components and View Transitions","section":true},{"no":49,"title":"Custom HTML elements for the shop"},{"no":50,"title":"Attributes are the inputs"},{"no":51,"title":"Events are the outputs"},{"no":52,"title":"Cleanup is part of the lifecycle"},{"no":53,"title":"When is a Custom Element worth it?"},{"no":54,"title":"Why does page CSS break my card?"},{"no":55,"title":"Template and Shadow Root"},{"no":56,"title":"Slots bring the content in"},{"no":57,"title":"Parts and Custom Properties are the design API"},{"no":58,"title":"Declarative Shadow DOM renders without JavaScript"},{"no":59,"title":"A jump confuses; motion explains"},{"no":60,"title":"startViewTransition creates before and after"},{"no":61,"title":"view-transition-name connects two elements"},{"no":62,"title":"Between pages only as an extra"},{"no":63,"title":"Offline and performance","section":true},{"no":64,"title":"Which storage fits which data?"},{"no":65,"title":"Saved data can be broken"},{"no":66,"title":"A Service Worker sits between page and network"},{"no":67,"title":"Two strategies cover the shop"},{"no":68,"title":"Register, update, clean up"},{"no":69,"title":"Three numbers for the feel of speed"},{"no":70,"title":"Good means: 75 percent of visits"},{"no":71,"title":"Measure in the field with PerformanceObserver"},{"no":72,"title":"Images decide LCP and CLS"},{"no":73,"title":"Fast responses need short tasks"},{"no":74,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-nodejs","title":"Node.js: Eine moderne Einführung","summary":"Runtime und Event Loop, asynchrone Muster, Webentwicklung mit Express, Testing und Skalierung mit Node.js 26.","topics":["Node.js"],"url":"https://slides.mikebild.dev/introduction-nodejs.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.pdf?v=53ea4f3ddcf2","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.mp4?v=53ea4f3ddcf2","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.png?v=53ea4f3ddcf2","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.de.vtt?v=53ea4f3ddcf2","repository":"https://github.com/MikeBild/introduction-nodejs","articles":["https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/"],"slide_count":107,"slides":[{"no":1,"title":"Node.js Backend, funktional und typsicher","section":true},{"no":2,"title":"Runtime, npm, Event Loop, Async","section":true},{"no":3,"title":"Warum Node.js?"},{"no":4,"title":"ESM ist der Standard"},{"no":5,"title":"TypeScript direkt ausführen"},{"no":6,"title":"Stolperfallen"},{"no":7,"title":"Was die Projektbasis ausmacht"},{"no":8,"title":"Dependencies sind Code"},{"no":9,"title":"package.json als Vertrag"},{"no":10,"title":"Lockfile und npm ci"},{"no":11,"title":"Workspaces"},{"no":12,"title":"Was Builds unvorhersehbar oder unsicher macht"},{"no":13,"title":"Concurrency ≠ Parallelism"},{"no":14,"title":"Die Phasen des Event Loop"},{"no":15,"title":"Reihenfolge im I/O Callback"},{"no":16,"title":"Den Event Loop blockieren"},{"no":17,"title":"Merksätze"},{"no":18,"title":"Warten ohne Chaos"},{"no":19,"title":"Parallel statt nacheinander"},{"no":20,"title":"Timeout und Cancellation"},{"no":21,"title":"Wo asynchroner Code Fehler verschluckt"},{"no":22,"title":"Drei Regeln für asynchrone Arbeit"},{"no":23,"title":"Errors, Files, Streams, CLI","section":true},{"no":24,"title":"Zwei Arten von Errors"},{"no":25,"title":"Erwartbares als Result"},{"no":26,"title":"Unerwartetes mit cause"},{"no":27,"title":"Globale Error Handler"},{"no":28,"title":"Wie Errors verloren gehen"},{"no":29,"title":"Dateien gehören zum Alltag"},{"no":30,"title":"node:fs/promises"},{"no":31,"title":"Paths richtig bauen"},{"no":32,"title":"Path Traversal verhindern"},{"no":33,"title":"Was Dateizugriffe fehleranfällig macht"},{"no":34,"title":"Alles auf einmal geht schief"},{"no":35,"title":"Vier Arten"},{"no":36,"title":"pipeline und Async Generators"},{"no":37,"title":"Backpressure"},{"no":38,"title":"Was Streams bricht und wann sie sich lohnen"},{"no":39,"title":"Tools statt Klickstrecken"},{"no":40,"title":"Arguments mit parseArgs"},{"no":41,"title":"Input und Output"},{"no":42,"title":"Abort und Exit Codes"},{"no":43,"title":"Was CLI Tools in Pipelines stört"},{"no":44,"title":"HTTP-API mit Express, Testing","section":true},{"no":45,"title":"Was Express über node:http legt"},{"no":46,"title":"Erste Routes"},{"no":47,"title":"Middleware und Router"},{"no":48,"title":"Error Handling zentral"},{"no":49,"title":"Testen per fetch"},{"no":50,"title":"TypeScript endet an der Boundary"},{"no":51,"title":"Schema statt Interface"},{"no":52,"title":"Parsen an der Boundary"},{"no":53,"title":"zod in Express"},{"no":54,"title":"Validation Errors als 400"},{"no":55,"title":"Wo Validation zu viel oder zu wenig tut"},{"no":56,"title":"Wo steckt die Logik?"},{"no":57,"title":"Core und Shell"},{"no":58,"title":"Composition"},{"no":59,"title":"Der Core entscheidet"},{"no":60,"title":"Die Shell bleibt dünn"},{"no":61,"title":"Was den Core unrein macht und was er bringt"},{"no":62,"title":"Warum Vitest?"},{"no":63,"title":"Den Core testen"},{"no":64,"title":"Die Shell testen"},{"no":65,"title":"Wie viel wovon?"},{"no":66,"title":"Was Tests unzuverlässig macht"},{"no":67,"title":"Config, Logging, Database","section":true},{"no":68,"title":"Config ist kein Code"},{"no":69,"title":"Einmal laden, sofort prüfen"},{"no":70,"title":"Config weiterreichen"},{"no":71,"title":"Secrets schützen"},{"no":72,"title":"Wie Config Fehler versteckt oder Secrets verrät"},{"no":73,"title":"Logs, die im Betrieb helfen"},{"no":74,"title":"Drei Regeln"},{"no":75,"title":"Ein JSON Logger ohne Package"},{"no":76,"title":"Child Logger und Request ID"},{"no":77,"title":"Maskierung"},{"no":78,"title":"Wann Logs teuer oder gefährlich werden"},{"no":79,"title":"ORM, Query Builder oder SQL?"},{"no":80,"title":"Queries mit postgres.js"},{"no":81,"title":"Transactions"},{"no":82,"title":"Migrations"},{"no":83,"title":"Was Datenbankzugriffe langsam oder falsch macht"},{"no":84,"title":"Betrieb, Performance, Architektur","section":true},{"no":85,"title":"Der Lifecycle eines Service"},{"no":86,"title":"Liveness und Readiness"},{"no":87,"title":"Graceful Shutdown"},{"no":88,"title":"Node im Container"},{"no":89,"title":"Was den Betrieb im Container stört"},{"no":90,"title":"Gefühlt langsam"},{"no":91,"title":"Der Messkreislauf"},{"no":92,"title":"CPU Profile lesen"},{"no":93,"title":"Memory und Leaks"},{"no":94,"title":"Typische Hebel"},{"no":95,"title":"Wenn alles von allem abhängt"},{"no":96,"title":"Ports and Adapters"},{"no":97,"title":"Funktional umgesetzt"},{"no":98,"title":"Verdrahten in main"},{"no":99,"title":"Modules und Trade-offs"},{"no":100,"title":"Sicherheit","section":true},{"no":101,"title":"Die Attack Surface"},{"no":102,"title":"Input und Injection"},{"no":103,"title":"Ressourcen und Outgoing Requests"},{"no":104,"title":"Limits und Headers in Express"},{"no":105,"title":"Supply Chain"},{"no":106,"title":"Least Privilege"},{"no":107,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Node.js Backend, funktional und typsicher","summary":"Du baust einen Node.js-Service mit Express 5 vom ersten Request bis zum Betrieb im Container, getestet, geloggt und gehärtet.","url":"https://slides.mikebild.dev/introduction-nodejs.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.pdf?v=53ea4f3ddcf2","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.mp4?v=53ea4f3ddcf2","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.png?v=53ea4f3ddcf2","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.de.vtt?v=53ea4f3ddcf2","slide_count":107,"slides":[{"no":1,"title":"Node.js Backend, funktional und typsicher","section":true},{"no":2,"title":"Runtime, npm, Event Loop, Async","section":true},{"no":3,"title":"Warum Node.js?"},{"no":4,"title":"ESM ist der Standard"},{"no":5,"title":"TypeScript direkt ausführen"},{"no":6,"title":"Stolperfallen"},{"no":7,"title":"Was die Projektbasis ausmacht"},{"no":8,"title":"Dependencies sind Code"},{"no":9,"title":"package.json als Vertrag"},{"no":10,"title":"Lockfile und npm ci"},{"no":11,"title":"Workspaces"},{"no":12,"title":"Was Builds unvorhersehbar oder unsicher macht"},{"no":13,"title":"Concurrency ≠ Parallelism"},{"no":14,"title":"Die Phasen des Event Loop"},{"no":15,"title":"Reihenfolge im I/O Callback"},{"no":16,"title":"Den Event Loop blockieren"},{"no":17,"title":"Merksätze"},{"no":18,"title":"Warten ohne Chaos"},{"no":19,"title":"Parallel statt nacheinander"},{"no":20,"title":"Timeout und Cancellation"},{"no":21,"title":"Wo asynchroner Code Fehler verschluckt"},{"no":22,"title":"Drei Regeln für asynchrone Arbeit"},{"no":23,"title":"Errors, Files, Streams, CLI","section":true},{"no":24,"title":"Zwei Arten von Errors"},{"no":25,"title":"Erwartbares als Result"},{"no":26,"title":"Unerwartetes mit cause"},{"no":27,"title":"Globale Error Handler"},{"no":28,"title":"Wie Errors verloren gehen"},{"no":29,"title":"Dateien gehören zum Alltag"},{"no":30,"title":"node:fs/promises"},{"no":31,"title":"Paths richtig bauen"},{"no":32,"title":"Path Traversal verhindern"},{"no":33,"title":"Was Dateizugriffe fehleranfällig macht"},{"no":34,"title":"Alles auf einmal geht schief"},{"no":35,"title":"Vier Arten"},{"no":36,"title":"pipeline und Async Generators"},{"no":37,"title":"Backpressure"},{"no":38,"title":"Was Streams bricht und wann sie sich lohnen"},{"no":39,"title":"Tools statt Klickstrecken"},{"no":40,"title":"Arguments mit parseArgs"},{"no":41,"title":"Input und Output"},{"no":42,"title":"Abort und Exit Codes"},{"no":43,"title":"Was CLI Tools in Pipelines stört"},{"no":44,"title":"HTTP-API mit Express, Testing","section":true},{"no":45,"title":"Was Express über node:http legt"},{"no":46,"title":"Erste Routes"},{"no":47,"title":"Middleware und Router"},{"no":48,"title":"Error Handling zentral"},{"no":49,"title":"Testen per fetch"},{"no":50,"title":"TypeScript endet an der Boundary"},{"no":51,"title":"Schema statt Interface"},{"no":52,"title":"Parsen an der Boundary"},{"no":53,"title":"zod in Express"},{"no":54,"title":"Validation Errors als 400"},{"no":55,"title":"Wo Validation zu viel oder zu wenig tut"},{"no":56,"title":"Wo steckt die Logik?"},{"no":57,"title":"Core und Shell"},{"no":58,"title":"Composition"},{"no":59,"title":"Der Core entscheidet"},{"no":60,"title":"Die Shell bleibt dünn"},{"no":61,"title":"Was den Core unrein macht und was er bringt"},{"no":62,"title":"Warum Vitest?"},{"no":63,"title":"Den Core testen"},{"no":64,"title":"Die Shell testen"},{"no":65,"title":"Wie viel wovon?"},{"no":66,"title":"Was Tests unzuverlässig macht"},{"no":67,"title":"Config, Logging, Database","section":true},{"no":68,"title":"Config ist kein Code"},{"no":69,"title":"Einmal laden, sofort prüfen"},{"no":70,"title":"Config weiterreichen"},{"no":71,"title":"Secrets schützen"},{"no":72,"title":"Wie Config Fehler versteckt oder Secrets verrät"},{"no":73,"title":"Logs, die im Betrieb helfen"},{"no":74,"title":"Drei Regeln"},{"no":75,"title":"Ein JSON Logger ohne Package"},{"no":76,"title":"Child Logger und Request ID"},{"no":77,"title":"Maskierung"},{"no":78,"title":"Wann Logs teuer oder gefährlich werden"},{"no":79,"title":"ORM, Query Builder oder SQL?"},{"no":80,"title":"Queries mit postgres.js"},{"no":81,"title":"Transactions"},{"no":82,"title":"Migrations"},{"no":83,"title":"Was Datenbankzugriffe langsam oder falsch macht"},{"no":84,"title":"Betrieb, Performance, Architektur","section":true},{"no":85,"title":"Der Lifecycle eines Service"},{"no":86,"title":"Liveness und Readiness"},{"no":87,"title":"Graceful Shutdown"},{"no":88,"title":"Node im Container"},{"no":89,"title":"Was den Betrieb im Container stört"},{"no":90,"title":"Gefühlt langsam"},{"no":91,"title":"Der Messkreislauf"},{"no":92,"title":"CPU Profile lesen"},{"no":93,"title":"Memory und Leaks"},{"no":94,"title":"Typische Hebel"},{"no":95,"title":"Wenn alles von allem abhängt"},{"no":96,"title":"Ports and Adapters"},{"no":97,"title":"Funktional umgesetzt"},{"no":98,"title":"Verdrahten in main"},{"no":99,"title":"Modules und Trade-offs"},{"no":100,"title":"Sicherheit","section":true},{"no":101,"title":"Die Attack Surface"},{"no":102,"title":"Input und Injection"},{"no":103,"title":"Ressourcen und Outgoing Requests"},{"no":104,"title":"Limits und Headers in Express"},{"no":105,"title":"Supply Chain"},{"no":106,"title":"Least Privilege"},{"no":107,"title":"Fragen?","section":true}],"articles":["https://www.mikebild.dev/de/blog/nodejs-training-event-loop-architektur/"]},"en":{"title":"Node.js backend, functional and type-safe","summary":"You build a Node.js service with Express 5 from the first request to container operations, tested, logged, and hardened.","url":"https://slides.mikebild.dev/introduction-nodejs.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.en.pdf?v=965710139dd0","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.en.mp4?v=965710139dd0","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.en.png?v=965710139dd0","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-nodejs/introduction-nodejs.en.vtt?v=965710139dd0","slide_count":107,"slides":[{"no":1,"title":"Node.js backend, functional and type-safe","section":true},{"no":2,"title":"Runtime, npm, event loop, async","section":true},{"no":3,"title":"Why Node.js?"},{"no":4,"title":"ESM is the standard"},{"no":5,"title":"Run TypeScript directly"},{"no":6,"title":"Common pitfalls"},{"no":7,"title":"What makes up the project baseline"},{"no":8,"title":"Dependencies are code"},{"no":9,"title":"package.json as a contract"},{"no":10,"title":"Lockfile and npm ci"},{"no":11,"title":"Workspaces"},{"no":12,"title":"What makes builds unpredictable or unsafe"},{"no":13,"title":"Concurrency ≠ parallelism"},{"no":14,"title":"The phases of the event loop"},{"no":15,"title":"Order in the I/O callback"},{"no":16,"title":"Blocking the event loop"},{"no":17,"title":"Key points"},{"no":18,"title":"Waiting without chaos"},{"no":19,"title":"Parallel instead of sequential"},{"no":20,"title":"Timeout and cancellation"},{"no":21,"title":"Where asynchronous code swallows errors"},{"no":22,"title":"Three rules for asynchronous work"},{"no":23,"title":"Errors, files, streams, CLI","section":true},{"no":24,"title":"Two kinds of errors"},{"no":25,"title":"Expected cases as a Result"},{"no":26,"title":"Unexpected failures with cause"},{"no":27,"title":"Global error handlers"},{"no":28,"title":"How errors get lost"},{"no":29,"title":"Files are everyday work"},{"no":30,"title":"node:fs/promises"},{"no":31,"title":"Build paths correctly"},{"no":32,"title":"Prevent Path Traversal"},{"no":33,"title":"What makes file access error-prone"},{"no":34,"title":"Doing everything at once goes wrong"},{"no":35,"title":"Four types"},{"no":36,"title":"pipeline and Async Generators"},{"no":37,"title":"Backpressure"},{"no":38,"title":"What breaks streams and when they pay off"},{"no":39,"title":"Tools instead of click paths"},{"no":40,"title":"Arguments with parseArgs"},{"no":41,"title":"Input and output"},{"no":42,"title":"Abort and exit codes"},{"no":43,"title":"What gets in the way of CLI tools in pipelines"},{"no":44,"title":"HTTP API with Express, testing","section":true},{"no":45,"title":"What Express adds on top of node:http"},{"no":46,"title":"First routes"},{"no":47,"title":"Middleware and routers"},{"no":48,"title":"Central error handling"},{"no":49,"title":"Testing with fetch"},{"no":50,"title":"TypeScript ends at the boundary"},{"no":51,"title":"Schema instead of interface"},{"no":52,"title":"Parse at the boundary"},{"no":53,"title":"zod in Express"},{"no":54,"title":"Validation errors as 400"},{"no":55,"title":"Where validation does too much or too little"},{"no":56,"title":"Where is the logic?"},{"no":57,"title":"Core and shell"},{"no":58,"title":"Composition"},{"no":59,"title":"The core decides"},{"no":60,"title":"The shell stays thin"},{"no":61,"title":"What makes the core impure, and what you gain"},{"no":62,"title":"Why Vitest?"},{"no":63,"title":"Test the core"},{"no":64,"title":"Test the shell"},{"no":65,"title":"How much of each?"},{"no":66,"title":"What makes tests unreliable"},{"no":67,"title":"Config, logging, database","section":true},{"no":68,"title":"Config is not code"},{"no":69,"title":"Load once, validate immediately"},{"no":70,"title":"Pass config along"},{"no":71,"title":"Protect secrets"},{"no":72,"title":"How config hides errors or reveals secrets"},{"no":73,"title":"Logs that help in operations"},{"no":74,"title":"Three rules"},{"no":75,"title":"A JSON logger without a package"},{"no":76,"title":"Child logger and request ID"},{"no":77,"title":"Redaction"},{"no":78,"title":"When logs become expensive or dangerous"},{"no":79,"title":"ORM, query builder, or SQL?"},{"no":80,"title":"Queries with postgres.js"},{"no":81,"title":"Transactions"},{"no":82,"title":"Migrations"},{"no":83,"title":"What makes database access slow or wrong"},{"no":84,"title":"Operations, performance, architecture","section":true},{"no":85,"title":"The lifecycle of a service"},{"no":86,"title":"Liveness and readiness"},{"no":87,"title":"Graceful shutdown"},{"no":88,"title":"Node in a container"},{"no":89,"title":"What gets in the way of container operations"},{"no":90,"title":"Feels slow"},{"no":91,"title":"The measurement loop"},{"no":92,"title":"Read a CPU profile"},{"no":93,"title":"Memory and leaks"},{"no":94,"title":"Typical levers"},{"no":95,"title":"When everything depends on everything"},{"no":96,"title":"Ports and Adapters"},{"no":97,"title":"Implemented functionally"},{"no":98,"title":"Wire in main"},{"no":99,"title":"Modules and trade-offs"},{"no":100,"title":"Security","section":true},{"no":101,"title":"The attack surface"},{"no":102,"title":"Input and injection"},{"no":103,"title":"Resources and outgoing requests"},{"no":104,"title":"Limits and headers in Express"},{"no":105,"title":"Supply chain"},{"no":106,"title":"Least privilege"},{"no":107,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-react","title":"React: Von der Komponente zur Architektur","summary":"Von JSX über Zustand, Daten und Routing bis zur Komponentenarchitektur mit React 19.","topics":["React","Frontend"],"url":"https://slides.mikebild.dev/introduction-react.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.pdf?v=a9fa9b32eb2d","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.mp4?v=a9fa9b32eb2d","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.png?v=a9fa9b32eb2d","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.de.vtt?v=a9fa9b32eb2d","repository":"https://github.com/MikeBild/introduction-react","articles":["https://www.mikebild.dev/de/blog/react-ueberblick-von-jsx-zur-architektur/"],"slide_count":133,"slides":[{"no":1,"title":"React mit TypeScript bis zur Produktion","section":true},{"no":2,"title":"Components, JSX, Composition, Styling","section":true},{"no":3,"title":"Warum Components?"},{"no":4,"title":"UI = f(props)"},{"no":5,"title":"Erst der Component Tree, dann der Code"},{"no":6,"title":"Rendering bleibt rein"},{"no":7,"title":"Eine Component ist eine Funktion"},{"no":8,"title":"JSX ist JavaScript"},{"no":9,"title":"In geschweifte Klammern gehören Ausdrücke"},{"no":10,"title":"Props sind ein typisierter Vertrag"},{"no":11,"title":"Daten fließen nach unten"},{"no":12,"title":"Drei typische Fehler am Anfang"},{"no":13,"title":"Zwanzig Props sind ein Warnsignal"},{"no":14,"title":"children nimmt beliebigen Inhalt auf"},{"no":15,"title":"Benannte Slots ersetzen Flags"},{"no":16,"title":"Daten fließen an der Hülle vorbei"},{"no":17,"title":"Nicht jedes Detail braucht einen Slot"},{"no":18,"title":"Wohin mit dem CSS?"},{"no":19,"title":"CSS Modules machen Klassen lokal"},{"no":20,"title":"Tailwind setzt auf Utility-Klassen"},{"no":21,"title":"Variants gehören in eine Map"},{"no":22,"title":"Ein Ansatz pro Projekt"},{"no":23,"title":"State, Events, Listen, Effects","section":true},{"no":24,"title":"Warum State?"},{"no":25,"title":"State ist ein Snapshot"},{"no":26,"title":"Vom Klick zur neuen UI"},{"no":27,"title":"Neue Objekte statt Mutation"},{"no":28,"title":"State hängt an der Position im Tree"},{"no":29,"title":"Wo lebt der State?"},{"no":30,"title":"Event Handler übergeben, nicht aufrufen"},{"no":31,"title":"Im Controlled Input entscheidet der State"},{"no":32,"title":"Eine Form mit typisierten Events"},{"no":33,"title":"Controlled oder Uncontrolled?"},{"no":34,"title":"Ein klares Muster für Events und Forms"},{"no":35,"title":"Aus Arrays werden Elemente"},{"no":36,"title":"Keys sind Identität"},{"no":37,"title":"Bedingungen sind normale Ausdrücke"},{"no":38,"title":"Ein Status statt vieler Booleans"},{"no":39,"title":"Ein neuer Key setzt State zurück"},{"no":40,"title":"Key aus den Daten, Status als Union Type"},{"no":41,"title":"Brauchst du den Effect?"},{"no":42,"title":"Effects synchronisieren mit der Außenwelt"},{"no":43,"title":"Jeder Effect startet und stoppt"},{"no":44,"title":"Alte Antworten dürfen nicht gewinnen"},{"no":45,"title":"Lesen, ohne zu reagieren"},{"no":46,"title":"Erst fragen, dann den Effect schreiben"},{"no":47,"title":"Custom Hooks, Context, Reducer","section":true},{"no":48,"title":"Dieselbe Logik, zweimal"},{"no":49,"title":"Ein Hook ist eine Funktion"},{"no":50,"title":"Hooks kapseln Effects"},{"no":51,"title":"Hooks brauchen eine feste Reihenfolge"},{"no":52,"title":"Ein guter Hook liest sich wie ein Satz"},{"no":53,"title":"Prop Drilling durch jede Ebene"},{"no":54,"title":"Context typsicher mit null als Default"},{"no":55,"title":"Provider lösen Re-Renders aus"},{"no":56,"title":"Jeder State hat seinen Ort"},{"no":57,"title":"Zwei Fehler in fast jedem Projekt"},{"no":58,"title":"Wann kippt useState?"},{"no":59,"title":"Erst States und Transitions zeichnen"},{"no":60,"title":"Der Reducer übersetzt das Diagramm"},{"no":61,"title":"Side Effects bleiben im Event Handler"},{"no":62,"title":"Redux ist dasselbe Prinzip, nur global"},{"no":63,"title":"Daten laden, Suspense, Routing, Forms","section":true},{"no":64,"title":"Server-Daten gehören nicht dir"},{"no":65,"title":"fetch liefert unknown, nicht Product"},{"no":66,"title":"Die langsame Antwort kommt zuletzt"},{"no":67,"title":"Ein Hook pro Ressource"},{"no":68,"title":"Wann sich eine Server-State-Library lohnt"},{"no":69,"title":"Laden, prüfen, abbrechen"},{"no":70,"title":"Überall if loading"},{"no":71,"title":"use liest ein Promise, cacht es aber nicht"},{"no":72,"title":"Boundaries gehören an Bereichsgrenzen"},{"no":73,"title":"react-error-boundary statt eigener Klasse"},{"no":74,"title":"Warten und Errors pro Bereich"},{"no":75,"title":"Nicht jeder Error landet in der Boundary"},{"no":76,"title":"Die URL ist State"},{"no":77,"title":"Routes sind Objekte, Layouts haben ein Outlet"},{"no":78,"title":"Der Loader lädt vor dem Rendering"},{"no":79,"title":"Search Params sind Eingaben von außen"},{"no":80,"title":"Jede Route fängt ihre Errors"},{"no":81,"title":"Typische Fehler beim Routing"},{"no":82,"title":"Validierungsregeln an drei Stellen"},{"no":83,"title":"Ein Schema für Browser und Server"},{"no":84,"title":"Erst safeParse, dann der Request"},{"no":85,"title":"Der Pfad eines Issues zeigt aufs Feld"},{"no":86,"title":"Errors gehören ans Feld"},{"no":87,"title":"Keine Form, die beim ersten Buchstaben schimpft"},{"no":88,"title":"Accessibility, Testing, Design System","section":true},{"no":89,"title":"Warum von Anfang an?"},{"no":90,"title":"Semantik zuerst"},{"no":91,"title":"Labels und Errors gehören ans Feld"},{"no":92,"title":"Focus muss sinnvoll wandern"},{"no":93,"title":"Werkzeuge finden viel, aber nicht alles"},{"no":94,"title":"Was ist ein guter Test?"},{"no":95,"title":"Vitest nutzt die Vite-Konfiguration"},{"no":96,"title":"Tests bedienen die UI wie Nutzende"},{"no":97,"title":"findBy wartet, ein fetch-Stub antwortet"},{"no":98,"title":"data-testid ist der letzte Ausweg"},{"no":99,"title":"Warum Component Design?"},{"no":100,"title":"Fünf Stufen vom Atom zur Page"},{"no":101,"title":"Atoms kennen nur ihre Props"},{"no":102,"title":"Erst die Page kennt echte Daten"},{"no":103,"title":"Vokabular schlägt Ordnerstruktur"},{"no":104,"title":"Eine Liste für jeden Typ?"},{"no":105,"title":"T kommt vom Aufrufer"},{"no":106,"title":"keyof erlaubt nur echte Spalten"},{"no":107,"title":"Jede Spalte rendert ihren Wert"},{"no":108,"title":"Varianten schließen sich aus"},{"no":109,"title":"Zu generisch ist auch falsch"},{"no":110,"title":"Architektur, Performance, Produktion","section":true},{"no":111,"title":"Ordner nach Technik skalieren nicht"},{"no":112,"title":"Ordne nach Features"},{"no":113,"title":"Dependencies zeigen nach unten"},{"no":114,"title":"Das Design System kennt keine Fachdaten"},{"no":115,"title":"Atomic Design oder Feature-Ordner?"},{"no":116,"title":"Entscheidungen gehören in kurze ADRs"},{"no":117,"title":"Wann rendert React?"},{"no":118,"title":"Erst messen"},{"no":119,"title":"Struktur vor Memo"},{"no":120,"title":"Memoization übernimmt der Compiler"},{"no":121,"title":"Eingaben bleiben dringend"},{"no":122,"title":"Ausblenden ohne State-Verlust"},{"no":123,"title":"Jede Form braucht dieselben Zustände"},{"no":124,"title":"useActionState liefert State und Pending"},{"no":125,"title":"useOptimistic zeigt das Erwartete sofort"},{"no":126,"title":"Im Error-Fall verschwindet der Eintrag"},{"no":127,"title":"Optimistic nur, wo fast alles gelingt"},{"no":128,"title":"vite build schreibt VITE_-Werte ins Bundle"},{"no":129,"title":"Weniger JavaScript, schnellerer Start"},{"no":130,"title":"Errors brauchen Release und Route"},{"no":131,"title":"Echte Nutzende messen, nicht den Laptop"},{"no":132,"title":"Rollback schlägt Hotfix"},{"no":133,"title":"Fragen?","section":true}],"languages":{"de":{"title":"React mit TypeScript bis zur Produktion","summary":"Du baust mit React, TypeScript und React Router eine App aus kleinen Components und bringst sie getestet und barrierearm in Produktion.","url":"https://slides.mikebild.dev/introduction-react.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.pdf?v=a9fa9b32eb2d","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.mp4?v=a9fa9b32eb2d","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.png?v=a9fa9b32eb2d","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.de.vtt?v=a9fa9b32eb2d","slide_count":133,"slides":[{"no":1,"title":"React mit TypeScript bis zur Produktion","section":true},{"no":2,"title":"Components, JSX, Composition, Styling","section":true},{"no":3,"title":"Warum Components?"},{"no":4,"title":"UI = f(props)"},{"no":5,"title":"Erst der Component Tree, dann der Code"},{"no":6,"title":"Rendering bleibt rein"},{"no":7,"title":"Eine Component ist eine Funktion"},{"no":8,"title":"JSX ist JavaScript"},{"no":9,"title":"In geschweifte Klammern gehören Ausdrücke"},{"no":10,"title":"Props sind ein typisierter Vertrag"},{"no":11,"title":"Daten fließen nach unten"},{"no":12,"title":"Drei typische Fehler am Anfang"},{"no":13,"title":"Zwanzig Props sind ein Warnsignal"},{"no":14,"title":"children nimmt beliebigen Inhalt auf"},{"no":15,"title":"Benannte Slots ersetzen Flags"},{"no":16,"title":"Daten fließen an der Hülle vorbei"},{"no":17,"title":"Nicht jedes Detail braucht einen Slot"},{"no":18,"title":"Wohin mit dem CSS?"},{"no":19,"title":"CSS Modules machen Klassen lokal"},{"no":20,"title":"Tailwind setzt auf Utility-Klassen"},{"no":21,"title":"Variants gehören in eine Map"},{"no":22,"title":"Ein Ansatz pro Projekt"},{"no":23,"title":"State, Events, Listen, Effects","section":true},{"no":24,"title":"Warum State?"},{"no":25,"title":"State ist ein Snapshot"},{"no":26,"title":"Vom Klick zur neuen UI"},{"no":27,"title":"Neue Objekte statt Mutation"},{"no":28,"title":"State hängt an der Position im Tree"},{"no":29,"title":"Wo lebt der State?"},{"no":30,"title":"Event Handler übergeben, nicht aufrufen"},{"no":31,"title":"Im Controlled Input entscheidet der State"},{"no":32,"title":"Eine Form mit typisierten Events"},{"no":33,"title":"Controlled oder Uncontrolled?"},{"no":34,"title":"Ein klares Muster für Events und Forms"},{"no":35,"title":"Aus Arrays werden Elemente"},{"no":36,"title":"Keys sind Identität"},{"no":37,"title":"Bedingungen sind normale Ausdrücke"},{"no":38,"title":"Ein Status statt vieler Booleans"},{"no":39,"title":"Ein neuer Key setzt State zurück"},{"no":40,"title":"Key aus den Daten, Status als Union Type"},{"no":41,"title":"Brauchst du den Effect?"},{"no":42,"title":"Effects synchronisieren mit der Außenwelt"},{"no":43,"title":"Jeder Effect startet und stoppt"},{"no":44,"title":"Alte Antworten dürfen nicht gewinnen"},{"no":45,"title":"Lesen, ohne zu reagieren"},{"no":46,"title":"Erst fragen, dann den Effect schreiben"},{"no":47,"title":"Custom Hooks, Context, Reducer","section":true},{"no":48,"title":"Dieselbe Logik, zweimal"},{"no":49,"title":"Ein Hook ist eine Funktion"},{"no":50,"title":"Hooks kapseln Effects"},{"no":51,"title":"Hooks brauchen eine feste Reihenfolge"},{"no":52,"title":"Ein guter Hook liest sich wie ein Satz"},{"no":53,"title":"Prop Drilling durch jede Ebene"},{"no":54,"title":"Context typsicher mit null als Default"},{"no":55,"title":"Provider lösen Re-Renders aus"},{"no":56,"title":"Jeder State hat seinen Ort"},{"no":57,"title":"Zwei Fehler in fast jedem Projekt"},{"no":58,"title":"Wann kippt useState?"},{"no":59,"title":"Erst States und Transitions zeichnen"},{"no":60,"title":"Der Reducer übersetzt das Diagramm"},{"no":61,"title":"Side Effects bleiben im Event Handler"},{"no":62,"title":"Redux ist dasselbe Prinzip, nur global"},{"no":63,"title":"Daten laden, Suspense, Routing, Forms","section":true},{"no":64,"title":"Server-Daten gehören nicht dir"},{"no":65,"title":"fetch liefert unknown, nicht Product"},{"no":66,"title":"Die langsame Antwort kommt zuletzt"},{"no":67,"title":"Ein Hook pro Ressource"},{"no":68,"title":"Wann sich eine Server-State-Library lohnt"},{"no":69,"title":"Laden, prüfen, abbrechen"},{"no":70,"title":"Überall if loading"},{"no":71,"title":"use liest ein Promise, cacht es aber nicht"},{"no":72,"title":"Boundaries gehören an Bereichsgrenzen"},{"no":73,"title":"react-error-boundary statt eigener Klasse"},{"no":74,"title":"Warten und Errors pro Bereich"},{"no":75,"title":"Nicht jeder Error landet in der Boundary"},{"no":76,"title":"Die URL ist State"},{"no":77,"title":"Routes sind Objekte, Layouts haben ein Outlet"},{"no":78,"title":"Der Loader lädt vor dem Rendering"},{"no":79,"title":"Search Params sind Eingaben von außen"},{"no":80,"title":"Jede Route fängt ihre Errors"},{"no":81,"title":"Typische Fehler beim Routing"},{"no":82,"title":"Validierungsregeln an drei Stellen"},{"no":83,"title":"Ein Schema für Browser und Server"},{"no":84,"title":"Erst safeParse, dann der Request"},{"no":85,"title":"Der Pfad eines Issues zeigt aufs Feld"},{"no":86,"title":"Errors gehören ans Feld"},{"no":87,"title":"Keine Form, die beim ersten Buchstaben schimpft"},{"no":88,"title":"Accessibility, Testing, Design System","section":true},{"no":89,"title":"Warum von Anfang an?"},{"no":90,"title":"Semantik zuerst"},{"no":91,"title":"Labels und Errors gehören ans Feld"},{"no":92,"title":"Focus muss sinnvoll wandern"},{"no":93,"title":"Werkzeuge finden viel, aber nicht alles"},{"no":94,"title":"Was ist ein guter Test?"},{"no":95,"title":"Vitest nutzt die Vite-Konfiguration"},{"no":96,"title":"Tests bedienen die UI wie Nutzende"},{"no":97,"title":"findBy wartet, ein fetch-Stub antwortet"},{"no":98,"title":"data-testid ist der letzte Ausweg"},{"no":99,"title":"Warum Component Design?"},{"no":100,"title":"Fünf Stufen vom Atom zur Page"},{"no":101,"title":"Atoms kennen nur ihre Props"},{"no":102,"title":"Erst die Page kennt echte Daten"},{"no":103,"title":"Vokabular schlägt Ordnerstruktur"},{"no":104,"title":"Eine Liste für jeden Typ?"},{"no":105,"title":"T kommt vom Aufrufer"},{"no":106,"title":"keyof erlaubt nur echte Spalten"},{"no":107,"title":"Jede Spalte rendert ihren Wert"},{"no":108,"title":"Varianten schließen sich aus"},{"no":109,"title":"Zu generisch ist auch falsch"},{"no":110,"title":"Architektur, Performance, Produktion","section":true},{"no":111,"title":"Ordner nach Technik skalieren nicht"},{"no":112,"title":"Ordne nach Features"},{"no":113,"title":"Dependencies zeigen nach unten"},{"no":114,"title":"Das Design System kennt keine Fachdaten"},{"no":115,"title":"Atomic Design oder Feature-Ordner?"},{"no":116,"title":"Entscheidungen gehören in kurze ADRs"},{"no":117,"title":"Wann rendert React?"},{"no":118,"title":"Erst messen"},{"no":119,"title":"Struktur vor Memo"},{"no":120,"title":"Memoization übernimmt der Compiler"},{"no":121,"title":"Eingaben bleiben dringend"},{"no":122,"title":"Ausblenden ohne State-Verlust"},{"no":123,"title":"Jede Form braucht dieselben Zustände"},{"no":124,"title":"useActionState liefert State und Pending"},{"no":125,"title":"useOptimistic zeigt das Erwartete sofort"},{"no":126,"title":"Im Error-Fall verschwindet der Eintrag"},{"no":127,"title":"Optimistic nur, wo fast alles gelingt"},{"no":128,"title":"vite build schreibt VITE_-Werte ins Bundle"},{"no":129,"title":"Weniger JavaScript, schnellerer Start"},{"no":130,"title":"Errors brauchen Release und Route"},{"no":131,"title":"Echte Nutzende messen, nicht den Laptop"},{"no":132,"title":"Rollback schlägt Hotfix"},{"no":133,"title":"Fragen?","section":true}],"articles":["https://www.mikebild.dev/de/blog/react-ueberblick-von-jsx-zur-architektur/"]},"en":{"title":"React with TypeScript all the way to production","summary":"You use React, TypeScript, and React Router to build an app from small components, then ship it to production with tests and good accessibility.","url":"https://slides.mikebild.dev/introduction-react.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.en.pdf?v=19f0d4ba8526","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.en.mp4?v=19f0d4ba8526","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.en.png?v=19f0d4ba8526","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-react/introduction-react.en.vtt?v=19f0d4ba8526","slide_count":133,"slides":[{"no":1,"title":"React with TypeScript all the way to production","section":true},{"no":2,"title":"components, JSX, composition, styling","section":true},{"no":3,"title":"Why components?"},{"no":4,"title":"UI = f(props)"},{"no":5,"title":"First the component tree, then the code"},{"no":6,"title":"Rendering stays pure"},{"no":7,"title":"A component is a function"},{"no":8,"title":"JSX is JavaScript"},{"no":9,"title":"Curly braces are for expressions"},{"no":10,"title":"Props are a typed contract"},{"no":11,"title":"Data flows downward"},{"no":12,"title":"Three typical beginner mistakes"},{"no":13,"title":"Twenty props are a warning sign"},{"no":14,"title":"children accepts any content"},{"no":15,"title":"Named slots replace flags"},{"no":16,"title":"Data flows past the wrapper"},{"no":17,"title":"Not every detail needs a slot"},{"no":18,"title":"Where should the CSS go?"},{"no":19,"title":"CSS Modules make classes local"},{"no":20,"title":"Tailwind uses utility classes"},{"no":21,"title":"Variants belong in a map"},{"no":22,"title":"One approach per project"},{"no":23,"title":"state, events, lists, effects","section":true},{"no":24,"title":"Why state?"},{"no":25,"title":"State is a snapshot"},{"no":26,"title":"From click to new UI"},{"no":27,"title":"New objects instead of mutation"},{"no":28,"title":"State is tied to the position in the tree"},{"no":29,"title":"Where does state live?"},{"no":30,"title":"Pass event handlers, do not call them"},{"no":31,"title":"In a controlled input, state decides"},{"no":32,"title":"A form with typed events"},{"no":33,"title":"Controlled or uncontrolled?"},{"no":34,"title":"A clear pattern for events and forms"},{"no":35,"title":"Arrays become elements"},{"no":36,"title":"Keys are identity"},{"no":37,"title":"Conditions are normal expressions"},{"no":38,"title":"One status instead of many booleans"},{"no":39,"title":"A new key resets state"},{"no":40,"title":"Key from the data, status as a union type"},{"no":41,"title":"Do you need the effect?"},{"no":42,"title":"Effects synchronize with the outside world"},{"no":43,"title":"Every effect starts and stops"},{"no":44,"title":"Old responses must not win"},{"no":45,"title":"Read without reacting"},{"no":46,"title":"Ask first, then write the effect"},{"no":47,"title":"custom hooks, context, reducer","section":true},{"no":48,"title":"The same logic, twice"},{"no":49,"title":"A hook is a function"},{"no":50,"title":"Hooks encapsulate effects"},{"no":51,"title":"Hooks need a fixed order"},{"no":52,"title":"A good hook reads like a sentence"},{"no":53,"title":"Prop drilling through every level"},{"no":54,"title":"Type-safe context with null as the default"},{"no":55,"title":"Providers cause re-renders"},{"no":56,"title":"Every state has its place"},{"no":57,"title":"Two mistakes in almost every project"},{"no":58,"title":"When does useState tip over?"},{"no":59,"title":"Draw states and transitions first"},{"no":60,"title":"The reducer translates the diagram"},{"no":61,"title":"Side effects stay in the event handler"},{"no":62,"title":"Redux is the same principle, just global"},{"no":63,"title":"loading data, Suspense, routing, forms","section":true},{"no":64,"title":"Server data does not belong to you"},{"no":65,"title":"fetch returns unknown, not Product"},{"no":66,"title":"The slow response arrives last"},{"no":67,"title":"One hook per resource"},{"no":68,"title":"When a server-state library is worth it"},{"no":69,"title":"Load, check, abort"},{"no":70,"title":"if loading everywhere"},{"no":71,"title":"use reads a Promise but does not cache it"},{"no":72,"title":"Boundaries belong at area borders"},{"no":73,"title":"react-error-boundary instead of your own class"},{"no":74,"title":"Waiting and errors per area"},{"no":75,"title":"Not every error lands in the boundary"},{"no":76,"title":"The URL is state"},{"no":77,"title":"Routes are objects, layouts have an Outlet"},{"no":78,"title":"The loader loads before rendering"},{"no":79,"title":"Search params are external input"},{"no":80,"title":"Each route catches its errors"},{"no":81,"title":"Common routing mistakes"},{"no":82,"title":"Validation rules in three places"},{"no":83,"title":"One schema for browser and server"},{"no":84,"title":"First safeParse, then the request"},{"no":85,"title":"An issue path points to the field"},{"no":86,"title":"Errors belong at the field"},{"no":87,"title":"No form that scolds on the first letter"},{"no":88,"title":"accessibility, testing, design system","section":true},{"no":89,"title":"Why from the start?"},{"no":90,"title":"Semantics first"},{"no":91,"title":"Labels and errors belong to the field"},{"no":92,"title":"Focus must move in a meaningful way"},{"no":93,"title":"Tools find a lot, but not everything"},{"no":94,"title":"What makes a good test?"},{"no":95,"title":"Vitest uses the Vite configuration"},{"no":96,"title":"Tests operate the UI like users"},{"no":97,"title":"findBy waits, a fetch stub responds"},{"no":98,"title":"data-testid is the last resort"},{"no":99,"title":"Why component design?"},{"no":100,"title":"Five levels from atom to page"},{"no":101,"title":"Atoms only know their props"},{"no":102,"title":"Only the Page knows real data"},{"no":103,"title":"Vocabulary beats folder structure"},{"no":104,"title":"One list for every type?"},{"no":105,"title":"T comes from the caller"},{"no":106,"title":"keyof allows only real columns"},{"no":107,"title":"Each column renders its value"},{"no":108,"title":"Variants exclude each other"},{"no":109,"title":"Too generic is also wrong"},{"no":110,"title":"architecture, performance, production","section":true},{"no":111,"title":"Folders by technology do not scale"},{"no":112,"title":"Organize by feature"},{"no":113,"title":"Dependencies point downward"},{"no":114,"title":"The design system knows no domain data"},{"no":115,"title":"Atomic Design or feature folders?"},{"no":116,"title":"Decisions belong in short ADRs"},{"no":117,"title":"When does React render?"},{"no":118,"title":"Measure first"},{"no":119,"title":"Structure before memo"},{"no":120,"title":"Memoization is handled by the compiler"},{"no":121,"title":"Inputs stay urgent"},{"no":122,"title":"Hide without losing state"},{"no":123,"title":"Every form needs the same states"},{"no":124,"title":"useActionState returns state and pending"},{"no":125,"title":"useOptimistic shows the expected result right away"},{"no":126,"title":"On error, the item disappears"},{"no":127,"title":"Optimistic only where almost everything succeeds"},{"no":128,"title":"vite build writes VITE_ values into the bundle"},{"no":129,"title":"Less JavaScript, faster startup"},{"no":130,"title":"Errors need release and route"},{"no":131,"title":"Measure real users, not the laptop"},{"no":132,"title":"Rollback beats hotfix"},{"no":133,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-svelte","title":"Svelte 5 und SvelteKit mit TypeScript","summary":"Der Compiler statt Virtual DOM, Runes, Snippets, geteilter Zustand und Context, Motion und Transitions bis zur App mit SvelteKit.","topics":["Svelte","Frontend"],"url":"https://slides.mikebild.dev/introduction-svelte.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.pdf?v=b2e7a5fb6237","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.mp4?v=b2e7a5fb6237","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.png?v=b2e7a5fb6237","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.de.vtt?v=b2e7a5fb6237","repository":"https://github.com/MikeBild/introduction-svelte","articles":["https://www.mikebild.dev/de/blog/svelte-slots-context-und-web-components/","https://www.mikebild.dev/de/blog/svelte-motion-transitions-animationen/","https://www.mikebild.dev/de/blog/svelte-stores-zustand-ausserhalb-der-komponente/","https://www.mikebild.dev/de/blog/svelte-reaktivitaet-compiler-ohne-virtual-dom/"],"slide_count":61,"slides":[{"no":1,"title":"Svelte 5 und SvelteKit mit TypeScript","section":true},{"no":2,"title":"Compiler und Runes","section":true},{"no":3,"title":"Ein Compiler statt einer Runtime-Bibliothek"},{"no":4,"title":"Die Analyse passiert einmal, beim Build"},{"no":5,"title":"Eine erste Komponente"},{"no":6,"title":"Reaktiv ist nur, was du markierst"},{"no":7,"title":"Svelte rechnet beim Build, nicht im Browser"},{"no":8,"title":"Runes sind Schlüsselwörter für den Compiler"},{"no":9,"title":"Deep State im Warenkorb"},{"no":10,"title":"$state.raw ersetzt nur, verändert nie"},{"no":11,"title":"$state.snapshot an der Systemgrenze"},{"no":12,"title":"Drei Varianten, eine Faustregel"},{"no":13,"title":"Werte aus Werten"},{"no":14,"title":"$derived.by für mehrere Zeilen"},{"no":15,"title":"$effect ist der Ausgang zur Außenwelt"},{"no":16,"title":"Der häufigste Fehler mit $effect"},{"no":17,"title":"State fließt, Effects stehen am Rand"},{"no":18,"title":"Props, Formulare, Snippets","section":true},{"no":19,"title":"Daten kommen per $props"},{"no":20,"title":"Events sind jetzt Callbacks"},{"no":21,"title":"Keyed each ordnet über die ID zu"},{"no":22,"title":"$bindable erlaubt Two-Way-Binding"},{"no":23,"title":"Daten rein, Events raus"},{"no":24,"title":"Bindings halten die Eingaben"},{"no":25,"title":"Das Schema kennt die Regeln"},{"no":26,"title":"Erst prüfen, dann melden"},{"no":27,"title":"Fehler gehören ans Feld"},{"no":28,"title":"Gute Formulare schimpfen nicht"},{"no":29,"title":"Snippets ersetzen Slots"},{"no":30,"title":"children rendern"},{"no":31,"title":"Snippets mit Parametern"},{"no":32,"title":"Der Aufrufer liefert das Markup"},{"no":33,"title":"Struktur innen, Inhalt außen"},{"no":34,"title":"Geteilter State und SvelteKit bis zur Produktion","section":true},{"no":35,"title":"Props durch jede Ebene skalieren nicht"},{"no":36,"title":"Der Warenkorb als Klasse"},{"no":37,"title":"Context setzt einmal und liest überall"},{"no":38,"title":"Modul-Variablen teilen alle Requests"},{"no":39,"title":"Stores bleiben für Streams"},{"no":40,"title":"Jeder State hat seinen Ort"},{"no":41,"title":"SvelteKit macht aus Komponenten eine Anwendung"},{"no":42,"title":"SvelteKit 3 konfiguriert im Vite-Plugin"},{"no":43,"title":"load liefert die Daten der Seite"},{"no":44,"title":"Was es nicht gibt, wird ein 404"},{"no":45,"title":"page aus $app/state ist reaktiv"},{"no":46,"title":"Form Actions nehmen POST-Requests an"},{"no":47,"title":"Die Action prüft mit demselben Schema"},{"no":48,"title":"fail für Erwartbares, redirect für Erfolg"},{"no":49,"title":"fail landet als form auf der Seite"},{"no":50,"title":"Der Weg einer Bestellung"},{"no":51,"title":"Drei Ebenen, drei Werkzeuge"},{"no":52,"title":"Runes testest du ohne Komponente"},{"no":53,"title":"Vitest kennt Svelte über das Vite-Plugin"},{"no":54,"title":"Teste, was Nutzende sehen und tun"},{"no":55,"title":"Tests, die Umbauten überstehen"},{"no":56,"title":"Der Adapter bestimmt die Zielplattform"},{"no":57,"title":"npm run build, dann node build"},{"no":58,"title":"Express 5 als Option davor"},{"no":59,"title":"Hinter einem Proxy zählt die Origin"},{"no":60,"title":"Ein Image, zwei Stufen"},{"no":61,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Svelte 5 und SvelteKit mit TypeScript","summary":"Du baust den Werkstatt-Shop mit Svelte 5, Runes und SvelteKit 3, von der ersten Komponente bis zum getesteten Node-Server.","url":"https://slides.mikebild.dev/introduction-svelte.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.pdf?v=b2e7a5fb6237","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.mp4?v=b2e7a5fb6237","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.png?v=b2e7a5fb6237","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.de.vtt?v=b2e7a5fb6237","slide_count":61,"slides":[{"no":1,"title":"Svelte 5 und SvelteKit mit TypeScript","section":true},{"no":2,"title":"Compiler und Runes","section":true},{"no":3,"title":"Ein Compiler statt einer Runtime-Bibliothek"},{"no":4,"title":"Die Analyse passiert einmal, beim Build"},{"no":5,"title":"Eine erste Komponente"},{"no":6,"title":"Reaktiv ist nur, was du markierst"},{"no":7,"title":"Svelte rechnet beim Build, nicht im Browser"},{"no":8,"title":"Runes sind Schlüsselwörter für den Compiler"},{"no":9,"title":"Deep State im Warenkorb"},{"no":10,"title":"$state.raw ersetzt nur, verändert nie"},{"no":11,"title":"$state.snapshot an der Systemgrenze"},{"no":12,"title":"Drei Varianten, eine Faustregel"},{"no":13,"title":"Werte aus Werten"},{"no":14,"title":"$derived.by für mehrere Zeilen"},{"no":15,"title":"$effect ist der Ausgang zur Außenwelt"},{"no":16,"title":"Der häufigste Fehler mit $effect"},{"no":17,"title":"State fließt, Effects stehen am Rand"},{"no":18,"title":"Props, Formulare, Snippets","section":true},{"no":19,"title":"Daten kommen per $props"},{"no":20,"title":"Events sind jetzt Callbacks"},{"no":21,"title":"Keyed each ordnet über die ID zu"},{"no":22,"title":"$bindable erlaubt Two-Way-Binding"},{"no":23,"title":"Daten rein, Events raus"},{"no":24,"title":"Bindings halten die Eingaben"},{"no":25,"title":"Das Schema kennt die Regeln"},{"no":26,"title":"Erst prüfen, dann melden"},{"no":27,"title":"Fehler gehören ans Feld"},{"no":28,"title":"Gute Formulare schimpfen nicht"},{"no":29,"title":"Snippets ersetzen Slots"},{"no":30,"title":"children rendern"},{"no":31,"title":"Snippets mit Parametern"},{"no":32,"title":"Der Aufrufer liefert das Markup"},{"no":33,"title":"Struktur innen, Inhalt außen"},{"no":34,"title":"Geteilter State und SvelteKit bis zur Produktion","section":true},{"no":35,"title":"Props durch jede Ebene skalieren nicht"},{"no":36,"title":"Der Warenkorb als Klasse"},{"no":37,"title":"Context setzt einmal und liest überall"},{"no":38,"title":"Modul-Variablen teilen alle Requests"},{"no":39,"title":"Stores bleiben für Streams"},{"no":40,"title":"Jeder State hat seinen Ort"},{"no":41,"title":"SvelteKit macht aus Komponenten eine Anwendung"},{"no":42,"title":"SvelteKit 3 konfiguriert im Vite-Plugin"},{"no":43,"title":"load liefert die Daten der Seite"},{"no":44,"title":"Was es nicht gibt, wird ein 404"},{"no":45,"title":"page aus $app/state ist reaktiv"},{"no":46,"title":"Form Actions nehmen POST-Requests an"},{"no":47,"title":"Die Action prüft mit demselben Schema"},{"no":48,"title":"fail für Erwartbares, redirect für Erfolg"},{"no":49,"title":"fail landet als form auf der Seite"},{"no":50,"title":"Der Weg einer Bestellung"},{"no":51,"title":"Drei Ebenen, drei Werkzeuge"},{"no":52,"title":"Runes testest du ohne Komponente"},{"no":53,"title":"Vitest kennt Svelte über das Vite-Plugin"},{"no":54,"title":"Teste, was Nutzende sehen und tun"},{"no":55,"title":"Tests, die Umbauten überstehen"},{"no":56,"title":"Der Adapter bestimmt die Zielplattform"},{"no":57,"title":"npm run build, dann node build"},{"no":58,"title":"Express 5 als Option davor"},{"no":59,"title":"Hinter einem Proxy zählt die Origin"},{"no":60,"title":"Ein Image, zwei Stufen"},{"no":61,"title":"Fragen?","section":true}],"articles":["https://www.mikebild.dev/de/blog/svelte-slots-context-und-web-components/","https://www.mikebild.dev/de/blog/svelte-motion-transitions-animationen/","https://www.mikebild.dev/de/blog/svelte-stores-zustand-ausserhalb-der-komponente/","https://www.mikebild.dev/de/blog/svelte-reaktivitaet-compiler-ohne-virtual-dom/"]},"en":{"title":"Svelte 5 and SvelteKit with TypeScript","summary":"You build the workshop store with Svelte 5, runes, and SvelteKit 3, from the first component to a tested Node server.","url":"https://slides.mikebild.dev/introduction-svelte.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.en.pdf?v=8ed6ed7c9262","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.en.mp4?v=8ed6ed7c9262","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.en.png?v=8ed6ed7c9262","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-svelte/introduction-svelte.en.vtt?v=8ed6ed7c9262","slide_count":61,"slides":[{"no":1,"title":"Svelte 5 and SvelteKit with TypeScript","section":true},{"no":2,"title":"Compiler and runes","section":true},{"no":3,"title":"A compiler instead of a runtime library"},{"no":4,"title":"The analysis happens once, during the build"},{"no":5,"title":"A first component"},{"no":6,"title":"Only what you mark is reactive"},{"no":7,"title":"Svelte calculates during the build, not in the browser"},{"no":8,"title":"Runes are compiler keywords"},{"no":9,"title":"Deep state in the cart"},{"no":10,"title":"$state.raw only replaces, never changes"},{"no":11,"title":"$state.snapshot at the system boundary"},{"no":12,"title":"Three variants, one rule of thumb"},{"no":13,"title":"Values from values"},{"no":14,"title":"$derived.by for multiple lines"},{"no":15,"title":"$effect is the exit to the outside world"},{"no":16,"title":"The most common mistake with $effect"},{"no":17,"title":"State flows, effects stay at the edge"},{"no":18,"title":"Props, forms, snippets","section":true},{"no":19,"title":"Data comes in via $props"},{"no":20,"title":"Events are callbacks now"},{"no":21,"title":"Keyed each matches by ID"},{"no":22,"title":"$bindable enables two-way binding"},{"no":23,"title":"Data in, events out"},{"no":24,"title":"Bindings keep the inputs"},{"no":25,"title":"The schema knows the rules"},{"no":26,"title":"Validate first, then report"},{"no":27,"title":"Errors belong at the field"},{"no":28,"title":"Good forms do not scold"},{"no":29,"title":"Snippets replace slots"},{"no":30,"title":"Render children"},{"no":31,"title":"Snippets with parameters"},{"no":32,"title":"The caller provides the markup"},{"no":33,"title":"Structure inside, content outside"},{"no":34,"title":"Shared state and SvelteKit through production","section":true},{"no":35,"title":"Props through every layer do not scale"},{"no":36,"title":"The cart as a class"},{"no":37,"title":"Context sets once and reads everywhere"},{"no":38,"title":"Module variables share all requests"},{"no":39,"title":"Stores remain for streams"},{"no":40,"title":"Every state has its place"},{"no":41,"title":"SvelteKit turns components into an application"},{"no":42,"title":"SvelteKit 3 configures in the Vite plugin"},{"no":43,"title":"load provides the page data"},{"no":44,"title":"What does not exist becomes a 404"},{"no":45,"title":"page from $app/state is reactive"},{"no":46,"title":"Form actions accept POST requests"},{"no":47,"title":"The action validates with the same schema"},{"no":48,"title":"fail for expected cases, redirect for success"},{"no":49,"title":"fail appears as form on the page"},{"no":50,"title":"The path of an order"},{"no":51,"title":"Three levels, three tools"},{"no":52,"title":"You test Runes without a component"},{"no":53,"title":"Vitest knows Svelte through the Vite plugin"},{"no":54,"title":"Test what users see and do"},{"no":55,"title":"Tests that survive refactoring"},{"no":56,"title":"The adapter defines the target platform"},{"no":57,"title":"npm run build, then node build"},{"no":58,"title":"Express 5 as an option in front"},{"no":59,"title":"Behind a proxy, the origin matters"},{"no":60,"title":"One image, two stages"},{"no":61,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-knockoutjs","title":"KnockoutJS modernisieren und schrittweise migrieren","summary":"MVVM und Observables mit Knockout 3.5, modern betrieben mit TypeScript, Vite und Vitest. Dazu schrittweise Migration über Web Components und Sicherheit.","topics":["KnockoutJS","Frontend"],"url":"https://slides.mikebild.dev/introduction-knockoutjs.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.pdf?v=65e98e30ed2f","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.mp4?v=65e98e30ed2f","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.png?v=65e98e30ed2f","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.de.vtt?v=65e98e30ed2f","repository":"https://github.com/MikeBild/introduction-knockoutjs","articles":[],"slide_count":73,"slides":[{"no":1,"title":"KnockoutJS modernisieren und schrittweise migrieren","section":true},{"no":2,"title":"Bestand, MVVM und Observables","section":true},{"no":3,"title":"Wo steckt Knockout heute?"},{"no":4,"title":"Was ist der Stand im Oktober 2026?"},{"no":5,"title":"Pflegen, modernisieren oder migrieren?"},{"no":6,"title":"Was alter Code verrät"},{"no":7,"title":"Drei Rollen, klare Grenzen"},{"no":8,"title":"Die View beschreibt nur Bindings"},{"no":9,"title":"Das ViewModel als Factory-Function"},{"no":10,"title":"applyBindings braucht einen Container"},{"no":11,"title":"Binding Context bei Verschachtelung"},{"no":12,"title":"Ein Observable ist eine Funktion"},{"no":13,"title":"Dependency Tracking beim Lesen"},{"no":14,"title":"Wann Knockout benachrichtigt"},{"no":15,"title":"Subscriptions gehören aufgeräumt"},{"no":16,"title":"Abgeleitete Werte statt Zähler"},{"no":17,"title":"computed rechnet immer, pureComputed nur bei Bedarf"},{"no":18,"title":"Schreibbare computeds als Wertkonverter"},{"no":19,"title":"Side Effects gehören nicht in read"},{"no":20,"title":"Listen, Bindings und Components","section":true},{"no":21,"title":"Was ein observableArray verfolgt"},{"no":22,"title":"Der Warenkorb mit Types"},{"no":23,"title":"Ändern über das observableArray"},{"no":24,"title":"Große Listen in einem Schritt"},{"no":25,"title":"Drei Familien von Bindings"},{"no":26,"title":"Produkte mit foreach"},{"no":27,"title":"Menge und Bestellung"},{"no":28,"title":"if entfernt, visible versteckt"},{"no":29,"title":"Ausdrücke im data-bind kurz halten"},{"no":30,"title":"Was eine Component ausmacht"},{"no":31,"title":"Registrieren mit Klasse"},{"no":32,"title":"Component im Template nutzen"},{"no":33,"title":"Lifecycle und dispose"},{"no":34,"title":"Tooling, Custom Bindings und Tests","section":true},{"no":35,"title":"Von Script-Tags zu ESM"},{"no":36,"title":"Der Einstieg mit Vite"},{"no":37,"title":"Types aus dem Paket"},{"no":38,"title":"Was TypeScript nicht sieht"},{"no":39,"title":"init einmal, update bei jeder Änderung"},{"no":40,"title":"Ein Binding für Beträge"},{"no":41,"title":"Listener sauber abräumen"},{"no":42,"title":"jQuery-Plugins einhegen"},{"no":43,"title":"Zwei Ebenen, zwei Testarten"},{"no":44,"title":"Das ViewModel allein"},{"no":45,"title":"Template binden und bedienen"},{"no":46,"title":"Asynchrone Updates im Test"},{"no":47,"title":"Wartung und schrittweise Migration","section":true},{"no":48,"title":"Synchron bei jeder Änderung"},{"no":49,"title":"deferUpdates bündelt Benachrichtigungen"},{"no":50,"title":"rateLimit für Eingaben und Requests"},{"no":51,"title":"Listen in einem Schritt füllen"},{"no":52,"title":"Das Strangler-Pattern"},{"no":53,"title":"Wo du anfängst"},{"no":54,"title":"Knockout als Web Component verpacken"},{"no":55,"title":"Attribute rein, Events raus"},{"no":56,"title":"TKO, Mapping und andere Altlasten"},{"no":57,"title":"Eine Quelle für geteilten State"},{"no":58,"title":"Ein Vertrag aus get und subscribe"},{"no":59,"title":"Knockout als Store und zurück"},{"no":60,"title":"Adapter im Lifecycle"},{"no":61,"title":"Sicherheit","section":true},{"no":62,"title":"text ist sicher, html nicht"},{"no":63,"title":"Links ohne innerHTML"},{"no":64,"title":"URLs in attr prüfen"},{"no":65,"title":"Lücken mit Tests schließen"},{"no":66,"title":"Ein Angriff ohne script-Tag"},{"no":67,"title":"So sieht der Angriff aus"},{"no":68,"title":"Fremdes HTML aus dem Binding halten"},{"no":69,"title":"Was eine CSP leistet"},{"no":70,"title":"Die Ausnahme für Knockout"},{"no":71,"title":"Trusted Types seit 3.5.2"},{"no":72,"title":"Schrittweise scharf schalten"},{"no":73,"title":"Fragen?","section":true}],"languages":{"de":{"title":"KnockoutJS modernisieren und schrittweise migrieren","summary":"Du pflegst eine Knockout-Anwendung mit TypeScript, Vite und Tests weiter, schließt Sicherheitslücken und planst die Migration in kleinen Schritten.","url":"https://slides.mikebild.dev/introduction-knockoutjs.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.pdf?v=65e98e30ed2f","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.mp4?v=65e98e30ed2f","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.png?v=65e98e30ed2f","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.de.vtt?v=65e98e30ed2f","slide_count":73,"slides":[{"no":1,"title":"KnockoutJS modernisieren und schrittweise migrieren","section":true},{"no":2,"title":"Bestand, MVVM und Observables","section":true},{"no":3,"title":"Wo steckt Knockout heute?"},{"no":4,"title":"Was ist der Stand im Oktober 2026?"},{"no":5,"title":"Pflegen, modernisieren oder migrieren?"},{"no":6,"title":"Was alter Code verrät"},{"no":7,"title":"Drei Rollen, klare Grenzen"},{"no":8,"title":"Die View beschreibt nur Bindings"},{"no":9,"title":"Das ViewModel als Factory-Function"},{"no":10,"title":"applyBindings braucht einen Container"},{"no":11,"title":"Binding Context bei Verschachtelung"},{"no":12,"title":"Ein Observable ist eine Funktion"},{"no":13,"title":"Dependency Tracking beim Lesen"},{"no":14,"title":"Wann Knockout benachrichtigt"},{"no":15,"title":"Subscriptions gehören aufgeräumt"},{"no":16,"title":"Abgeleitete Werte statt Zähler"},{"no":17,"title":"computed rechnet immer, pureComputed nur bei Bedarf"},{"no":18,"title":"Schreibbare computeds als Wertkonverter"},{"no":19,"title":"Side Effects gehören nicht in read"},{"no":20,"title":"Listen, Bindings und Components","section":true},{"no":21,"title":"Was ein observableArray verfolgt"},{"no":22,"title":"Der Warenkorb mit Types"},{"no":23,"title":"Ändern über das observableArray"},{"no":24,"title":"Große Listen in einem Schritt"},{"no":25,"title":"Drei Familien von Bindings"},{"no":26,"title":"Produkte mit foreach"},{"no":27,"title":"Menge und Bestellung"},{"no":28,"title":"if entfernt, visible versteckt"},{"no":29,"title":"Ausdrücke im data-bind kurz halten"},{"no":30,"title":"Was eine Component ausmacht"},{"no":31,"title":"Registrieren mit Klasse"},{"no":32,"title":"Component im Template nutzen"},{"no":33,"title":"Lifecycle und dispose"},{"no":34,"title":"Tooling, Custom Bindings und Tests","section":true},{"no":35,"title":"Von Script-Tags zu ESM"},{"no":36,"title":"Der Einstieg mit Vite"},{"no":37,"title":"Types aus dem Paket"},{"no":38,"title":"Was TypeScript nicht sieht"},{"no":39,"title":"init einmal, update bei jeder Änderung"},{"no":40,"title":"Ein Binding für Beträge"},{"no":41,"title":"Listener sauber abräumen"},{"no":42,"title":"jQuery-Plugins einhegen"},{"no":43,"title":"Zwei Ebenen, zwei Testarten"},{"no":44,"title":"Das ViewModel allein"},{"no":45,"title":"Template binden und bedienen"},{"no":46,"title":"Asynchrone Updates im Test"},{"no":47,"title":"Wartung und schrittweise Migration","section":true},{"no":48,"title":"Synchron bei jeder Änderung"},{"no":49,"title":"deferUpdates bündelt Benachrichtigungen"},{"no":50,"title":"rateLimit für Eingaben und Requests"},{"no":51,"title":"Listen in einem Schritt füllen"},{"no":52,"title":"Das Strangler-Pattern"},{"no":53,"title":"Wo du anfängst"},{"no":54,"title":"Knockout als Web Component verpacken"},{"no":55,"title":"Attribute rein, Events raus"},{"no":56,"title":"TKO, Mapping und andere Altlasten"},{"no":57,"title":"Eine Quelle für geteilten State"},{"no":58,"title":"Ein Vertrag aus get und subscribe"},{"no":59,"title":"Knockout als Store und zurück"},{"no":60,"title":"Adapter im Lifecycle"},{"no":61,"title":"Sicherheit","section":true},{"no":62,"title":"text ist sicher, html nicht"},{"no":63,"title":"Links ohne innerHTML"},{"no":64,"title":"URLs in attr prüfen"},{"no":65,"title":"Lücken mit Tests schließen"},{"no":66,"title":"Ein Angriff ohne script-Tag"},{"no":67,"title":"So sieht der Angriff aus"},{"no":68,"title":"Fremdes HTML aus dem Binding halten"},{"no":69,"title":"Was eine CSP leistet"},{"no":70,"title":"Die Ausnahme für Knockout"},{"no":71,"title":"Trusted Types seit 3.5.2"},{"no":72,"title":"Schrittweise scharf schalten"},{"no":73,"title":"Fragen?","section":true}],"articles":[]},"en":{"title":"Modernize KnockoutJS and migrate step by step","summary":"You maintain a Knockout application with TypeScript, Vite, and tests, close security gaps, and plan the migration in small steps.","url":"https://slides.mikebild.dev/introduction-knockoutjs.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.en.pdf?v=db3087c1f285","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.en.mp4?v=db3087c1f285","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.en.png?v=db3087c1f285","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-knockoutjs/introduction-knockoutjs.en.vtt?v=db3087c1f285","slide_count":73,"slides":[{"no":1,"title":"Modernize KnockoutJS and migrate step by step","section":true},{"no":2,"title":"Inventory, MVVM, and observables","section":true},{"no":3,"title":"Where is Knockout today?"},{"no":4,"title":"What is the status in October 2026?"},{"no":5,"title":"Maintain, modernize, or migrate?"},{"no":6,"title":"What old code reveals"},{"no":7,"title":"Three roles, clear boundaries"},{"no":8,"title":"The View only describes bindings"},{"no":9,"title":"The ViewModel as a factory function"},{"no":10,"title":"applyBindings needs a container"},{"no":11,"title":"Binding context with nesting"},{"no":12,"title":"An Observable is a function"},{"no":13,"title":"Dependency tracking when reading"},{"no":14,"title":"When Knockout notifies"},{"no":15,"title":"Subscriptions need cleanup"},{"no":16,"title":"Derived values instead of counters"},{"no":17,"title":"computed always runs, pureComputed only when needed"},{"no":18,"title":"Writable computeds as value converters"},{"no":19,"title":"Side effects do not belong in read"},{"no":20,"title":"Lists, bindings, and components","section":true},{"no":21,"title":"What an observableArray tracks"},{"no":22,"title":"The cart with types"},{"no":23,"title":"Changing through the observableArray"},{"no":24,"title":"Large lists in one step"},{"no":25,"title":"Three families of bindings"},{"no":26,"title":"Products with foreach"},{"no":27,"title":"Quantity and order"},{"no":28,"title":"if removes, visible hides"},{"no":29,"title":"Keep expressions in data-bind short"},{"no":30,"title":"What makes a component"},{"no":31,"title":"Registering with a class"},{"no":32,"title":"Use the component in the template"},{"no":33,"title":"Lifecycle and dispose"},{"no":34,"title":"Tooling, custom bindings, and tests","section":true},{"no":35,"title":"From script tags to ESM"},{"no":36,"title":"Getting started with Vite"},{"no":37,"title":"Types from the package"},{"no":38,"title":"What TypeScript does not see"},{"no":39,"title":"init once, update on every change"},{"no":40,"title":"A binding for amounts"},{"no":41,"title":"Clean up listeners reliably"},{"no":42,"title":"Contain jQuery plugins"},{"no":43,"title":"Two layers, two test types"},{"no":44,"title":"The ViewModel on its own"},{"no":45,"title":"Bind and use the template"},{"no":46,"title":"Asynchronous updates in tests"},{"no":47,"title":"Maintenance and step-by-step migration","section":true},{"no":48,"title":"Synchronous on every change"},{"no":49,"title":"deferUpdates batches notifications"},{"no":50,"title":"rateLimit for inputs and requests"},{"no":51,"title":"Fill lists in one step"},{"no":52,"title":"The Strangler Pattern"},{"no":53,"title":"Where you start"},{"no":54,"title":"Wrap Knockout as a Web Component"},{"no":55,"title":"Attributes in, events out"},{"no":56,"title":"TKO, mapping and other legacy code"},{"no":57,"title":"A single source for shared state"},{"no":58,"title":"A contract of get and subscribe"},{"no":59,"title":"Knockout as a store and back"},{"no":60,"title":"Adapters in the lifecycle"},{"no":61,"title":"Security","section":true},{"no":62,"title":"text is safe, html is not"},{"no":63,"title":"Links without innerHTML"},{"no":64,"title":"Check URLs in attr"},{"no":65,"title":"Close gaps with tests"},{"no":66,"title":"An attack without a script tag"},{"no":67,"title":"This is what the attack looks like"},{"no":68,"title":"Keep external HTML out of the binding"},{"no":69,"title":"What a CSP does"},{"no":70,"title":"The exception for Knockout"},{"no":71,"title":"Trusted Types since 3.5.2"},{"no":72,"title":"Turn it on step by step"},{"no":73,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-graphql","title":"GraphQL: Vom Type System zum Produktionsbetrieb","summary":"Schema, Abfragen und Resolver, Echtzeit, Caching und Sicherheit bis zur föderierten API.","topics":["GraphQL","API"],"url":"https://slides.mikebild.dev/introduction-graphql.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.pdf?v=a904d4f12af2","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.mp4?v=a904d4f12af2","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.png?v=a904d4f12af2","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.de.vtt?v=a904d4f12af2","repository":"https://github.com/MikeBild/introduction-graphql","articles":["https://www.mikebild.dev/de/blog/graphql-ueberblick-vom-schema-zur-foederierten-api/","https://www.mikebild.dev/de/blog/graphql-konzepte-schema-resolver-ausfuehrung/"],"slide_count":127,"slides":[{"no":1,"title":"GraphQL vom Schema bis zur Produktion","section":true},{"no":2,"title":"Basics und erster Server","section":true},{"no":3,"title":"Feste Endpoints, viele Clients"},{"no":4,"title":"Ein Endpoint, ein Graph"},{"no":5,"title":"Die Bestellübersicht als Query"},{"no":6,"title":"Wann nicht?"},{"no":7,"title":"Deine Entscheidung"},{"no":8,"title":"Ein Schema als Vertrag"},{"no":9,"title":"Object Types und Scalars"},{"no":10,"title":"Nullability bewusst setzen"},{"no":11,"title":"Query und Mutation"},{"no":12,"title":"Wo Typen im Schema falsch gewählt sind"},{"no":13,"title":"Übung: das Schema des Shops"},{"no":14,"title":"Was ein Server tut"},{"no":15,"title":"Schema und erste Resolver"},{"no":16,"title":"Apollo Server mit Express"},{"no":17,"title":"Queries und Responses"},{"no":18,"title":"Was beim ersten Server schiefgeht"},{"no":19,"title":"Übung: der Shop antwortet"},{"no":20,"title":"Hartcodierte Queries"},{"no":21,"title":"Variables"},{"no":22,"title":"Fragments"},{"no":23,"title":"Aliases und Directives"},{"no":24,"title":"Woran Operations bei der Validierung scheitern"},{"no":25,"title":"Übung: die Bestellübersicht"},{"no":26,"title":"Schema, Resolver, Mutations, Errors","section":true},{"no":27,"title":"Tabellen sind kein API-Modell"},{"no":28,"title":"Vom Fachbegriff zum Type"},{"no":29,"title":"Vom Screen rückwärts"},{"no":30,"title":"Regeln, die weit tragen"},{"no":31,"title":"Was ein Schema unscharf macht"},{"no":32,"title":"Übung: vom Screen zum Schema"},{"no":33,"title":"Ein Resolver pro Field"},{"no":34,"title":"Das N+1-Problem"},{"no":35,"title":"DataLoader bündelt"},{"no":36,"title":"Ein Request, ein Loader"},{"no":37,"title":"Wo DataLoader falsche Daten liefert"},{"no":38,"title":"Übung: Zugriffe zählen"},{"no":39,"title":"CRUD über GraphQL"},{"no":40,"title":"Fachaktionen statt Updates"},{"no":41,"title":"Input rein, Payload raus"},{"no":42,"title":"Der Resolver bleibt dünn"},{"no":43,"title":"Was Mutations unzuverlässig macht"},{"no":44,"title":"Übung: Bestellung stornieren"},{"no":45,"title":"Zwei Arten von Errors"},{"no":46,"title":"Das errors-Field"},{"no":47,"title":"Fachfehler als Types"},{"no":48,"title":"Technische Errors maskieren"},{"no":49,"title":"Was das Error Handling unbrauchbar macht"},{"no":50,"title":"Übung: Fehler als Daten"},{"no":51,"title":"Design und Struktur","section":true},{"no":52,"title":"Woher bekommt ein Resolver seine Abhängigkeiten?"},{"no":53,"title":"Die context-Function läuft einmal pro Request"},{"no":54,"title":"Was gehört in den Context?"},{"no":55,"title":"Warum darf kein Resolver hineinschreiben?"},{"no":56,"title":"Resolver testen, ohne HTTP zu starten"},{"no":57,"title":"Was den Context unzuverlässig macht"},{"no":58,"title":"Was macht dieser Resolver alles?"},{"no":59,"title":"Was eine Prüfung braucht, legt ihre Schicht fest"},{"no":60,"title":"Die Fachlogik kennt kein GraphQL"},{"no":61,"title":"Der Resolver übersetzt in beide Richtungen"},{"no":62,"title":"Imports zeigen nur nach unten"},{"no":63,"title":"Was die Schichten wieder verklebt"},{"no":64,"title":"Ein Ordner je Fachbereich"},{"no":65,"title":"Jedes Modul erweitert Query und Mutation"},{"no":66,"title":"Zusammenbauen ist eigener Code"},{"no":67,"title":"Zwei Module, ein Field"},{"no":68,"title":"Ein Test sichert den Merge ab"},{"no":69,"title":"Schema-first oder Code-first?"},{"no":70,"title":"Apollo Client","section":true},{"no":71,"title":"Eine Query für alles"},{"no":72,"title":"Apollo Client einrichten"},{"no":73,"title":"Fragments bei der Komponente"},{"no":74,"title":"Die Seite komponiert"},{"no":75,"title":"Was Datenkomponenten typischerweise falsch machen"},{"no":76,"title":"Übung: Bestellübersicht in React"},{"no":77,"title":"Dieselben Daten, zwei Stellen"},{"no":78,"title":"Normalization"},{"no":79,"title":"Mutation aktualisiert den Cache"},{"no":80,"title":"Schneller wirken"},{"no":81,"title":"Wann der Client-Cache falsche Daten zeigt"},{"no":82,"title":"Übung: optimistisch stornieren"},{"no":83,"title":"Lists ohne Grenze"},{"no":84,"title":"Das Connection-Pattern"},{"no":85,"title":"Der Resolver"},{"no":86,"title":"Blättern mit Apollo Client"},{"no":87,"title":"Wann Pagination falsch oder teuer wird"},{"no":88,"title":"Übung: Bestellungen blättern"},{"no":89,"title":"Scalars, Testing, REST","section":true},{"no":90,"title":"String ist kein Datum"},{"no":91,"title":"Drei Richtungen eines Scalars"},{"no":92,"title":"Scalar im Schema"},{"no":93,"title":"DateTime implementieren"},{"no":94,"title":"Nicht selbst bauen"},{"no":95,"title":"Übung: createdAt als DateTime"},{"no":96,"title":"Was testen?"},{"no":97,"title":"Fachlogik zuerst"},{"no":98,"title":"Testbare App"},{"no":99,"title":"Operation über HTTP"},{"no":100,"title":"Welche Tests zu wenig oder zu viel prüfen"},{"no":101,"title":"Übung: Tests für den Shop"},{"no":102,"title":"Die Realität"},{"no":103,"title":"GraphQL als Fassade"},{"no":104,"title":"Ein Client-Modul pro Dienst"},{"no":105,"title":"Resolver mit Loader"},{"no":106,"title":"Was beim Einbinden von REST schiefgeht"},{"no":107,"title":"Übung: Bestand aus dem Lagerdienst"},{"no":108,"title":"Limits, Caching, Schema Evolution","section":true},{"no":109,"title":"Eine Query, viel Last"},{"no":110,"title":"Drei Schutzschichten"},{"no":111,"title":"Depth Limit als Validation Rule"},{"no":112,"title":"Query Cost mit Variables"},{"no":113,"title":"Persisted Operations als Allowlist"},{"no":114,"title":"Welche Schutzmaßnahmen nur scheinbar schützen"},{"no":115,"title":"Warum kein HTTP Cache?"},{"no":116,"title":"Die Ebenen"},{"no":117,"title":"Cache Hints im Schema"},{"no":118,"title":"Response Cache in Apollo Server"},{"no":119,"title":"Cache Invalidation"},{"no":120,"title":"Falsches Caching ist schlimmer als keines"},{"no":121,"title":"Kein v2 im Pfad"},{"no":122,"title":"Expand und Contract"},{"no":123,"title":"Deprecation im Schema"},{"no":124,"title":"Breaking Changes erkennen"},{"no":125,"title":"Was Schemaänderungen riskant macht"},{"no":126,"title":"Übung: von total zu totalPrice"},{"no":127,"title":"Fragen?","section":true}],"languages":{"de":{"title":"GraphQL vom Schema bis zur Produktion","summary":"Du baust eine GraphQL-API mit Apollo vom ersten Schema bis zum öffentlichen Graph, der Kosten begrenzt und sich sicher weiterentwickeln lässt.","url":"https://slides.mikebild.dev/introduction-graphql.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.pdf?v=a904d4f12af2","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.mp4?v=a904d4f12af2","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.png?v=a904d4f12af2","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.de.vtt?v=a904d4f12af2","slide_count":127,"slides":[{"no":1,"title":"GraphQL vom Schema bis zur Produktion","section":true},{"no":2,"title":"Basics und erster Server","section":true},{"no":3,"title":"Feste Endpoints, viele Clients"},{"no":4,"title":"Ein Endpoint, ein Graph"},{"no":5,"title":"Die Bestellübersicht als Query"},{"no":6,"title":"Wann nicht?"},{"no":7,"title":"Deine Entscheidung"},{"no":8,"title":"Ein Schema als Vertrag"},{"no":9,"title":"Object Types und Scalars"},{"no":10,"title":"Nullability bewusst setzen"},{"no":11,"title":"Query und Mutation"},{"no":12,"title":"Wo Typen im Schema falsch gewählt sind"},{"no":13,"title":"Übung: das Schema des Shops"},{"no":14,"title":"Was ein Server tut"},{"no":15,"title":"Schema und erste Resolver"},{"no":16,"title":"Apollo Server mit Express"},{"no":17,"title":"Queries und Responses"},{"no":18,"title":"Was beim ersten Server schiefgeht"},{"no":19,"title":"Übung: der Shop antwortet"},{"no":20,"title":"Hartcodierte Queries"},{"no":21,"title":"Variables"},{"no":22,"title":"Fragments"},{"no":23,"title":"Aliases und Directives"},{"no":24,"title":"Woran Operations bei der Validierung scheitern"},{"no":25,"title":"Übung: die Bestellübersicht"},{"no":26,"title":"Schema, Resolver, Mutations, Errors","section":true},{"no":27,"title":"Tabellen sind kein API-Modell"},{"no":28,"title":"Vom Fachbegriff zum Type"},{"no":29,"title":"Vom Screen rückwärts"},{"no":30,"title":"Regeln, die weit tragen"},{"no":31,"title":"Was ein Schema unscharf macht"},{"no":32,"title":"Übung: vom Screen zum Schema"},{"no":33,"title":"Ein Resolver pro Field"},{"no":34,"title":"Das N+1-Problem"},{"no":35,"title":"DataLoader bündelt"},{"no":36,"title":"Ein Request, ein Loader"},{"no":37,"title":"Wo DataLoader falsche Daten liefert"},{"no":38,"title":"Übung: Zugriffe zählen"},{"no":39,"title":"CRUD über GraphQL"},{"no":40,"title":"Fachaktionen statt Updates"},{"no":41,"title":"Input rein, Payload raus"},{"no":42,"title":"Der Resolver bleibt dünn"},{"no":43,"title":"Was Mutations unzuverlässig macht"},{"no":44,"title":"Übung: Bestellung stornieren"},{"no":45,"title":"Zwei Arten von Errors"},{"no":46,"title":"Das errors-Field"},{"no":47,"title":"Fachfehler als Types"},{"no":48,"title":"Technische Errors maskieren"},{"no":49,"title":"Was das Error Handling unbrauchbar macht"},{"no":50,"title":"Übung: Fehler als Daten"},{"no":51,"title":"Design und Struktur","section":true},{"no":52,"title":"Woher bekommt ein Resolver seine Abhängigkeiten?"},{"no":53,"title":"Die context-Function läuft einmal pro Request"},{"no":54,"title":"Was gehört in den Context?"},{"no":55,"title":"Warum darf kein Resolver hineinschreiben?"},{"no":56,"title":"Resolver testen, ohne HTTP zu starten"},{"no":57,"title":"Was den Context unzuverlässig macht"},{"no":58,"title":"Was macht dieser Resolver alles?"},{"no":59,"title":"Was eine Prüfung braucht, legt ihre Schicht fest"},{"no":60,"title":"Die Fachlogik kennt kein GraphQL"},{"no":61,"title":"Der Resolver übersetzt in beide Richtungen"},{"no":62,"title":"Imports zeigen nur nach unten"},{"no":63,"title":"Was die Schichten wieder verklebt"},{"no":64,"title":"Ein Ordner je Fachbereich"},{"no":65,"title":"Jedes Modul erweitert Query und Mutation"},{"no":66,"title":"Zusammenbauen ist eigener Code"},{"no":67,"title":"Zwei Module, ein Field"},{"no":68,"title":"Ein Test sichert den Merge ab"},{"no":69,"title":"Schema-first oder Code-first?"},{"no":70,"title":"Apollo Client","section":true},{"no":71,"title":"Eine Query für alles"},{"no":72,"title":"Apollo Client einrichten"},{"no":73,"title":"Fragments bei der Komponente"},{"no":74,"title":"Die Seite komponiert"},{"no":75,"title":"Was Datenkomponenten typischerweise falsch machen"},{"no":76,"title":"Übung: Bestellübersicht in React"},{"no":77,"title":"Dieselben Daten, zwei Stellen"},{"no":78,"title":"Normalization"},{"no":79,"title":"Mutation aktualisiert den Cache"},{"no":80,"title":"Schneller wirken"},{"no":81,"title":"Wann der Client-Cache falsche Daten zeigt"},{"no":82,"title":"Übung: optimistisch stornieren"},{"no":83,"title":"Lists ohne Grenze"},{"no":84,"title":"Das Connection-Pattern"},{"no":85,"title":"Der Resolver"},{"no":86,"title":"Blättern mit Apollo Client"},{"no":87,"title":"Wann Pagination falsch oder teuer wird"},{"no":88,"title":"Übung: Bestellungen blättern"},{"no":89,"title":"Scalars, Testing, REST","section":true},{"no":90,"title":"String ist kein Datum"},{"no":91,"title":"Drei Richtungen eines Scalars"},{"no":92,"title":"Scalar im Schema"},{"no":93,"title":"DateTime implementieren"},{"no":94,"title":"Nicht selbst bauen"},{"no":95,"title":"Übung: createdAt als DateTime"},{"no":96,"title":"Was testen?"},{"no":97,"title":"Fachlogik zuerst"},{"no":98,"title":"Testbare App"},{"no":99,"title":"Operation über HTTP"},{"no":100,"title":"Welche Tests zu wenig oder zu viel prüfen"},{"no":101,"title":"Übung: Tests für den Shop"},{"no":102,"title":"Die Realität"},{"no":103,"title":"GraphQL als Fassade"},{"no":104,"title":"Ein Client-Modul pro Dienst"},{"no":105,"title":"Resolver mit Loader"},{"no":106,"title":"Was beim Einbinden von REST schiefgeht"},{"no":107,"title":"Übung: Bestand aus dem Lagerdienst"},{"no":108,"title":"Limits, Caching, Schema Evolution","section":true},{"no":109,"title":"Eine Query, viel Last"},{"no":110,"title":"Drei Schutzschichten"},{"no":111,"title":"Depth Limit als Validation Rule"},{"no":112,"title":"Query Cost mit Variables"},{"no":113,"title":"Persisted Operations als Allowlist"},{"no":114,"title":"Welche Schutzmaßnahmen nur scheinbar schützen"},{"no":115,"title":"Warum kein HTTP Cache?"},{"no":116,"title":"Die Ebenen"},{"no":117,"title":"Cache Hints im Schema"},{"no":118,"title":"Response Cache in Apollo Server"},{"no":119,"title":"Cache Invalidation"},{"no":120,"title":"Falsches Caching ist schlimmer als keines"},{"no":121,"title":"Kein v2 im Pfad"},{"no":122,"title":"Expand und Contract"},{"no":123,"title":"Deprecation im Schema"},{"no":124,"title":"Breaking Changes erkennen"},{"no":125,"title":"Was Schemaänderungen riskant macht"},{"no":126,"title":"Übung: von total zu totalPrice"},{"no":127,"title":"Fragen?","section":true}],"articles":["https://www.mikebild.dev/de/blog/graphql-ueberblick-vom-schema-zur-foederierten-api/","https://www.mikebild.dev/de/blog/graphql-konzepte-schema-resolver-ausfuehrung/"]},"en":{"title":"GraphQL from schema to production","summary":"You build a GraphQL API with Apollo, from the first schema to a public graph that limits cost and can evolve safely.","url":"https://slides.mikebild.dev/introduction-graphql.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.en.pdf?v=a1a1bae43fe5","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.en.mp4?v=a1a1bae43fe5","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.en.png?v=a1a1bae43fe5","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-graphql/introduction-graphql.en.vtt?v=a1a1bae43fe5","slide_count":127,"slides":[{"no":1,"title":"GraphQL from schema to production","section":true},{"no":2,"title":"Basics and first server","section":true},{"no":3,"title":"Fixed endpoints, many clients"},{"no":4,"title":"One endpoint, one graph"},{"no":5,"title":"The order overview as a Query"},{"no":6,"title":"When not?"},{"no":7,"title":"Your decision"},{"no":8,"title":"A schema as a contract"},{"no":9,"title":"Object types and scalars"},{"no":10,"title":"Set nullability deliberately"},{"no":11,"title":"Query and Mutation"},{"no":12,"title":"Where schema types are chosen badly"},{"no":13,"title":"Exercise: the shop schema"},{"no":14,"title":"What a server does"},{"no":15,"title":"Schema and first resolvers"},{"no":16,"title":"Apollo Server with Express"},{"no":17,"title":"Queries and responses"},{"no":18,"title":"What breaks in the first server"},{"no":19,"title":"Exercise: the shop responds"},{"no":20,"title":"Hard-coded queries"},{"no":21,"title":"Variables"},{"no":22,"title":"Fragments"},{"no":23,"title":"Aliases and directives"},{"no":24,"title":"Where operations fail validation"},{"no":25,"title":"Exercise: the order overview"},{"no":26,"title":"Schema, resolver, mutations, errors","section":true},{"no":27,"title":"Tables are not an API model"},{"no":28,"title":"From domain term to type"},{"no":29,"title":"Work backward from the screen"},{"no":30,"title":"Rules that go far"},{"no":31,"title":"What makes a schema blurry"},{"no":32,"title":"Exercise: from screen to schema"},{"no":33,"title":"One resolver per field"},{"no":34,"title":"The N+1 problem"},{"no":35,"title":"DataLoader batches"},{"no":36,"title":"One request, one loader"},{"no":37,"title":"Where DataLoader returns wrong data"},{"no":38,"title":"Exercise: count accesses"},{"no":39,"title":"CRUD via GraphQL"},{"no":40,"title":"Domain actions instead of updates"},{"no":41,"title":"Input in, payload out"},{"no":42,"title":"The resolver stays thin"},{"no":43,"title":"What makes mutations unreliable"},{"no":44,"title":"Exercise: cancel an order"},{"no":45,"title":"Two kinds of errors"},{"no":46,"title":"The errors field"},{"no":47,"title":"Domain errors as types"},{"no":48,"title":"Mask technical errors"},{"no":49,"title":"What makes error handling unusable"},{"no":50,"title":"Exercise: errors as data"},{"no":51,"title":"Design and structure","section":true},{"no":52,"title":"Where does a resolver get its dependencies?"},{"no":53,"title":"The context function runs once per request"},{"no":54,"title":"What belongs in the context?"},{"no":55,"title":"Why must no resolver write into it?"},{"no":56,"title":"Test resolvers without starting HTTP"},{"no":57,"title":"What makes the context unreliable"},{"no":58,"title":"What does this resolver do?"},{"no":59,"title":"What a check needs defines its layer"},{"no":60,"title":"Business logic knows no GraphQL"},{"no":61,"title":"The resolver translates in both directions"},{"no":62,"title":"Imports point only downward"},{"no":63,"title":"What glues the layers back together"},{"no":64,"title":"One folder per domain"},{"no":65,"title":"Each module extends Query and Mutation"},{"no":66,"title":"Assembly is your own code"},{"no":67,"title":"Two modules, one field"},{"no":68,"title":"A test secures the merge"},{"no":69,"title":"Schema-first or Code-first?"},{"no":70,"title":"Apollo Client","section":true},{"no":71,"title":"One query for everything"},{"no":72,"title":"Set up Apollo Client"},{"no":73,"title":"Fragments next to the component"},{"no":74,"title":"The page composes"},{"no":75,"title":"What data components usually get wrong"},{"no":76,"title":"Exercise: Order overview in React"},{"no":77,"title":"Same data, two places"},{"no":78,"title":"Normalization"},{"no":79,"title":"A mutation updates the cache"},{"no":80,"title":"Feel faster"},{"no":81,"title":"When the client cache shows wrong data"},{"no":82,"title":"Exercise: cancel optimistically"},{"no":83,"title":"Lists without limits"},{"no":84,"title":"The connection pattern"},{"no":85,"title":"The resolver"},{"no":86,"title":"Paging with Apollo Client"},{"no":87,"title":"When pagination becomes wrong or expensive"},{"no":88,"title":"Exercise: page through orders"},{"no":89,"title":"Scalars, testing, REST","section":true},{"no":90,"title":"String is not a date"},{"no":91,"title":"Three directions of a scalar"},{"no":92,"title":"Scalar in the schema"},{"no":93,"title":"Implement DateTime"},{"no":94,"title":"Do not build it yourself"},{"no":95,"title":"Exercise: createdAt as DateTime"},{"no":96,"title":"What should you test?"},{"no":97,"title":"Domain logic first"},{"no":98,"title":"Testable app"},{"no":99,"title":"Operation over HTTP"},{"no":100,"title":"Which tests check too little or too much"},{"no":101,"title":"Exercise: tests for the shop"},{"no":102,"title":"The reality"},{"no":103,"title":"GraphQL as a facade"},{"no":104,"title":"One client module per service"},{"no":105,"title":"Resolver with loader"},{"no":106,"title":"What goes wrong when integrating REST"},{"no":107,"title":"Exercise: inventory from the inventory service"},{"no":108,"title":"Limits, caching, schema evolution","section":true},{"no":109,"title":"A query, heavy load"},{"no":110,"title":"Three protection layers"},{"no":111,"title":"Depth limit as a validation rule"},{"no":112,"title":"Query cost with variables"},{"no":113,"title":"Persisted operations as an allowlist"},{"no":114,"title":"Which protections only seem to protect"},{"no":115,"title":"Why no HTTP cache?"},{"no":116,"title":"The levels"},{"no":117,"title":"Cache hints in the schema"},{"no":118,"title":"Response cache in Apollo Server"},{"no":119,"title":"Cache invalidation"},{"no":120,"title":"Wrong caching is worse than none"},{"no":121,"title":"No v2 in the path"},{"no":122,"title":"Expand and contract"},{"no":123,"title":"Deprecation in the schema"},{"no":124,"title":"Detect breaking changes"},{"no":125,"title":"What makes schema changes risky"},{"no":126,"title":"Exercise: from total to totalPrice"},{"no":127,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-reactive-programming","title":"Reactive Programming mit RxJS","summary":"Streams für Suche, Live-Status und Benutzereingaben, mit Operatoren, Error Handling und Tests auf virtueller Zeit.","topics":["RxJS","Reactive"],"url":"https://slides.mikebild.dev/introduction-reactive-programming.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.pdf?v=d0df6308a9e1","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.mp4?v=d0df6308a9e1","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.png?v=d0df6308a9e1","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.de.vtt?v=d0df6308a9e1","repository":"https://github.com/MikeBild/Reactive-Programming","articles":[],"slide_count":61,"slides":[{"no":1,"title":"Reactive Programming mit RxJS","section":true},{"no":2,"title":"Push, Observable, Creation","section":true},{"no":3,"title":"Werte kommen über die Zeit"},{"no":4,"title":"Callbacks und Flags werden schnell unlesbar"},{"no":5,"title":"Dieselbe Suche als Stream"},{"no":6,"title":"Wann du kein RxJS brauchst"},{"no":7,"title":"Wer stößt den nächsten Wert an?"},{"no":8,"title":"Vier Arten, Werte zu liefern"},{"no":9,"title":"Wann Pull die bessere Wahl ist"},{"no":10,"title":"Gleiche Operatoren, anderes Modell"},{"no":11,"title":"Observable, Observer, Subscription"},{"no":12,"title":"Der Vertrag ist streng"},{"no":13,"title":"Lazy wie eine Funktion"},{"no":14,"title":"Ein Observable selbst schreiben"},{"no":15,"title":"Werte, Arrays, Iterables"},{"no":16,"title":"Events und Timer werden zu Observables"},{"no":17,"title":"Promises lazy machen mit defer"},{"no":18,"title":"Callback-APIs einbinden"},{"no":19,"title":"Operatoren, Lebensdauer, Kombinieren","section":true},{"no":20,"title":"Ein Operator macht aus einem Stream einen neuen"},{"no":21,"title":"Marble-Diagramme lesen"},{"no":22,"title":"State über die Zeit mit scan"},{"no":23,"title":"Eigene Operatoren mit pipe"},{"no":24,"title":"Endlose Streams halten Ressourcen fest"},{"no":25,"title":"Ressourcen an den Stream binden"},{"no":26,"title":"Drei Wege, eine Subscription zu beenden"},{"no":27,"title":"Ein Signal für alle Subscriptions"},{"no":28,"title":"Vier Arten, Streams zu verbinden"},{"no":29,"title":"Aktueller Stand mit combineLatest"},{"no":30,"title":"Ein Trigger, viel Kontext"},{"no":31,"title":"forkJoin wartet auf complete"},{"no":32,"title":"Cold und Hot, Async, Flattening","section":true},{"no":33,"title":"Film auf Abruf oder Live-Sendung"},{"no":34,"title":"Zwei Subscriber, zwei Requests"},{"no":35,"title":"Einen Producer teilen"},{"no":36,"title":"Wann Hot zum Problem wird"},{"no":37,"title":"Ein Promise lässt sich nur mit Signal abbrechen"},{"no":38,"title":"Wo welche Welt hingehört"},{"no":39,"title":"Zurück zu await"},{"no":40,"title":"async-Functions abbrechbar einbinden"},{"no":41,"title":"Ein Wert startet einen neuen Stream"},{"no":42,"title":"Vier Strategien für den laufenden Stream"},{"no":43,"title":"Der Use Case entscheidet"},{"no":44,"title":"Wo Flattening Daten verliert oder überlastet"},{"no":45,"title":"Fehler, Subjects, Zeit, Tests","section":true},{"no":46,"title":"Ein error ist das Ende"},{"no":47,"title":"catchError gehört in den inneren Stream"},{"no":48,"title":"Fehler sind Werte für die UI"},{"no":49,"title":"Wiederholen mit Backoff"},{"no":50,"title":"Observable und Observer zugleich"},{"no":51,"title":"Drei Subjects, drei Gedächtnisse"},{"no":52,"title":"Der Letzte macht das Licht aus"},{"no":53,"title":"Cachen mit shareReplay"},{"no":54,"title":"Push kennt keine Bremse"},{"no":55,"title":"Scheduler steuern, wann Arbeit läuft"},{"no":56,"title":"Vier Strategien gegen die Flut"},{"no":57,"title":"Warum echte Zeit Tests kaputt macht"},{"no":58,"title":"Marble-Syntax"},{"no":59,"title":"Ein Test mit virtueller Zeit"},{"no":60,"title":"Testen ohne Mocks"},{"no":61,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Reactive Programming mit RxJS","summary":"Du beschreibst Suche, Live-Status und Benutzereingaben als Streams mit RxJS und testest zeitabhängigen Code ohne echte Wartezeit.","url":"https://slides.mikebild.dev/introduction-reactive-programming.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.pdf?v=d0df6308a9e1","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.mp4?v=d0df6308a9e1","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.png?v=d0df6308a9e1","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.de.vtt?v=d0df6308a9e1","slide_count":61,"slides":[{"no":1,"title":"Reactive Programming mit RxJS","section":true},{"no":2,"title":"Push, Observable, Creation","section":true},{"no":3,"title":"Werte kommen über die Zeit"},{"no":4,"title":"Callbacks und Flags werden schnell unlesbar"},{"no":5,"title":"Dieselbe Suche als Stream"},{"no":6,"title":"Wann du kein RxJS brauchst"},{"no":7,"title":"Wer stößt den nächsten Wert an?"},{"no":8,"title":"Vier Arten, Werte zu liefern"},{"no":9,"title":"Wann Pull die bessere Wahl ist"},{"no":10,"title":"Gleiche Operatoren, anderes Modell"},{"no":11,"title":"Observable, Observer, Subscription"},{"no":12,"title":"Der Vertrag ist streng"},{"no":13,"title":"Lazy wie eine Funktion"},{"no":14,"title":"Ein Observable selbst schreiben"},{"no":15,"title":"Werte, Arrays, Iterables"},{"no":16,"title":"Events und Timer werden zu Observables"},{"no":17,"title":"Promises lazy machen mit defer"},{"no":18,"title":"Callback-APIs einbinden"},{"no":19,"title":"Operatoren, Lebensdauer, Kombinieren","section":true},{"no":20,"title":"Ein Operator macht aus einem Stream einen neuen"},{"no":21,"title":"Marble-Diagramme lesen"},{"no":22,"title":"State über die Zeit mit scan"},{"no":23,"title":"Eigene Operatoren mit pipe"},{"no":24,"title":"Endlose Streams halten Ressourcen fest"},{"no":25,"title":"Ressourcen an den Stream binden"},{"no":26,"title":"Drei Wege, eine Subscription zu beenden"},{"no":27,"title":"Ein Signal für alle Subscriptions"},{"no":28,"title":"Vier Arten, Streams zu verbinden"},{"no":29,"title":"Aktueller Stand mit combineLatest"},{"no":30,"title":"Ein Trigger, viel Kontext"},{"no":31,"title":"forkJoin wartet auf complete"},{"no":32,"title":"Cold und Hot, Async, Flattening","section":true},{"no":33,"title":"Film auf Abruf oder Live-Sendung"},{"no":34,"title":"Zwei Subscriber, zwei Requests"},{"no":35,"title":"Einen Producer teilen"},{"no":36,"title":"Wann Hot zum Problem wird"},{"no":37,"title":"Ein Promise lässt sich nur mit Signal abbrechen"},{"no":38,"title":"Wo welche Welt hingehört"},{"no":39,"title":"Zurück zu await"},{"no":40,"title":"async-Functions abbrechbar einbinden"},{"no":41,"title":"Ein Wert startet einen neuen Stream"},{"no":42,"title":"Vier Strategien für den laufenden Stream"},{"no":43,"title":"Der Use Case entscheidet"},{"no":44,"title":"Wo Flattening Daten verliert oder überlastet"},{"no":45,"title":"Fehler, Subjects, Zeit, Tests","section":true},{"no":46,"title":"Ein error ist das Ende"},{"no":47,"title":"catchError gehört in den inneren Stream"},{"no":48,"title":"Fehler sind Werte für die UI"},{"no":49,"title":"Wiederholen mit Backoff"},{"no":50,"title":"Observable und Observer zugleich"},{"no":51,"title":"Drei Subjects, drei Gedächtnisse"},{"no":52,"title":"Der Letzte macht das Licht aus"},{"no":53,"title":"Cachen mit shareReplay"},{"no":54,"title":"Push kennt keine Bremse"},{"no":55,"title":"Scheduler steuern, wann Arbeit läuft"},{"no":56,"title":"Vier Strategien gegen die Flut"},{"no":57,"title":"Warum echte Zeit Tests kaputt macht"},{"no":58,"title":"Marble-Syntax"},{"no":59,"title":"Ein Test mit virtueller Zeit"},{"no":60,"title":"Testen ohne Mocks"},{"no":61,"title":"Fragen?","section":true}],"articles":[]},"en":{"title":"Reactive programming with RxJS","summary":"You describe search, live status, and user input as streams with RxJS and test time-dependent code without real waiting time.","url":"https://slides.mikebild.dev/introduction-reactive-programming.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.en.pdf?v=51202b99fbfc","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.en.mp4?v=51202b99fbfc","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.en.png?v=51202b99fbfc","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-reactive-programming/introduction-reactive-programming.en.vtt?v=51202b99fbfc","slide_count":61,"slides":[{"no":1,"title":"Reactive programming with RxJS","section":true},{"no":2,"title":"Push, Observable, creation","section":true},{"no":3,"title":"Values arrive over time"},{"no":4,"title":"Callbacks and flags quickly become unreadable"},{"no":5,"title":"The same search as a stream"},{"no":6,"title":"When you do not need RxJS"},{"no":7,"title":"Who triggers the next value?"},{"no":8,"title":"Four ways to deliver values"},{"no":9,"title":"When pull is the better choice"},{"no":10,"title":"Same operators, different model"},{"no":11,"title":"Observable, Observer, Subscription"},{"no":12,"title":"The contract is strict"},{"no":13,"title":"Lazy like a function"},{"no":14,"title":"Write an Observable yourself"},{"no":15,"title":"Values, arrays, iterables"},{"no":16,"title":"Events and timers become Observables"},{"no":17,"title":"Make Promises lazy with defer"},{"no":18,"title":"Connect callback APIs"},{"no":19,"title":"Operators, lifetime, combining","section":true},{"no":20,"title":"An operator turns one stream into a new one"},{"no":21,"title":"Read Marble diagrams"},{"no":22,"title":"State over time with scan"},{"no":23,"title":"Your own operators with pipe"},{"no":24,"title":"Endless streams hold on to resources"},{"no":25,"title":"Tie resources to the stream"},{"no":26,"title":"Three ways to end a subscription"},{"no":27,"title":"One signal for all subscriptions"},{"no":28,"title":"Four ways to connect streams"},{"no":29,"title":"Current state with combineLatest"},{"no":30,"title":"One trigger, lots of context"},{"no":31,"title":"forkJoin waits for complete"},{"no":32,"title":"Cold and hot, async, flattening","section":true},{"no":33,"title":"On-demand movie or live broadcast"},{"no":34,"title":"Two subscribers, two requests"},{"no":35,"title":"Share one producer"},{"no":36,"title":"When hot becomes a problem"},{"no":37,"title":"A Promise can only be canceled with a signal"},{"no":38,"title":"Where each world belongs"},{"no":39,"title":"Back to await"},{"no":40,"title":"Connect async functions with cancellation"},{"no":41,"title":"One value starts a new stream"},{"no":42,"title":"Four strategies for the running stream"},{"no":43,"title":"The Use Case decides"},{"no":44,"title":"Where flattening loses data or overloads"},{"no":45,"title":"Errors, Subjects, time, tests","section":true},{"no":46,"title":"An error is the end"},{"no":47,"title":"catchError belongs in the inner stream"},{"no":48,"title":"Errors are values for the UI"},{"no":49,"title":"Retry with backoff"},{"no":50,"title":"Observable and Observer at the same time"},{"no":51,"title":"Three Subjects, three memories"},{"no":52,"title":"The last one turns off the lights"},{"no":53,"title":"Caching with shareReplay"},{"no":54,"title":"Push has no brakes"},{"no":55,"title":"Schedulers control when work runs"},{"no":56,"title":"Four strategies against the flood"},{"no":57,"title":"Why real time breaks tests"},{"no":58,"title":"Marble syntax"},{"no":59,"title":"A test with virtual time"},{"no":60,"title":"Testing without mocks"},{"no":61,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-docker-kubernetes","title":"Docker & Kubernetes","summary":"Die Werkstatt-Shop-API in Containern und im Cluster: von Image und Compose bis Rollout, Gateway API und Härtung, lokal mit kind.","topics":["Docker","Kubernetes","DevOps"],"url":"https://slides.mikebild.dev/introduction-docker-kubernetes.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.pdf?v=ada5b80ab5b4","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.mp4?v=ada5b80ab5b4","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.png?v=ada5b80ab5b4","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.de.vtt?v=ada5b80ab5b4","repository":"https://github.com/MikeBild/introduction-docker","articles":["https://www.mikebild.dev/de/blog/docker-eigene-registry/","https://www.mikebild.dev/de/blog/docker-logging-mit-elk/","https://www.mikebild.dev/de/blog/docker-compose-nodejs-redis/"],"slide_count":73,"slides":[{"no":1,"title":"Docker & Kubernetes","section":true},{"no":2,"title":"Container und Images","section":true},{"no":3,"title":"Was steckt in einem Container?"},{"no":4,"title":"Isolation kommt vom Kernel"},{"no":5,"title":"Vier Befehle zeigen es"},{"no":6,"title":"Wann eine VM die bessere Wahl ist"},{"no":7,"title":"Ein Image besteht aus Layern"},{"no":8,"title":"Zwei Stages, ein kleines Image"},{"no":9,"title":"Der Build Context ist kein Papierkorb"},{"no":10,"title":"Base Image bewusst wählen"},{"no":11,"title":"Was ein Image langsam oder unsicher macht"},{"no":12,"title":"Der Container ist Wegwerfware"},{"no":13,"title":"Postgres mit Named Volume"},{"no":14,"title":"Container finden sich über Namen"},{"no":15,"title":"Kleine Fehler verlieren Daten oder öffnen die Datenbank"},{"no":16,"title":"Compose, Healthchecks, Logs, Registry","section":true},{"no":17,"title":"Vom Befehl zum Zielzustand"},{"no":18,"title":"Der Werkstatt-Shop als Stack"},{"no":19,"title":"Der Alltag mit Compose"},{"no":20,"title":"Was Compose nicht garantiert"},{"no":21,"title":"Läuft, aber arbeitet nicht"},{"no":22,"title":"Healthchecks für Postgres und API"},{"no":23,"title":"Warten auf healthy"},{"no":24,"title":"Was ein Healthcheck nicht leistet"},{"no":25,"title":"Die App loggt, die Plattform transportiert"},{"no":26,"title":"Alle Services an einer Stelle"},{"no":27,"title":"Rotation statt voller Platte"},{"no":28,"title":"Wann es zentrale Logs braucht"},{"no":29,"title":"Der Name ist die Adresse"},{"no":30,"title":"Eine eigene Registry in einer Zeile"},{"no":31,"title":"Taggen, pushen, pullen"},{"no":32,"title":"Betrieb einer Registry"},{"no":33,"title":"Kubernetes-Grundlagen","section":true},{"no":34,"title":"Sollzustand statt Befehlsfolge"},{"no":35,"title":"Control Plane und Nodes"},{"no":36,"title":"Ein Cluster auf dem Laptop"},{"no":37,"title":"Objekte erkunden statt raten"},{"no":38,"title":"Pod, ReplicaSet, Deployment"},{"no":39,"title":"Das Deployment der API"},{"no":40,"title":"Anwenden und beobachten"},{"no":41,"title":"Warum startet der Pod nicht?"},{"no":42,"title":"Warum Pods einen Service brauchen"},{"no":43,"title":"Der Service der API"},{"no":44,"title":"Drinnen und draußen testen"},{"no":45,"title":"Typen von Services"},{"no":46,"title":"Ein Image, viele Umgebungen"},{"no":47,"title":"ConfigMap und Secret anlegen"},{"no":48,"title":"Im Deployment verwenden"},{"no":49,"title":"Was ein Secret nicht kann"},{"no":50,"title":"Betrieb im Cluster","section":true},{"no":51,"title":"Drei Probes, drei Folgen"},{"no":52,"title":"Probes für die API"},{"no":53,"title":"Wenn die Datenbank fehlt"},{"no":54,"title":"Falsche Probes töten gesunde Pods"},{"no":55,"title":"Requests und Limits"},{"no":56,"title":"Ressourcen der API"},{"no":57,"title":"Node.js kennt sein Limit"},{"no":58,"title":"Schlecht gesetzte Ressourcen rächen sich unter Last"},{"no":59,"title":"Pods schrittweise tauschen"},{"no":60,"title":"Die Strategie im Deployment"},{"no":61,"title":"Ausrollen und zurücknehmen"},{"no":62,"title":"Wann ein Rollout hängt"},{"no":63,"title":"Von Ingress zur Gateway API"},{"no":64,"title":"Drei Objekte, drei Rollen"},{"no":65,"title":"Ein Eingang für den Namespace"},{"no":66,"title":"Die Route der API"},{"no":67,"title":"Lokal ausprobieren"},{"no":68,"title":"Sicherheit","section":true},{"no":69,"title":"Jedes Paket ist Angriffsfläche"},{"no":70,"title":"Scannen zeigt den Unterschied"},{"no":71,"title":"Distroless statt Slim"},{"no":72,"title":"Dem Container Rechte nehmen"},{"no":73,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Docker & Kubernetes","summary":"Du bringst die Werkstatt-Shop-API in Container und betreibst sie in Kubernetes: von Image und Compose bis Rollout, Gateway API und Härtung.","url":"https://slides.mikebild.dev/introduction-docker-kubernetes.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.pdf?v=ada5b80ab5b4","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.mp4?v=ada5b80ab5b4","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.png?v=ada5b80ab5b4","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.de.vtt?v=ada5b80ab5b4","slide_count":73,"slides":[{"no":1,"title":"Docker & Kubernetes","section":true},{"no":2,"title":"Container und Images","section":true},{"no":3,"title":"Was steckt in einem Container?"},{"no":4,"title":"Isolation kommt vom Kernel"},{"no":5,"title":"Vier Befehle zeigen es"},{"no":6,"title":"Wann eine VM die bessere Wahl ist"},{"no":7,"title":"Ein Image besteht aus Layern"},{"no":8,"title":"Zwei Stages, ein kleines Image"},{"no":9,"title":"Der Build Context ist kein Papierkorb"},{"no":10,"title":"Base Image bewusst wählen"},{"no":11,"title":"Was ein Image langsam oder unsicher macht"},{"no":12,"title":"Der Container ist Wegwerfware"},{"no":13,"title":"Postgres mit Named Volume"},{"no":14,"title":"Container finden sich über Namen"},{"no":15,"title":"Kleine Fehler verlieren Daten oder öffnen die Datenbank"},{"no":16,"title":"Compose, Healthchecks, Logs, Registry","section":true},{"no":17,"title":"Vom Befehl zum Zielzustand"},{"no":18,"title":"Der Werkstatt-Shop als Stack"},{"no":19,"title":"Der Alltag mit Compose"},{"no":20,"title":"Was Compose nicht garantiert"},{"no":21,"title":"Läuft, aber arbeitet nicht"},{"no":22,"title":"Healthchecks für Postgres und API"},{"no":23,"title":"Warten auf healthy"},{"no":24,"title":"Was ein Healthcheck nicht leistet"},{"no":25,"title":"Die App loggt, die Plattform transportiert"},{"no":26,"title":"Alle Services an einer Stelle"},{"no":27,"title":"Rotation statt voller Platte"},{"no":28,"title":"Wann es zentrale Logs braucht"},{"no":29,"title":"Der Name ist die Adresse"},{"no":30,"title":"Eine eigene Registry in einer Zeile"},{"no":31,"title":"Taggen, pushen, pullen"},{"no":32,"title":"Betrieb einer Registry"},{"no":33,"title":"Kubernetes-Grundlagen","section":true},{"no":34,"title":"Sollzustand statt Befehlsfolge"},{"no":35,"title":"Control Plane und Nodes"},{"no":36,"title":"Ein Cluster auf dem Laptop"},{"no":37,"title":"Objekte erkunden statt raten"},{"no":38,"title":"Pod, ReplicaSet, Deployment"},{"no":39,"title":"Das Deployment der API"},{"no":40,"title":"Anwenden und beobachten"},{"no":41,"title":"Warum startet der Pod nicht?"},{"no":42,"title":"Warum Pods einen Service brauchen"},{"no":43,"title":"Der Service der API"},{"no":44,"title":"Drinnen und draußen testen"},{"no":45,"title":"Typen von Services"},{"no":46,"title":"Ein Image, viele Umgebungen"},{"no":47,"title":"ConfigMap und Secret anlegen"},{"no":48,"title":"Im Deployment verwenden"},{"no":49,"title":"Was ein Secret nicht kann"},{"no":50,"title":"Betrieb im Cluster","section":true},{"no":51,"title":"Drei Probes, drei Folgen"},{"no":52,"title":"Probes für die API"},{"no":53,"title":"Wenn die Datenbank fehlt"},{"no":54,"title":"Falsche Probes töten gesunde Pods"},{"no":55,"title":"Requests und Limits"},{"no":56,"title":"Ressourcen der API"},{"no":57,"title":"Node.js kennt sein Limit"},{"no":58,"title":"Schlecht gesetzte Ressourcen rächen sich unter Last"},{"no":59,"title":"Pods schrittweise tauschen"},{"no":60,"title":"Die Strategie im Deployment"},{"no":61,"title":"Ausrollen und zurücknehmen"},{"no":62,"title":"Wann ein Rollout hängt"},{"no":63,"title":"Von Ingress zur Gateway API"},{"no":64,"title":"Drei Objekte, drei Rollen"},{"no":65,"title":"Ein Eingang für den Namespace"},{"no":66,"title":"Die Route der API"},{"no":67,"title":"Lokal ausprobieren"},{"no":68,"title":"Sicherheit","section":true},{"no":69,"title":"Jedes Paket ist Angriffsfläche"},{"no":70,"title":"Scannen zeigt den Unterschied"},{"no":71,"title":"Distroless statt Slim"},{"no":72,"title":"Dem Container Rechte nehmen"},{"no":73,"title":"Fragen?","section":true}],"articles":["https://www.mikebild.dev/de/blog/docker-eigene-registry/","https://www.mikebild.dev/de/blog/docker-logging-mit-elk/","https://www.mikebild.dev/de/blog/docker-compose-nodejs-redis/"]},"en":{"title":"Docker & Kubernetes","summary":"You put the workshop shop API into containers and run it in Kubernetes: from image and Compose to rollout, Gateway API, and hardening.","url":"https://slides.mikebild.dev/introduction-docker-kubernetes.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.en.pdf?v=dcfe9fd4c4f6","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.en.mp4?v=dcfe9fd4c4f6","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.en.png?v=dcfe9fd4c4f6","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-docker-kubernetes/introduction-docker-kubernetes.en.vtt?v=dcfe9fd4c4f6","slide_count":73,"slides":[{"no":1,"title":"Docker & Kubernetes","section":true},{"no":2,"title":"Containers and images","section":true},{"no":3,"title":"What is inside a container?"},{"no":4,"title":"Isolation comes from the kernel"},{"no":5,"title":"Four commands show it"},{"no":6,"title":"When a VM is the better choice"},{"no":7,"title":"An image consists of layers"},{"no":8,"title":"Two stages, one small image"},{"no":9,"title":"The build context is not a trash can"},{"no":10,"title":"Choose the base image deliberately"},{"no":11,"title":"What makes an image slow or unsafe"},{"no":12,"title":"The container is disposable"},{"no":13,"title":"Postgres with a named volume"},{"no":14,"title":"Containers find each other by name"},{"no":15,"title":"Small mistakes lose data or open the database"},{"no":16,"title":"Compose, health checks, logs, registry","section":true},{"no":17,"title":"From command to target state"},{"no":18,"title":"The workshop shop as a stack"},{"no":19,"title":"Everyday work with Compose"},{"no":20,"title":"What Compose does not guarantee"},{"no":21,"title":"Running, but not working"},{"no":22,"title":"Health checks for Postgres and API"},{"no":23,"title":"Wait for healthy"},{"no":24,"title":"What a health check does not do"},{"no":25,"title":"The app logs, the platform forwards"},{"no":26,"title":"All services in one place"},{"no":27,"title":"Rotation instead of a full disk"},{"no":28,"title":"When central logs are needed"},{"no":29,"title":"The name is the address"},{"no":30,"title":"Your own registry in one line"},{"no":31,"title":"Tag, push, pull"},{"no":32,"title":"Operating a registry"},{"no":33,"title":"Kubernetes basics","section":true},{"no":34,"title":"Desired state instead of command sequence"},{"no":35,"title":"Control plane and nodes"},{"no":36,"title":"A cluster on your laptop"},{"no":37,"title":"Explore objects instead of guessing"},{"no":38,"title":"Pod, ReplicaSet, Deployment"},{"no":39,"title":"The API Deployment"},{"no":40,"title":"Apply and observe"},{"no":41,"title":"Why does the Pod not start?"},{"no":42,"title":"Why Pods need a Service"},{"no":43,"title":"The API Service"},{"no":44,"title":"Test inside and outside"},{"no":45,"title":"Types of Services"},{"no":46,"title":"One image, many environments"},{"no":47,"title":"Create ConfigMap and Secret"},{"no":48,"title":"Use them in the Deployment"},{"no":49,"title":"What a Secret cannot do"},{"no":50,"title":"Running in the cluster","section":true},{"no":51,"title":"Three probes, three outcomes"},{"no":52,"title":"Probes for the API"},{"no":53,"title":"When the database is missing"},{"no":54,"title":"Wrong probes kill healthy pods"},{"no":55,"title":"Requests and limits"},{"no":56,"title":"API resources"},{"no":57,"title":"Node.js knows its limit"},{"no":58,"title":"Misconfigured resources hurt under load"},{"no":59,"title":"Swap Pods step by step"},{"no":60,"title":"The strategy in the Deployment"},{"no":61,"title":"Roll out and roll back"},{"no":62,"title":"When a rollout hangs"},{"no":63,"title":"From Ingress to Gateway API"},{"no":64,"title":"Three objects, three roles"},{"no":65,"title":"One entry point for the namespace"},{"no":66,"title":"The API route"},{"no":67,"title":"Try it locally"},{"no":68,"title":"Security","section":true},{"no":69,"title":"Every package is attack surface"},{"no":70,"title":"Scanning shows the difference"},{"no":71,"title":"Distroless instead of slim"},{"no":72,"title":"Remove container permissions"},{"no":73,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-aws-serverless","title":"AWS Serverless mit Lambda, CDK und DynamoDB","summary":"Lambda, DynamoDB, AppSync, Cognito, Step Functions und SES: serverlose Dienste auf AWS, vom Datenmodell bis zum Workflow.","topics":["AWS","Lambda","DynamoDB"],"url":"https://slides.mikebild.dev/introduction-aws-serverless.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.pdf?v=3c288d19e4b3","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.mp4?v=3c288d19e4b3","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.png?v=3c288d19e4b3","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.de.vtt?v=3c288d19e4b3","repository":"https://github.com/MikeBild/introduction-aws","articles":["https://www.mikebild.dev/de/blog/lambda-performance-und-cold-starts/","https://www.mikebild.dev/de/blog/ses-email-hook-serverless/","https://www.mikebild.dev/de/blog/dynamodb-datenmodellierung-single-table/","https://www.mikebild.dev/de/blog/appsync-dynamodb-graphql-api/","https://www.mikebild.dev/de/blog/step-functions-serverless-workflows/","https://www.mikebild.dev/de/blog/cognito-userpool-auth-serverless/"],"slide_count":56,"slides":[{"no":1,"title":"AWS Serverless mit Lambda, CDK und DynamoDB","section":true},{"no":2,"title":"Grundhaltung, Lambda, CDK, IAM","section":true},{"no":3,"title":"Beschreiben statt betreiben"},{"no":4,"title":"Das wiederkehrende Muster"},{"no":5,"title":"Bezahlen pro Request"},{"no":6,"title":"Wo stößt Serverless an Grenzen?"},{"no":7,"title":"Event rein, Ergebnis raus"},{"no":8,"title":"Init-Phase und Invoke-Phase"},{"no":9,"title":"Grenzen, die du kennen musst"},{"no":10,"title":"Ein Handler in TypeScript"},{"no":11,"title":"Warum nicht per Klick?"},{"no":12,"title":"Von TypeScript zu CloudFormation"},{"no":13,"title":"Constructs in drei Stufen"},{"no":14,"title":"Ein Stack in CDK v2"},{"no":15,"title":"Wer darf was worauf?"},{"no":16,"title":"Eine Role pro Funktion"},{"no":17,"title":"grant statt Wildcard"},{"no":18,"title":"HTTP-API, DynamoDB, Konfiguration","section":true},{"no":19,"title":"Drei Wege zur Funktion"},{"no":20,"title":"Wie viele Funktionen pro API?"},{"no":21,"title":"Routes in CDK"},{"no":22,"title":"Das Event im Handler"},{"no":23,"title":"Die umgedrehte Reihenfolge"},{"no":24,"title":"Partition Key und Sort Key"},{"no":25,"title":"Neue Fragen mit einem GSI"},{"no":26,"title":"Query statt Scan"},{"no":27,"title":"Ein Layout für mehrere Entities"},{"no":28,"title":"Warum es keinen Join gibt"},{"no":29,"title":"Wann ist es überzogen?"},{"no":30,"title":"Der Fallstrick FilterExpression"},{"no":31,"title":"Konfiguration ist kein Secret"},{"no":32,"title":"Zwei Stores zur Wahl"},{"no":33,"title":"Laden mit Cache"},{"no":34,"title":"Events, Mail, Workflows, Cold Starts","section":true},{"no":35,"title":"Queue oder Event?"},{"no":36,"title":"Mindestens einmal heißt idempotent"},{"no":37,"title":"Ein Event veröffentlichen"},{"no":38,"title":"Batches mit Teilfehlern"},{"no":39,"title":"Zwei Richtungen"},{"no":40,"title":"Drei organisatorische Hürden"},{"no":41,"title":"Eingehende Mails verarbeiten"},{"no":42,"title":"Eine Bestätigung verschicken"},{"no":43,"title":"Wo steckt dein Ablauf heute?"},{"no":44,"title":"Der Ablauf als State Machine"},{"no":45,"title":"Standard oder Express?"},{"no":46,"title":"Wann nicht?"},{"no":47,"title":"Ein Task mit Retry und Catch"},{"no":48,"title":"Was ein Cold Start ist"},{"no":49,"title":"Erst Bundle und Init-Code verkleinern"},{"no":50,"title":"Mehr Memory bringt auch mehr CPU"},{"no":51,"title":"Vorgewärmt mit Provisioned Concurrency"},{"no":52,"title":"Messen in CloudWatch"},{"no":53,"title":"Praxis: Werkstatt-Shop end-to-end deployen","section":true},{"no":54,"title":"Ein Stack für die Bestellung"},{"no":55,"title":"Nach dem Request geht es weiter"},{"no":56,"title":"Fragen?","section":true}],"languages":{"de":{"title":"AWS Serverless mit Lambda, CDK und DynamoDB","summary":"Du baust den Bestellprozess des Werkstatt-Shops serverless auf AWS, mit Lambda, DynamoDB, Events und Step Functions, alles als Code in CDK.","url":"https://slides.mikebild.dev/introduction-aws-serverless.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.pdf?v=3c288d19e4b3","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.mp4?v=3c288d19e4b3","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.png?v=3c288d19e4b3","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.de.vtt?v=3c288d19e4b3","slide_count":56,"slides":[{"no":1,"title":"AWS Serverless mit Lambda, CDK und DynamoDB","section":true},{"no":2,"title":"Grundhaltung, Lambda, CDK, IAM","section":true},{"no":3,"title":"Beschreiben statt betreiben"},{"no":4,"title":"Das wiederkehrende Muster"},{"no":5,"title":"Bezahlen pro Request"},{"no":6,"title":"Wo stößt Serverless an Grenzen?"},{"no":7,"title":"Event rein, Ergebnis raus"},{"no":8,"title":"Init-Phase und Invoke-Phase"},{"no":9,"title":"Grenzen, die du kennen musst"},{"no":10,"title":"Ein Handler in TypeScript"},{"no":11,"title":"Warum nicht per Klick?"},{"no":12,"title":"Von TypeScript zu CloudFormation"},{"no":13,"title":"Constructs in drei Stufen"},{"no":14,"title":"Ein Stack in CDK v2"},{"no":15,"title":"Wer darf was worauf?"},{"no":16,"title":"Eine Role pro Funktion"},{"no":17,"title":"grant statt Wildcard"},{"no":18,"title":"HTTP-API, DynamoDB, Konfiguration","section":true},{"no":19,"title":"Drei Wege zur Funktion"},{"no":20,"title":"Wie viele Funktionen pro API?"},{"no":21,"title":"Routes in CDK"},{"no":22,"title":"Das Event im Handler"},{"no":23,"title":"Die umgedrehte Reihenfolge"},{"no":24,"title":"Partition Key und Sort Key"},{"no":25,"title":"Neue Fragen mit einem GSI"},{"no":26,"title":"Query statt Scan"},{"no":27,"title":"Ein Layout für mehrere Entities"},{"no":28,"title":"Warum es keinen Join gibt"},{"no":29,"title":"Wann ist es überzogen?"},{"no":30,"title":"Der Fallstrick FilterExpression"},{"no":31,"title":"Konfiguration ist kein Secret"},{"no":32,"title":"Zwei Stores zur Wahl"},{"no":33,"title":"Laden mit Cache"},{"no":34,"title":"Events, Mail, Workflows, Cold Starts","section":true},{"no":35,"title":"Queue oder Event?"},{"no":36,"title":"Mindestens einmal heißt idempotent"},{"no":37,"title":"Ein Event veröffentlichen"},{"no":38,"title":"Batches mit Teilfehlern"},{"no":39,"title":"Zwei Richtungen"},{"no":40,"title":"Drei organisatorische Hürden"},{"no":41,"title":"Eingehende Mails verarbeiten"},{"no":42,"title":"Eine Bestätigung verschicken"},{"no":43,"title":"Wo steckt dein Ablauf heute?"},{"no":44,"title":"Der Ablauf als State Machine"},{"no":45,"title":"Standard oder Express?"},{"no":46,"title":"Wann nicht?"},{"no":47,"title":"Ein Task mit Retry und Catch"},{"no":48,"title":"Was ein Cold Start ist"},{"no":49,"title":"Erst Bundle und Init-Code verkleinern"},{"no":50,"title":"Mehr Memory bringt auch mehr CPU"},{"no":51,"title":"Vorgewärmt mit Provisioned Concurrency"},{"no":52,"title":"Messen in CloudWatch"},{"no":53,"title":"Praxis: Werkstatt-Shop end-to-end deployen","section":true},{"no":54,"title":"Ein Stack für die Bestellung"},{"no":55,"title":"Nach dem Request geht es weiter"},{"no":56,"title":"Fragen?","section":true}],"articles":["https://www.mikebild.dev/de/blog/lambda-performance-und-cold-starts/","https://www.mikebild.dev/de/blog/ses-email-hook-serverless/","https://www.mikebild.dev/de/blog/dynamodb-datenmodellierung-single-table/","https://www.mikebild.dev/de/blog/appsync-dynamodb-graphql-api/","https://www.mikebild.dev/de/blog/step-functions-serverless-workflows/","https://www.mikebild.dev/de/blog/cognito-userpool-auth-serverless/"]},"en":{"title":"AWS serverless with Lambda, CDK, and DynamoDB","summary":"You build the workshop shop order flow serverless on AWS, with Lambda, DynamoDB, events, and Step Functions, all as code in CDK.","url":"https://slides.mikebild.dev/introduction-aws-serverless.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.en.pdf?v=686d760b188f","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.en.mp4?v=686d760b188f","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.en.png?v=686d760b188f","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-aws-serverless/introduction-aws-serverless.en.vtt?v=686d760b188f","slide_count":56,"slides":[{"no":1,"title":"AWS serverless with Lambda, CDK, and DynamoDB","section":true},{"no":2,"title":"Mindset, Lambda, CDK, IAM","section":true},{"no":3,"title":"Describe, don’t operate"},{"no":4,"title":"The recurring pattern"},{"no":5,"title":"Pay per request"},{"no":6,"title":"Where does serverless hit limits?"},{"no":7,"title":"Event in, result out"},{"no":8,"title":"Init phase and invoke phase"},{"no":9,"title":"Limits you need to know"},{"no":10,"title":"A handler in TypeScript"},{"no":11,"title":"Why not click it?"},{"no":12,"title":"From TypeScript to CloudFormation"},{"no":13,"title":"Constructs at three levels"},{"no":14,"title":"A stack in CDK v2"},{"no":15,"title":"Who may do what to what?"},{"no":16,"title":"One role per function"},{"no":17,"title":"grant instead of wildcard"},{"no":18,"title":"HTTP API, DynamoDB, configuration","section":true},{"no":19,"title":"Three ways to the function"},{"no":20,"title":"How many functions per API?"},{"no":21,"title":"Routes in CDK"},{"no":22,"title":"The event in the handler"},{"no":23,"title":"The reversed order"},{"no":24,"title":"Partition key and sort key"},{"no":25,"title":"New questions with a GSI"},{"no":26,"title":"Query instead of scan"},{"no":27,"title":"One layout for multiple entities"},{"no":28,"title":"Why there is no join"},{"no":29,"title":"When is it overdone?"},{"no":30,"title":"The FilterExpression trap"},{"no":31,"title":"Configuration is not a secret"},{"no":32,"title":"Two stores to choose from"},{"no":33,"title":"Load with a cache"},{"no":34,"title":"Events, email, workflows, cold starts","section":true},{"no":35,"title":"Queue or event?"},{"no":36,"title":"At least once means idempotent"},{"no":37,"title":"Publish an event"},{"no":38,"title":"Batches with partial failures"},{"no":39,"title":"Two directions"},{"no":40,"title":"Three organizational hurdles"},{"no":41,"title":"Process incoming email"},{"no":42,"title":"Send a confirmation"},{"no":43,"title":"Where is your workflow today?"},{"no":44,"title":"The workflow as a state machine"},{"no":45,"title":"Standard or Express?"},{"no":46,"title":"When not to use it?"},{"no":47,"title":"A Task with Retry and Catch"},{"no":48,"title":"What a cold start is"},{"no":49,"title":"First shrink the bundle and init code"},{"no":50,"title":"More memory also brings more CPU"},{"no":51,"title":"Pre-warmed with Provisioned Concurrency"},{"no":52,"title":"Measure in CloudWatch"},{"no":53,"title":"Practice: deploy the workshop shop end to end","section":true},{"no":54,"title":"One stack for the order"},{"no":55,"title":"After the request, work continues"},{"no":56,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-microservices","title":"Microservices mit Node.js, Express 5 und Docker Compose","summary":"Vom Modulith zu Services mit Express 5: Verträge, Docker Compose, Events mit Outbox, Sagas, Resilienz und Contract Tests.","topics":["Microservices","Architektur"],"url":"https://slides.mikebild.dev/introduction-microservices.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.pdf?v=77faddde1953","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.mp4?v=77faddde1953","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.png?v=77faddde1953","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.de.vtt?v=77faddde1953","repository":"https://github.com/MikeBild/introduction-microservices","articles":[],"slide_count":71,"slides":[{"no":1,"title":"Microservices mit Node.js, Express 5 und Docker Compose","section":true},{"no":2,"title":"Warum, wann und wo schneiden","section":true},{"no":3,"title":"Was ist ein Microservice?"},{"no":4,"title":"Was du gewinnst, was du bezahlst"},{"no":5,"title":"Conway’s Law gilt in beide Richtungen"},{"no":6,"title":"Modulith zuerst"},{"no":7,"title":"Miss, was sich gemeinsam ändert"},{"no":8,"title":"Ein Wort, drei Bedeutungen"},{"no":9,"title":"Grenzen findest du im Gespräch"},{"no":10,"title":"Die Context Map zeigt die Kanten"},{"no":11,"title":"Der Anti-Corruption Layer übersetzt an einer Stelle"},{"no":12,"title":"Kontext ist nicht gleich Service"},{"no":13,"title":"Ein Deployment, mehrere Module"},{"no":14,"title":"Öffentlich ist nur index.ts"},{"no":15,"title":"Eine Grenze braucht einen Test"},{"no":16,"title":"Vom Modul zum Service"},{"no":17,"title":"Der erste Service und seine Verträge","section":true},{"no":18,"title":"Der Service catalog"},{"no":19,"title":"App und Server trennen"},{"no":20,"title":"Konfiguration kommt aus der Umgebung"},{"no":21,"title":"Testen ohne Netzwerk-Setup"},{"no":22,"title":"Der Vertrag ist die einzige Kopplung"},{"no":23,"title":"Eine Quelle: zod-Schemas"},{"no":24,"title":"OpenAPI 3.1 aus dem Schema"},{"no":25,"title":"Am Eingang prüfen, mit Problem Details antworten"},{"no":26,"title":"Verträge ändern, ohne Clients zu brechen"},{"no":27,"title":"orders fragt catalog nach Preisen"},{"no":28,"title":"Verfügbarkeit multipliziert sich"},{"no":29,"title":"Jeder Aufruf hat einen Timeout"},{"no":30,"title":"Was tust du, wenn catalog fehlt?"},{"no":31,"title":"Ein Image pro Service"},{"no":32,"title":"compose.yaml beschreibt das System"},{"no":33,"title":"Live und ready sind zwei Fragen"},{"no":34,"title":"Start nach Bereitschaft, Stopp ohne Abbruch"},{"no":35,"title":"Daten, Events und Konsistenz","section":true},{"no":36,"title":"Die geteilte Datenbank koppelt heimlich"},{"no":37,"title":"Eine Datenbank pro Service"},{"no":38,"title":"Fremde Daten: fragen oder kopieren"},{"no":39,"title":"Die Kopie übernimmt nur Neueres"},{"no":40,"title":"Ein Event meldet eine Tatsache"},{"no":41,"title":"Events entkoppeln Zeit und Verfügbarkeit"},{"no":42,"title":"Ein Event hat einen Umschlag"},{"no":43,"title":"Die Inbox macht doppelte Zustellung harmlos"},{"no":44,"title":"HTTP reicht, ein Broker skaliert"},{"no":45,"title":"Zwei Schreibvorgänge, ein Absturz"},{"no":46,"title":"Das Event wohnt erst in der eigenen Datenbank"},{"no":47,"title":"Bestellung und Event in einer Transaktion"},{"no":48,"title":"Das Relay liefert at least once"},{"no":49,"title":"Varianten in Produktion"},{"no":50,"title":"Kein Rollback über Service-Grenzen"},{"no":51,"title":"Kompensation ist eine fachliche Aktion"},{"no":52,"title":"Die Saga als Pure Function"},{"no":53,"title":"Duplikate und Nachzügler"},{"no":54,"title":"Choreografie oder Orchestrierung?"},{"no":55,"title":"Resilienz, Observability und Tests","section":true},{"no":56,"title":"Nicht jeder Fehler ist vorübergehend"},{"no":57,"title":"Backoff mit Jitter"},{"no":58,"title":"Ein Retry darf nicht doppelt bestellen"},{"no":59,"title":"Idempotency-Key als Middleware"},{"no":60,"title":"Wenn ein Service lange ausfällt"},{"no":61,"title":"Drei Logs, ein Fehler"},{"no":62,"title":"W3C Trace Context"},{"no":63,"title":"Den Kontext weitergeben"},{"no":64,"title":"Logs als JSON mit Trace-ID"},{"no":65,"title":"Drei Signale je Service genügen für den Anfang"},{"no":66,"title":"Der End-to-End-Zoo wird langsam und rot"},{"no":67,"title":"Der Consumer schreibt auf, was er braucht"},{"no":68,"title":"Ein Vertrag, zwei Tests"},{"no":69,"title":"Der Provider prüft jeden Vertrag"},{"no":70,"title":"Pact und Broker für viele Teams"},{"no":71,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Microservices mit Node.js, Express 5 und Docker Compose","summary":"Du schneidest den Werkstatt-Shop an fachlichen Grenzen in Services und verbindest sie mit Verträgen, Events, Outbox und Sagas.","url":"https://slides.mikebild.dev/introduction-microservices.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.pdf?v=77faddde1953","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.mp4?v=77faddde1953","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.png?v=77faddde1953","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.de.vtt?v=77faddde1953","slide_count":71,"slides":[{"no":1,"title":"Microservices mit Node.js, Express 5 und Docker Compose","section":true},{"no":2,"title":"Warum, wann und wo schneiden","section":true},{"no":3,"title":"Was ist ein Microservice?"},{"no":4,"title":"Was du gewinnst, was du bezahlst"},{"no":5,"title":"Conway’s Law gilt in beide Richtungen"},{"no":6,"title":"Modulith zuerst"},{"no":7,"title":"Miss, was sich gemeinsam ändert"},{"no":8,"title":"Ein Wort, drei Bedeutungen"},{"no":9,"title":"Grenzen findest du im Gespräch"},{"no":10,"title":"Die Context Map zeigt die Kanten"},{"no":11,"title":"Der Anti-Corruption Layer übersetzt an einer Stelle"},{"no":12,"title":"Kontext ist nicht gleich Service"},{"no":13,"title":"Ein Deployment, mehrere Module"},{"no":14,"title":"Öffentlich ist nur index.ts"},{"no":15,"title":"Eine Grenze braucht einen Test"},{"no":16,"title":"Vom Modul zum Service"},{"no":17,"title":"Der erste Service und seine Verträge","section":true},{"no":18,"title":"Der Service catalog"},{"no":19,"title":"App und Server trennen"},{"no":20,"title":"Konfiguration kommt aus der Umgebung"},{"no":21,"title":"Testen ohne Netzwerk-Setup"},{"no":22,"title":"Der Vertrag ist die einzige Kopplung"},{"no":23,"title":"Eine Quelle: zod-Schemas"},{"no":24,"title":"OpenAPI 3.1 aus dem Schema"},{"no":25,"title":"Am Eingang prüfen, mit Problem Details antworten"},{"no":26,"title":"Verträge ändern, ohne Clients zu brechen"},{"no":27,"title":"orders fragt catalog nach Preisen"},{"no":28,"title":"Verfügbarkeit multipliziert sich"},{"no":29,"title":"Jeder Aufruf hat einen Timeout"},{"no":30,"title":"Was tust du, wenn catalog fehlt?"},{"no":31,"title":"Ein Image pro Service"},{"no":32,"title":"compose.yaml beschreibt das System"},{"no":33,"title":"Live und ready sind zwei Fragen"},{"no":34,"title":"Start nach Bereitschaft, Stopp ohne Abbruch"},{"no":35,"title":"Daten, Events und Konsistenz","section":true},{"no":36,"title":"Die geteilte Datenbank koppelt heimlich"},{"no":37,"title":"Eine Datenbank pro Service"},{"no":38,"title":"Fremde Daten: fragen oder kopieren"},{"no":39,"title":"Die Kopie übernimmt nur Neueres"},{"no":40,"title":"Ein Event meldet eine Tatsache"},{"no":41,"title":"Events entkoppeln Zeit und Verfügbarkeit"},{"no":42,"title":"Ein Event hat einen Umschlag"},{"no":43,"title":"Die Inbox macht doppelte Zustellung harmlos"},{"no":44,"title":"HTTP reicht, ein Broker skaliert"},{"no":45,"title":"Zwei Schreibvorgänge, ein Absturz"},{"no":46,"title":"Das Event wohnt erst in der eigenen Datenbank"},{"no":47,"title":"Bestellung und Event in einer Transaktion"},{"no":48,"title":"Das Relay liefert at least once"},{"no":49,"title":"Varianten in Produktion"},{"no":50,"title":"Kein Rollback über Service-Grenzen"},{"no":51,"title":"Kompensation ist eine fachliche Aktion"},{"no":52,"title":"Die Saga als Pure Function"},{"no":53,"title":"Duplikate und Nachzügler"},{"no":54,"title":"Choreografie oder Orchestrierung?"},{"no":55,"title":"Resilienz, Observability und Tests","section":true},{"no":56,"title":"Nicht jeder Fehler ist vorübergehend"},{"no":57,"title":"Backoff mit Jitter"},{"no":58,"title":"Ein Retry darf nicht doppelt bestellen"},{"no":59,"title":"Idempotency-Key als Middleware"},{"no":60,"title":"Wenn ein Service lange ausfällt"},{"no":61,"title":"Drei Logs, ein Fehler"},{"no":62,"title":"W3C Trace Context"},{"no":63,"title":"Den Kontext weitergeben"},{"no":64,"title":"Logs als JSON mit Trace-ID"},{"no":65,"title":"Drei Signale je Service genügen für den Anfang"},{"no":66,"title":"Der End-to-End-Zoo wird langsam und rot"},{"no":67,"title":"Der Consumer schreibt auf, was er braucht"},{"no":68,"title":"Ein Vertrag, zwei Tests"},{"no":69,"title":"Der Provider prüft jeden Vertrag"},{"no":70,"title":"Pact und Broker für viele Teams"},{"no":71,"title":"Fragen?","section":true}],"articles":[]},"en":{"title":"Microservices with Node.js, Express 5, and Docker Compose","summary":"You split the workshop shop into services along domain boundaries and connect them with contracts, events, outbox, and sagas.","url":"https://slides.mikebild.dev/introduction-microservices.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.en.pdf?v=755b9c76bf78","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.en.mp4?v=755b9c76bf78","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.en.png?v=755b9c76bf78","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-microservices/introduction-microservices.en.vtt?v=755b9c76bf78","slide_count":71,"slides":[{"no":1,"title":"Microservices with Node.js, Express 5, and Docker Compose","section":true},{"no":2,"title":"Why, when, and where to cut","section":true},{"no":3,"title":"What is a microservice?"},{"no":4,"title":"What you gain, what you pay"},{"no":5,"title":"Conway’s Law applies in both directions"},{"no":6,"title":"Modulith first"},{"no":7,"title":"Measure what changes together"},{"no":8,"title":"One word, three meanings"},{"no":9,"title":"You find boundaries in conversation"},{"no":10,"title":"The Context Map shows the edges"},{"no":11,"title":"The Anti-Corruption Layer translates in one place"},{"no":12,"title":"Context is not the same as service"},{"no":13,"title":"One deployment, multiple modules"},{"no":14,"title":"Only index.ts is public"},{"no":15,"title":"A boundary needs a test"},{"no":16,"title":"From module to service"},{"no":17,"title":"The first service and its contracts","section":true},{"no":18,"title":"The catalog service"},{"no":19,"title":"Separate app and server"},{"no":20,"title":"Configuration comes from the environment"},{"no":21,"title":"Test without network setup"},{"no":22,"title":"The contract is the only coupling"},{"no":23,"title":"One source: zod schemas"},{"no":24,"title":"OpenAPI 3.1 from the schema"},{"no":25,"title":"Validate at the boundary and return Problem Details"},{"no":26,"title":"Change contracts without breaking clients"},{"no":27,"title":"orders asks catalog for prices"},{"no":28,"title":"Availability multiplies"},{"no":29,"title":"Every call has a timeout"},{"no":30,"title":"What do you do when catalog is missing?"},{"no":31,"title":"One image per service"},{"no":32,"title":"compose.yaml describes the system"},{"no":33,"title":"Live and ready are two questions"},{"no":34,"title":"Start when ready, stop without aborting"},{"no":35,"title":"Data, events, and consistency","section":true},{"no":36,"title":"The shared database couples secretly"},{"no":37,"title":"One database per service"},{"no":38,"title":"External data: ask or copy"},{"no":39,"title":"The copy applies only newer data"},{"no":40,"title":"An event reports a fact"},{"no":41,"title":"Events decouple time and availability"},{"no":42,"title":"An event has an envelope"},{"no":43,"title":"The inbox makes duplicate delivery harmless"},{"no":44,"title":"HTTP is enough; a broker scales"},{"no":45,"title":"Two writes, one crash"},{"no":46,"title":"The event first lives in its own database"},{"no":47,"title":"Order and event in one transaction"},{"no":48,"title":"The relay delivers at least once"},{"no":49,"title":"Production variants"},{"no":50,"title":"No rollback across service boundaries"},{"no":51,"title":"Compensation is a domain action"},{"no":52,"title":"The saga as a Pure Function"},{"no":53,"title":"Duplicates and latecomers"},{"no":54,"title":"Choreography or orchestration?"},{"no":55,"title":"Resilience, observability, and tests","section":true},{"no":56,"title":"Not every error is temporary"},{"no":57,"title":"Backoff with jitter"},{"no":58,"title":"A retry must not order twice"},{"no":59,"title":"Idempotency key as middleware"},{"no":60,"title":"When a service is down for a long time"},{"no":61,"title":"Three logs, one error"},{"no":62,"title":"W3C Trace Context"},{"no":63,"title":"Pass the context on"},{"no":64,"title":"Logs as JSON with a trace ID"},{"no":65,"title":"Three signals per service are enough to start"},{"no":66,"title":"The end-to-end zoo turns slow and red"},{"no":67,"title":"The consumer writes down what it needs"},{"no":68,"title":"One contract, two tests"},{"no":69,"title":"The provider verifies every contract"},{"no":70,"title":"Pact and brokers for many teams"},{"no":71,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-design-patterns","title":"Design Patterns als Funktionen","summary":"Adapter, Chain of Responsibility, Strategy, Provider und Observer als Funktionen in TypeScript, wiedererkannt in Express, React und Apollo.","topics":["Design Patterns","TypeScript"],"url":"https://slides.mikebild.dev/introduction-design-patterns.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.pdf?v=346286ff1417","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.mp4?v=346286ff1417","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.png?v=346286ff1417","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.de.vtt?v=346286ff1417","repository":"https://github.com/MikeBild/introduction-design-patterns","articles":[],"slide_count":63,"slides":[{"no":1,"title":"Design Patterns als Funktionen","section":true},{"no":2,"title":"Anbinden und verketten","section":true},{"no":3,"title":"Was ist ein Pattern?"},{"no":4,"title":"Warum Funktionen statt Klassen?"},{"no":5,"title":"Zehn Probleme, zehn Patterns"},{"no":6,"title":"Was bewusst fehlt"},{"no":7,"title":"Du nutzt Patterns längst"},{"no":8,"title":"Wenn alles von allem abhängt"},{"no":9,"title":"Ports and Adapters"},{"no":10,"title":"Funktional umgesetzt"},{"no":11,"title":"Verdrahten in main"},{"no":12,"title":"Modules und Trade-offs"},{"no":13,"title":"Zwei Aufrufer, und einer vergisst den Bestand"},{"no":14,"title":"Eine Facade steht vor drei Services"},{"no":15,"title":"Ein Proxy behält den Vertrag und cacht davor"},{"no":16,"title":"Ein Proxy darf auch verweigern"},{"no":17,"title":"Facade, Proxy oder Adapter?"},{"no":18,"title":"Wo du beide schon nutzt"},{"no":19,"title":"Ein Handler, der nicht aufhören kann"},{"no":20,"title":"Weiter oder Schluss"},{"no":21,"title":"Eine Chain in wenigen Zeilen"},{"no":22,"title":"Express-Middleware ist dieselbe Chain"},{"no":23,"title":"ApolloLink nutzt forward statt next"},{"no":24,"title":"Chain oder Pipeline?"},{"no":25,"title":"Austauschen und erzeugen","section":true},{"no":26,"title":"Eine Funktion mit drei Aufgaben"},{"no":27,"title":"Gleiche Signatur hinein und heraus"},{"no":28,"title":"Schichten von außen nach innen"},{"no":29,"title":"Jeder Decorator hat dieselbe Form"},{"no":30,"title":"Decorator oder Proxy?"},{"no":31,"title":"Handler-Wrapper in Express"},{"no":32,"title":"Warum wächst dieser switch immer weiter?"},{"no":33,"title":"Eine Strategy ist nur eine Funktion"},{"no":34,"title":"Eine Tabelle ersetzt den switch"},{"no":35,"title":"Ein Command macht aus einem Aufruf einen Wert"},{"no":36,"title":"Was kann ein Aufruf als Wert mehr?"},{"no":37,"title":"Ein GoF-Command ist kein CQRS-Command"},{"no":38,"title":"Was stört an let auf Modulebene?"},{"no":39,"title":"createX bekommt Abhängigkeiten und liefert Verhalten"},{"no":40,"title":"Jede Instanz hat ihren eigenen State"},{"no":41,"title":"Abhängigkeiten kommen als Argument"},{"no":42,"title":"Drei Factories aus deinem Stack"},{"no":43,"title":"Wo Factories schiefgehen"},{"no":44,"title":"Teilen und reagieren","section":true},{"no":45,"title":"Dasselbe Pattern an drei Stellen"},{"no":46,"title":"Erst Props, dann children, dann Context"},{"no":47,"title":"In React 19 ist der Context selbst der Provider"},{"no":48,"title":"In GraphQL ist der Request der Bereich"},{"no":49,"title":"In Node trägt AsyncLocalStorage den Wert"},{"no":50,"title":"Wo endet die Reichweite?"},{"no":51,"title":"Warum kennt placeOrder alle Empfänger?"},{"no":52,"title":"Ein Observer ist eine Menge von Funktionen"},{"no":53,"title":"subscribe liefert die Teardown-Function"},{"no":54,"title":"EventEmitter und Rx sind auch Observer"},{"no":55,"title":"Welche Übergänge sind überhaupt erlaubt?"},{"no":56,"title":"Die Tabelle entscheidet, der Observer meldet"},{"no":57,"title":"Was kostet ein Pattern?"},{"no":58,"title":"Die Dreimal-Regel bremst die Abstraktion"},{"no":59,"title":"Eine Implementierung braucht keine Strategy"},{"no":60,"title":"Ein Modul ist schon ein Singleton"},{"no":61,"title":"Der Service Locator versteckt Abhängigkeiten"},{"no":62,"title":"Zurückbauen in kleinen Schritten"},{"no":63,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Design Patterns als Funktionen","summary":"Du löst wiederkehrende Probleme im Werkstatt-Shop mit Design Patterns als Funktionen und erkennst sie in Express, React und Apollo wieder.","url":"https://slides.mikebild.dev/introduction-design-patterns.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.pdf?v=346286ff1417","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.mp4?v=346286ff1417","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.png?v=346286ff1417","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.de.vtt?v=346286ff1417","slide_count":63,"slides":[{"no":1,"title":"Design Patterns als Funktionen","section":true},{"no":2,"title":"Anbinden und verketten","section":true},{"no":3,"title":"Was ist ein Pattern?"},{"no":4,"title":"Warum Funktionen statt Klassen?"},{"no":5,"title":"Zehn Probleme, zehn Patterns"},{"no":6,"title":"Was bewusst fehlt"},{"no":7,"title":"Du nutzt Patterns längst"},{"no":8,"title":"Wenn alles von allem abhängt"},{"no":9,"title":"Ports and Adapters"},{"no":10,"title":"Funktional umgesetzt"},{"no":11,"title":"Verdrahten in main"},{"no":12,"title":"Modules und Trade-offs"},{"no":13,"title":"Zwei Aufrufer, und einer vergisst den Bestand"},{"no":14,"title":"Eine Facade steht vor drei Services"},{"no":15,"title":"Ein Proxy behält den Vertrag und cacht davor"},{"no":16,"title":"Ein Proxy darf auch verweigern"},{"no":17,"title":"Facade, Proxy oder Adapter?"},{"no":18,"title":"Wo du beide schon nutzt"},{"no":19,"title":"Ein Handler, der nicht aufhören kann"},{"no":20,"title":"Weiter oder Schluss"},{"no":21,"title":"Eine Chain in wenigen Zeilen"},{"no":22,"title":"Express-Middleware ist dieselbe Chain"},{"no":23,"title":"ApolloLink nutzt forward statt next"},{"no":24,"title":"Chain oder Pipeline?"},{"no":25,"title":"Austauschen und erzeugen","section":true},{"no":26,"title":"Eine Funktion mit drei Aufgaben"},{"no":27,"title":"Gleiche Signatur hinein und heraus"},{"no":28,"title":"Schichten von außen nach innen"},{"no":29,"title":"Jeder Decorator hat dieselbe Form"},{"no":30,"title":"Decorator oder Proxy?"},{"no":31,"title":"Handler-Wrapper in Express"},{"no":32,"title":"Warum wächst dieser switch immer weiter?"},{"no":33,"title":"Eine Strategy ist nur eine Funktion"},{"no":34,"title":"Eine Tabelle ersetzt den switch"},{"no":35,"title":"Ein Command macht aus einem Aufruf einen Wert"},{"no":36,"title":"Was kann ein Aufruf als Wert mehr?"},{"no":37,"title":"Ein GoF-Command ist kein CQRS-Command"},{"no":38,"title":"Was stört an let auf Modulebene?"},{"no":39,"title":"createX bekommt Abhängigkeiten und liefert Verhalten"},{"no":40,"title":"Jede Instanz hat ihren eigenen State"},{"no":41,"title":"Abhängigkeiten kommen als Argument"},{"no":42,"title":"Drei Factories aus deinem Stack"},{"no":43,"title":"Wo Factories schiefgehen"},{"no":44,"title":"Teilen und reagieren","section":true},{"no":45,"title":"Dasselbe Pattern an drei Stellen"},{"no":46,"title":"Erst Props, dann children, dann Context"},{"no":47,"title":"In React 19 ist der Context selbst der Provider"},{"no":48,"title":"In GraphQL ist der Request der Bereich"},{"no":49,"title":"In Node trägt AsyncLocalStorage den Wert"},{"no":50,"title":"Wo endet die Reichweite?"},{"no":51,"title":"Warum kennt placeOrder alle Empfänger?"},{"no":52,"title":"Ein Observer ist eine Menge von Funktionen"},{"no":53,"title":"subscribe liefert die Teardown-Function"},{"no":54,"title":"EventEmitter und Rx sind auch Observer"},{"no":55,"title":"Welche Übergänge sind überhaupt erlaubt?"},{"no":56,"title":"Die Tabelle entscheidet, der Observer meldet"},{"no":57,"title":"Was kostet ein Pattern?"},{"no":58,"title":"Die Dreimal-Regel bremst die Abstraktion"},{"no":59,"title":"Eine Implementierung braucht keine Strategy"},{"no":60,"title":"Ein Modul ist schon ein Singleton"},{"no":61,"title":"Der Service Locator versteckt Abhängigkeiten"},{"no":62,"title":"Zurückbauen in kleinen Schritten"},{"no":63,"title":"Fragen?","section":true}],"articles":[]},"en":{"title":"Design patterns as functions","summary":"You solve recurring problems in the workshop shop with design patterns as functions and recognize them again in Express, React, and Apollo.","url":"https://slides.mikebild.dev/introduction-design-patterns.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.en.pdf?v=d9e4820e2aef","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.en.mp4?v=d9e4820e2aef","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.en.png?v=d9e4820e2aef","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-design-patterns/introduction-design-patterns.en.vtt?v=d9e4820e2aef","slide_count":63,"slides":[{"no":1,"title":"Design patterns as functions","section":true},{"no":2,"title":"Connecting and chaining","section":true},{"no":3,"title":"What is a pattern?"},{"no":4,"title":"Why functions instead of classes?"},{"no":5,"title":"Ten problems, ten patterns"},{"no":6,"title":"What is deliberately missing"},{"no":7,"title":"You already use patterns"},{"no":8,"title":"When everything depends on everything"},{"no":9,"title":"Ports and Adapters"},{"no":10,"title":"Implemented functionally"},{"no":11,"title":"Wire in main"},{"no":12,"title":"Modules and trade-offs"},{"no":13,"title":"Two callers, and one forgets the stock"},{"no":14,"title":"A Facade stands in front of three services"},{"no":15,"title":"A Proxy keeps the contract and caches first"},{"no":16,"title":"A Proxy can also refuse"},{"no":17,"title":"Facade, Proxy, or Adapter?"},{"no":18,"title":"Where you already use both"},{"no":19,"title":"A handler that cannot stop"},{"no":20,"title":"Continue or stop"},{"no":21,"title":"A chain in a few lines"},{"no":22,"title":"Express Middleware is the same chain"},{"no":23,"title":"ApolloLink uses forward instead of next"},{"no":24,"title":"Chain or pipeline?"},{"no":25,"title":"Swapping and creating","section":true},{"no":26,"title":"A function with three jobs"},{"no":27,"title":"Same signature in and out"},{"no":28,"title":"Layers from outside to inside"},{"no":29,"title":"Every Decorator has the same shape"},{"no":30,"title":"Decorator or Proxy?"},{"no":31,"title":"Handler wrapper in Express"},{"no":32,"title":"Why does this switch keep growing?"},{"no":33,"title":"A Strategy is just a function"},{"no":34,"title":"A table replaces the switch"},{"no":35,"title":"A Command turns a call into a value"},{"no":36,"title":"What more can a call as a value do?"},{"no":37,"title":"A GoF Command is not a CQRS Command"},{"no":38,"title":"What is wrong with let at module level?"},{"no":39,"title":"createX gets dependencies and returns behavior"},{"no":40,"title":"Each instance has its own state"},{"no":41,"title":"Dependencies are passed as arguments"},{"no":42,"title":"Three factories from your stack"},{"no":43,"title":"Where factories go wrong"},{"no":44,"title":"Sharing and reacting","section":true},{"no":45,"title":"The same pattern in three places"},{"no":46,"title":"Props first, then children, then Context"},{"no":47,"title":"In React 19, the Context itself is the provider"},{"no":48,"title":"In GraphQL, the request is the scope"},{"no":49,"title":"In Node, AsyncLocalStorage carries the value"},{"no":50,"title":"Where does the scope end?"},{"no":51,"title":"Why does placeOrder know all receivers?"},{"no":52,"title":"An Observer is a set of functions"},{"no":53,"title":"subscribe returns the teardown function"},{"no":54,"title":"EventEmitter and Rx are also Observers"},{"no":55,"title":"Which transitions are allowed at all?"},{"no":56,"title":"The table decides, the Observer notifies"},{"no":57,"title":"What does a pattern cost?"},{"no":58,"title":"The rule of three slows abstraction"},{"no":59,"title":"One implementation does not need a Strategy"},{"no":60,"title":"A module is already a Singleton"},{"no":61,"title":"The Service Locator hides dependencies"},{"no":62,"title":"Remove it in small steps"},{"no":63,"title":"Questions?","section":true}],"articles":[]}}},{"id":"introduction-cqrs-event-sourcing","title":"Architektur: DDD, CQRS und Event Sourcing","summary":"Commands, Events und Queries trennen, das Aggregat als Konsistenzgrenze, Read Models als Projections und ein Event-Store auf AWS.","topics":["CQRS","Event Sourcing","DDD"],"url":"https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.pdf?v=52932c059f5f","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.mp4?v=52932c059f5f","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.png?v=52932c059f5f","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.de.vtt?v=52932c059f5f","repository":"https://github.com/MikeBild/introduction-nodejs/tree/master/EXAMPLES/ARCHITECTURE","articles":["https://www.mikebild.dev/de/blog/event-sourcing-auf-aws-dynamodb-streams/","https://www.mikebild.dev/de/blog/wann-cqrs-und-event-sourcing-zu-viel-ist/","https://www.mikebild.dev/de/blog/event-sourcing-der-event-store-als-logbuch/","https://www.mikebild.dev/de/blog/read-models-sind-projektionen/","https://www.mikebild.dev/de/blog/aggregat-als-konsistenzgrenze/","https://www.mikebild.dev/de/blog/commands-events-queries-trennen/","https://www.mikebild.dev/de/blog/cqrs-fachliche-grenze-kein-framework/"],"slide_count":68,"slides":[{"no":1,"title":"Architektur: DDD, CQRS und Event Sourcing","section":true},{"no":2,"title":"Die Domäne verstehen","section":true},{"no":3,"title":"Warum heißt im Code alles update?"},{"no":4,"title":"Ein Wort, eine Bedeutung"},{"no":5,"title":"Event Storming beginnt mit dem, was passiert ist"},{"no":6,"title":"Commands und Policies erklären das Warum"},{"no":7,"title":"Hotspots sind die wertvollsten Haftnotizen"},{"no":8,"title":"Das Board als Code prüft die Sprache"},{"no":9,"title":"Ein Produkt, drei Bedeutungen"},{"no":10,"title":"Ein Bounded Context ist eine Sprachgrenze"},{"no":11,"title":"Core, Supporting oder Generic?"},{"no":12,"title":"Die Kanten sind die Architektur"},{"no":13,"title":"Ein Anti-Corruption Layer übersetzt an einer Stelle"},{"no":14,"title":"Erst die Grenze, dann der Service"},{"no":15,"title":"Was rutscht durch, wenn alles string ist?"},{"no":16,"title":"Eine Entity hat eine Identität"},{"no":17,"title":"Ein Value Object ist nur sein Wert"},{"no":18,"title":"Smart Constructors prüfen einmal"},{"no":19,"title":"Positionen sind eingefrorene Werte"},{"no":20,"title":"Regeln, Messages und getrennte Modelle","section":true},{"no":21,"title":"Wer schützt die Regeln der Bestellung?"},{"no":22,"title":"Die Root ist der einzige Eingang"},{"no":23,"title":"Andere Aggregate nur per ID"},{"no":24,"title":"Eine Transaktion, ein Aggregat"},{"no":25,"title":"Mit erwarteter Version speichern"},{"no":26,"title":"Drei Fallstricke"},{"no":27,"title":"Was bedeutet updateOrder?"},{"no":28,"title":"Drei Messages, drei Bedeutungen"},{"no":29,"title":"decide prüft, evolve wendet an"},{"no":30,"title":"Wunsch, Tatsache, Antwort"},{"no":31,"title":"Wo die Benennung in die Irre führt"},{"no":32,"title":"Ein Modell für alles wird zu groß"},{"no":33,"title":"CQRS trennt Modelle, nicht Datenbanken"},{"no":34,"title":"Die Schreibseite prüft und schweigt"},{"no":35,"title":"Die Leseseite liefert genau die Zeile"},{"no":36,"title":"Ein Store genügt für den Anfang"},{"no":37,"title":"Event Sourcing","section":true},{"no":38,"title":"Ein Update vergisst, wie es dazu kam"},{"no":39,"title":"Der Zustand ist ein Left Fold"},{"no":40,"title":"Das Aggregat entscheidet, der Store hängt an"},{"no":41,"title":"Projections sind wegwerfbar"},{"no":42,"title":"Was Event Sourcing kostet"},{"no":43,"title":"Projection oder Cache?"},{"no":44,"title":"Ein Fold mit Checkpoint"},{"no":45,"title":"Neuaufbau ist dieselbe Funktion ab null"},{"no":46,"title":"Side Effects gehören in einen Reactor"},{"no":47,"title":"Snapshots sind gemerkte Folds"},{"no":48,"title":"Das Schema ändert sich, das Logbuch nicht"},{"no":49,"title":"Jedes Event steckt in einem Umschlag"},{"no":50,"title":"Ein Upcaster pro Version"},{"no":51,"title":"Upcasten bis zur aktuellen Version"},{"no":52,"title":"Nicht jede Änderung braucht eine Version"},{"no":53,"title":"Konsistenz und Entscheidungen","section":true},{"no":54,"title":"Zwei Systeme, kein gemeinsamer Commit"},{"no":55,"title":"Der Relay liest ab seinem Checkpoint"},{"no":56,"title":"Consumer erkennen Duplikate"},{"no":57,"title":"Eventual Consistency ist ein bewusster Handel"},{"no":58,"title":"Read-your-writes per Position"},{"no":59,"title":"Warum steht das so im Code?"},{"no":60,"title":"Fünf Abschnitte, eine Entscheidung"},{"no":61,"title":"Ein ADR wird nie überschrieben"},{"no":62,"title":"Wann lohnt sich ein ADR?"},{"no":63,"title":"Die Baseline heißt CRUD"},{"no":64,"title":"Was die Patterns wirklich kosten"},{"no":65,"title":"Ein Entscheidungsfluss pro Kontext"},{"no":66,"title":"Der Fluss als Code"},{"no":67,"title":"Das Pattern als Selbstzweck"},{"no":68,"title":"Fragen?","section":true}],"languages":{"de":{"title":"Architektur: DDD, CQRS und Event Sourcing","summary":"Du modellierst den Werkstatt-Shop mit DDD, trennst Schreiben und Lesen mit CQRS und speicherst Bestellungen als Events, nur dort, wo es sich lohnt.","url":"https://slides.mikebild.dev/introduction-cqrs-event-sourcing.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.pdf?v=52932c059f5f","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.mp4?v=52932c059f5f","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.png?v=52932c059f5f","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.de.vtt?v=52932c059f5f","slide_count":68,"slides":[{"no":1,"title":"Architektur: DDD, CQRS und Event Sourcing","section":true},{"no":2,"title":"Die Domäne verstehen","section":true},{"no":3,"title":"Warum heißt im Code alles update?"},{"no":4,"title":"Ein Wort, eine Bedeutung"},{"no":5,"title":"Event Storming beginnt mit dem, was passiert ist"},{"no":6,"title":"Commands und Policies erklären das Warum"},{"no":7,"title":"Hotspots sind die wertvollsten Haftnotizen"},{"no":8,"title":"Das Board als Code prüft die Sprache"},{"no":9,"title":"Ein Produkt, drei Bedeutungen"},{"no":10,"title":"Ein Bounded Context ist eine Sprachgrenze"},{"no":11,"title":"Core, Supporting oder Generic?"},{"no":12,"title":"Die Kanten sind die Architektur"},{"no":13,"title":"Ein Anti-Corruption Layer übersetzt an einer Stelle"},{"no":14,"title":"Erst die Grenze, dann der Service"},{"no":15,"title":"Was rutscht durch, wenn alles string ist?"},{"no":16,"title":"Eine Entity hat eine Identität"},{"no":17,"title":"Ein Value Object ist nur sein Wert"},{"no":18,"title":"Smart Constructors prüfen einmal"},{"no":19,"title":"Positionen sind eingefrorene Werte"},{"no":20,"title":"Regeln, Messages und getrennte Modelle","section":true},{"no":21,"title":"Wer schützt die Regeln der Bestellung?"},{"no":22,"title":"Die Root ist der einzige Eingang"},{"no":23,"title":"Andere Aggregate nur per ID"},{"no":24,"title":"Eine Transaktion, ein Aggregat"},{"no":25,"title":"Mit erwarteter Version speichern"},{"no":26,"title":"Drei Fallstricke"},{"no":27,"title":"Was bedeutet updateOrder?"},{"no":28,"title":"Drei Messages, drei Bedeutungen"},{"no":29,"title":"decide prüft, evolve wendet an"},{"no":30,"title":"Wunsch, Tatsache, Antwort"},{"no":31,"title":"Wo die Benennung in die Irre führt"},{"no":32,"title":"Ein Modell für alles wird zu groß"},{"no":33,"title":"CQRS trennt Modelle, nicht Datenbanken"},{"no":34,"title":"Die Schreibseite prüft und schweigt"},{"no":35,"title":"Die Leseseite liefert genau die Zeile"},{"no":36,"title":"Ein Store genügt für den Anfang"},{"no":37,"title":"Event Sourcing","section":true},{"no":38,"title":"Ein Update vergisst, wie es dazu kam"},{"no":39,"title":"Der Zustand ist ein Left Fold"},{"no":40,"title":"Das Aggregat entscheidet, der Store hängt an"},{"no":41,"title":"Projections sind wegwerfbar"},{"no":42,"title":"Was Event Sourcing kostet"},{"no":43,"title":"Projection oder Cache?"},{"no":44,"title":"Ein Fold mit Checkpoint"},{"no":45,"title":"Neuaufbau ist dieselbe Funktion ab null"},{"no":46,"title":"Side Effects gehören in einen Reactor"},{"no":47,"title":"Snapshots sind gemerkte Folds"},{"no":48,"title":"Das Schema ändert sich, das Logbuch nicht"},{"no":49,"title":"Jedes Event steckt in einem Umschlag"},{"no":50,"title":"Ein Upcaster pro Version"},{"no":51,"title":"Upcasten bis zur aktuellen Version"},{"no":52,"title":"Nicht jede Änderung braucht eine Version"},{"no":53,"title":"Konsistenz und Entscheidungen","section":true},{"no":54,"title":"Zwei Systeme, kein gemeinsamer Commit"},{"no":55,"title":"Der Relay liest ab seinem Checkpoint"},{"no":56,"title":"Consumer erkennen Duplikate"},{"no":57,"title":"Eventual Consistency ist ein bewusster Handel"},{"no":58,"title":"Read-your-writes per Position"},{"no":59,"title":"Warum steht das so im Code?"},{"no":60,"title":"Fünf Abschnitte, eine Entscheidung"},{"no":61,"title":"Ein ADR wird nie überschrieben"},{"no":62,"title":"Wann lohnt sich ein ADR?"},{"no":63,"title":"Die Baseline heißt CRUD"},{"no":64,"title":"Was die Patterns wirklich kosten"},{"no":65,"title":"Ein Entscheidungsfluss pro Kontext"},{"no":66,"title":"Der Fluss als Code"},{"no":67,"title":"Das Pattern als Selbstzweck"},{"no":68,"title":"Fragen?","section":true}],"articles":["https://www.mikebild.dev/de/blog/event-sourcing-auf-aws-dynamodb-streams/","https://www.mikebild.dev/de/blog/wann-cqrs-und-event-sourcing-zu-viel-ist/","https://www.mikebild.dev/de/blog/event-sourcing-der-event-store-als-logbuch/","https://www.mikebild.dev/de/blog/read-models-sind-projektionen/","https://www.mikebild.dev/de/blog/aggregat-als-konsistenzgrenze/","https://www.mikebild.dev/de/blog/commands-events-queries-trennen/","https://www.mikebild.dev/de/blog/cqrs-fachliche-grenze-kein-framework/"]},"en":{"title":"Architecture: DDD, CQRS, and Event Sourcing","summary":"You model the workshop shop with DDD, separate writes and reads with CQRS, and store orders as events, only where it pays off.","url":"https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html","pdf_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.en.pdf?v=d420df81ac12","video_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.en.mp4?v=d420df81ac12","poster_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.en.png?v=d420df81ac12","captions_url":"https://media.mikebild.dev/site/mikebild/decks/introduction-cqrs-event-sourcing/introduction-cqrs-event-sourcing.en.vtt?v=d420df81ac12","slide_count":68,"slides":[{"no":1,"title":"Architecture: DDD, CQRS, and Event Sourcing","section":true},{"no":2,"title":"Understand the domain","section":true},{"no":3,"title":"Why is everything called update in the code?"},{"no":4,"title":"One word, one meaning"},{"no":5,"title":"Event Storming starts with what happened"},{"no":6,"title":"Commands and Policies explain why"},{"no":7,"title":"Hotspots are the most valuable sticky notes"},{"no":8,"title":"The board as code checks the language"},{"no":9,"title":"One product, three meanings"},{"no":10,"title":"A Bounded Context is a language boundary"},{"no":11,"title":"Core, Supporting, or Generic?"},{"no":12,"title":"The edges are the architecture"},{"no":13,"title":"An Anti-Corruption Layer translates in one place"},{"no":14,"title":"First the boundary, then the service"},{"no":15,"title":"What slips through when everything is string?"},{"no":16,"title":"An Entity has an identity"},{"no":17,"title":"A Value Object is only its value"},{"no":18,"title":"Smart Constructors check once"},{"no":19,"title":"Line items are frozen values"},{"no":20,"title":"Rules, messages, and separate models","section":true},{"no":21,"title":"Who protects the order’s rules?"},{"no":22,"title":"The root is the only entry point"},{"no":23,"title":"Other aggregates only by ID"},{"no":24,"title":"One transaction, one aggregate"},{"no":25,"title":"Save with the expected version"},{"no":26,"title":"Three pitfalls"},{"no":27,"title":"What does updateOrder mean?"},{"no":28,"title":"Three messages, three meanings"},{"no":29,"title":"decide checks, evolve applies"},{"no":30,"title":"Wish, fact, answer"},{"no":31,"title":"Where naming misleads"},{"no":32,"title":"One model for everything gets too large"},{"no":33,"title":"CQRS separates models, not databases"},{"no":34,"title":"The write side validates and stays silent"},{"no":35,"title":"The read side returns exactly the row"},{"no":36,"title":"One store is enough to start"},{"no":37,"title":"Event Sourcing","section":true},{"no":38,"title":"An update forgets how it got there"},{"no":39,"title":"The state is a Left Fold"},{"no":40,"title":"The aggregate decides, the store appends"},{"no":41,"title":"Projections are disposable"},{"no":42,"title":"What Event Sourcing costs"},{"no":43,"title":"Projection or cache?"},{"no":44,"title":"A fold with a checkpoint"},{"no":45,"title":"Rebuild is the same function from zero"},{"no":46,"title":"Side effects belong in a reactor"},{"no":47,"title":"Snapshots are stored folds"},{"no":48,"title":"The schema changes, the event log does not"},{"no":49,"title":"Every event is inside an envelope"},{"no":50,"title":"One upcaster per version"},{"no":51,"title":"Upcast to the current version"},{"no":52,"title":"Not every change needs a version"},{"no":53,"title":"Consistency and decisions","section":true},{"no":54,"title":"Two systems, no shared commit"},{"no":55,"title":"The relay reads from its checkpoint"},{"no":56,"title":"Consumers detect duplicates"},{"no":57,"title":"Eventual Consistency is a deliberate trade-off"},{"no":58,"title":"Read-your-writes by position"},{"no":59,"title":"Why is this written this way?"},{"no":60,"title":"Five sections, one decision"},{"no":61,"title":"An ADR is never overwritten"},{"no":62,"title":"When is an ADR worth it?"},{"no":63,"title":"The baseline is CRUD"},{"no":64,"title":"What the patterns really cost"},{"no":65,"title":"One decision flow per context"},{"no":66,"title":"The flow as code"},{"no":67,"title":"The pattern as an end in itself"},{"no":68,"title":"Questions?","section":true}],"articles":[]}}}]}