0Pricing
Node.js Backend Development Bootcamp · 강의

읽기 모델 및 프로젝션 만들기

이벤트 스트림에서 쿼리 측에 최적화된 프로젝션을 도출하고 최종적 일관성을 유지합니다.

읽기 모델 및 프로젝션 만들기은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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.

자주 묻는 질문

“읽기 모델 및 프로젝션 만들기” 강의는 무료인가요?

네 — “읽기 모델 및 프로젝션 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.

“읽기 모델 및 프로젝션 만들기”에서 뭘 배우나요?

이벤트 스트림에서 쿼리 측에 최적화된 프로젝션을 도출하고 최종적 일관성을 유지합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“읽기 모델 및 프로젝션 만들기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 진실의 원천으로서의 이벤트 및 추가 전용 로그
  2. 집합체, 명령 및 도메인 이벤트 모델링
  3. 읽기 모델 및 프로젝션 만들기
  4. 스냅샷, 버전 관리 및 이벤트 스키마 진화
← Node.js Backend Development Bootcamp(으)로 돌아가기