A marketplace contract download should return a recipient-marked PDF through a short-lived, single-purpose URL, while an append-only audit event binds the recipient, document revision, watermark digest, and download decision. The least complex design that preserves batch throughput is a Node.js control plane backed by a bounded Go worker pool: prepare each recipient copy once, store it under an opaque object key, and authorize downloads without regenerating the PDF on the request path.
Short answer: watermark asynchronously, publish only after the artifact and audit record both succeed, and expire authorization independently from object retention. A page for download latency means this boundary failed; adding more request workers merely hides it until the next contract batch.
The page says contract_download_latency_burn_rate_high. On-call sees successful authorization checks followed by requests waiting on CPU-heavy PDF work, a growing preparation queue, and no corresponding rise in object-store reads. The user sees a spinner precisely when a signed contract should feel final.
Too late.
That is the wrong moment to compose a document.
What should have fired before download latency burned the SLO?
The earlier signal is queue age, not queue depth. Depth says how much work exists, but a marketplace batch can legitimately create a large queue; the age of the oldest ready job says whether available capacity is keeping its promise. Define two service-level indicators: preparation success before the contract's publish deadline, and authorization latency for an already prepared artifact. Keep PDF execution time as a diagnostic distribution, not as the user-facing objective.
Capacity planning starts with a plain inequality. If a launch produces 48,000 recipient artifacts over a 20-minute preparation window, required sustained throughput is 40 artifacts per second before headroom. Measure one worker's safe throughput on representative contracts, including font embedding and image-heavy pages, then set the concurrency bound from CPU and memory saturation rather than from queue length. Those numbers are an example workload, not a benchmark; replace them with measured arrival volume and service time. Suppose a test shows a worker slowing sharply on image-heavy contracts: increasing the pool from 8 to 16 might raise completions while also pushing memory into swap, so the apparent capacity gain disappears in the tail. I would keep the smaller bound until a mixed corpus demonstrates that the larger pool improves deadline attainment without exhausting memory. That is a capacity decision, not a preference for a runtime.
The alert should compare oldest-job age with the remaining publish window and page only when the error-budget burn is actionable. A warning can fire when projected drain time approaches the deadline. The page fires when the projection crosses it for long enough to exclude a short batch spike.
How should Node.js prepare a per-recipient PDF watermark before download?
The control plane accepts a contract revision and recipient identifier, creates an opaque job ID, and records the requested operation. A worker retrieves immutable source bytes, applies visible recipient text, computes a digest of the resulting bytes, stores the artifact, and commits an audit event before marking the job publishable. The object key must not contain an email address or contract title.
Do not treat a visible watermark as an access-control system. It supplies attribution after authorized delivery; authorization still requires a narrowly scoped, expiring capability. Likewise, signing a URL does not sign the contract's contents. PDF structure is standardized by ISO 32000-2, while the legal or cryptographic meaning of a contract signature is a separate concern that must be specified for the jurisdiction and workflow.
This runnable Go example isolates the concurrency and publication rule. Render stands behind a PDF implementation tested against the document profiles the marketplace accepts; keeping that interface narrow makes malformed-input tests and renderer replacement possible without changing delivery semantics.
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sync"
)
type Job struct {
ID, ContractRevision, RecipientID string
}
type Artifact struct {
Key, SHA256 string
}
type Renderer interface {
Render(context.Context, Job) ([]byte, error)
}
type Store interface {
Put(context.Context, string, []byte) error
}
type Audit interface {
AppendPrepared(context.Context, Job, Artifact) error
}
func prepare(ctx context.Context, r Renderer, s Store, a Audit, j Job) (Artifact, error) {
b, err := r.Render(ctx, j)
if err != nil {
return Artifact{}, fmt.Errorf("render %s: %w", j.ID, err)
}
digest := sha256.Sum256(b)
artifact := Artifact{
Key: "contracts/derived/" + j.ID + ".pdf",
SHA256: hex.EncodeToString(digest[:]),
}
if err := s.Put(ctx, artifact.Key, b); err != nil {
return Artifact{}, fmt.Errorf("store %s: %w", j.ID, err)
}
if err := a.AppendPrepared(ctx, j, artifact); err != nil {
return Artifact{}, fmt.Errorf("audit %s: %w", j.ID, err)
}
return artifact, nil
}
func runPool(ctx context.Context, workers int, jobs <-chan Job, work func(context.Context, Job) error) error {
if workers < 1 {
return errors.New("workers must be positive")
}
var wg sync.WaitGroup
errCh := make(chan error, workers)
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobs {
if err := work(ctx, j); err != nil {
select { case errCh <- err: case <-ctx.Done(): return }
}
}
}()
}
wg.Wait()
close(errCh)
return errors.Join(func() []error {
var all []error
for err := range errCh { all = append(all, err) }
return all
}()...)
}
func main() {}
One detail matters: a retry uses the same job ID and therefore the same object key. The store and audit layer must make that operation idempotent by accepting the same digest and rejecting a different digest for an already published job. Otherwise a renderer change during a retry can leave the audit trail describing bytes the recipient never received.
Retries aren't free.
Short-lived download authorization should bind an artifact key, recipient, expiry instant, and random token ID. Store only a hash of that token ID if one-time redemption is required. Evaluate expiry with server time, reject an artifact whose job is not publishable, append the outcome, and then redirect or stream; never put recipient data into a query string merely to make the watermark traceable.
Instrument the point where work waits
Four measurements are enough to expose the first-order failure: oldest ready-job age, completed artifacts per second, preparation failures by bounded reason, and active workers against the configured limit. Add histograms for render duration and output size because the tail, not the average, determines how much concurrency fits in memory.
Instrumentation belongs around state transitions. A job moving from ready to running records queue wait; running to prepared records execution duration; an authorization decision records allow or deny without logging the raw capability. Audit events and operational logs serve different retention and access needs, even when both begin with the same event envelope.
type Transition struct {
JobID string
From string
To string
Reason string
OccurredUTC string
ArtifactSHA string
}
func validTransition(from, to string) bool {
allowed := map[string]map[string]bool{
"ready": {"running": true},
"running": {"ready": true, "prepared": true, "failed": true},
}
return allowed[from][to]
}
The transition schema deliberately excludes email addresses, names, signed URLs, and contract text. Correlation uses pseudonymous identifiers; privileged audit lookup can resolve them through a separately controlled system. Logs remain useful without becoming a second document repository.
Test the unhappy paths before tuning concurrency: a truncated source PDF, a renderer timeout, an object write that succeeds before the audit append fails, duplicate delivery of one queue message, an expired capability, and two workers claiming the same job. For batch tests, vary page count and embedded image size rather than cloning one small fixture thousands of times. A uniform fixture gives a reassuring throughput number and a misleading memory ceiling.
Choose the operating model by throughput, not fashion
The relevant buy-versus-build question is who owns the throughput envelope and the evidence chain. It is not a feature checklist.
| Decision surface | Managed document path | Self-operated worker path | Evidence required |
|---|---|---|---|
| Burst capacity | Contracted quotas and escalation path | Tested queue drain rate and autoscaling lag | Load test at expected batch shape |
| On-call load | External dependency plus integration ownership | Renderer, queue, storage, and patch ownership | Named responder and runbook |
| Lock-in | Export format, audit export, and exit behavior | Internal interfaces and migration maintenance | Restore or migration exercise |
| Failure isolation | Provider boundary may limit diagnosis | Full telemetry with a larger support surface | Fault-injection results |
A managed route can reduce component ownership, but quota behavior and evidence export become acceptance criteria. A self-operated route gives direct control over concurrency and telemetry, while placing parser security, dependency updates, and capacity tests on the platform team. Neither answer is universally safer. The batch arrival curve, deadline, document complexity, compliance review, and staffed on-call rotation decide.
The worker-pool design has a clear limitation: it is a poor fit when every download must reflect data changed seconds earlier, because precomputation either serves stale content or repeatedly discards expensive artifacts. In that case, generate on demand behind a strict concurrency gate and accept a higher latency objective, or generate a stable base PDF ahead of time and add only the recipient overlay during delivery. It is also the wrong ownership choice for a team without capacity to patch a parser and rehearse recovery; a managed document service may reduce that burden, provided its quota, audit-export, deletion, and exit behavior pass review. The trade-off is control over batch throughput in exchange for more on-call surface.
Deployment should canary renderer changes against a fixed corpus and compare output digests only when deterministic output is an explicit invariant. Otherwise validate structural readability, expected page count, required watermark presence, and audit linkage. Roll back before mixing renderer versions inside one contract revision unless the audit schema records the renderer build.
Set the page threshold without training on-call to ignore it
The final trap is paging on any nonzero queue age. That threshold catches normal bursts, wakes someone who cannot improve the outcome, and teaches the team to distrust the signal. Conversely, a threshold at the full publish window leaves no time to drain the queue.
Set warning and page thresholds from measured drain rate, remaining deadline, and error-budget policy. Recalculate the projection when worker saturation or render-time distribution changes. Then replay representative batch traces against the rule and count pages that demanded no action; false-positive cost belongs in the review alongside missed deadlines, because an alert that is routinely silenced is not a control.
The operational decision is concise: keep watermark generation off the download path, publish only audited artifacts, and page on threatened deadlines rather than on raw backlog. Everything else is an implementation choice that should survive a load test and an evidence review.
Further reading
- ISO 32000-2, Portable Document Format: https://www.iso.org/standard/75839.html
Top comments (0)