Saturday 5th December 2026
Ho Chi Minh, Vietnam

Tenants as Data: lessons from running two Toyota markets on one stack

Every multi-tenant platform eventually asks how to add a new customer without copy-pasting half the infrastructure. This post shows how a telematics integration service handles it with Terraform. Adding a market is a small code change, not a new project.

The problem

The service connects our platform to Toyota’s telematics service providers (TSPs). It serves two markets, each of which we treat as a tenant, called a channel in the code:

  • tmca for Australia
  • tnz for New Zealand

Each tenant needs its own API path (/tmca/..., /tnz/...), its own routing rules, its own DNS names and API key, and tenant-specific behaviour in the application. We also needed demo tenants (tmcademo, tnzdemo) that behave like the real ones but talk to a mock TSP instead of Toyota.

Three ways to model tenants

ModelIsolationCostConsistencyOps effort
Stack per tenant (copy of the code)HighHighDrifts over timeHigh
Workspace/state per tenantHighHighGoodMedium
Shared stack, tenants via for_eachLowLowExcellentLow

The two markets have near-identical behaviour, traffic is modest, and the product team wanted new markets quickly. We chose the shared stack. The trade-offs are covered later.

Pattern 1: tenants are a list, everything else is derived

The whole tenant model starts with one local value:

locals {
  # Real Toyota TSP
  channels_integrated = ["tmca", "tnz"]

  # Mock TSP, for demos and testing
  channels_mocked = ["tmcademo", "tnzdemo"]

  channels_served = concat(local.channels_integrated, local.channels_mocked)

  primary_channel        = local.channels_integrated[0]
  primary_mocked_channel = local.channels_mocked[0]
  has_mocked_channels    = length(local.channels_mocked) > 0

  channel_routing_priorities = {
    "tmca"     = 15
    "tnz"      = 20
    "tmcademo" = 65
    "tnzdemo"  = 70
  }
}

Service names, DNS records, API Gateway resources and discovery entries are all computed from these lists. Nothing else in the codebase hard-codes the tenant names.

Pattern 2: one primary, lightweight aliases for the rest

Running a full ECS service, load balancer and gateway per tenant would defeat the point. Instead, the primary tenant owns the heavy resources, and every other tenant gets only a thin alias that points at it.

locals {
  ambassador_service_names = { for chan in local.channels_integrated : chan => "${chan}-ambassador" }
}

# Real service, created once, for the primary tenant
resource "aws_service_discovery_service" "ambassador_service" {
  name = local.ambassador_service_names[local.primary_channel]
  # ...
}

# Alias per additional tenant, as a CNAME to the primary
resource "aws_service_discovery_service" "ambassador_service_alt" {
  for_each = { for k, v in local.ambassador_service_names : k => v if k != local.primary_channel }
  name     = each.value

  dns_config {
    namespace_id = local.service_registry_id
    dns_records {
      ttl  = 2
      type = "CNAME"
    }
    routing_policy = "WEIGHTED"
  }
}

resource "aws_route53_record" "ambassador_reference_record_alt" {
  for_each = { for k, v in local.ambassador_service_names : k => v if k != local.primary_channel }
  name     = "${each.key}.ambassador."
  type     = "CNAME"
  zone_id  = data.aws_route53_zone.private_hosted_zone_ambassador.id
  ttl      = "600"
  records  = ["${local.ambassador_service_name_primary}.service."]
}

The if k != local.primary_channel filter in the for_each expression is the idiom doing the work. Internally, tnz-ambassador resolves to tmca-ambassador, so there is one set of containers and as many names as tenants.

Pattern 3: a per-tenant API surface

All tenants share one REST API in API Gateway, and each gets its own path. First we build a map from each tenant to the stack that serves it:

locals {
  channel_interfaces_integrated = { for chan in local.channels_integrated : chan => local.primary_channel }
  channel_interfaces_mocked     = { for chan in local.channels_mocked     : chan => local.primary_mocked_channel }
  channel_interfaces            = merge(local.channel_interfaces_integrated, local.channel_interfaces_mocked)
}

Every API resource then iterates over it:

resource "aws_api_gateway_resource" "adapter_interface_channel_root" {
  for_each    = local.channel_interfaces
  rest_api_id = data.aws_api_gateway_rest_api.tsp_integration.id
  parent_id   = data.aws_api_gateway_rest_api.tsp_integration.root_resource_id
  path_part   = lower(each.key)      # /tmca, /tnz, /tmcademo, /tnzdemo
}

The same for_each creates the /services/{proxy+} and vehicle endpoints, their methods and integrations, and a request validator per tenant.

Pattern 4: stage variables pick the backend

Each tenant gets its own API Gateway deployment through a reusable module. The interesting part is how a tenant chooses between the real and the mocked backend:

module "adapter_api_deployment" {
  for_each = local.channel_interfaces
  source   = "git@github.com:<org>/<tsp-services-repo>.git//component-infra/modules/tsp-adapter-stage?ref=main"

  channel = each.key

