Guide

How Should You Cache Screenshots at Scale?

The built-in cache saves render time, not quota. Here is how its key and TTL behave, and how to build your own cache layer when you need to reuse captures across many views.

Asad AliNovember 12, 20259 min read

Screenshots take seconds of browser time to render, but the result is usually a few hundred kilobytes that stays valid for hours or days. Caching is how you avoid paying for the same render twice. There are two separate layers to think about:

  1. Screenshotly's built-in cache (cache: true), which skips the browser render when an identical request arrived recently.
  2. Your own cache: Redis, object storage, or a CDN in front of your app. This is the only layer that saves quota.

This guide covers both, and when to use each. For reducing the time a single fresh capture takes (wait strategy, viewport, format), see How to Speed Up Screenshot API Capture Times. Caching is about reuse and freshness. Performance tuning is about what happens on a miss.

For HTTP caching background, RFC 9111 is the specification, and MDN explains Cache-Control and ETag more readably.

How the built-in cache works

Send cache: true on a POST /api/screenshot request (Basic plan and above). cacheTtl sets how long the result is kept, from 60 to 86,400 seconds. The default is 3,600.

curl -X POST https://screenshotly.app/api/screenshot \
  -H "x-api-key: $SCREENSHOTLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/pricing",
    "width": 1280,
    "height": 800,
    "format": "webp",
    "quality": 80,
    "cache": true,
    "cacheTtl": 86400
  }' \
  --output pricing.webp

What the service does with that request:

  • Cache key. The server hashes (SHA-256) the validated capture parameters, with schema defaults filled in, excluding cache, cacheTtl, storage, and webhook. Two requests hit the same entry only when every other parameter matches. Because defaults are applied first, {"url": "https://example.com"} and {"url": "https://example.com", "fullPage": false} are the same request.
  • No URL normalization. The url string is hashed as sent. Trailing slashes, query parameter order, and tracking parameters all create separate entries.
  • Storage. When the service is configured with Redis, entries are stored there with the TTL you set. Otherwise it may fall back to a small in-process memory cache (up to 100 entries per process). A hit is likely when you repeat a request within the TTL, but it is not guaranteed. Results larger than roughly 5 MB after base64 encoding are not written to Redis, so very large full-page PNGs may never be cached.
  • Response header. A binary response sent with cache: true carries Cache-Control: public, max-age=<cacheTtl>. Without it, the header is no-cache, no-store, must-revalidate. If you proxy the image through your own CDN, that header tells the CDN how long it may keep the file.

What the built-in cache does not do

It does not save quota. A cached response is still a successful 200 capture, and successful captures count toward your monthly allowance. That is 100 total on Free, then 2,500, 12,000, or 50,000 per month on Basic, Growth, and Scale. There is no automatic overage: once the allowance is used up, requests return 429 until it resets. Failed captures are not counted. See pricing for the current plans.

It also cannot be purged by request. If you need a fresh image before the TTL runs out, send the request without cache: true, or change a parameter.

Use the built-in cache when the same request is repeated in a short window: a dashboard re-rendering a preview, retries after your own timeout, or several workers asking for the same page. When the same image is shown many times, keep your own copy.

When your own cache is worth it

Here is some quick arithmetic. Say a link-preview feature shows 300 distinct URLs, and each image is viewed 50 times a day. Capturing on every view is 15,000 requests a day, which uses up a Growth plan's monthly allowance in under a day. Capturing each URL once a day and serving your stored copy costs about 9,000 captures a month.

The pattern is always the same:

  1. Normalize the request and build a stable key.
  2. Look it up in your cache.
  3. On a miss, call the API, store the bytes with a TTL, then serve them.

Cache key design

Normalize everything that should not change the image, and include everything that should.

import { createHash } from 'node:crypto';

const DROP_PARAMS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid', 'ref'];

export function normalizeUrl(input) {
  const url = new URL(input);
  url.hash = '';
  for (const name of DROP_PARAMS) url.searchParams.delete(name);
  url.searchParams.sort();
  return url.toString();
}

