Architecture

One door to the database, enforced by lint

Any route or job could query the task tables directly, and many did. I put them behind a repository and let a lint rule hold the line while the old code moved over.

The problem

Any route or background job could query the task and company tables directly, and many did. The same operation existed as a hand-written query in dozens of places.

That made every rule fragile. Changing how a task is scoped to a client meant finding every query that touched it. A missed one did not fail. It was quietly wrong, in a system where each client's data has to stay separate.

One door

I put each area of the database behind a repository: the only code allowed to touch those tables. A route shrinks to decoding the request, calling the repository and encoding the answer. A background job shrinks the same way: load context, call the repository, classify the result.

The repository throws only its own typed errors, never raw database errors. The route wrappers translate them into HTTP responses, so a handler no longer checks every query result by hand.

Same methods, two callers

There are two kinds of caller. A user's request arrives with a database client where the database itself enforces who can see what. A background job has full access and has to check ownership on its own.

Two factories, one bodyIllustrative
// In a route handler: the user's client. The database enforces access.
export function repoForRequest(client: DbClient): TasksRepo {
  return buildRepo(client);
}

// In a background job: full access. The caller must check ownership.
export function repoForJob(client: DbClient): TasksRepo {
  return buildRepo(client);
}

function buildRepo(client: DbClient): TasksRepo {
  return {
    forClient: (clientId) => buildBoundRepo(client, clientId),
    tasks: { findById: (id) => findTaskById(client, id) /* ...written once */ },
  };
}

Both factories return the same set of methods, built by the same function. The code reads the same either way, and the difference is visible in one line: the name of the factory at the call site.

If a method ever needs to behave differently for a route and a job, I treat that as a smell. The difference belongs in the caller, or in the input.

Bind the tenant once

Calling forClient with a client id fixes the tenant up front. The id is part of the binding, not an argument someone has to remember on every call.

A bound write checks whose task it isIllustrative
// Called as: repo.forClient(clientId).comments.create(input)
async function createComment(db: DbClient, boundClientId: string, input: NewComment) {
  const task = await loadTask(db, input.taskId);
  if (!task) throw new NotFoundError('task');

  // The tenant was fixed when the repo was bound. A mismatch is refused,
  // even for a job running with full access.
  if (task.clientId !== boundClientId) {
    throw new ValidationError('task belongs to another client');
  }
  return insertComment(db, input);
}

For a user's request the database would already block this. The explicit check gives a job, which has full access, the same guarantee. A job that tries to write a comment on another client's task is refused instead of succeeding quietly.

The test I use for what goes behind the binding: would calling this for the wrong tenant be silently wrong, or loudly wrong? If silently, it goes behind forClient.

A route handler and a background job each get a tasks repository through their own factory. The repository is the only path to the tasks schema, and forClient binds the tenant. A new direct query is caught by a lint rule that reads a baseline list, and CI fails.
Two callers, one repository. Anything that goes around it fails the build.

A list that only shrinks

A boundary nobody enforces erodes. I added a lint rule that bans direct access to the task tables outside the repository, and put every existing violation into a checked-in list: file path, and how many direct calls that file is allowed.

What the list looks likeIllustrative
{
  "app/api/tasks/route.ts": 12,
  "app/dashboard/page.tsx": 2,
  "components/Sidebar.tsx": 1,
  "lib/ai/summaries.ts": 2
}

The rule counts the direct calls in each file and compares the count with the list.

The rule fails in both directionsIllustrative
create(context) {
  const allowed = baseline[fileOf(context)] ?? 0;
  const hits = [];
  return {
    [DIRECT_TABLE_ACCESS](node) {
      hits.push(node);
    },
    'Program:exit'(node) {
      // More than the list allows: new debt. Fail.
      for (const hit of hits.slice(allowed)) {
        context.report({ node: hit, message: 'Go through the repository.' });
      }
      // Fewer than the list says: the list is stale. Fail until it is lowered.
      if (hits.length < allowed) {
        context.report({ node, message: 'Lower this file\'s entry in the list.' });
      }
    },
  };
}

More calls than the list allows is an error. Fewer is also an error, until the entry is lowered or deleted. So fixing a file forces the list down, and nothing can push it back up.

That is what let the change happen alongside normal work. Old code moved one file at a time, and the problem could not get worse in the meantime.

One lesson came from an earlier attempt. I found the guards against direct table access were silently dead, because overlapping lint blocks had collapsed into one. I replaced them with a single dedicated rule checked in CI.

What changed

What is not finished: the tasks boundary is complete, but the companies boundary is enforced only for its original tables. A few newer tables still have direct callers, and the repo says so plainly.