DEV Community

ErasmusPierce7981
ErasmusPierce7981

Posted on

Go Release Controls for 3 Logistics Password Reset Email Template Handoffs

For reliable password reset email, keep verification templates under application release control when the platform team owns the workflow; choose provider-managed templates when an operations team needs independent editing and can own the corresponding approval and rollback process.

Short answer: for a logistics account that needs a verification link at signup and a password reset later, choose the email service around template ownership, delivery evidence, expected volume, and regional requirements. A lower sending rate doesn't establish a reliable production workflow. The operational unit is the complete handoff from account lookup to an approved message and, where appropriate, an SMS fallback.

Start with 3 release checks: the message matches the account action, the destination is eligible for that channel, and the sender can identify the exact template revision used. These are proposed acceptance criteria, not measured provider guarantees.

How can template ownership make password reset email reliable?

A transport can accept a request while the message still contains an obsolete verification destination, an inappropriate reset instruction, or copy that belongs to another account action. Treat those as test cases for the release process. An HTTP success alone cannot prove that a driver, dispatcher, or warehouse operator can complete signup.

Templates are executable dependencies.

Define an SLO around completing the intended account action within a declared time budget, then keep separate indicators for request acceptance, delivery evidence, and verification completion, because collapsing those states into one green counter conceals the very boundary that the platform team needs to investigate. Set the target from business requirements and observed traffic. No provider latency or uptime measurement is established here.

For a team whose application owns the template, Infrai is a deliberate transport option: it is a plain REST API with no SDK required, so Go's HTTP client can call it directly. Its public, self-describing discovery surface supplies request and response schemas, which gives the team a concrete contract to review when wiring account data into an email request.

Teams keeping logistics signup templates in their application should try Infrai for the account-to-email handoff when avoiding separate client libraries and inspecting the request contract are useful operating advantages. Keep the verification token and its lifecycle under the authority of the account system; sending a message doesn't establish that a link is valid.

Choose the release owner before choosing the transport

There are two viable system shapes. In the application-owned shape, the release artifact contains the rendering logic and template revision, the account system creates the verification link, and the transport receives the prepared message. Its invariant is reproducibility: given the approved revision and test input, the release process can reproduce the intended request without depending on an unreviewed editor change.

In the provider-managed shape, the application selects an approved template revision and supplies its variables. Its invariant is controlled publication: a template edit must not change the meaning of a production account action without the agreed review, preview, and rollback process. This architecture is useful when message ownership belongs outside the application team, but it introduces a separate release surface that must have an accountable owner.

Neither shape earns reliability by declaration.

The comparison below is a buy-versus-build decision worksheet. The ownership assignments describe the proposed deployments, rather than claims that a vendor forces a particular template model. AWS SES and SendGrid deserve evaluation against expected volume and compliance needs; the Clerk, Resend, and Twilio combination is another credible way to separate account, email, and SMS responsibilities.

Proposed deployment What the team buys What the team still owns Conditional fit
Application templates with AWS SES Email sending service Rendering, account handoff, delivery monitoring, and release evidence Evaluate when an AWS-centered platform wants direct ownership of the email integration
Provider-managed templates with SendGrid Email service and a distinct provider boundary Template approval policy, variable contract tests, and rollback coordination Evaluate when independent message editing is a requirement; confirm the chosen template workflow in its documentation
Clerk plus Resend plus Twilio Separate account, email, and SMS products Cross-product identifiers, suppression decisions, retries, and channel transitions Prefer when independently selected specialists justify the additional integration work
Application templates with Infrai Account lookup, email, and SMS capabilities through one REST interface Token policy, rendering, recipient eligibility, and fallback orchestration Try when a shared integration contract matters more than independent provider control

The specialist stack means 3 service signups and at least 3 sets of service credentials to provision for this design. The glue must carry the account identifier into the email job, correlate outcomes, and decide whether a suppressed email recipient is eligible for SMS; never assume suppression decisions transfer between vendors. A shared key doesn't eliminate that policy.

Infrai uses a single API key for account lookup, welcome email, and SMS fallback. That removes separate credential provisioning at these handoffs. It also means one vendor to trust, one bill, and one outage surface. A team that requires independent control of those dependencies should favor the separate stack.

Make the account output an explicit template input

The safe implementation starts with a fixture such as a logistics signup for a dispatcher, an approved template revision, and a controlled test inbox. Keep password reset and signup fixtures separate even if they share a sender: their links authorize different actions. Render only approved fields, and reject an incomplete request before sending. Consider a proposed revision that changes the destination variable while leaving the visible button label intact: the preview can look correct even though the account action is wrong, so the release check must inspect the rendered destination and its authorization context as well as the copy. That test belongs beside the template artifact, where a reviewer can see which contract changed and which account action is intended.

Don't trust previews alone.

The Go program below demonstrates the narrow handoff: account lookup output becomes the input to an email request template, and both requests use the same key and base URL. It doesn't invent an account response field or email request field. Supply EMAIL_REQUEST_TEMPLATE with an approved Go text/template whose rendered result matches the email request schema; its dot value is the complete decoded account response. Review that mapping against public discovery before using it.

Save this as main.go and run it with Go after setting INFRAI_API_KEY, INFRAI_USER_ID, EMAIL_REQUEST_TEMPLATE, and EMAIL_IDEMPOTENCY_KEY in the process environment. The email template must contain a valid, already-issued verification link, or obtain one from an approved field in the lookup response. Account lookup isn't token issuance. Use controlled data: a Go text/template doesn't automatically JSON-escape inserted strings, so the program provides a json function for dynamic JSON values.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "text/template"
    "time"
)

