Screenshot API for SaaS: Multi-Tenant Implementation
One Screenshotly workspace, many tenants. How to meter, throttle, queue, and correlate captures per tenant without leaking keys or letting one customer use up everyone's quota.
Many SaaS products eventually need screenshots: link previews, report and invoice PDFs, dashboard thumbnails, or "share as image" exports. Calling a screenshot API once is easy. Doing it for hundreds of tenants, without leaking your key, mixing up results, or letting one customer use up the shared quota, takes a few design decisions.
This guide assumes one Screenshotly workspace that serves all your tenants. It covers the parts that are specific to multi-tenancy. For request parameters, see the screenshot API reference. For the async contract, see the async jobs reference.
The constraints you are designing around
These come from Screenshotly itself and shape everything else:
| Constraint | Value |
|---|---|
| Per-minute request rate | Free 5 · Basic 40 · Growth 80 · Scale 200 |
| Monthly successful captures | Free 100 total · Basic 2,500 · Growth 12,000 · Scale 50,000 |
| Over the allowance | Requests return 429 until the period resets. There is no automatic overage |
| What counts | Successful (2xx) captures only. Failed captures are free |
| Feature gates | Set by the workspace owner's plan. PDF/HTML, webhooks, storage, headers/cookies: Basic+. AI removal, JavaScript, mockups, scrolling, batch jobs: Growth+. Regional proxy, WebM: Scale |
| Async jobs | POST /api/jobs, Basic+ · POST /api/jobs/batch, up to 20 captures, Growth+ |
| Keys | Belong to a workspace. Up to 10 active per user. Additional keys do not add throughput or quota |
Two consequences:
- Your Screenshotly plan has to cover the most demanding feature any tenant uses. If one premium tier offers AI cookie-banner removal, the workspace needs Growth, even if most tenants only take plain PNGs. Enforce your own product tiers in your code.
- Rate and quota are shared. Every tenant draws from the same per-minute rate and monthly allowance, so fairness is your job. See Screenshot API rate limits for how the two limits behave.
Architecture
Tenant request ──► Your API ──► tenant checks (plan, throttle, allowance)
│
▼
POST /api/jobs (server-side key, Idempotency-Key)
│
Screenshotly worker renders, retries, stores result
│
webhook (signed) ──► /hooks/screenshotly?tenant=…&resource=…
│
copy result into tenant-scoped storage, record usage
Keep the API key on your server. Never put it in browser code, mobile apps, or tenant-visible configuration. Anyone who has it can spend your quota with your plan's features. Your API checks the tenant, calls Screenshotly, and returns your own URLs.
Queue captures per tenant
For anything a tenant triggers in bulk, or anything that may take longer than a user will wait, use an async job (Basic+) instead of holding a synchronous request open. The job endpoint accepts the same body as POST /api/screenshot.
const API = 'https://screenshotly.app';
export async function queueTenantCapture({ tenantId, resourceId, version, url, format = 'png' }) {
await assertTenantAllowance(tenantId); // your throttle + monthly allowance, below
const hook = new URL('https://app.example.com/hooks/screenshotly');
hook.searchParams.set('tenant', tenantId);
hook.searchParams.set('resource', resourceId);
const response = await fetch(`${API}/api/jobs`, {
method: 'POST',
headers: {
'x-api-key': process.env.SCREENSHOTLY_API_KEY,
'Content-Type': 'application/json',
// Printable ASCII without spaces, max 200 characters, unique per workspace.
'Idempotency-Key': `t_${tenantId}_r_${resourceId}_v_${version}`,
},
body: JSON.stringify({
url,
format,
width: 1280,
height: 800,
webhook: {
url: hook.toString(),
secret: process.env.SCREENSHOTLY_WEBHOOK_SECRET,
headers: { 'X-Tenant-Id': tenantId },
},
}),
});
if (response.status === 429) {
const retryAfter = Number(response.headers.get('Retry-After') || 60);
throw new RetryLaterError(retryAfter); // your error type
}
if (!response.ok) throw new Error(`Queue failed: ${response.status} ${await response.text()}`);
const job = await response.json(); // { id, status, replayed, statusUrl }
await db.captures.upsert({ tenantId, resourceId, version, jobId: job.id, status: job.status });
return job;
}
How the job endpoint behaves:
202for a new job,200for a replay. If the sameIdempotency-Keywas already used in your workspace, you get the original job back withreplayed: true, so a retried request will not queue the job twice. The key is not checked against the body, so build it from the tenant, the resource, and a content version. Do not reuse a key for a different capture.- Status values are
QUEUED,RUNNING,SUCCEEDED,FAILED, andCANCELED. A failed capture is retried by the worker with exponential backoff, up to three attempts in total, before the job is markedFAILED. GET /api/jobs/{id}returns the job. A successful job includes aresultUrlthat is valid for about 15 minutes. Read the job again for a fresh link.DELETE /api/jobs/{id}requests cancellation.- Results are kept for your account's retention setting (1 to 30 days). Copy anything a tenant needs to keep into your own storage.
When a tenant uploads a list of pages, POST /api/jobs/batch (Growth+) queues up to 20 captures in one call. It derives per-item idempotency keys as <your key>:<index>, so keep the base key to 180 characters. See batch screenshot processing for chunking larger lists.
Receive and attribute the webhook
The webhook body tells you what was captured, but not which tenant or job it belongs to:
{
"event": "screenshot.completed",
"timestamp": "2026-11-13T10:15:02.114Z",
"data": {
"url": "https://example.com/report/42",
"format": "png",
"size": 183422,
"storageUrl": "https://screenshotly.app/api/assets/…?expires=…&signature=…",
"duration": 4210
}
}
A failed job sends screenshot.failed with data.url, data.format, and data.error. Your identifiers come back through the webhook URL and any webhook.headers you set, which are sent with every attempt. Verify the signature before trusting any of them:
import crypto from 'node:crypto';
import express from 'express';
const app = express();
app.post('/hooks/screenshotly', express.raw({ type: 'application/json' }), async (req, res) => {
const expected = 'sha256=' + crypto
.createHmac('sha256', process.env.SCREENSHOTLY_WEBHOOK_SECRET)
.update(req.body) // raw bytes, exactly as received
.digest('hex');
const received = req.get('X-Screenshotly-Signature') || '';
const valid = received.length === expected.length
&& crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
if (!valid) return res.status(401).end();
const { tenant, resource } = req.query;
const event = JSON.parse(req.body.toString('utf8'));
// Deliveries can repeat. Make the update idempotent on (tenant, resource, event).
const first = await db.captureEvents.insertIfAbsent({ tenant, resource, event: event.event });
if (first && event.event === 'screenshot.completed') {
await copyToTenantStorage(tenant, resource, event.data.storageUrl); // signed URL is valid ~24 h
await db.usage.increment({ tenant, month: event.timestamp.slice(0, 7) });
}
res.status(204).end();
});
Delivery details worth designing for:
- Any 2xx response counts as delivered. A non-2xx response, a timeout over 10 seconds, or a redirect counts as a failure and is retried, up to five attempts in total.
X-Screenshotly-Timestamprepeats the body'stimestamp. Reject events that are far older than your tolerance.- Respond quickly and do heavy work (copying the file, regenerating thumbnails) in a background job.
The webhooks guide goes deeper into verification and retries. If a webhook is lost, poll GET /api/jobs/{id} using the job ID you stored when you queued it.
Per-tenant throttles and allowances
Two checks before every capture: a short-window throttle so one tenant cannot use the whole per-minute rate, and a monthly allowance so one tenant cannot use up the shared quota.
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
// Example: Growth plan = 80 requests/minute. Keep headroom for retries and polling.
const TENANT_PER_MINUTE = { free: 2, pro: 10, enterprise: 30 };
export async function assertTenantAllowance(tenantId) {
const tenant = await db.tenants.findById(tenantId);
const windowKey = `shots:rate:${tenantId}:${Math.floor(Date.now() / 60000)}`;
const count = await redis.incr(windowKey);
if (count === 1) await redis.expire(windowKey, 120);
if (count > TENANT_PER_MINUTE[tenant.tier]) throw new RetryLaterError(60);
const month = new Date().toISOString().slice(0, 7);
const used = await db.usage.count({ tenant: tenantId, month });
if (used >= tenant.monthlyCaptureAllowance) throw new AllowanceExceededError(tenantId);
}
Size the per-tenant ceilings so that the tenants you expect to be active at the same time stay under your plan's rate. Monthly allowances across tenants can add up to more than your plan's quota, but watch the total. In Screenshotly's account controls you can set a warning threshold (50% to 100%), an optional hard stop below the plan limit, and an HTTPS usage webhook that sends usage.warning and usage.limit events. Usage webhooks are not signed, so treat them as a prompt to check usage, not as an authenticated command.
Billing tenants for captures
Use your own usage table as the source of truth: one row or counter per tenant per month, incremented only on successful captures. That matches what Screenshotly counts, so your invoices and your quota line up. At the end of the period, or continuously, report each tenant's count to your billing provider's metered-usage API. Stripe, for example, handles this with usage-based billing and meters. Do not bill for FAILED jobs: they did not cost you quota either.
Branded output
Do not composite logos onto screenshots afterwards. Render the branded page yourself and capture that:
- Add a route such as
/render/:tenant/:resourcethat loads the tenant's logo, colors, and fonts. - Protect it with a short-lived signed token in the query string, or pass credentials with
headersorcookies(Basic+). - Capture it as PNG for previews or
format: "pdf"(Basic+) for documents. PDF output is fixed at A4 with 1 cm margins, so design the print layout for that size.
The render route has to be reachable on the public internet. Screenshotly rejects local and private-network URLs with 400 Unsafe URL, and validates tenant-supplied target URLs the same way, which also protects you when tenants submit their own URLs.
Errors to translate for tenants
| Screenshotly response | Meaning | What to show the tenant |
|---|---|---|
400 Invalid request data / Unsafe URL |
Bad parameters or a disallowed URL | A validation message. Do not retry |
403 Plan upgrade required (minimumPlan) |
Your workspace plan lacks the feature | Disable the feature in your product, or upgrade your plan |
429 with Retry-After |
Per-minute rate or monthly quota reached | "Queued, will retry". Back off for Retry-After seconds |
5xx |
Capture or service failure | Retry the call with backoff. Inside an async job, the worker already retries the capture |
More detail is in screenshot API error handling.
Checklist
- API key only on the server. One key per environment, rotated through workspace key management.
- Tenant ID and resource ID in your database next to the Screenshotly job ID.
Idempotency-Keybuilt from the tenant, the resource, and a version.- Webhook signature verified on the raw body. Duplicate deliveries handled.
- Results copied to tenant-scoped storage before the signed URL and retention window expire.
- Per-tenant throttle and monthly allowance enforced before calling the API.
- Usage counted on success only, then reported to billing.
Related
- Async screenshots: when to queue instead of waiting on a synchronous request.
- Caching screenshots: stop recapturing the same tenant page on every view.
- Batch processing and performance tuning.
- Pricing: plan features, rates, and quotas.
Create a free account → to test the request shape. Async jobs and webhooks require the Basic plan or higher.
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
Should each of my tenants get their own Screenshotly API key?
Usually not. Keys belong to a Screenshotly workspace, and the workspace owner's plan controls features, the per-minute rate, and the monthly quota. Extra keys do not add throughput or quota, and each user can have at most 10 active keys. Use one key per environment or service, keep it on your server, and track tenants in your own database.
How do I meter screenshot usage per tenant for billing?
Record a usage row in your database when a capture succeeds: when a synchronous call returns 2xx, or when an async job reaches SUCCEEDED or its screenshot.completed webhook arrives. Screenshotly counts only successful captures against your quota, so counting the same events keeps your numbers aligned. Report the per-tenant totals to your billing provider's metered-usage API.
How do I rate-limit per tenant without affecting others?
Put a per-tenant limiter in front of your Screenshotly calls, keyed on tenant ID, and set the tenant ceilings so their sum stays under your plan's per-minute rate (5, 40, 80, or 200 requests per minute on Free, Basic, Growth, and Scale). Add a per-tenant monthly allowance in your database so one customer cannot use up the shared monthly quota.
How do I know which tenant a webhook belongs to?
The webhook body contains the event, a timestamp, and capture details (URL, format, size, a signed result URL, duration), but not your tenant or job ID. Put your identifiers in the webhook URL query string or in webhook.headers when you create the job. Both are sent back on every delivery attempt, and you should verify the X-Screenshotly-Signature HMAC before trusting either.
What's the cleanest way to apply per-tenant branding to captures?
Render the output on your own app, for example /render/:tenant/:resource, using the tenant's logo, colors, and fonts, then capture that URL. The page must be reachable on the public internet, because Screenshotly rejects private and local addresses. Protect it with a short-lived signed token in the URL, or with headers or cookies (Basic plan and above).
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.