Brass balance scale weighing stacks of server modules of different sizes, representing cost attribution per tenant

SaaS Cost per Tenant: Designing a Tenant Cost Attribution Pipeline

•11 min read

Knowing your SaaS cost per tenant lets you price tiers on data instead of instinct. Building the software is mostly a one-time investment (we covered those price ranges in our guide to how much custom software costs in 2026). Running it is different: it comes back every month and grows with every customer you add. This article covers the system that tells you which customers drive that monthly bill. That means the data model, the pipeline, the allocation rules, the trade-offs between approaches, and the places where it usually breaks.

Why SaaS cost per tenant is hard to compute

AWS's own write-up on calculating tenant costs in SaaS environments puts it plainly: in single-tenant environments the calculation is straightforward, but in a pooled model, where tenants share resources, attribution gets much harder. If every tenant has its own account or its own tagged resources, you just read the bill. If one database cluster, one queue and one container fleet serve everyone, the bill has no tenant column at all.

Most real products are hybrids: pooled for the long tail, siloed for a few large customers. The AWS Well-Architected SaaS Lens describes the general solution: correlate tenant consumption data with infrastructure costs, and automate it using Cost and Usage Report data. In practice that gives you a system with three inputs and one output:

  • Cost data: what the cloud provider charged, per resource, per day.
  • Consumption data: what each tenant actually used, emitted by your application.
  • Allocation rules: how to split costs you cannot measure per tenant.
  • Output: a daily per-tenant cost ledger that adds up exactly to the bill.

Classify every dollar into three cost classes

Before writing code, decide which class each line of the bill belongs to. This decision drives everything else.

  1. Direct cost. The resource belongs to one tenant: a dedicated database, a per-tenant bucket, an enterprise silo. You attribute it through a tag or an account ID.
  2. Shared, metered cost. A pooled resource where you can measure each tenant's share through a proxy: requests, CPU-milliseconds, stored bytes, messages processed, LLM tokens. You split the cost proportionally to that meter.
  3. Shared, unmetered cost (overhead). NAT gateways, observability, CI runners, the control plane. Nobody "uses" these per request. You need an explicit policy, and the common options are an equal split, tier-weighted shares, or a hybrid where direct costs go direct and shared costs follow usage (this multi-tenant AWS guide lists those three).

One design decision pays off later: report overhead as its own visible line per tenant instead of folding it invisibly into the metered costs. When someone asks why a small tenant looks expensive, you will want to see how much of that comes from the policy and how much from real usage.

Architecture of a tenant cost attribution pipeline

Cloud billing export (daily) ───────┐
                                    ├──> Allocation job (daily, idempotent) ──> tenant_cost_daily
App usage metering (events→rollups) ┘                ^
Tenant registry + versioned allocation rules ────────┘

The cost source

On AWS, the source of truth is the Cost and Usage Report. The CUR documentation describes Data Exports with CUR 2.0 as the new and recommended way to receive detailed cost and usage data. According to the Data Exports FAQ, you define exports with basic SQL over AWS-provided tables, and they are delivered on a recurring basis. Two settings matter for tenant attribution:

  • Include resource IDs, which also adds the tag column you need to read tenant_id.
  • Split cost allocation data, which creates line items per ECS task or Kubernetes pod. The split line item reference notes this is limited to Amazon ECS (including Fargate), AWS Batch and Amazon EKS. The FAQ also notes this data is not currently available in the FOCUS 1.2 export, so choose CUR 2.0 if you need it.

Other clouds have equivalent billing exports. The design below does not depend on the provider, only on getting a daily, line-level file into your warehouse.

Tags for direct costs

User-defined tags do nothing for billing until you activate them. Per the AWS documentation on activating cost allocation tags, newly applied tags can take up to 24 hours to appear for activation, and up to another 24 hours to activate. The UpdateCostAllocationTagsStatus API lets you activate tags in bulk. Do not rely on humans to remember tags. Enforce them in infrastructure as code:

