# How Apache Maka's Event-Sourced Architecture Works: A Deep Dive into the Runtime Event Log

> Explore Apache Maka's event-sourced architecture. Learn how its append-only SQLite event log stores immutable RuntimeEvents and derives application state through projections.

- Repository: [The Apache Software Foundation/maka](https://github.com/apache/maka)
- Tags: deep-dive
- Published: 2026-09-09

---

**Apache Maka uses a single append-only SQLite event log as the authoritative source of truth, where every interaction is stored as an immutable `RuntimeEvent` and all application state is derived through projections that replay the event sequence.**

Apache Maka is an open-source agent framework that implements a pure event-sourced architecture to guarantee deterministic session replay and crash resilience. Unlike traditional applications that mutate state directly in a database, Maka persists every model message, tool invocation, and permission decision as an immutable record in the **runtime event log**, deriving all higher-level functionality—including UI views, prompt contexts, and recovery states—from this sequential ledger.

## The Core Components of Apache Maka's Event-Sourced Architecture

### Runtime Event Log and SQLite Storage

At the heart of Apache Maka's event-sourced architecture lies the **append-only event log** stored in SQLite. This log resides in the `runtime_events` table and functions as the sole durable record of every interaction within a session. The system never updates or deletes existing records; it only appends new `RuntimeEvent` entries via the `appendRuntimeEvent` method implemented in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts).

Each event carries a unique identifier, timestamp, type discriminator (such as `modelMessage` or `toolResult`), and a monotonically increasing `event_seq` number. This sequencing ensures that every projection can reconstruct state deterministically by processing events in strict order.

### SessionManager and AgentRun Lifecycle

The **SessionManager** and **AgentRun** classes own the execution lifecycle, including turn management and run continuations. Rather than maintaining mutable state objects, these components read the immutable prefix of the event log to reconstruct the current context before generating the next prompt or scheduling agent work. This design enables the **Agent Graph** to coordinate multi-agent scheduling without duplicating state, as child sessions emit events that are stored in the same unified log.

### Projections: Deriving State from Events

All derived views in Apache Maka are **projections** computed from the event log. Whether rendering the desktop UI, building conversation transcripts, or generating crash-recovery snapshots, the system replays the relevant `RuntimeEvent` sequence to materialize the current state. Because the log is immutable, projections can be discarded and rebuilt at any time without data loss, ensuring that the UI and internal state remain perfectly synchronized with the underlying event stream.

### Runtime Host as the Write Authority

The **Runtime Host** acts as the sole write authority for a given state root, ensuring that all clients—whether Desktop, TUI, CLI, or automated bots—interact with a single consistent event stream. By centralizing write operations through the host, Apache Maka prevents conflicting state mutations and maintains the integrity of the append-only log across multiple simultaneous access patterns.

## How the Event-Sourced Workflow Executes

The interaction flow follows a strict append-only pattern that preserves complete auditability:

1. **Client Request Processing**: When a client sends a request, the Runtime Host creates a new `RuntimeEvent` (e.g., recording that a model spoke or a tool executed).

2. **Atomic Event Persistence**: The host calls `appendRuntimeEvent` in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts) to durably write the event to the SQLite `runtime_events` table. This operation is atomic, ensuring that once an event is persisted, it becomes part of the permanent record.

