Original English publication: 2026-06-14T10:04:02.999+03:00. Technical review: 28 October 2026. This corrected edition preserves the original publication date.
Editorial update: factual and safety corrections are documented separately. Examples are illustrative and runtime-untested; no operational action was performed.
This article examines established architecture patterns for reliable data handling and maintainable services.
Architecture guides can prompt a useful question: before adopting serverless platforms, Kubernetes or more services, have we understood the boundaries and consistency requirements of the system we already operate? The patterns below are established options, not new universal prescriptions.
We examine CQRS and Event Sourcing, Transactional Outbox, and Hexagonal (Ports and Adapters) Architecture. Each addresses a different problem and introduces trade-offs; use them when actual requirements justify their complexity.
The Architectural Debt of "Move Fast and Break Things"
Consider an application that began with a straightforward MVC design. As its workload changes, long read queries, coordination across services or framework dependencies may become difficult to manage. These are possible failure modes, not inevitable consequences of MVC or a single database.
Architectural debt appears when the design no longer fits requirements. A single relational database remains appropriate for many systems; measure bottlenecks and identify boundaries before adding distributed components.
Pattern 1: CQRS and Event Sourcing (Decoupling Reads from Writes)
CQRS separates read and write models. It is related to, but distinct from, method-level Command–Query Separation. CQRS can use one data store or separate stores, and it does not require Event Sourcing. A command may report its outcome without becoming a general-purpose query.
Why it matters now
Read-heavy workloads can benefit from independently optimized read models. A shared relational database is not automatically a bottleneck: query plans, indexes, isolation, hardware and workload determine whether separation is justified.
The Architecture in Action
By pairing CQRS with Event Sourcing, instead of storing the current state of an object, we store a sequence of state-changing events.
[Client]
│
├── (Command: SubmitOrder) ──> [Write Service] ──> [Append Event] ──> [Event Store (Postgres/Kafka)]
│ │
│ (Async Projection)
│ ▼
└── (Query: GetOrderHistory) ─> [Read Service] <── [Read DB (Redis/Elasticsearch)]
An illustrative event-sourced order aggregate in JavaScript
The following in-memory illustration records state transitions. It is not a persistent event store: production use also needs durable append, concurrency/version checks, authorization, validation, schema evolution and recovery. No runtime test was performed.
// A simple implementation of an Event-Sourced Order Entity
class Order {
constructor() {
this.orderId = null;
this.status = 'NEW';
this.items = [];
this.total = 0;
this.changes = []; // Track uncommitted events
}
// Command Handler
createOrder(orderId, items, total) {
if (this.status !== 'NEW') throw new Error('Order already created.');
this.applyChange({
type: 'ORDER_CREATED',
payload: { orderId, items, total, timestamp: Date.now() }
});
}
payOrder() {
if (this.status !== 'CREATED') throw new Error("Order cannot be paid.");
this.applyChange({
type: 'ORDER_PAID',
payload: { orderId: this.orderId, timestamp: Date.now() }
});
}
// Apply state changes
applyChange(event, isNew = true) {
this.playback(event);
if (isNew) this.changes.push(event);
}
// The Rehydration Logic (State Projection)
playback(event) {
switch (event.type) {
case 'ORDER_CREATED':
this.orderId = event.payload.orderId;
this.items = event.payload.items;
this.total = event.payload.total;
this.status = 'CREATED';
break;
case 'ORDER_PAID':
this.status = 'PAID';
break;
}
}
}
Replaying events for an order can rebuild its state. Audit quality depends on durable storage, ordering, complete event capture and access controls; an append-only convention alone does not make a log tamper-proof. Replay must not repeat external side effects.
Pattern 2: Transactional Outbox and reliable event handoff
If you've adopted microservices, you know the pain of distributed transactions. Let's say a user registers. You need to save the user to your database AND publish a UserRegistered event to an external message broker like Apache Kafka or RabbitMQ.
What happens if your database write succeeds, but the network hiccups and your message broker is unreachable? Your system is now in an inconsistent state. The user exists, but downstream services (like the email notifier) have no idea.
The Solution: The Outbox Pattern
Transactional Outbox writes the business change and a durable event record in the same local database transaction. Publication to the external broker happens later through a relay; it is not part of that database transaction. The relay needs retries, ordering and monitoring.
Database Schema Example
Here is what your SQL schema might look like to support this pattern:
-- The primary business entity table
CREATE TABLE users (
id UUID PRIMARY KEY,
email VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- The transactional outbox table
CREATE TABLE outbox_events (
id UUID PRIMARY KEY,
aggregate_type VARCHAR(100) NOT NULL,
aggregate_id VARCHAR(100) NOT NULL,
event_type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
status VARCHAR(50) DEFAULT 'PENDING', -- PENDING, PROCESSED, FAILED
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
When you register a user, you execute both inserts in a single transaction:
BEGIN TRANSACTION;
INSERT INTO users (id, email)
VALUES ('d3b07384-d113-4956-a534-1123456789ab', 'alex@sysseder.com');
INSERT INTO outbox_events (id, aggregate_type, aggregate_id, event_type, payload)
VALUES (
'e5c18495-e224-5067-b645-2234567890bc',
'User',
'd3b07384-d113-4956-a534-1123456789ab',
'USER_REGISTERED',
'{"email": "alex@sysseder.com", "userId": "d3b07384-d113-4956-a534-1123456789ab"}'
);
COMMIT;
On a transactional PostgreSQL database, a successful commit makes both inserts durable according to its configured durability guarantees. A polling relay or a configured change-data-capture pipeline such as Debezium then publishes committed events. Crashes can cause duplicate delivery, so consumers must be idempotent; retention, failed-message handling and relay monitoring remain necessary.
Pattern 3: Hexagonal Architecture (Protecting Your Domain)
Also known as "Ports and Adapters", Hexagonal Architecture aims to isolate your core business logic from external concerns like databases, web frameworks, email services, and UI components.
Think about how often you've wanted to switch from MongoDB to PostgreSQL, or swap out Express.js for Fastify, only to realize that database queries or framework-specific request objects are scattered across your entire codebase. Hexagonal Architecture prevents this coupling by defining interfaces (Ports) and implementations (Adapters).
Anatomy of a Hexagon
- Domain core: Business rules that do not depend on infrastructure or UI adapters. Language or suitable domain libraries are not categorically forbidden.
- Ports: Interfaces that define how data goes in and out of the core (e.g., a
UserRepositoryinterface). - Adapters: The actual implementations of those interfaces (e.g., a
PostgresUserRepositoryor aRESTExpressController).
A TypeScript Implementation of Ports and Adapters
The TypeScript illustration shows dependency boundaries, not a working database adapter. Its methods only log messages and return a sample user. Checking for an @ is not complete email validation; production validation, privacy-safe logging and persistence are separate tasks.
// 1. PORT (Interface) - Must be stored in the Domain boundary
interface UserRepository {
findById(id: string): Promise<User | null>;
save(user: User): Promise<void>;
}
// 2. DOMAIN ENTITY (Core Business Logic)
class User {
constructor(public readonly id: string, public email: string) {}
changeEmail(newEmail: string) {
if (!newEmail.includes('@')) {
throw new Error("Invalid email format");
}
this.email = newEmail;
}
}
// 3. ADAPTER (External Dependency Implementation)
class PostgresUserRepository implements UserRepository {
async findById(id: string): Promise<User | null> {
// Imagine actual DB queries running here via Knex/Prisma/pg
console.log(`Querying Postgres for user: ${id}`);
return new User(id, "alex@sysseder.com");
}
async save(user: User): Promise<void> {
console.log(`Saving user ${user.id} to Postgres`);
}
}
// 4. USE CASE (orchestrator using the Port, not the Adapter)
class ChangeEmailUseCase {
constructor(private userRepository: UserRepository) {}
async execute(userId: string, newEmail: string): Promise<void> {
const user = await this.userRepository.findById(userId);
if (!user) throw new Error("User not found");
user.changeEmail(newEmail);
await this.userRepository.save(user);
}
}
// How we wire it all together (Dependency Injection)
const dbAdapter = new PostgresUserRepository();
const emailService = new ChangeEmailUseCase(dbAdapter);
Depending on a port lets tests supply an in-memory adapter and can limit infrastructure-driven changes. Replacing a persistence technology still requires verifying transaction, query and consistency semantics; an interface alone cannot guarantee a zero-change migration.
Conclusion: The Classics Are Classics for a Reason
Cloud products change, but data boundaries, consistency and maintainability remain recurring concerns. Not every application needs separate read and write systems or eventual consistency; select the simplest design that satisfies measured requirements.
By understanding and selectively applying patterns like CQRS, the Transactional Outbox, and Hexagonal Architecture, you can write code that scales gracefully and remains a joy to work in—years down the line.
What about you? What classic architectural patterns do you find yourself reaching for most often in your day-to-day work? Have you ever had to migrate away from a system because these boundaries weren't set up early on? Let me know in the comments below, or hit me up on Twitter!
Until next time, happy coding!
Diagram labels distinguish commands, durable event append, asynchronous projections and read queries. The diagram is conceptual; a broker alone is not automatically a complete event store.