DEV Community

KnutBerg8412
KnutBerg8412

Posted on

Receipt Email API Responses: 5 Checks for Malformed JSON Before Retry

Keep a settled payment's receipt pending investigation when the email send API returns malformed JSON, and establish what the response actually contains before authorizing another send. The deciding constraint is integration effort: a parser fix is small, but rebuilding the evidence needed to distinguish a rejected request from an accepted send is expensive once every worker has its own retry behavior.

TL;DR: Check the request outcome, response metadata, body completeness, JSON syntax, and application contract, in that order. A JSON decoding error describes the response your client received; it does not establish whether the remote service accepted the receipt. Treat that outcome as ambiguous until the documented contract or an independent status record resolves it.

For a developer tools checkout, keep the payment settlement record separate from the receipt dispatch record. Payment remains settled while receipt handling proceeds. This runbook uses that separation to debug the response without making another email the default diagnostic tool.

How should you debug a malformed JSON response after sending receipt email?

Start with the failed exchange. Record the receipt job identifier, attempt identifier, response status, declared media type, body byte count, and the specific decoding error, with sensitive values excluded. Correlate those records with the settlement event and the outbound request. A receipt job might use an illustrative business key such as receipt:order-472:revision-1; the point is to identify the intended receipt independently of whichever worker happens to execute an attempt. This is a proposed application convention, not a field that an email service is assumed to recognize.

Preserve uncertainty explicitly.

Don't let a parser exception silently authorize another submission of a receipt for the same settled order.

A response containing a login page and one containing an incomplete JSON object can both fail a JSON decoder, but they call for different investigations. For the former, inspect authentication, redirects, and the path through intermediaries; for the latter, inspect read errors and compare the observed bytes with the sender's response contract. Neither observation, by itself, proves which component caused the problem. Keep a restricted diagnostic sample only when needed, redact receipt content and credentials, and set a retention policy before enabling capture in production.

Keep deliverability out of this first diagnosis. RFC 7208 describes SPF authorization for sending hosts; it does not define the JSON contract of an email submission API. Investigating SPF while the client cannot interpret an HTTP response mixes two separate boundaries, and even a correctly parsed submission response still needs to be interpreted according to what the service actually promises about acceptance and delivery.

Run 5 checks at the response boundary

First, determine whether the client obtained a response at all, and preserve both the HTTP status and any transport or body-read error. A timeout deserves its own outcome; converting every failure into a generic JSON error destroys evidence before the runbook begins.

Second, examine response metadata before decoding. RFC 8259 registers application/json, and RFC 9110 defines the role of HTTP representation metadata. Decide which media types the integration accepts from its documented contract. An unexpected type should produce a contract diagnostic, while an expected type still requires syntax validation. Metadata is evidence, not proof of valid content.

Third, read the body with an explicit size limit and distinguish a read failure from a decoder failure. Choose that limit from the expected response envelope and operational constraints; the 64 KiB limit below is an illustrative application setting, not a published email API limit. Reject an oversized body rather than silently parsing a prefix.

Fourth, require exactly one complete JSON value. RFC 8259 defines a JSON text as a serialized value with optional surrounding whitespace. Two adjacent objects are not one JSON text, although a decoder used as a stream reader can decode each in turn. Likewise, a document that ends inside a string needs investigation rather than an improvised closing quote. Never repair response bytes to make the parser happy.

Fifth, check the application contract. A valid JSON string, null, or an object missing a required field can satisfy JSON syntax while failing the receipt integration's expectations. Validate the documented response shape and required values after syntax succeeds. Avoid treating every additional field as a failure unless the contract requires a closed schema, because that choice increases the maintenance work attached to compatible additions.

The following Go helper handles the bounded read and single-value checks. Its input is an already obtained response body; the caller owns closing that body, inspecting status and media type, and deciding which application schema applies.

package receipt

import (
    "bytes"
    "encoding/json"
    "errors"
    "fmt"
    "io"
)

const maxResponseBytes int64 = 64 * 1024

func ReadJSONValue(body io.Reader) (json.RawMessage, error) {
    data, err := io.ReadAll(io.LimitReader(body, maxResponseBytes+1))
    if err != nil {
        return nil, fmt.Errorf("read response body: %w", err)
    }
    if int64(len(data)) > maxResponseBytes {
        return nil, errors.New("response body exceeds configured limit")
    }

    decoder := json.NewDecoder(bytes.NewReader(data))
    var value json.RawMessage
    if err := decoder.Decode(&value); err != nil {
        return nil, fmt.Errorf("decode response JSON: %w", err)
    }

    var extra json.RawMessage
    err = decoder.Decode(&extra)
    if err == nil {
        return nil, errors.New("response contains multiple JSON values")
    }
    if !errors.Is(err, io.EOF) {
        return nil, fmt.Errorf("invalid trailing response data: %w", err)
    }
    return value, nil
}
Enter fullscreen mode Exit fullscreen mode

