The short answer
A thumbnail request should not own the full image transformation and storage transaction. Put the original and derivative jobs behind a durable queue, carry the document's deletion deadline as data, and let a worker upload a completed object with an idempotency key. The request can return after the source is durably accepted.
That design fixes the timeout, but it also prevents a nastier support-system failure: a preview that survives after the signed document it represents was supposed to be deleted. The deadline must travel with every derivative, and deletion must be a separate, observable workflow rather than an assumption about object prefixes.
How can image thumbnail processing finish before upload times out?
The obvious diagnosis is slow image work. A large scan arrives, decoding consumes memory, resizing takes longer than the request budget, and the final upload has not started when the client gives up. The less obvious problem is partial state. The source may exist while its preview does not; a retry may create two previews; or a preview may be uploaded successfully after the caller has already retried the job.
For signed customer documents, those states have different consequences. A missing preview is inconvenient. A derivative left behind after the retention deadline is a records-management defect. I treat the deadline as part of the object manifest, alongside the source identifier, content type, checksum, and version. A worker that cannot read the manifest should not guess.
The first implementation I would reach for is a synchronous handler: download the source, resize it, upload the thumbnail, then answer. It is easy to trace locally and wrong at the boundary where the request budget meets image size. The queue adds another moving part, but it gives the expensive work its own retry policy and lets the retention policy remain explicit. I initially treated the timeout as a throughput problem; the useful correction was to treat it as a state and deadline problem too.
The deadline is the payload.
Before copying this shape, measure three things on representative scans: decode time, transform time, and upload time at the selected object size. Add queue wait and retry delay to the same timeline. A median is not enough; the p95 and the largest permitted input determine whether the request path is viable.
What should cross the asynchronous boundary?
Do not put a temporary file path in a message and hope it remains readable when a worker receives it. Send a stable source reference plus immutable policy data. The worker can then validate that the message is still current before doing expensive work.
Here is the small contract I use for a preview job. It is deliberately boring. Boring contracts are easier to audit six months later.
type ThumbnailJob = {
jobId: string;
documentId: string;
sourceKey: string;
sourceVersion: string;
outputKey: string;
width: number;
height: number;
deleteAfter: string;
attempt: number;
};
function isExpired(job: ThumbnailJob, now = new Date()): boolean {
return now.getTime() >= Date.parse(job.deleteAfter);
}
function outputId(job: ThumbnailJob): string {
return `${job.documentId}:${job.sourceVersion}:${job.width}x${job.height}`;
}
The output identity is derived from document version and dimensions, not from a random retry identifier. That gives the storage adapter a stable idempotency key. A retry can safely discover the existing derivative, verify its metadata, and acknowledge the job instead of creating another object. If a source is replaced, its version changes and the old derivative remains addressable for the cleanup process.
The deadline is an ISO timestamp because it can be compared across workers with different local time zones. In production, I would also reject a deadline that is missing, malformed, or earlier than the acceptance time unless the job is explicitly a cleanup task. Silent normalization is how retention bugs hide.
Which failure belongs to the worker, and which belongs to the queue?
A queue is not a magic guarantee of exactly-once processing. Assume at-least-once delivery. The worker should be safe to run twice, and the queue should control when a failed attempt is retried. Image decoding errors, unsupported formats, and corrupt source bytes are usually permanent after validation; a transient storage timeout is not. Those classes need different handling.
The worker should record a state transition such as accepted, processing, stored, expired, or rejected, with the job ID and source version attached. It should never mark a thumbnail stored before the storage operation has returned success. It should also avoid deleting the source as part of thumbnail success: retention cleanup owns deletion, so one failed derivative cannot accidentally destroy the record it was meant to represent.
A compact worker boundary might look like this:
interface ObjectStore {
head(key: string): Promise<{ etag: string; metadata: Record<string, string> } | null>;
put(
key: string,
body: Uint8Array,
metadata: Record<string, string>,
idempotencyKey: string
): Promise<void>;
}
async function handleThumbnail(
job: ThumbnailJob,
store: ObjectStore,
render: (sourceKey: string, width: number, height: number) => Promise<Uint8Array>,
now = new Date()
): Promise<"stored" | "expired"> {
if (isExpired(job, now)) return "expired";
const existing = await store.head(job.outputKey);
if (existing?.metadata["source-version"] === job.sourceVersion) return "stored";
const thumbnail = await render(job.sourceKey, job.width, job.height);
await store.put(
job.outputKey,
thumbnail,
{
"document-id": job.documentId,
"source-version": job.sourceVersion,
"delete-after": job.deleteAfter,
"content-kind": "document-thumbnail"
},
outputId(job)
);
return "stored";
}
The storage adapter may implement conditional creation differently across object stores. That is a reason to isolate it behind the interface, not a reason to make the request handler understand three APIs. The contract that matters above the adapter is stable: same logical input, same output identity, and metadata that makes later cleanup possible. The practical trade-off is deliberate: one extra inventory write buys a cleanup query, while relying on a filename convention saves a write but makes orphan detection a guess.
How should deletion cover originals and derivatives?
Run cleanup from a durable inventory, not from a listing that happens to find familiar key names. The inventory should contain the document version, source key, derivative keys, and deletion deadline. At the deadline, a cleanup worker claims the record, checks that no newer policy has superseded it, deletes every associated object, and records the result. A failed deletion stays visible for retry.
This is where object-store differences become an engineering trade-off. Amazon S3, Google Cloud Storage, and Azure Blob Storage all expose object-storage APIs, but their conditional requests, lifecycle configuration, versioning behavior, and metadata conventions are not interchangeable. Provider lifecycle rules can help with a coarse expiration policy; they do not remove the need to model document versions and derivative relationships in the application. Read the selected service's current lifecycle and deletion semantics before treating a policy rule as proof of deletion.
| Storage option | Useful boundary for this workflow | Limitation to account for |
|---|---|---|
| Amazon S3 | Lifecycle policies and object metadata can support scheduled cleanup | Application inventory is still needed to relate derivatives to document versions |
| Google Cloud Storage | Lifecycle management can express age-based deletion conditions | Provider policy does not replace version-aware job state |
| Azure Blob Storage | Lifecycle management can target blob data by rule | Cleanup logic still needs explicit ownership and retry records |
The table is a design prompt, not a ranking. The right adapter is the one whose conditional-write and lifecycle semantics you can test and operate.
I keep the application-level deadline even when an infrastructure lifecycle rule exists. It supports an audit query, catches objects created outside the normal path, and gives the cleanup process something to compare against. Storage pricing and request charges are real inputs, but they are secondary here. A low-cost cleanup strategy that cannot demonstrate which signed document a thumbnail belongs to is not a sound retention strategy.
A useful invariant is: every stored derivative has a source version, an explicit deadline, and an owner record that can delete it. Test that invariant after normal success, a worker retry, a duplicate message, a source replacement, and a cleanup failure. Those tests expose more than a happy-path upload test.
What should be measured before shipping?
Instrument the stages separately: queue delay, source read, decode, resize, output encode, upload, and acknowledgement. Include input byte size and output byte size, but do not log document contents or signed-page pixels. Correlate events with a job ID and document version.
Set a request timeout below the platform's hard limit and return an acceptance response only after the source and job record are durable. The worker needs its own timeout budget. A retry policy should cap attempts, use backoff with jitter, and route permanent validation failures to a reviewable dead-letter path.
For a small team, the operational dashboard can start with four questions: How many jobs are waiting? How old is the oldest job? Which stage is consuming the budget? Which deadlines are approaching with unfinished cleanup? The last question is the one synchronous designs rarely answer.
I would ship this only after a test creates a signed document, submits a thumbnail job, forces a timeout during upload, delivers the same job twice, replaces the document version, and advances the clock past the deletion deadline. The expected result is one derivative for the active version, no derivative for an expired job, and a cleanup record for every object that existed.
The practical rule is narrow: move image work out of the request, make retries idempotent, and carry retention data all the way to cleanup. That combination addresses the timeout without turning a preview feature into an untracked copy of a signed record.
Further reading
- Amazon S3 pricing and request-cost model: https://aws.amazon.com/s3/pricing/
- Amazon S3 lifecycle management: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html
- Google Cloud Storage object lifecycle management: https://cloud.google.com/storage/docs/lifecycle
- Azure Blob Storage lifecycle management: https://learn.microsoft.com/azure/storage/blobs/lifecycle-management-overview
- HTTP conditional requests (RFC 9110): https://www.rfc-editor.org/rfc/rfc9110.html
Top comments (0)