Node.js Backend Development Bootcamp · Lezione

Creazione di read model e proiezioni

Derivi proiezioni ottimizzate per le query dallo stream di eventi e le mantenga eventualmente consistenti.

Lezione 3 di 413 passaggi

Creazione di read model e proiezioni è una lezione Node.js Backend Development Bootcamp gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Node.js Backend Development Bootcamp, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Node.js Backend Development Bootcamp include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Why Read Models Exist

In an event-sourced system, the write side stores facts as an append-only stream of events. That stream is great for capturing history but terrible for queries like "show me all open orders sorted by total".

The read side solves this. A read model (also called a projection) is a denormalized, query-optimized view derived purely from events. This is the Q in CQRS: commands mutate the event stream, queries hit read models.

  • One event stream can feed many read models, each shaped for a specific query.
  • Read models are disposable — you can delete and rebuild them from events at any time.
  • They are eventually consistent with the write side, not transactionally consistent.

A Projection Is a Left Fold

At its core, a projection is just a reduce over the event stream: you start with an initial state and apply each event in order to produce the next state.

Conceptually: readModel = events.reduce(apply, initialState). The apply function is a pure switch over event types. Anything you can fold, you can project.

// Pure projection: fold the event stream into a read model
const events = [
  { type: 'OrderPlaced', orderId: 'o1', total: 50 },
  { type: 'OrderPlaced', orderId: 'o2', total: 20 },
  { type: 'OrderPaid', orderId: 'o1' },
  { type: 'OrderCancelled', orderId: 'o2' },
];

function apply(state, event) {
  const next = { ...state };
  switch (event.type) {
    case 'OrderPlaced':
      next[event.orderId] = { status: 'placed', total: event.total };
      break;
    case 'OrderPaid':
      if (next[event.orderId]) next[event.orderId].status = 'paid';
      break;
    case 'OrderCancelled':
      delete next[event.orderId];
      break;
  }
  return next;
}

const readModel = events.reduce(apply, {});
console.log(readModel);
// { o1: { status: 'paid', total: 50 } }

A Projector Class

A real projector is more than a single fold. It owns three things:

  • handlers — a map from event type to an update function.
  • state — the read model it maintains (in memory, in a table, in a cache).
  • position — how far it has consumed the stream (the checkpoint).

Events it does not care about are simply ignored. This keeps each projector focused on exactly the data its queries need.

class OrderSummaryProjection {
  constructor() {
    this.state = new Map();
    this.handlers = {
      OrderPlaced: (e) => this.state.set(e.orderId, {
        status: 'placed', total: e.total, customer: e.customer,
      }),
      OrderShipped: (e) => {
        const r = this.state.get(e.orderId);
        if (r) r.status = 'shipped';
      },
    };
  }

  when(event) {
    const handler = this.handlers[event.type];
    if (handler) handler(event); // ignore unknown event types
  }

  query(orderId) {
    return this.state.get(orderId) ?? null;
  }
}

const proj = new OrderSummaryProjection();
proj.when({ type: 'OrderPlaced', orderId: 'o1', total: 99, customer: 'Ada' });
proj.when({ type: 'OrderShipped', orderId: 'o1' });
proj.when({ type: 'Irrelevant', foo: 1 });
console.log(proj.query('o1'));
// { status: 'shipped', total: 99, customer: 'Ada' }

Persisting to a Read Store

In production the read model lives in a database tuned for queries — Postgres, MongoDB, Redis, Elasticsearch — whatever fits the query shape. Each event handler issues an idempotent upsert against that store.

Note the SQL below is a fragment that assumes an order_summary table already exists, so it is illustrative rather than standalone-runnable.

// Postgres read-model upsert inside a projector (using node-postgres)
async function onOrderPlaced(pool, event) {
  await pool.query(
    `INSERT INTO order_summary (order_id, status, total, customer)
     VALUES ($1, 'placed', $2, $3)
     ON CONFLICT (order_id) DO UPDATE
       SET status = EXCLUDED.status,
           total  = EXCLUDED.total,
           customer = EXCLUDED.customer`,
    [event.orderId, event.total, event.customer]
  );
}

async function onOrderShipped(pool, event) {
  await pool.query(
    `UPDATE order_summary SET status = 'shipped' WHERE order_id = $1`,
    [event.orderId]
  );
}

Subscribing to the Event Stream

