Considering billing and metering
I'm thinking about what needs to be metered and how to compute those metrics, including rounding and pricing units. I want to avoid double billing, which means I should charge only for successful attempts and clearly define my approach for retries. For the metering pipeline, I'll emit usage events from a worker or sidecar and sign them. Additionally, I need to keep operational concerns in mind, including observability, abuse prevention, versioned transforms, and cleanup. Lastly, I’ll outline an example workflow.
Below is a practical design for a multi-tenant media transform pipeline (images/video/audio/docs) that emphasizes sandboxed workers, hard resource limits, idempotency, and billing that doesn’t double-charge on retries.
1) High-level architecture (control plane vs data plane)
Control plane
- API:
POST /jobs with input URI(s), transform spec, output location, idempotency key.
- Metadata DB (Postgres recommended): job state machine, attempts, idempotency records, pricing plan, quotas.
- Queue: at-least-once delivery (SQS/PubSub/Kafka). Messages contain
job_id, attempt.
- Scheduler / admission control: enforces per-tenant quotas and picks worker pool/class (cpu/mem/gpu).
Data plane
- Object storage: source + output + caches (S3/GCS/Azure). Prefer signed URLs or internal service identities.
- Worker fleet: sandboxed execution environment running ffmpeg/imagemagick/etc.
- Metering: usage events emitted per job/attempt and aggregated into invoices.
2) Sandboxed workers (multi-tenant safe execution)
Media libraries have a long history of parser bugs. Treat every input as hostile.
Isolation options (strong → weaker)
- MicroVMs (Firecracker/Cloud Hypervisor): best isolation; good for untrusted customer inputs at scale.
- gVisor / Kata Containers on Kubernetes: strong isolation with container ergonomics.
- Containers with hardened profiles: acceptable if inputs are semi-trusted and you keep dependencies patched aggressively.
Recommended sandbox rules
- No outbound network by default. Allow only:
- object storage endpoints (or through a proxy that enforces allowlists and rate limits)
- internal metadata/metering endpoints if needed
- Read-only root filesystem; writable temp at
/work with size limit.
- Drop privileges:
- run as non-root, no
CAP_SYS_ADMIN
- seccomp + AppArmor/SELinux profile; block
mount, ptrace, raw sockets, etc.
- Pin tool versions (ffmpeg build, ImageMagick policy.xml). Version every “transform runtime” so output is reproducible.
File handling
- Always copy inputs into the sandbox temp area (avoid streaming directly into decoders unless you can bound memory).
- Enforce limits before decode when possible (e.g., file size caps, container header checks).
3) Resource limits (hard caps + fair scheduling)
You want two layers: hard per-job caps and per-tenant quotas.
Per-job hard limits (enforced by runtime)
- CPU: cgroups v2
cpu.max (or K8s requests/limits).
- Memory: cgroups memory limit + OOM kill. Don’t rely on library behavior.
- Wall-clock timeout: kill after
T seconds (separate from CPU time).
- Temp disk: sandbox
/work size cap; media transforms can explode outputs.
- I/O rate limiting: optional but useful (blkio / storage class / tc for network).
- Output constraints: max output size, max duration, max pixel count, max frame count.
Per-tenant quotas (admission control)
- Max concurrent jobs
- Max CPU-seconds per minute/hour
- Max bytes in/out per day
- Priority tiers (paid > free), with separate queues or weighted scheduling
Preflight checks (cheap rejection)
Before scheduling a job, validate:
- input size < plan limit
- declared transform parameters are allowed (codec allowlist, max resolution)
- estimated cost within tenant’s budget (if you support budget caps)
4) Idempotency (job creation + execution + outputs)
There are two idempotency problems:
- “Don’t create the same job twice.”
- “If the worker retries, don’t duplicate outputs or billing.”
A. Idempotent job creation
Require an Idempotency-Key (client-provided) and store it with a uniqueness constraint:
- Key scope:
(tenant_id, idempotency_key) unique
- Store a hash of the request payload too. If the same key is reused with different payload, return
409.
Typical flow:
- Client submits
POST /jobs with idempotency key.
- Server does an UPSERT:
- if new: create job + enqueue
- if existing: return existing
job_id + status
B. Deterministic transform identity (for caching and dedupe)
Compute a canonical “transform fingerprint”:
fingerprint = SHA256( runtime_version + normalized_transform_spec + input_content_hashes + relevant_headers )
Use it to:
- Cache outputs (if allowed by your product)
- Make output paths deterministic:
outputs/{tenant}/{fingerprint}/...
- Ensure retries overwrite the same object key (or use atomic “commit” below)
C. Exactly-once “commit” pattern for outputs
Avoid partial/corrupt outputs and duplicate finalization:
- Worker writes outputs to a staging key:
staging/{job_id}/{attempt}/output.mp4
- Validate output (probe with ffprobe, checksum, size/duration constraints).
- Atomically “commit” by copying/renaming to final deterministic key:
outputs/{tenant}/{fingerprint}/output.mp4
- Mark job
SUCCEEDED in DB with the final output URIs.
If object storage lacks atomic rename, implement commit as:
- write final only if absent using conditional put/copy (
If-None-Match: *)
- or store a DB “output_committed=true” gate with transactional semantics
D. Retry semantics
Use at-least-once queue delivery, but make the worker idempotent:
- Each attempt has
(job_id, attempt_no) unique.
- Worker must be safe to run multiple times:
- if job already
SUCCEEDED, exit early
- if output already committed for the fingerprint, exit early
5) Billing & metering (accurate, retry-safe)
A robust approach is: meter per attempt, charge per successful job (or explicitly define attempt billing for some products).
What to meter (common dimensions)
- CPU-seconds (or vCPU-seconds)
- Memory GB-seconds (optional, more complex)
- Wall time (less fair but simpler)
- Input bytes processed
- Output bytes produced
- Egress bytes (if you deliver to customer endpoints/CDN)
- Special resources: GPU-seconds, licensed codecs, premium presets
Where to measure
Prefer platform-measured metrics over self-reported:
- If on Kubernetes: cAdvisor / container runtime stats → per-pod CPU time, memory peak
- If microVM: host-level cgroup stats for the VM process
- Storage bytes: from object store metadata or proxy logs
Usage event ledger (prevents double-billing)
Create an append-only usage_events table with a uniqueness constraint like:
unique(tenant_id, job_id, attempt_no, event_type) for attempt-level
unique(tenant_id, job_id, event_type='JOB_FINALIZED') for final charge trigger
Flow:
- Worker emits
ATTEMPT_FINISHED event with measured usage.
- Billing service aggregates attempt usage for reporting.
- Only when job is committed to
SUCCEEDED does the system emit JOB_FINALIZED (exactly once).
- Invoice uses
JOB_FINALIZED to decide what is billable, referencing the associated measured usage.
Key point: retries can generate multiple ATTEMPT_FINISHED rows, but only one JOB_FINALIZED exists, so you don’t double-charge unless your pricing explicitly bills failed attempts.
If you do bill failed attempts
Still avoid duplication by uniqueness on (job_id, attempt_no) and ensure attempt numbers are assigned by the control plane, not the worker.
6) State machine (minimal but sufficient)
In DB, maintain:
PENDING (created)
QUEUED
RUNNING (with attempt_no, worker_id, start time)
SUCCEEDED (output URIs + fingerprint)
FAILED (error category + retriable flag)
CANCELED
Transitions should be guarded with compare-and-swap updates:
UPDATE jobs SET state='RUNNING' ... WHERE job_id=? AND state IN ('QUEUED')
This prevents two workers from “owning” the same job.
7) Operational essentials (often missed)
- Dependency patching cadence for codecs/parsers; CVE response playbook.
- Content policy: disallow dangerous formats/codecs if needed.
- Observability: per job trace: download → decode → transform → encode → upload → commit.
- Poison pill handling: detect repeated failures, move to dead-letter queue, surface actionable error messages.
- Cleanup: TTL for staging objects and temp artifacts; lifecycle policies in object storage.
- Versioned runtimes: changes to ffmpeg version can change output bits; include runtime version in fingerprint.
8) Concrete “happy path” flow (end-to-end)
- Client
POST /jobs with input URI + transform spec + Idempotency-Key.
- API validates, stores job + fingerprint, enqueues.
- Worker claims job (CAS), starts sandbox with strict limits.
- Downloads input → transform → writes staging outputs.
- Validates outputs; commits to deterministic final key.
- Worker writes
ATTEMPT_FINISHED usage event.
- Control plane marks job
SUCCEEDED and emits JOB_FINALIZED once.
- Billing aggregates finalized jobs into invoice; retries don’t double-charge.
If you share your expected workload (image vs video, typical durations/sizes, multi-step pipelines vs single-step) and target platform (Kubernetes, ECS, bare VMs), I can propose concrete limit values, queue topology, and an idempotency/billing schema you can lift directly into code.