All writing

Writing

Hexagonal DDD from Day One: Building Matcha to Be Built by Agents

By Aggelos Konstantilieris·May 23, 2026·6 min read·Updated October 28, 2026

Matcha is a multi-tenant WhatsApp booking platform. A customer messages a business, and an AI agent proposes times, answers questions, takes payment and confirms the appointment. The product is a pnpm monorepo with a NestJS backend, a Next.js dashboard, an operator console and a shared contract package. The same repository also holds the AI agent, the evaluation harness that grades it, and the autonomous loop that writes most of the code.

I chose that setup on day one: hexagonal DDD, everything in one place, and no external dependency I did not control. Here is why, and what was hard.

Hexagonal DDD from day one

Matcha did not grow into this architecture. The domain / application / infrastructure / interface/http split was in place before the first feature shipped. So were the ports, the Symbol() injection tokens and the one-way dependency rule. For a single developer that looks like over-engineering, and for the first weeks it was.

Then agents started doing most of the writing, and I became one person directing a team. A team needs boundaries it cannot cross by accident. The planner's Review Agent fails any plan that imports infrastructure into the domain or bypasses a port, before any code is written.

Why a monorepo

Three reasons, in the order they drove the decision.

Context. Agents only know what they can see. In one repository, the planner, implementer and reviewer all have the product, the shared contract, the conventions doc and the eval suite within reach. Split the code across repos and every task starts with the agent missing half the picture.

Ergonomics. There is one install and one pnpm check. A type changed in @matcha/contract reaches every app at once.

No dependency I don't control. The eval harness lives in the repo instead of a SaaS. The agent's memory is MongoDB instead of a managed vector store. As far as possible, I can read, seed and run every part locally. That keeps evaluation deterministic and the system portable.

Every outside system is a port

Nothing volatile reaches the core. The Meta WhatsApp Cloud API, the payment provider, the AI model and Mongo itself each sit behind a port. A port is an interface the domain defines and the outside world implements. Which implementation answers at runtime is a wiring choice.

PortProduction adapterTest / dev adapter
WhatsAppProviderPortMetaCloudProvider (Graph API)MockWaProvider
WhatsAppWebhookParserPortMeta payload parserMockWaParser
*RepositoryPortMongo*Adaptermongodb-memory-server

The application layer never learns which one it got. When Meta changes its envelope, one file in infrastructure/ changes.

Multi-tenancy you can't forget to apply

The worst bug in a multi-tenant product lets tenant A see tenant B's data. Matcha reads the tenant id only from the X-Business-Id header, never from the body, query or URL. One global guard checks membership on every authenticated route.

// common/guards/business-tenant.guard.ts (trimmed)
async canActivate(ctx: ExecutionContext): Promise<boolean> {
  if (this.isPublicOrSkipped(ctx)) return true;
 
  const req = ctx.switchToHttp().getRequest<Request>();
  const target = req.headers['x-business-id'] as string | undefined;
 
  // BusinessMembership is the sole tenant gate, read LIVE from Mongo on every
  // request — no cache — so revoking access takes effect immediately.
  const membership = await this.memberships.findByUserAndBusiness(
    req.user.id,
    target,
  );
  if (!membership || !membership.active) return false;
  await this.assertBusinessActive(target); // reject suspended / archived
 
  req.businessId = target; // controllers read it via the @Tenant() decorator
  return true;
}

The id arrives in one place and is checked in one place. A controller cannot forget to scope a query, because it receives a businessId that is already proven. An earlier version fell back through params, body, query and header. I deleted that chain on purpose, since every extra source for a tenant id is another way for it to leak.

Conversations as a concurrency-safe state machine

A booking negotiation over WhatsApp is a distributed-systems problem behind a chat window. The agent proposes a slot and the customer takes ninety seconds to reply "yes". Meanwhile a 10-minute TTL might expire the offer, or staff might cancel it. Each negotiation is a workflow with an explicit state machine that only moves forward:

const ALLOWED_TRANSITIONS = new Map([
  [Proposed,             new Set([AwaitingConfirmation])],
  [AwaitingConfirmation, new Set([Confirmed, Cancelled, Expired, Failed])],
  [Confirmed,            new Set([Executed, Cancelled, Expired, Failed])],
]);
 
export function assertTransition(from, to) {
  if (TERMINAL_STATUSES.has(from) || !ALLOWED_TRANSITIONS.get(from)?.has(to)) {
    throw new InvalidTransitionError(from, to);
  }
}

A Confirmed workflow cannot rewind to Proposed. Races are handled with optimistic concurrency. The write lands only if the version read is still the version stored.

const doc = await this.model.findOneAndUpdate(
  { workflowId, version: expectedVersion }, // ← the guard lives in the filter
  { $set: setFields, $inc: { version: 1 } },
  { new: true },
);
if (!doc) throw new ConcurrencyConflictError(workflowId, expectedVersion);

If the customer's "yes" and the TTL sweep move the same workflow, one wins. The other gets a ConcurrencyConflictError instead of overwriting state.

The hard part: the booking agent

The architecture was the easy decision, because hexagonal DDD is a known shape. The booking agent was the hard part.

I did not find a public pattern for an agent that books real appointments, takes real payments and holds a multi-turn negotiation over WhatsApp. So I had to design each piece myself. A parent graph routes to booking, information and account subgraphs. A preflight check blocks any mutating tool whose validator has not cleared it, so the agent cannot confirm a booking it cannot make. A checkpointer per chat, plus short-lived cached state, carries the conversation through a customer's silence.

With no outside benchmark for a good booking agent, I also built the evaluation harness.

What the structure costs

This is a lot of structure for one person: ports, tokens, adapters, a guard, a state machine, a contract package, an eval suite. For a weekend project it would be absurd. Here it lets a team of agents work on tenants, integrations, payments and AI bookings without breaking the rules that keep them safe.

The Matcha case study shows the product this repository runs.