Post

Multi-tenant REST with Trysil.Http

Multi-tenant REST with Trysil.Http

SaaS applications almost always need multi-tenancy, and “one database per tenant” is the shape that keeps the promise easiest to state: each customer’s data lives in its own database, with no tenant-ID column on every row and no WHERE tenant_id = ? that one forgotten query can leak through.

The last post built a single-database API. This one serves many databases from the same controllers, with Trysil.Http.MultiTenant.

Two pieces

The module is small, and it is two things:

  • TTTenantConfig (Trysil.Http.MultiTenant.Config) - an abstract class you extend. Given a tenant name, it says which FireDAC connection definition that tenant uses and with which parameters.
  • TTMultiTenant<T> (Trysil.Http.MultiTenant) - a thread-safe registry of tenants, one singleton per config class. GetOrAdd(AName) returns the tenant, building it and registering its connection the first time the name is asked for.

Everything else - where the name comes from, which names exist, what to answer for an unknown one - is yours, and this post is mostly about doing that part right.

The tenant configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
type
  TAppTenantConfig = class(TTTenantConfig)
  strict protected
    function GetConnectionName: String; override;
    function GetParameters: TTFireDACConnectionParameters; override;
  end;

function TAppTenantConfig.GetConnectionName: String;
begin
  result := Format('Tenant_%s', [FName]);
end;

function TAppTenantConfig.GetParameters: TTFireDACConnectionParameters;
begin
  result := TTFireDACConnectionParameters.Create(
    'MSSQL',
    TAppConfig.Instance.DatabaseServer,
    TAppConfig.Instance.DatabaseUser,
    TAppConfig.Instance.DatabasePassword,
    Format('App_%s', [FName]));
end;

FName is the tenant name the registry passed to the constructor. Two rules come with the two methods. They run outside any lock, so two requests asking for a new tenant at the same moment can both run them: they must be thread-safe. And GetParameters must return the same parameters every time, because registering the same definition twice is accepted only when it is identical.

Where the tenant name comes from

Three common sources, each with its own trade-off:

  • Subdomain - acme.api.example.com. Clean URLs, but it costs you a DNS entry and a certificate that covers the wildcard.
  • Header - X-Tenant: acme. Easy for a client that already knows which tenant it works for.
  • A claim in the token - the tenant is part of the identity the server signed. The only one of the three that the client cannot simply change.

All three arrive with the request, and that matters more than it looks, for one reason specific to how Trysil.Http serves a request.

The context is built before anyone is authenticated

The server builds your per-request context first, then resolves the route, then runs authentication, then checks the areas, and only then calls the controller. It has to be in that order: authentication is your code and it receives the context, because deciding who the caller is usually means asking the database.

So whatever TAppContext.Create does is reachable by anyone, for any URI, with no token at all. If it resolved the tenant and opened its database, an anonymous caller rotating the X-Tenant header would make the server open connections - or try to - at will.

The right place is one step later: the constructor of the controller. By then the route exists and authentication has run, so a request that reaches it is one you meant to serve.

A base controller that owns the tenant

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
type
  TAppController = class(TTHttpController<TAppContext>)
  strict private
    FConnection: TTConnection;

    function GetTenantName: String;
  strict protected
    FTenantContext: TTHttpContext;
  public
    constructor Create(
      const AContext: TAppContext;
      const ARequest: TTHttpRequest;
      const AResponse: TTHttpResponse); override;
    destructor Destroy; override;
  end;

constructor TAppController.Create(
  const AContext: TAppContext;
  const ARequest: TTHttpRequest;
  const AResponse: TTHttpResponse);
var
  LTenant: TTTenant<TAppTenantConfig>;
begin
  inherited Create(AContext, ARequest, AResponse);
  LTenant := TTMultiTenant<TAppTenantConfig>.Instance.GetOrAdd(
    GetTenantName);
  FRequest.User.Tenant := LTenant.Name;
  FConnection := LTenant.Connection.CreateConnection;
  FTenantContext := TTHttpContext.Create(FConnection);
end;