  stage_variables = {
    "adapter_vpc_link_id"    = contains(local.channels_mocked, each.key) ? aws_api_gateway_vpc_link.adapter_mocked[0].id    : aws_api_gateway_vpc_link.adapter.id
    "ambassador_vpc_link_id" = contains(local.channels_mocked, each.key) ? aws_api_gateway_vpc_link.ambassador_mocked[0].id : aws_api_gateway_vpc_link.ambassador.id
    "mock_vpc_link_id"       = contains(local.channels_mocked, each.key) ? aws_api_gateway_vpc_link.mock_demo[0].id         : aws_api_gateway_vpc_link.mock.id
  }

  routing_rule_priority = local.channel_routing_priorities[each.key]
}

The API definitions are identical for every tenant. A VPC link stage variable decides whether a request goes to the real network load balancer or the mocked one. That is how /tnzdemo and /tnz can share an API model but never share a backend.

Pattern 5: mock tenants as first-class citizens

Demo tenants are a normal part of the stack. The mocked adapter is configured differently from the real one:

adapter_mocked_env_vars = concat([
  { name = "TSP_VEHICLES_HOST", value = "http://${local.mock_demo_service_name_primary}.service:8080" },
  # Demo traffic must not trigger real failure alerts
  { name = "FAILURE_TOPIC", value = "" },
  # No real credentials needed
  { name = "tsp.apikey", value = "mock" },
  { name = "SHOULD_SEND_MOCK_DATA", value = "true" },
  # Tenant-to-country mapping
  { name = "vehicle.channel.countries.AU", value = upper(local.channels_mocked[0]) },
  { name = "vehicle.channel.countries.NZ", value = upper(local.channels_mocked[1]) },
  { name = "TSP_CACHE_TABLE_NAME", value = aws_dynamodb_table.tsp_data_dynamodb_table_mocked.name },
], ...)

The mocked stack gets:

  • its own DynamoDB cache table, so test data can never pollute production data
  • stubbed credentials, so no real secrets are exposed to demo traffic
  • no failure-topic publishing, so demo traffic doesn’t page anyone

The mocked resources are also optional. Each is wrapped in for_each = local.has_mocked_channels ? {...} : {}, so an environment with no mocked channels creates none of them.

Tenants vs environments: two different axes

It is easy to blur these, so we keep them separate:

  • Environments (dev, test, prod) are separated by AWS account. Terragrunt reads one config file per account.
  • Tenants (tmca, tnz) are separated inside a stack with for_each.

Each environment therefore runs the same code and creates the same tenants. A single terraform apply updates every tenant in that account.

Pitfalls and lessons learned

1. No compute isolation. Tenants share ECS tasks and load balancers. A bad deploy or a noisy neighbour affects both markets. This is acceptable for two similar markets and wouldn’t be for tenants with different SLAs or compliance needs.

2. The primary is positional. primary_channel = channels_integrated[0] means reordering the list changes which tenant owns the real resources, which causes recreation. An explicit primary_channel variable would be safer.

3. Index-based assumptions don’t scale. Mapping AU to channels[0] and NZ to channels[1] works for two tenants. A third market would need code changes, not just a list entry.

4. for_each keys are identities. Terraform tracks resources by key, so renaming a tenant is a destroy and create, or a terraform state mv. Choose tenant keys carefully and treat them as permanent.

5. Parallel lists drift. Tenant names, priorities and country codes live in separate structures. It is easy to update one and forget another.

6. Redeployments need a nudge. API Gateway deployments don’t redeploy automatically when methods change. We pass a redeployment_change_hash built from the file contents and the key integration IDs, which forces a new deployment when they change.

What I’d do next

The biggest improvement is to replace the parallel lists with one object per tenant. This is my proposed design, not what the repo does today:

variable "tenants" {
  type = map(object({
    country  = string
    priority = number
    mocked   = bool
  }))
  default = {
    tmca     = { country = "AU", priority = 15, mocked = false }
    tnz      = { country = "NZ", priority = 20, mocked = false }
    tmcademo = { country = "AU", priority = 65, mocked = true }
    tnzdemo  = { country = "NZ", priority = 70, mocked = true }
  }
}

That removes the index lookups and the drift between lists. Adding a market becomes a single, self-describing entry, and you can derive integrated, mocked and primary from it with simple for expressions. Beyond that:

  • extract the tenant-specific resources into a module
  • run terraform plan per environment in CI, with policy checks such as Checkov
  • define an exit criterion for graduating a tenant to its own isolated stack, for example a stricter SLA, a different data residency rule or sustained heavy traffic

Takeaways

  1. Model tenants as data, and derive every name, route and record from it.
  2. Share the expensive parts, alias the cheap ones. A primary tenant owns the compute, and the others own names and routes.
  3. Use stage variables or similar indirection so one API definition can serve real and mock backends.
  4. Treat mock tenants as real citizens with isolated data, stubbed secrets and no alerting.
  5. Keep environments and tenants on separate axes.
  6. Know where shared tenancy stops working, and write down when you would split.

Multi-tenancy in Terraform doesn’t need a framework. A map, for_each and a few conditional expressions go a long way, as long as you are honest about the isolation you’re giving up.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top