For a multi-school platform, save one private original and a fixed set of replaceable thumbnails, but make the tenant-owned database record the authority for every upload, crop, resize, read, and deletion. Let the browser send large media directly to private object storage, let a Node.js worker use Sharp, and activate a generation only after its required sizes exist. The object path helps operators; it does not prove ownership.
That is the whole design in one paragraph.
The awkward part is governance. An instructor may teach for two schools, a learner may transfer, and a profile may be visible inside one classroom but not another. If the image pipeline treats tenant-a/user-42 as identity, those ordinary edtech events become dangerous key-renaming exercises. Instead, treat each upload as evidence attached to an immutable tenant, avatar, and generation. Image processing then becomes a subordinate function: useful, retryable, and unable to broaden access.
The example below assumes three square display sizes - 48, 96, and 192 pixels - because a concrete policy is easier to inspect than "several thumbnails." They are example values, not web standards. Keep or change them after measuring actual layouts and delivery volume.
Put the ownership ledger ahead of image processing
Start with an application record, not a bucket prefix. The record needs an opaque tenant ID, subject ID, avatar ID, generation ID, lifecycle state, original object key, crop policy, required derivative set, and active-generation pointer. The authenticated tenant context selects that record before the backend creates any storage authority. A caller never supplies a tenant prefix and asks the service to trust it.
The direct-upload sequence is deliberately narrow. The application authenticates the caller, creates an upload intent for one staging object, and returns time-limited authority for that exact destination. The browser transfers the large file to private storage without pushing the bytes through the application process. Completion moves the record into validation and processing; it does not make the image readable. This distinction matters because an upload acknowledgment establishes that an object arrived, while the worker still has to decode it and apply the platform's media policy.
Keep the staging object private.
The ledger also resolves a surprisingly hard school-transfer case. Suppose learner u-1842 has generation g17 under tenant north-campus, then joins south-campus while processing is queued. Do not edit a string in the key and call that a transfer. Either finish g17 under its original tenant and require a separately authorized adoption process, or revoke that generation and create a fresh upload intent under the new tenant. The decision should follow the institution's data policy; I'm not sure a universal transfer rule exists because schools can have different retention obligations. What should be universal is the evidence: no generation changes tenant merely because a path was rewritten.
This ledger gives compliance and support teams useful answers without listing a bucket: who authorized the upload, which crop policy created the visible image, which generation is active, and which objects must be removed after a deletion request. It also keeps broad storage credentials away from request handlers. The handler asks for one logical operation. A small adapter converts that operation into a narrowly scoped storage capability.
How should a Node.js Sharp worker crop, resize, and save avatar thumbnails?
Sharp should implement the pixel policy, not the authorization policy. Pass the worker a server-created job containing trusted identifiers and an original key. Validate the decoded media against configured limits, normalize the orientation according to the chosen original-retention policy, apply one focal point consistently, and write every output beneath a generation-specific key. A centered cover crop is predictable, but it may cut off a face near an edge; if the UI captures a focal point, store normalized coordinates and validate their range before processing.
All code in this article is Python by editorial convention, so this example describes the control-plane contract rather than pretending to be a Sharp tutorial. A Node.js adapter can map each planned operation to Sharp while the tenant and publication rules remain testable without an image library.
from dataclasses import dataclass from typing import Literal @dataclass(frozen=True) class AvatarJob: tenant_id: str avatar_id: str generation_id: str original_key: str focal_x: float = 0.5 focal_y: float = 0.5 @dataclass(frozen=True) class Variant: key: str width: int height: int fit: Literal["cover"] = "cover" SQUARE_SIZES = (48, 96, 192) def plan_variants(job: AvatarJob) -> tuple[Variant, ...]: if not 0.0 <= job.focal_x <= 1.0 or not 0.0 <= job.focal_y <= 1.0: raise ValueError("focal point must use normalized coordinates") root = ( f"tenants/{job.tenant_id}/avatars/" f"{job.avatar_id}/generations/{job.generation_id}" ) return tuple( Variant( key=f"{root}/square-{size}.webp", width=size, height=size, ) for size in SQUARE_SIZES ) The same generation ID belongs in the database row, queue message, object keys, and telemetry dimensions. It is a correlation boundary, not an authentication credential. On retry, the job receives the same plan and destinations. Publication is a separate database action: verify the expected derivative records, then atomically change the active pointer from g17 to g18. Readers stay on g17 until that change, so an avatar never consists of a 48-pixel file from one crop and a 192-pixel file from another.
Do not infer readiness by listing a prefix. The manifest is the declared set, and the database state is the publication decision. Store statuses such as uploaded, processing, ready, and rejected; record safe rejection categories such as unsupported media or capacity exceeded. Keep signed URLs, raw object keys, and user filenames out of general logs because those fields tend to reach more systems and people than the image itself.
The word "original" needs a written definition. It may mean the untouched upload, or it may mean an orientation-normalized archival image. Both policies can support later recropping, but they have different retention and forensic implications. Pick one, document it, and make deletion cover it. Don't let two teams use the same label for different bytes.
Test tenant transitions before testing perfect pixels
Pixel snapshots are useful after the security model holds. Begin with attempts that cross a boundary: tenant A requests an upload intent for tenant B's avatar; a worker job carries a valid object key but the wrong tenant ID; an authenticated reader knows another school's avatar ID; deletion begins while a derivative job is queued; the same generation is delivered to the worker twice. Every one of these cases should resolve through application state, not through whether an object happens to exist.
A compact authorization function makes the test target explicit:
from dataclasses import dataclass @dataclass(frozen=True) class AvatarRecord: tenant_id: str avatar_id: str active_generation: str | None allowed_sizes: frozenset[int] def resolve_variant( record: AvatarRecord, authenticated_tenant: str, requested_size: int, ) -> tuple[str, str, int]: if record.tenant_id != authenticated_tenant: raise PermissionError("avatar is outside the authenticated tenant") if record.active_generation is None: raise LookupError("avatar has no active generation") if requested_size not in record.allowed_sizes: raise ValueError("unsupported avatar size") return record.avatar_id, record.active_generation, requested_size At the external boundary, consider returning the same absence response for an unknown avatar and an avatar owned by a different tenant when revealing existence is sensitive. Internally, preserve separate audit outcomes. Compliance investigations need to distinguish a typo from an attempted cross-tenant lookup even when the client cannot.
Only then test crop geometry: orientation handling, a focal point at each boundary, a source smaller than the largest output, extreme aspect ratios, transparent input, and deterministic results on duplicate jobs. Also test capacity limits with exact configured values rather than a vague "large file" fixture. Deliverability work teaches a relevant lesson here: a successful handoff is not the same as a successful outcome. An accepted upload is not a published avatar, just as an accepted message is not proof that it reached an inbox.
Operational telemetry should follow the state machine. Record stage duration, tenant ID, avatar ID, generation ID, decoded dimensions, input bytes, output bytes, and a bounded result category. Alert on jobs that remain outside a terminal state and reconcile manifest records against objects. The first reconciliation pass should report; automatic deletion can wait until the team understands why orphans exist.
Separate private delivery from browser presentation
Private object storage answers where bytes may live. It does not answer who may request them. For a read, the backend should first resolve (authenticated tenant, avatar ID, requested size) against the active manifest, then either stream the object or issue short-lived read authority for the server-selected key. The right delivery method depends on the threat model, caching needs, and how much request traffic the application should carry.
Content-Disposition controls browser presentation, not authorization. MDN documents the inline and attachment response forms plus filename parameters. An avatar intended to render in a page can use inline; an explicit original-download flow may use attachment semantics. Neither choice makes a private object safe to expose. Treat a user-supplied filename as display metadata and never splice it into an object key.
Direct browser upload changes the transfer path - the backend still owns policy. Documentation for managed storage such as Firebase Cloud Storage shows client uploads operating alongside authentication and security rules. Exact capability scope and expiry behavior vary by storage system, so verify them in the selected system's primary documentation before deployment. The architectural requirement stays stable: the application chooses one destination and binds it to one tenant-owned intent.
There is a real trade-off. Direct private upload plus an asynchronous worker keeps large media bytes away from application connections, but the team must operate upload expiry, a queue, idempotent processing, reconciliation, and private delivery. It is not suitable when the team cannot own that lifecycle. For modest files, stick with an app-proxied upload when one synchronous enforcement point matters more than conserving application bandwidth. Public derivatives are appropriate only after an explicit product decision that cross-tenant visibility is acceptable; private classroom profiles don't meet that condition by accident.
Precomputed sizes trade added storage and write work for bounded read-time behavior. On-demand resize avoids unused variants but adds cache-key design and abuse controls to the request path. Your mileage may vary. Measure the actual layout set and read distribution before adding a fourth or fifth rendition.
Roll out deletion before expanding thumbnail sizes
Deploy the smallest complete lifecycle: one tenant-aware record, one private original, one required thumbnail, one active-generation pointer, and one deletion path that revokes reads before removing objects. Run it for a single internal school. Exercise duplicate jobs, an abandoned upload, deletion during processing, and a learner transfer before widening access.
Next, add the remaining fixed sizes and compare processing time, output bytes, rejection categories, and read demand. Keep new generations immutable. A policy change creates g19; it does not overwrite g18. Once readers use the manifest rather than guessed paths, old generations can be retired according to the written retention policy without racing active requests.
Deletion is the release criterion.
The system is ready when a tenant boundary survives upload, processing, read, transfer, retry, and removal. Sharp can then do what it is good at - crop and resize images - while the application keeps the harder promise: a school sees only the media it is authorized to see.