destructor TAppController.Destroy;
begin
  if Assigned(FTenantContext) then
    FTenantContext.Free;
  if Assigned(FConnection) then
    FConnection.Free;
  inherited Destroy;
end;

The Assigned checks in the destructor are not decoration: when the constructor raises, Delphi calls the destructor on the half-built object, and the fields that were never assigned are nil.

Your entity controllers now extend TAppController and use FTenantContext where the single-database version used FContext.Context. That is the only change they see. Whether FTenantContext points at App_acme or App_globex is invisible to them.

Resolving the name against a closed list

1
2
3
4
5
6
function TAppController.GetTenantName: String;
begin
  result := FRequest.Headers.Value['X-Tenant'];
  if not TAppConfig.Instance.Tenants.Contains(result) then
    raise ETHttpNotFound.CreateFmt('Unknown tenant %s', [result]);
end;

TAppConfig.Instance.Tenants is the list of tenants you actually have, loaded at startup from a configuration file or a master database. Checking against it is the step that cannot be skipped. A tenant name is request data, and it ends up as a FireDAC connection definition name and, here, as part of a database name. GetOrAdd refuses a name that cannot be a name at all - it raises ETTenantNameNotValid for ../, for a separator smuggled into a connection string, for an empty string - but that is a floor: acme and wilecoyote both pass it, and only you know which of them is a customer.

Because unknown names are turned away first, a failure inside GetOrAdd is a real server-side problem - the database is down, the parameters are wrong - and a 500 is the honest answer. GetOrAdd always raises ETTenantUnavailable in that case, carrying TenantName and OriginalClassName, never the underlying exception, so the class you see does not depend on timing. It descends from ETException, not from the HTTP exceptions, so it becomes a 500 with the fixed error body, and the reason goes to the log only. If you ever resolve a name without the list in front, catch it and raise ETHttpNotFound yourself, or every unknown tenant answers 500.

Failures are also rate limited. A name that failed is remembered for FailureCooldown milliseconds (5000 by default, 0 disables it), and calls inside that window fail without touching the disk or the network. The failure is not memoized forever on purpose: a tenant you repair must come back without a restart.

Adding a tenant at runtime

A new customer is a new database plus a new name in the list. Nothing else: the first request that names the tenant makes GetOrAdd build it and register its connection, and from then on it is served like the others. No redeploy, no restart.

Remove(AName) is the other direction, with a narrower meaning than it suggests: it makes the registry forget the tenant, so the next GetOrAdd builds it again from fresh configuration. It does not close the connection pool and it does not revoke the customer. Revoking is taking the name out of your list, which is checked first.

Shared data

One database per tenant leaves one awkward class of data: what is shared by all of them - the tenant list itself, feature flags, data the vendor reads across customers. Keep it in a master database that no tenant context can reach. A separate connection, read at startup or by vendor-only endpoints, never by TAppController, means a tenant request cannot fetch shared data from the wrong place, because it has no handle to it.

The tenant in the log

The constructor above sets FRequest.User.Tenant. That one line is what puts the tenant in the request log: TTHttpLogResponse copies the user, tenant included, into the response entry.

Two details are worth knowing. The response entry is the one that carries it, because the request entry is written before routing and authentication, when nobody knows the tenant yet - the two entries share the TaskID, so a writer that needs the tenant of a request reads it from the response. And write an identifier there, a name or a code: the tenant is copied into every entry as it is, and no redaction reaches it.

Without it, after an incident on an installation with one database per tenant, the log tells you who, what and when, and not on which database.

Closing

Trysil.Http.MultiTenant gives you the registry and the connection plumbing. The decisions that make it safe are in your code and they fit in one base controller: resolve the tenant after authentication, check the name against the tenants you have, choose the status for a tenant that cannot be served, and write the tenant into the log.

One hole is still open. The tenant comes from a header, and a header is whatever the client sends. A user of acme with a valid session can send X-Tenant: globex. The next post adds JWT authentication and closes it, by making the tenant part of what the server verifies.

This post is licensed under CC BY 4.0 by the author.