function stableStringify(value) {
  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
  if (value && typeof value === 'object') {
    return `{${Object.keys(value)
      .filter((key) => value[key] !== undefined)
      .sort()
      .map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`)
      .join(',')}}`;
  }
  return JSON.stringify(value);
}

// `version` is your own invalidation signal: a deploy ID, a CMS updatedAt, etc.
export function cacheKey(request, version = 'v1') {
  const normalized = { ...request, url: normalizeUrl(request.url) };
  const digest = createHash('sha256').update(stableStringify(normalized)).digest('hex');
  return `shot:${version}:${digest}`;
}

Send the normalized URL to the API as well, so your cache and the built-in cache agree on what counts as the same page.

Redis for hot entries

Redis works well for small, frequently read images with short TTLs. This sketch uses the redis package and stores images as base64 strings so it works the same way across client versions.

import { createClient } from 'redis';
import { cacheKey } from './cache-key.mjs';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

async function capture(request) {
  const response = await fetch('https://screenshotly.app/api/screenshot', {
    method: 'POST',
    headers: {
      'x-api-key': process.env.SCREENSHOTLY_API_KEY,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });
  if (!response.ok) {
    throw new Error(`Capture failed: ${response.status} ${await response.text()}`);
  }
  return Buffer.from(await response.arrayBuffer());
}

export async function getScreenshot(request, { ttlSeconds = 86400, version } = {}) {
  const key = cacheKey(request, version);
  const cached = await redis.get(key);
  if (cached) return Buffer.from(cached, 'base64');

  const image = await capture(request);
  await redis.set(key, image.toString('base64'), { EX: ttlSeconds });
  return image;
}

Keep Redis for images you serve often. Base64 encoding adds about a third to the size, and memory is the expensive part, so set maxmemory with an eviction policy such as allkeys-lru rather than letting the cache grow until it hits the limit.

Object storage for the long tail

For thousands of distinct URLs, or TTLs measured in days, store the bytes in S3-compatible object storage under the same key. Keep the capture time in object metadata (or in your database) so you can decide when an object is too old. A lifecycle rule on the bucket handles cleanup. Serve the objects through your CDN instead of reading them through your app on every view.

Screenshotly's own retained delivery (storage: {"enabled": true}, Basic and above) is not a substitute for this. It returns a signed download URL that is valid for 24 hours, and the stored file is kept for your account's retention setting (1 to 30 days, 7 by default). Use it to hand a result to another system, not as a permanent public image host.

CDN in front of your own route

The simplest setup for public images is a route on your own domain that returns the image with long-lived cache headers, with a CDN in front of it:

// e.g. GET /previews/:id.webp in an Express-style handler
export async function previewHandler(req, res) {
  const page = await db.pages.findById(req.params.id); // your data
  const image = await getScreenshot(
    { url: page.publicUrl, width: 1200, height: 630, format: 'webp', quality: 80 },
    { ttlSeconds: 86400, version: page.updatedAt.toISOString() },
  );
  res.set('Content-Type', 'image/webp');
  res.set('Cache-Control', 'public, max-age=3600, s-maxage=86400, stale-while-revalidate=3600');
  res.send(image);
}

s-maxage applies to shared caches such as CDNs, and max-age to browsers. stale-while-revalidate lets caches that support it serve the old image while they fetch a new one. Check how your CDN handles it: see Cloudflare's cache documentation or Vercel's caching documentation.

Picking TTLs

Capture type Suggested approach
Social preview / OG images of your own pages Key on the page's updatedAt, so the TTL can be long (a day or more)
Thumbnails of third-party sites 1–7 days, depending on how much a stale image matters
Documentation screenshots Key on deploy or release ID; recapture in CI
Generated reports, invoices Capture once and store as a document; no TTL
Monitoring and visual regression Do not cache. Fresh captures are the point

These are starting points. Measure how often your users actually see an out-of-date image.

Invalidation

  • Version in the key. This is the most reliable approach. When the version changes, old keys stop being read and expire on their own.
  • Explicit delete. Delete the key from Redis or object storage when a webhook from your CMS fires, then purge the CDN path.
  • TTL only. Good enough for third-party pages where you have no change signal.

Avoid keying on a target page's Last-Modified header unless you have confirmed that the site sends one that changes reliably. Many dynamic pages send the current time, or no header at all.

Monitoring the cache

Track your hit rate and your capture count side by side. Your capture count is what draws on quota. If it rises while traffic stays flat, a key is probably varying (often a timestamp or tracking parameter in the URL). If the hit rate is high but users report stale images, shorten the TTL or add a version signal.

Create a free account → to test the request shape with 100 free captures. Response caching requires the Basic plan or higher.

caching
performance
redis
cdn
optimization

About the Author

Asad Ali

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

Does Screenshotly's built-in cache reduce my monthly quota usage?

No. A request with cache: true that is answered from the cache still returns 200 and is recorded as a successful capture, so it counts toward your monthly allowance. The built-in cache saves render time. To avoid spending quota on repeat views, keep your own copy of the image (object storage, Redis, or a CDN) and only call the API when that copy is missing or too old.

Which plans can use cache and cacheTtl?

Response caching is a Basic-plan feature and above. On the Free plan, a request with cache: true is rejected with 403 and minimumPlan: basic. cacheTtl accepts 60 to 86,400 seconds and defaults to 3,600 (one hour).

Why did my cached capture miss even though the URL was the same?

The server cache key is a SHA-256 hash of every capture parameter except cache, cacheTtl, storage, and webhook. Changing anything else, such as width, format, quality, delay, cookies, or an extra query string on the URL, produces a different key. The URL string is not normalized, so https://example.com/page?utm_source=x and https://example.com/page are different entries. Normalize URLs on your side before sending them.

What TTL should I use for screenshots?

Match it to how often the page changes and how much a stale image matters. Social preview images and thumbnails of slow-moving pages can usually live for a day. Documentation captures can be kept until your next deploy, then invalidated. Monitoring and visual regression captures should skip caching, because the point is to see the current page.

How do I invalidate cached screenshots when a page changes?

In your own cache, put a version or content signal into the key: a deploy ID, a CMS updatedAt timestamp, or a hash of the data the page renders. When that signal changes, the next lookup misses and you capture again. The built-in cache cannot be purged by request, so for content that must refresh right away, either change a capture parameter or send the request without cache: true.

Ready to capture your first screenshot?

Get started with 100 free screenshots. No credit card required.

Related Articles