Skip to content

Per-tenant cost attribution on PaaS — tagging, reporting, and chargeback patterns

Your agency invoices customers a flat hosting fee, but two tenants are quietly consuming 60% of the PaaS bill. Until you can attribute compute to tenants in a defensible way, you can't price anyone correctly.

You’re a SaaS company hosting tenant environments on a managed PaaS, or an agency hosting 30 client sites on the same provider. The monthly bill arrives. It’s gone up 22% since January. You don’t know who’s responsible. Two engineers spend a day in spreadsheets, trying to reconstruct which tenant grew, what node was added, which database doubled in size. You make a guess, raise three customers, and lose two of them because the increase wasn’t actually theirs. The missing capability is not budgeting — it’s attribution.

What’s happening

PaaS providers bill per environment, per cloudlet-hour, per outbound GB, per backup GB. They do not bill per tenant — because “tenant” is your construct, not theirs. If you’ve adopted one-environment-per-tenant, attribution is trivial: the environment name is the tenant. If you’re running shared environments with namespaces, you need to build attribution yourself.

Attribution has three layers and most teams only build one:

  1. Tagging at the resource layer. Every environment, every node group, every backup target gets a tenant=<slug> and tier=<level> tag. This is the foundation — without it, nothing downstream works.
  2. Metering at the workload layer. Inside a shared environment, you need to measure per-tenant compute (PHP-FPM time per vhost), per-tenant storage (filesystem usage per tenant directory), per-tenant database size (per-database or per-schema), and per-tenant outbound traffic (LB access log).
  3. Reporting at the customer layer. A monthly export that maps tenant_slug → compute_hours + storage_gb + egress_gb + database_gb + support_minutes. This is what becomes the line items on the customer invoice — or what defends the flat price you charge.

Skip layer 2 and you can split fixed costs by tenant count but you can’t explain why one tenant should pay more. Skip layer 3 and you’ve measured but never communicated.

How to verify

Check that every environment has the required tags:

curl -fsS -X POST "${JEM_API}/1.0/environment/control/rest/getallenvs" \
  -d "session=${SESSION}" \
  | jq -r '.infos[] | "\(.env.envName)\t\(.env.properties.tags // "MISSING")"' \
  | grep -E "MISSING|^$" || echo "all environments tagged"

Per-vhost PHP execution time on a shared LiteSpeed container — the canonical “who’s burning the CPU” question:

# Aggregate request_time by Host header from access log
awk '{
  host=""; for(i=1;i<=NF;i++) if($i ~ /^"GET|^"POST|^"PUT/) { host=$(i-1) }
  print host, $NF
}' /usr/local/lsws/logs/access.log \
  | awk '{sum[$1]+=$2; cnt[$1]++} END {for(h in sum) printf "%-40s %8d reqs %10.2f sec total\n", h, cnt[h], sum[h]}' \
  | sort -k4 -rn | head -20

Per-tenant filesystem usage (assumes tenants are subdirectories under /data/tenants/):