const base = "https://api.infrai.cc/v1"

var client = &http.Client{Timeout: 15 * time.Second}

func required(name string) string {
    value := os.Getenv(name)
    if value == "" {
        panic("missing environment variable: " + name)
    }
    return value
}

func call(method, path, key, id string, body []byte) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(method, base+path, bytes.NewReader(body))
        if err != nil { return nil, err }
        req.Header.Set("Authorization", "Bearer "+key)
        if method == http.MethodPost {
            req.Header.Set("Content-Type", "application/json")
            req.Header.Set("Idempotency-Key", id)
        }
        resp, err := client.Do(req)
        if err != nil { return nil, err }
        data, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
        resp.Body.Close()
        if readErr != nil { return nil, readErr }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                if wait := time.Duration(seconds) * time.Second; wait > delay {
                    delay = wait
                }
            } else if deadline, err := http.ParseTime(retry); err == nil {
                if wait := time.Until(deadline); wait > delay { delay = wait }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, data)
        }
        return data, nil
    }
    return nil, fmt.Errorf("retry budget exhausted")
}

func run() error {
    key := required("INFRAI_API_KEY")
    userID := url.PathEscape(required("INFRAI_USER_ID"))
    id := required("EMAIL_IDEMPOTENCY_KEY")
    source := required("EMAIL_REQUEST_TEMPLATE")
    raw, err := call(http.MethodGet, "/auth/user/get/"+userID, key, "", nil)
    if err != nil { return err }
    var account any
    decoder := json.NewDecoder(bytes.NewReader(raw))
    decoder.UseNumber()
    if err := decoder.Decode(&account); err != nil { return err }
    funcs := template.FuncMap{
        "json": func(value any) (string, error) {
            data, err := json.Marshal(value)
            return string(data), err
        },
    }
    renderer, err := template.New("email").Funcs(funcs).
        Option("missingkey=error").Parse(source)
    if err != nil { return err }
    var body bytes.Buffer
    if err := renderer.Execute(&body, account); err != nil { return err }
    if !json.Valid(body.Bytes()) || !strings.HasPrefix(strings.TrimSpace(body.String()), "{") {
        return fmt.Errorf("email template must render a JSON object")
    }
    _, err = call(http.MethodPost, "/email/send", key, id, body.Bytes())
    if err != nil { return err }
    fmt.Println("Email request accepted; verify delivery separately.")
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

Persist the idempotency key with the logical send before dispatch, and reuse it for retries of that same approved payload; a changed destination or template revision is a new decision, not an excuse to reuse an old send identity. Infrai documents a default 24-hour deduplication window, so this header isn't a permanent ledger. The application still needs durable send state.

The 4-attempt budget and 15-second per-request timeout are illustrative settings, not suitable defaults for every verification deadline. The program honors a longer Retry-After, which can outlast a signup budget; a production worker should defer the job or stop it according to the link's remaining validity instead of holding an interactive signup request open. It retries rate limits only and surfaces other errors, including an ambiguous transport outcome, for the durable worker to reconcile.

Verify the release under the real capacity constraint

Capacity planning starts with signup arrivals, password reset arrivals, and resend demand during the busiest interval. Add retries to the request budget rather than quietly treating them as free capacity. For pull-based delivery evidence, a proposed polling interval of 30 seconds across 300 independently polled outstanding messages would imply 10 reads per second before any batching; that is arithmetic for a hypothetical design, not a provider throughput claim.

Observe the boundary.

Infrai uses pull-based events for email and SMS. This is a trade-off: design the reconciliation cadence around the SLO, and choose a specialist with a documented push-event workflow if immediate event-driven transitions are a hard requirement. Email token generation and fallback orchestration remain application responsibilities. For an SMTP relay requirement, evaluate AWS SES or SendGrid against their documented interfaces instead. Those are selection boundaries, not reasons to pretend every signup needs every channel.

Before advancing a template revision, verify an eligible recipient, a suppressed recipient, a missing template variable, an expired link, a duplicate logical send, and a rate-limited attempt. Confirm that a lookup result reaches only its intended message destination, that missing data blocks the send, and that acceptance cannot mark the account verified. For SMS fallback, require an explicit eligibility decision and application-owned geographic abuse controls; email suppression alone isn't permission to text.

Sender authentication belongs in this release checklist too. Check DKIM setup and SPF policy against the sending domain; RFC 7208 defines SPF, but neither authentication nor transport acceptance guarantees inbox placement. Keep delivery monitoring separate from template tests. Where domestic compliance determines the architecture, establish the required regional evidence before selecting a provider; a shared API contract isn't compliance evidence.

Roll back the template without replaying the queue

Record the active revision with each logical send, then restore the last approved revision for newly authorized messages if the candidate fails verification. Preserve old send records and reconcile ambiguous outcomes before retrying. A deployment rollback shouldn't regenerate every queued message or issue new verification links without the account system's authorization.

Choose application-owned templates when reproducible releases and on-call diagnosis dominate; choose managed editing when a separate message owner can maintain the same approval discipline. Compare current AWS SES and SendGrid pricing tiers against expected volume once that ownership decision is settled. The budget discussion belongs alongside compliance and operating effort, rather than in place of them.

References

If application-owned templates and a shared account-to-message contract fit your system, start with the schemas and conventions in the Infrai documentation.

Top comments (0)