3. **State Reconstruction**: The SessionManager reads the immutable prefix of the log using `readRuntimeEvents`, then decodes each record via `decodeRuntimeEvent` (defined in [`packages/core/src/runtime-event.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-event.ts)) to rebuild the in-memory context required for the next execution step.

4. **Projection Updates**: UI panels, transcript views, and recovery snapshots recompute their state by scanning the updated event sequence, guaranteeing that all observers see exactly the same history that produced the original output.

## Crash Recovery and Deterministic Replay

Apache Maka leverages the immutable nature of its event log to provide robust fault tolerance. Because the log is append-only and each event carries a monotonic `event_seq`, the system can **replay** any past run deterministically by reloading the event sequence from the beginning.

When recovering from a crash, the SessionManager loads the last saved prefix of the `runtime_events` table and replays the remaining events to restore the exact state that existed prior to failure. This approach eliminates the need for complex state snapshots or checkpointing mechanisms, as documented in [`docs/architecture/runtime-resume-architecture.md`](https://github.com/apache/maka/blob/main/docs/architecture/runtime-resume-architecture.md). The same immutability enables **multi-agent scheduling**, where child sessions emit events stored in the shared log, allowing the Agent Graph to coordinate work without maintaining separate state copies.

## Code Implementation: Appending and Reading Events

The following TypeScript examples demonstrate how Apache Maka persists and retrieves events using the core storage mechanisms.

Appending a new event to the log:

```typescript
import { RuntimeEvent, canonicalizeRuntimeEventForStorage } from '@maka/core/runtime-event';
import { SQLiteRuntimeStore } from '@maka/storage/sqlite-runtime-store';

async function recordModelMessage(
  store: SQLiteRuntimeStore,
  sessionId: string,
  runId: string,
  msg: string,
) {
  const event: RuntimeEvent = {
    id: crypto.randomUUID(),
    ts: Date.now(),
    type: 'modelMessage',
    payload: { text: msg },
    // …other required metadata (sessionId, turnId, etc.)
  };

  // The store ensures the event is durable and appended atomically.
  await store.appendRuntimeEvent(event);
}

```

Replaying events to reconstruct session context:

```typescript
import { SQLiteRuntimeStore } from '@maka/storage/sqlite-runtime-store';
import { decodeRuntimeEvent } from '@maka/core/runtime-event';

async function loadSessionHistory(store: SQLiteRuntimeStore, sessionId: string, runId: string) {
  const rawEvents = await store.readRuntimeEvents(sessionId, runId);
  const events = rawEvents.map(decodeRuntimeEvent);

  // Apply each event to rebuild the in-memory state (e.g., a transcript)
  const transcript: string[] = [];
  for (const ev of events) {
    if (ev.type === 'modelMessage') {
      transcript.push(`🧠 ${ev.payload.text}`);
    } else if (ev.type === 'toolResult') {
      transcript.push(`🔧 ${ev.payload.result}`);
    }
    // …handle other event types
  }
  return transcript;
}

```

## Summary

- **Single Source of Truth**: Apache Maka stores every interaction as an immutable `RuntimeEvent` in a SQLite `runtime_events` table, making the append-only log the authoritative record of system state.

- **Projection-Based State**: All UI views, prompt contexts, and recovery mechanisms are computed projections derived by replaying the event sequence, ensuring perfect reproducibility.

- **Deterministic Replay**: The monotonic `event_seq` assigned to each event enables deterministic session replay and crash recovery without complex checkpointing logic.

- **Centralized Write Authority**: The Runtime Host acts as the sole write authority, coordinating multiple clients (Desktop, TUI, CLI) through a unified event stream stored in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts).

## Frequently Asked Questions

### What makes Apache Maka's architecture "event-sourced"?

Apache Maka follows classic event-sourcing principles by treating the sequence of `RuntimeEvent` records as the primary source of truth rather than storing mutable state. According to the source code in [`ARCHITECTURE.md`](https://github.com/apache/maka/blob/main/ARCHITECTURE.md), the system derives all current state—including UI displays and conversation context—by projecting the immutable event log, ensuring that the history of every session remains fully auditable and replayable.

### How does Apache Maka handle crash recovery using the event log?

When recovering from a crash, the SessionManager loads the immutable prefix of the `runtime_events` table and replays the remaining events to reconstruct the exact pre-crash state, as detailed in [`docs/architecture/runtime-resume-architecture.md`](https://github.com/apache/maka/blob/main/docs/architecture/runtime-resume-architecture.md). Because events are never modified or deleted, recovery simply involves reading the log from the beginning and applying each event sequentially until reaching the latest record.

### Can multiple clients interact with the same session simultaneously?

Yes, multiple clients such as Desktop, TUI, and CLI interfaces can interact with the same session because the Runtime Host serves as the sole write authority for the event log. All clients communicate with this central host, which appends events atomically to the SQLite store in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts), ensuring that every client observes the same consistent event stream without state conflicts.

### Where are the events physically stored in Apache Maka?

Events are physically persisted in a SQLite database within the `runtime_events` table, implemented in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts). The storage layer provides fast indexed access via `readRuntimeEvents` while maintaining the append-only invariant through `appendRuntimeEvent`, without duplicating state or maintaining separate transaction logs.