du -sh /data/tenants/* | sort -h

Per-database size in PostgreSQL:

SELECT datname,
       pg_size_pretty(pg_database_size(datname)) AS size,
       pg_database_size(datname) AS bytes
FROM pg_database
WHERE datname NOT IN ('postgres','template0','template1')
ORDER BY bytes DESC;

If any of these checks returns “MISSING” or a tenant you don’t have a slug for, your tag discipline broke down somewhere — usually in a manual environment created outside the provisioning pipeline.

The fix

A pragmatic chargeback stack that you can run today on Jelastic + PostgreSQL + a small Python aggregator. Three pieces.

Piece 1 — enforce tags at provisioning. Wrap environment creation so a tenant slug is mandatory:

#!/usr/bin/env bash
set -euo pipefail

TENANT_SLUG="${1:?usage: $0 <tenant-slug> <tier>}"
TENANT_TIER="${2:?usage: $0 <tenant-slug> <tier>}"
ENV_NAME="${TENANT_SLUG}-prod"

# Sanity check slug format
[[ "$TENANT_SLUG" =~ ^[a-z0-9-]+$ ]] || { echo "slug must be kebab-case ascii"; exit 1; }
[[ "$TENANT_TIER" =~ ^(standard|premium|trial)$ ]] || { echo "tier must be standard|premium|trial"; exit 1; }

curl -fsS -X POST \
  "${JEM_API}/1.0/environment/control/rest/setenvproperty" \
  -d "session=${SESSION}" \
  -d "envName=${ENV_NAME}" \
  -d 'name=tags' \
  --data-urlencode "value={\"tenant\":\"${TENANT_SLUG}\",\"tier\":\"${TENANT_TIER}\",\"created\":\"$(date -u +%Y-%m-%d)\"}"

Piece 2 — daily collection cron. Runs on a small VM that has API access. Writes to a Postgres tenant_usage_daily table:

CREATE TABLE IF NOT EXISTS tenant_usage_daily (
  collected_at   date    NOT NULL,
  tenant_slug    text    NOT NULL,
  tier           text    NOT NULL,
  env_name       text    NOT NULL,
  cloudlet_hours numeric NOT NULL DEFAULT 0,
  storage_gb     numeric NOT NULL DEFAULT 0,
  egress_gb      numeric NOT NULL DEFAULT 0,
  db_size_gb     numeric NOT NULL DEFAULT 0,
  PRIMARY KEY (collected_at, tenant_slug)
);
#!/usr/bin/env python3
"""Daily usage collector — one row per tenant per day."""
import os, json, datetime, requests, psycopg2

JEM_API = os.environ['JEM_API']
SESSION = os.environ['JEM_SESSION']

def jem(method, path, **payload):
    r = requests.post(f"{JEM_API}/1.0/{path}",
                      data={'session': SESSION, **payload}, timeout=30)
    r.raise_for_status()
    return r.json()

today = datetime.date.today()
envs = jem('POST', 'environment/control/rest/getallenvs')['infos']

with psycopg2.connect(os.environ['PG_DSN']) as conn, conn.cursor() as cur:
    for info in envs:
        env = info['env']
        tags = json.loads(env.get('properties', {}).get('tags', '{}'))
        slug = tags.get('tenant')
        tier = tags.get('tier', 'unknown')
        if not slug:
            # untagged environment — log loudly, skip
            print(f"WARN untagged env {env['envName']}")
            continue
        stats = jem('POST', 'statistic/system/rest/getsumstat',
                    envName=env['envName'],
                    starttime=str(today),
                    endtime=str(today))
        cloudlet_hours = stats.get('cloudlets', 0) / 3600
        storage_gb = stats.get('diskspace', 0) / 1e9
        egress_gb = stats.get('extip_traffic_out', 0) / 1e9
        cur.execute("""
          INSERT INTO tenant_usage_daily
                 (collected_at, tenant_slug, tier, env_name,
                  cloudlet_hours, storage_gb, egress_gb, db_size_gb)
          VALUES (%s, %s, %s, %s, %s, %s, %s, 0)
          ON CONFLICT (collected_at, tenant_slug)
          DO UPDATE SET cloudlet_hours = EXCLUDED.cloudlet_hours,
                        storage_gb = EXCLUDED.storage_gb,
                        egress_gb  = EXCLUDED.egress_gb
        """, (today, slug, tier, env['envName'],
              cloudlet_hours, storage_gb, egress_gb))

Piece 3 — monthly report. A single SQL query gives the customer-facing line items:

SELECT tenant_slug,
       tier,
       SUM(cloudlet_hours) AS cloudlet_hours,
       AVG(storage_gb)     AS avg_storage_gb,
       SUM(egress_gb)      AS egress_gb
FROM tenant_usage_daily
WHERE collected_at >= date_trunc('month', current_date - interval '1 month')
  AND collected_at <  date_trunc('month', current_date)
GROUP BY tenant_slug, tier
ORDER BY cloudlet_hours DESC;

That output goes to whoever writes the invoices, or feeds your own internal cost model. Internal models do not need dollar amounts on the marketing site, but they do need to map back to provider bill line items — otherwise the next disputed invoice puts you back in the spreadsheet.

For an environment that already has 40 tenants and no tags, do not retrofit tags onto a single environment all at once. Tag each tenant the day they are touched by a deploy, a migration, or a support ticket — within six months everything active is tagged, and anything still untagged is dormant.

Stack Harbor builds chargeback pipelines as part of environment management for SaaS operators and agencies hosting tenant environments on managed PaaS — measurement, tagging discipline, and the monthly report that survives audit. If your bill is going up and you don’t know who’s responsible, the agency partner program starts with attribution before anything else — book a chargeback review.