DEV Community

LiamFoster1844
LiamFoster1844

Posted on

Monthly PDF Packet Backlogs — 4 API Signals While Onboarding Forms Assemble

The page arrives at 08:07: the monthly onboarding archive is late, 612 employees are waiting, and the signing queue is still growing. The on-call engineer can see completed files, failed jobs, and a deadline, but none of those explains whether the system is recovering. The useful answer is to treat fill, merge, sign, and archive as separate bounded stages, then control admission with measured throughput and queue age. Do not hide the whole packet behind one long request.

TL;DR: accept a packet manifest, persist immutable inputs, process every stage idempotently, and expose a status resource whose timestamps survive retries. Page on projected SLO exhaustion, not merely on a large queue. For a monthly media-company cohort, capacity must be based on the slowest stage and the time left before the archive deadline; CPU counts and average render latency are supporting measurements, not the decision.

The first response to this page is operational: stop admitting discretionary reruns, confirm that workers are making forward progress, and identify the oldest packet blocked at each stage. Replaying the entire batch is dangerous because a retry may create a second signature request or archive a second copy. A packet-level idempotency key and stable document identifiers turn recovery into a bounded action instead of a guess.

How should an API assemble, fill, and sign an onboarding PDF packet?

Queue depth is tempting and usually insufficient. A queue of 1,000 packets can be harmless with two hours remaining and a sustained completion rate of 20 packets per minute; a queue of 200 can be fatal when a certificate service slows down and the deadline is ten minutes away. The earlier signal is projected drain time compared with the remaining SLO budget.

Track four signals: oldest runnable packet age, completed packets per minute, retry-adjusted failure rate by stage, and projected drain time. The last one should use a conservative recent throughput window rather than a lifetime average. If Q is runnable packets, R is sustained completions per second, and T is seconds remaining, the immediate risk test is Q / R > T. Add headroom for variance and for work that has been accepted but has not yet entered the visible queue.

One number still cannot tell the whole story. A merge queue can drain while signature callbacks stall, so the packet SLO needs an end-to-end clock from accepted manifest to durable archive confirmation. Per-stage service-level indicators explain the burn; they do not replace that clock.

Short pages matter.

Retries lie.

A practical page includes the batch identifier, deadline, oldest packet age, current and required completion rates, the constrained stage, and links to traces sampled from both successful and slow packets. It does not include employee form contents. Names, tax identifiers, bank details, and signatures belong in access-controlled storage, not labels, logs, or pager payloads.

Instrument the workflow as a state machine

The API boundary should be asynchronous. The caller submits a manifest containing ordered document references, field data references, signature requirements, and an archive policy; the service returns a stable packet identifier. Workers then move the packet through explicit states such as accepted, filled, merged, awaiting_signature, signed, and archived. State changes are conditional writes, so two workers cannot both advance the same revision.

The manifest itself should be immutable. Corrections create a new revision linked to the old one, which makes it possible to answer what was signed without reconstructing mutable database rows after the fact. Hash each source object and the assembled pre-signature PDF, retain the ordering declaration, and store timestamps for every transition. ISO 32000-2 defines PDF itself; it does not define your job lifecycle, retry semantics, or evidence model. Those remain application responsibilities.

Here is a deliberately small Go model for the measurements that belong on every transition. It excludes employee data by design.

package packet

import "time"

type Transition struct {
    PacketID     string    `json:"packet_id"`
    Revision     int       `json:"revision"`
    From         string    `json:"from"`
    To           string    `json:"to"`
    Attempt      int       `json:"attempt"`
    InputSHA256  string    `json:"input_sha256"`
    OutputSHA256 string    `json:"output_sha256,omitempty"`
    StartedAt    time.Time `json:"started_at"`
    CompletedAt  time.Time `json:"completed_at,omitempty"`
}
Enter fullscreen mode Exit fullscreen mode

That event is useful for traces and audit reconstruction, but events alone do not enforce correctness. The database update must compare the expected revision, the object store write must use a deterministic key, and any external signature operation must carry a stable correlation identifier. A timeout means "outcome unknown," not "nothing happened." Query the recorded state before issuing another side effect.

PDF assembly also needs structural validation before signing: expected page count or document count, declared ordering, readable cross-reference structures, embedded font checks appropriate to the templates, and a final hash. Visual regression tests with representative templates catch clipping and pagination changes that structural checks miss. Keep test fixtures synthetic; a realistic-looking tax form is still a poor excuse for putting production personal data in a repository.

Capacity is a deadline calculation, not a worker count