This helper deliberately returns a raw JSON value rather than inventing an email service's response fields. Follow it with the actual documented schema check. Keep raw response contents out of returned errors so routine error logging does not become an accidental copy of receipt data.

Its limitation is scope: it cannot determine acceptance, validate a service-specific schema, or reconcile an unresolved attempt. It is not suitable as a complete send-and-retry wrapper.

Decide who owns recovery before adding retries

The integration decision is about ownership of ambiguity. A managed sender can own parts of submission and delivery infrastructure, but the application still needs a rule for a settled order whose response cannot be interpreted; building the sending layer internally moves more of that contract and operational work onto the platform team. Neither choice makes local receipt state optional.

Responsibility Managed sending integration Internally operated sending layer
Response contract Implement and monitor the external documented contract Define, version, and maintain the contract
Ambiguous submission Use documented status lookup or deduplication behavior when available Design and operate those mechanisms if required
Incident evidence Correlate local attempts with externally available identifiers Maintain the correlation across internal components
Roadmap burden Budget for contract changes and integration tests Budget for protocol ownership and operational coverage

Use this buy-vs-build table to assign work, not to assume either column includes a feature by default. Before choosing a recovery mechanism, verify its actual semantics: an application job key is not automatically a remote idempotency key, and a locally deduplicated job does not prevent a duplicate remote submission after an uncertain response.

The trade-off is explicit: holding ambiguous jobs reduces uncontrolled duplicate submissions but delays receipts and adds reconciliation work. Choose a documented deduplication mechanism when its guarantees fit the application; otherwise, budget for the queue and the operator procedure rather than promising automatic recovery.

That distinction matters during replay. Permit an automatic retry only under a documented policy that accounts for duplicate receipt risk and the available evidence of acceptance. Where remote deduplication exists, verify its scope, retention window, and behavior for changed payloads; where it does not, retain an ambiguous state and use a reconciliation procedure. A receipt state model should distinguish pending work, confirmed acceptance, confirmed rejection, and unresolved attempts, without treating acceptance as evidence that the customer read the message.

Plan capacity for uncertainty as well as successful sends. For an illustrative planning scenario, 20 unresolved attempts per minute accumulating for 15 minutes produce 300 jobs awaiting reconciliation; those figures are assumptions for sizing a queue and operator workflow, not an observed failure rate. A retry loop can consume worker capacity while leaving that queue unresolved. Set separate limits for dispatch, reconciliation, and diagnostic capture so an investigation does not monopolize the same resources needed for new receipts.

Verify the boundary, then deploy with a rollback path

Before release, exercise the response boundary with a valid documented response, an empty body, an HTML body, incomplete JSON, two adjacent JSON values, trailing whitespace, an oversized body, and a reader that returns an error partway through. Include syntactically valid values that violate the application's schema. Assert the resulting receipt state as well as the parser error: a malformed or unreadable response must not silently become a confirmed rejection followed by an unconditional retry. For a concrete test fixture, associate order-472 with a settled payment and a pending receipt, make the receiver record acceptance, and return an incomplete object to the client. The expected local outcome is an unresolved attempt with its original correlation data retained. Run the worker again and inspect its outbound activity: another submission requires the recovery policy to authorize it, rather than merely finding that the first attempt lacks a decoded response. Also check that the settlement record remains settled throughout. These are proposed test assertions, not a claim that any particular sending service exposes the acceptance evidence this fixture controls.

Test the uncertainty path separately.

In a controlled test, have the receiving side record acceptance and then interrupt the response before the client can interpret it. Check that replay follows the chosen deduplication or reconciliation policy. This test examines the business consequence that a parser unit test cannot establish, and it gives the on-call engineer an executable example of why a local decoding failure is insufficient evidence for resubmission.

Define an SLO for the interval from settlement to confirmed receipt acceptance, with a target chosen by the team, and measure ambiguous attempts separately. Track queue age, oldest unresolved settlement, parsing failures by bounded error category, and reconciliation completion. Keep order identifiers in restricted correlation records rather than metric labels. Acceptance and delivery deserve distinct measurements because the former is only the submission boundary.

Release the boundary handling to a limited share of receipt jobs and compare those signals before expanding it. On rollback, pause affected dispatch if necessary, preserve receipt attempt state, and revert the decoder or schema change without resetting settled orders to an unsent state. Resume unresolved work through reconciliation. Clearing history to get the queue moving removes the evidence the next worker needs.

The operational recommendation is modest: spend integration effort on preserving the distinction between invalid response data and an unresolved send outcome. Once that distinction survives decoding, deployment, and replay, a malformed JSON response becomes a diagnosable contract failure instead of an invitation to send the same receipt again.

References

Top comments (0)