A projector does not poll forever blindly — it subscribes to the event store and receives events in order as they are appended. The contract every event store gives you:

  • Events arrive in global commit order (or per-stream order).
  • Each event carries a monotonic position (global offset or sequence number).
  • The subscription can start from a given position — essential for resuming.

You drive the projector by feeding each received event to its when method, then advancing the checkpoint.

// A minimal in-memory event bus a projector can subscribe to
class EventStore {
  constructor() { this.log = []; this.subs = []; }
  append(event) {
    const stored = { ...event, position: this.log.length + 1 };
    this.log.push(stored);
    for (const cb of this.subs) cb(stored);
  }
  subscribeFrom(position, cb) {
    for (const e of this.log) if (e.position > position) cb(e); // catch up
    this.subs.push(cb); // then live
  }
}

const store = new EventStore();
store.append({ type: 'OrderPlaced', orderId: 'o1', total: 10 });
let count = 0;
store.subscribeFrom(0, (e) => { count++; });
store.append({ type: 'OrderPaid', orderId: 'o1' });
console.log('events seen:', count); // 2 (1 catch-up + 1 live)

Checkpoints: Remembering Your Position

If your service restarts, you must not reprocess the entire stream from the beginning (slow) nor skip events (data loss). The fix is a checkpoint: persist the position of the last successfully processed event.

On boot, the projector reads its checkpoint and resumes the subscription from that position. The golden rule:

  • Process the event and update the read model.
  • Then advance and persist the checkpoint.
  • Ideally write the read-model change and the checkpoint in the same transaction.
// Resuming from a stored checkpoint
async function startProjector(store, checkpointRepo, projection) {
  const last = await checkpointRepo.load(projection.name); // e.g. 42

  store.subscribeFrom(last, async (event) => {
    await projection.when(event);              // 1. update read model
    await checkpointRepo.save(
      projection.name, event.position          // 2. advance checkpoint
    );
  });
}

// checkpointRepo example backed by a 'projection_checkpoints' table:
// load:  SELECT position FROM projection_checkpoints WHERE name = $1
// save:  INSERT ... ON CONFLICT (name) DO UPDATE SET position = $2

Idempotency: Surviving Redelivery

Because the checkpoint is saved after processing, a crash between "update read model" and "save checkpoint" means the same event will be redelivered on restart. This is at-least-once delivery, and it is normal.

Therefore every handler must be idempotent — applying the same event twice yields the same state. Two reliable techniques:

  • Use upserts instead of blind inserts (no duplicate rows).
  • For non-idempotent ops (counters, sums), record the last applied position per row and skip events at or below it.
// Guarding a running total against redelivery using a per-row version
function applyRevenue(state, event) {
  const row = state[event.customer] ?? { revenue: 0, lastPos: 0 };
  if (event.position <= row.lastPos) {
    return state; // already applied — skip duplicate
  }
  row.revenue += event.amount;
  row.lastPos = event.position;
  return { ...state, [event.customer]: row };
}

let s = {};
const paid = { type: 'OrderPaid', customer: 'Ada', amount: 30, position: 5 };
s = applyRevenue(s, paid);
s = applyRevenue(s, paid); // redelivered, ignored
console.log(s.Ada.revenue); // 30, not 60

Eventual Consistency and the Read-Your-Writes Gap

Projections update asynchronously, so right after a command succeeds the read model may not reflect it yet. This read-your-writes gap surprises users: they place an order and the list still looks empty for a few milliseconds.

Strategies to manage it:

  • Return the new state from the command so the UI can render optimistically without re-querying.
  • Wait-for-projection: the command returns the event position; the client polls the read model until its checkpoint reaches that position.
  • Design the UX to tolerate brief staleness (spinners, "processing" states).

Never try to make projections synchronous "just to be safe" — you lose the scalability and decoupling that make CQRS worthwhile.

Multiple Projections From One Stream

The real power of CQRS: a single event stream feeds many independent read models, each optimized for a different query. The same OrderPlaced event might update:

  • an OrderList projection for the customer's order history,
  • a DailyRevenue projection for analytics,
  • a SearchIndex projection feeding Elasticsearch.

Each runs with its own handlers and its own checkpoint, so they can be added, rebuilt, or scaled independently.

// One dispatcher fans an event out to many projections
const projections = [];

function register(name, handlers) {
  projections.push({ name, handlers, state: {} });
}

function dispatch(event) {
  for (const p of projections) {
    const h = p.handlers[event.type];
    if (h) h(p.state, event);
  }
}