# Terraform: every resource in a tenant silo inherits these tags
provider "aws" {
  alias  = "tenant"
  region = var.region
  default_tags {
    tags = {
      tenant_id   = var.tenant_id   # opaque ID, never a customer name
      cost_class  = "direct"
      environment = var.environment
    }
  }
}

Metering for pooled resources

Emit usage where tenant context is already known and trusted, which usually means right after authentication. Do not write one row per request into your transactional database. Aggregate in memory and flush rollups.

// Express-style middleware; req.tenant is resolved from the auth token, never the body
app.use((req, res, next) => {
  const start = process.hrtime.bigint();
  res.on("finish", () => {
    const ms = Number(process.hrtime.bigint() - start) / 1e6;
    usage.add(req.tenant.id, "api.requests", 1);
    usage.add(req.tenant.id, "api.ms", ms);
  });
  next();
});

The buffer flushes every few seconds with an idempotency key, so retries after a timeout do not double count:

INSERT INTO usage_rollup (instance_id, flush_id, tenant_id, meter, hour, qty)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (instance_id, flush_id, tenant_id, meter, hour) DO NOTHING;

Background jobs must carry tenant_id in their payload and meter their own work. For LLM features, record the token counts that the provider returns with each response, keyed by tenant.

Data model

CREATE TABLE cost_line (
  usage_date     date        NOT NULL,
  service        text        NOT NULL,
  resource_id    text        NOT NULL,
  tenant_tag     text,                    -- null when untagged
  net_cost       numeric(18,6) NOT NULL,  -- never float
  currency       char(3)     NOT NULL,
  export_version text        NOT NULL,
  PRIMARY KEY (usage_date, service, resource_id, export_version)
);

CREATE TABLE allocation_rule (
  service    text NOT NULL,
  cost_class text NOT NULL CHECK (cost_class IN ('direct','metered','overhead')),
  meter      text,              -- for metered: which usage meter splits it
  policy     text,              -- for overhead: equal | proportional | tier_weight
  valid_from date NOT NULL,
  valid_to   date
);

CREATE TABLE tenant_cost_daily (
  usage_date date NOT NULL,
  tenant_id  text NOT NULL,     -- includes the pseudo-tenant 'unallocated'
  service    text NOT NULL,
  cost_class text NOT NULL,
  amount     numeric(18,6) NOT NULL,
  currency   char(3) NOT NULL,
  run_id     uuid NOT NULL,
  PRIMARY KEY (usage_date, tenant_id, service, cost_class)
);

The unallocated pseudo-tenant matters. Untagged resources and services with no usage data go there, so the ledger always sums to the bill and the gap stays visible.

The allocation job

for each day D in the recompute window:
  begin transaction
  delete from tenant_cost_daily where usage_date = D
  for each service S with cost on D:
    rule = active_rule(S, D)
    if rule.class == direct:
      for each line L: add(L.tenant_tag if valid_tenant(L.tenant_tag) else 'unallocated', L.net_cost)
    elif rule.class == metered:
      shares = usage(rule.meter, D) / sum(usage(rule.meter, D))
      if no usage: add('unallocated', cost(S, D))
      else: for each tenant t: add(t, cost(S, D) * shares[t])
    else:  # overhead, after direct and metered are done
      distribute(cost(S, D), rule.policy)
  round with the largest-remainder method so cents add up
  assert sum(tenant_cost_daily on D) == sum(cost_line on D)
  commit

Three properties make this job safe to run repeatedly:

  • Delete-and-replace per day inside one transaction. Re-running gives the same answer, with no duplicate rows and no partial days.
  • A recompute window, not just "yesterday". The CUR documentation notes that AWS keeps updating reports after delivery starts. Treat past days as mutable and recompute them each run.
  • A balance assertion. If the allocated total does not match the source total, fail loudly. A cost ledger that silently drifts is worse than none.

Kubernetes and other pooled compute