Monthly work is bursty. Size the path from a measured service-time distribution for each stage, then run a full-volume rehearsal with the same document complexity and concurrency limits expected in production. Average latency conceals the long tail that determines whether the last packet reaches the archive. Report p50, p95, and p99 stage duration alongside sustained end-to-end completions.

Suppose 612 packets remain with 51 minutes to the archive objective. The system must sustain 12 completed packets per minute merely to finish on time. A 30% operating margin raises the planning target to 15.6 per minute; round capacity up, but do not claim safety until a rehearsal demonstrates it under retry load. These numbers are an example calculation, not a benchmark. Document size, page complexity, network behavior, and signature latency decide the real rate.

Backpressure belongs at admission and between stages. Cap in-flight work separately for rendering, merging, and outbound signing because they consume different constrained resources. A single shared worker pool lets slow network calls occupy slots needed by CPU-bound rendering. Conversely, unlimited render concurrency can exhaust memory and turn an ordinary backlog into a process-restart loop.

The operating choice is less glamorous than the implementation choice:

Boundary Managed service favors Self-hosted component favors SLO question
PDF fill and merge Reduced patching and simpler burst capacity Template control and data locality Can the stage sustain the required batch rate with headroom?
Signature workflow Established identity and evidence procedures Control over integration and storage boundaries Can retries avoid duplicate requests and preserve evidence?
Archive Lifecycle controls and delegated durability operations Direct policy control and portability What confirms durable acceptance before the deadline?

No row decides the answer. A managed boundary may reduce on-call work while adding rate limits and an external dependency; a self-hosted boundary may improve control while transferring upgrades, scaling, and incident response to the platform team. I would score both against measured throughput, recovery time, data handling, exit effort, and on-call load. Feature counts do not carry a monthly batch through a missed dependency window.

This approach has limits. It is a poor fit for a tiny, infrequent cohort when a controlled manual workflow already meets the deadline and produces adequate evidence; operating queues, workers, traces, and reconciliation can cost more attention than the automation removes. It is also unsuitable when the team cannot define authoritative packet states or obtain stable correlation identifiers from a signing boundary, because retries then remain ambiguous. At the other extreme, a very large batch with fixed templates may justify a streaming or partitioned pipeline rather than one logical queue. The trade-off is operational control against coordination overhead: explicit stages make failures visible and recovery narrow, but they add state transitions, storage, and deployment compatibility obligations. Choose the staged design only when the deadline, volume, or audit burden pays for that machinery.

Measure it.

Recovery needs packet-level proof

Retries should resume at the last verified transition. If filling succeeded and merging failed, do not refill every form. If a signature request was accepted but its callback was delayed, reconcile by correlation identifier before creating another request. If archive confirmation is missing, compare the expected object hash and metadata at the destination. Each action needs an operator-visible reason code, not a generic failed state.

Define a dead-letter path for packets that cannot progress automatically, with a redacted diagnostic summary and a controlled requeue operation. The requeue must preserve the packet identifier and increment an attempt or revision; deleting the failed record and starting over destroys evidence precisely when evidence is most useful. Set retention by document class and legal policy rather than allowing temporary render artifacts to live forever.

Deployment follows the same caution. Roll template or renderer changes through a representative canary batch, compare structural and visual outputs, and keep the previous worker version available until the new cohort reaches durable archive confirmation. During a monthly peak, schema changes should remain backward compatible with workers already holding leases.

The SLO itself needs two views: batch completion by the contractual deadline and per-packet processing time for ordinary arrivals. The batch view protects the business event. The per-packet view prevents a healthy monthly aggregate from hiding individual employees stuck behind poison documents.

Set the alert where action is still possible

The final instrumentation change is a forecast alert with a runbook action attached. Fire when conservative projected drain time consumes a chosen fraction of the remaining deadline budget and the condition persists across enough evaluation windows to reject a brief throughput dip. Route stage-specific warnings earlier, but reserve the page for a state where an engineer can change admission, increase proven capacity, or isolate a blocked dependency.

Thresholds deserve skepticism. Set the forecast too tight and every small queue fluctuation wakes someone; responders learn that the alert usually clears itself, and attention decays. Set it too loose and the first actionable signal becomes the deadline breach described at the start. Review alert precision after each batch: how many pages required action, how many resolved without intervention, and how much decision time remained. Tune with several cohorts, because one quiet month is not evidence of capacity.

The architecture decision follows from that operational test. Choose boundaries that let the team measure forward progress, suppress duplicate side effects, and recover one packet without replaying 611 healthy ones. The winning design is the one that meets the archive SLO under a rehearsed burst while leaving an on-call engineer a small, explicit set of safe actions.

Further reading

Top comments (0)