register('orderCount', {
  OrderPlaced: (s) => { s.count = (s.count ?? 0) + 1; },
});
register('revenue', {
  OrderPlaced: (s) => { s.sum = (s.sum ?? 0) + 1; },
  OrderPaid:   (s, e) => { s.paid = (s.paid ?? 0) + e.total; },
});

dispatch({ type: 'OrderPlaced', orderId: 'o1', total: 40 });
dispatch({ type: 'OrderPaid', orderId: 'o1', total: 40 });
console.log(projections.map((p) => [p.name, p.state]));

Rebuilding a Projection

Because read models are derived data, you can throw them away and recompute them. You rebuild a projection when you:

  • change its schema (add a new column or denormalized field),
  • fix a bug in a handler,
  • add a brand-new read model that needs historical data.

The rebuild recipe:

  • Reset the read store (truncate the table) and reset the checkpoint to 0.
  • Replay the entire stream from the beginning through the handlers.
  • For zero-downtime, build into a new table and atomically swap (blue-green) once it catches up to live.
// Rebuild by replaying the whole log into a fresh projection
function rebuild(eventLog, projection) {
  projection.state = {};          // reset read model
  projection.checkpoint = 0;      // reset position
  for (const event of eventLog) {
    projection.when(event);
    projection.checkpoint = event.position;
  }
  return projection;
}

const log = [
  { type: 'OrderPlaced', orderId: 'o1', total: 10, position: 1 },
  { type: 'OrderPlaced', orderId: 'o2', total: 25, position: 2 },
];
const proj = {
  state: {}, checkpoint: 0,
  when(e) { if (e.type === 'OrderPlaced') this.state[e.orderId] = e.total; },
};
rebuild(log, proj);
console.log(proj.state, 'at', proj.checkpoint);
// { o1: 10, o2: 25 } at 2

Ordering, Failures, and Poison Events

A projector consumes events sequentially to preserve order — a shipped event must never be applied before its placed event. That constraint shapes how you handle errors:

  • On a transient failure (DB blip), retry with backoff; do not advance the checkpoint, so the event is re-applied.
  • On a poison event (one that always throws), you must not block the whole projection forever. Move it to a dead-letter log and alert, so the rest of the stream keeps flowing.
  • Parallelize across partitions (e.g. by aggregate id) when you need throughput, keeping order within each partition.

Keep handlers small and deterministic so failures are rare and reproducible.

Quick Check: The Checkpoint Decision

A projector updates a Postgres read model and stores its checkpoint in a separate table. The service can crash at any moment. Which approach best guarantees correctness?

Recap: Read Models and Projections

You now know how the query side of an event-sourced system is built:

  • A projection is a left fold over the event stream into a denormalized, query-optimized read model.
  • A projector owns handlers, persisted state, and a checkpoint; it subscribes to the store and applies events in order.
  • Save the checkpoint after processing and make handlers idempotent to survive at-least-once redelivery (upserts, per-row position guards).
  • Read models are eventually consistent — manage the read-your-writes gap with optimistic responses or wait-for-projection, never by forcing synchronous projections.
  • One stream can feed many read models, and any of them can be rebuilt by replaying the stream (build-and-swap for zero downtime).
  • Process sequentially per partition; retry transient failures without advancing the checkpoint, and dead-letter poison events.
Gratis per iniziare

Impara JavaScript con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
22
Lezioni
92

Domande Frequenti

La lezione «Creazione di read model e proiezioni» è gratuita?

Sì — il testo completo di «Creazione di read model e proiezioni» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Node.js Backend Development Bootcamp, passa a CoddyKit PRO. Il corso Node.js Backend Development Bootcamp include 4 lezioni in totale.

Cosa imparerò in «Creazione di read model e proiezioni»?

Derivi proiezioni ottimizzate per le query dallo stream di eventi e le mantenga eventualmente consistenti. Eserciti Node.js Backend Development Bootcamp con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Node.js Backend Development Bootcamp?

Non è richiesta alcuna esperienza precedente. Node.js Backend Development Bootcamp su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Creazione di read model e proiezioni»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Node.js Backend Development Bootcamp?

Sì. Ogni lezione Node.js Backend Development Bootcamp include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Eventi come fonte di verità e log append-only
  2. Aggregati, comandi e modellazione degli eventi di dominio
  3. Creazione di read model e proiezioni
  4. Snapshot, versioning ed evoluzione dello schema degli eventi
← Torna a Node.js Backend Development Bootcamp