A pod in a shared deployment serves many tenants, so pod-level cost is still a shared, metered cost. You need two layers. First, get the cost of the workload. Then split it with your application meters. For the first layer you have two options:

If you run namespace-per-tenant for large customers, those namespaces become direct costs, and only the shared ones need meters.

Failure modes to design for

  • Untagged or mistagged resources. Validate tag values against the tenant registry. Unknown values go to unallocated. Alert when the unallocated share passes a threshold you choose.
  • Lost usage data. If a deploy drops an in-memory buffer, the tenants on that instance are under-counted and everyone else's share inflates. Flush often, and consider a durable outbox for meters you bill on.
  • Discounts and commitments. Allocate net or effective cost, not list price. In CUR 2.0, split_line_item_net_split_cost is defined as the effective cost of a task or pod after all discounts.
  • Rule changes. Version rules with valid_from/valid_to. Changing a policy should not silently rewrite last quarter's margins.
  • Multiple currencies. Store the currency per line and convert only at reporting time, with a recorded rate.

Security and privacy

  • Cost allocation tags are visible to anyone with billing access. Use opaque tenant IDs, never customer names or emails.
  • Per-tenant cost data is commercially sensitive. Restrict who can read it. If you show it to tenants (showback), enforce row-level security in the database instead of filtering in the API layer.
  • Always derive tenant_id for metering from the authenticated session. If a client can set it, a client can shift costs.

Trade-offs between approaches

  • Account or silo per tenant. The cleanest attribution, because the bill is already split (Scale Factory notes it suits products with a few large tenants). Operational overhead grows with tenant count.
  • Pooled with metering. Efficient infrastructure, but attribution is only as good as your meters and your choice of proxy.
  • Buy vs. build. OpenCost or a commercial cost tool gives you visibility quickly. Build your own pipeline when cost per tenant feeds pricing, quotas or billing logic, because then you need full control of the rules.
  • Daily vs. hourly. Daily is enough for margin analysis. Hourly helps you catch noisy neighbors, but it multiplies storage and recompute time.

Common mistakes

  • Splitting the whole bill by request count, so a tenant running heavy reports looks as cheap as one making health checks.
  • Using float for money and then chasing rounding mismatches against the invoice.
  • Dropping untagged costs instead of keeping them in an unallocated bucket.
  • Running the job only for yesterday and never picking up restated bills.
  • Hiding overhead inside metered costs, which makes small tenants look unprofitable for the wrong reason.

Checklist

  1. Classify every billed service as direct, metered or overhead.
  2. Enable a line-level billing export (CUR 2.0 on AWS) with resource IDs, and split cost data if you run containers.
  3. Enforce tenant_id tags in IaC and activate them in billing.
  4. Meter pooled resources from authenticated context, with idempotent flushes.
  5. Store rules with validity dates and money as numeric.
  6. Run an idempotent daily job over a recompute window, with a balance assertion.
  7. Track unallocated as a metric and alert on it.
  8. Lock down access to per-tenant cost data.

If you are planning a multi-tenant product and want cost attribution built in from the first sprint rather than added later, that is the kind of architecture our custom software development team designs and builds.

Frequently asked questions

Do I need cost per tenant before I have many customers?

You do not need the full pipeline on day one. You do need tenant_id in your tags, logs and usage events from the start, because adding tenant context later is much harder than computing costs later.

Is AWS Cost Explorer enough to see cost per tenant?

For siloed resources with activated tags, it shows per-tenant spend directly. For pooled resources it cannot, because the bill has no tenant dimension. You need the CUR joined with your own usage data, and pod-level splits are only available in the CUR.

How should I attribute LLM API costs to tenants?

Treat them as a shared, metered cost. Record the token usage that the provider returns with each call, keyed by the tenant that triggered it, and split the provider's invoice in proportion to those tokens.

Comments

No comments yet. Be the first to share what you think.

Leave a comment

It is never published.