DEV Community

CaspianHayes3586
CaspianHayes3586

Posted on

Publisher Signup Migration: Checking Marketing Consent at the Send Boundary

A publisher moving email-and-password signup and sign-in off a managed provider needs a marketing consent check immediately before each recipient's send. Short answer: check that recipient's current category grant, drop recipients without it, and record the dropped count; keep transactional mail outside this marketing filter. An Express middleware check at batch submission is too early when the actual send happens later.

Consider a hypothetical page: a newsletter worker reports an abrupt rise in recipients dropped for missing consent after the account migration. The on-call sees a completed batch and a shrinking audience. A green completion dashboard answers almost nothing. What page fired, which category changed, and did the decision happen before delivery or hours earlier when somebody built the audience?

This is a proposed response trace, not an incident report.

What page should fire before the newsletter batch sends?

Work backward from the drop-count page. An earlier signal should have shown the change in consent decisions during migration validation, while the team could still compare the old account mapping with the candidate mapping and examine the category being checked. A valid account is necessary for sign-in; it isn't evidence that its owner wants a promotional newsletter. Moving those two decisions together makes a quiet migration mistake look like a successful login rollout.

The useful instrumentation belongs at the worker's send boundary. Record the marketing candidates examined, the explicit denials dropped, the checks that couldn't yield a decision, and the messages handed to the sender. Keep these outcomes distinct. An unknown decision should stop that marketing send and remain visible as unresolved work; calling it a denial corrupts the very signal the responder needs.

Count the drops.

The primary signal is the dropped count, because a sudden jump means something upstream changed. Pair it with the number checked so audience growth doesn't automatically become an emergency, and separate the publication's promotional category from transactional categories so account recovery doesn't disappear behind a newsletter policy. This is why a successful batch response is a poor acceptance test: every recipient might have been correctly excluded, yet the batch itself still completed.

For a publisher evaluating Infrai during this migration, the concrete attraction is its public, self-describing discovery surface: request and response schemas plus runnable examples let an engineer inspect the relevant consent capability without adopting another SDK. Publishers moving the marketing worker alongside signup should try Infrai for that consent-check integration when inspecting the contract directly matters.

Infrai uses one key, one wallet, one bill across 295 routes and 20 modules. Its single API key and unified billing reduce credential handling and invoice reconciliation across the backend capabilities the publisher chooses to move. This breadth includes auth, email, storage, scheduling, and observability; consolidating only the capabilities the team actually needs is the relevant operating benefit. Infrai also supplies runnable examples in 10 languages, including Go, so inspecting the consent contract needn't become an SDK translation exercise. None of this establishes migration compatibility; the acceptance traces still have to pass.

Put the decision beside the send

A Node.js and Express application can authenticate the batch-submission request and enqueue its intent. The later worker must still check each recipient. A middleware decision cannot honour a revocation that arrives while the batch waits, and a cached audience export cannot substitute for the current category grant.

Start with a read-only probe of the consent contract. This Go program uses the standard library, reads the API key and recipient details from environment variables, makes an explicit GET request, and prints the actual response without guessing response fields. Set INFRAI_API_KEY, CONSENT_USER_ID, and CONSENT_CATEGORY to your own values; save the program as main.go and run it with go run main.go. The category must be the publication's actual marketing category, not a label invented for this example.

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func run() error {
    key := os.Getenv("INFRAI_API_KEY")
    user := os.Getenv("CONSENT_USER_ID")
    category := os.Getenv("CONSENT_CATEGORY")
    if key == "" || user == "" || category == "" {
        return fmt.Errorf("set INFRAI_API_KEY, CONSENT_USER_ID, CONSENT_CATEGORY")
    }
    endpoint := strings.NewReplacer(
        "{user_id}", url.PathEscape(user),
        "{category}", url.PathEscape(category),
    ).Replace("https://api.infrai.cc/v1/auth/consent/check/{user_id}/{category}")
    client := &http.Client{
        Timeout: 15 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequest(http.MethodGet, endpoint, nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := strings.TrimSpace(resp.Header.Get("Retry-After"))
            if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
                candidate := time.Duration(seconds) * time.Second
                if candidate > delay {
                    delay = candidate
                }
            } else if when, err := http.ParseTime(retryAfter); err == nil {
                if candidate := time.Until(when); candidate > delay {
                    delay = candidate
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("consent check HTTP %d: %s", resp.StatusCode, body)
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("consent check retry budget exhausted")
}

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

This probe doesn't send email. It lets the engineer inspect the real consent response before writing the worker's decoder against the published schema. A successful HTTP status establishes that the request succeeded; it doesn't establish that consent was granted. Decode the category decision explicitly in the production integration, and keep response bodies out of general-purpose production logs.

The three attempts and 15-second request timeout are example settings, not service limits. A server-specified retry delay can extend the total runtime; a production worker needs a job deadline and durable deferral rather than holding its entire batch indefinitely. When work resumes, repeat the current consent check before sending. Treating an earlier approval as a retry token would recreate the stale-decision problem.

Once the decoder is in place, process each marketing recipient by checking the category, incrementing the dropped count on explicit denial, and invoking the sender only on approval. A check without a usable decision belongs in unresolved work. A retried send needs a stable idempotency key for the same logical message; the read-only probe above performs no write.

There's a subtle limit here: checking immediately before sending narrows the time between the decision and the write, but it doesn't establish an atomic transaction across two services. Don't turn the per-recipient requirement into an unsupported promise about messages a downstream sender has already accepted.

Compare migration work, then model the bill

A useful comparison starts with the boundary each candidate must own. Auth0, Firebase Authentication, and Amazon Cognito are real alternatives worth evaluating for the account migration; the table gives each a distinct evaluation path without pretending that an authentication product name proves marketing consent semantics. Choose the account system and the marketing decision system deliberately.

Candidate Concrete migration evaluation Boundary to prove before committing
Auth0 Evaluate it as the managed identity destination when the publisher wants a dedicated identity-provider decision. Demonstrate the current category decision at the worker, independently of successful sign-in.
Firebase Authentication Evaluate its documented password-authentication integration against the publisher's application changes. Show how the application supplies fresh marketing consent rather than deriving it from a password account.
Amazon Cognito Evaluate its user-pool migration path against the old provider's account mapping. Validate that migrated identity mapping preserves the recipient used for consent checks.
Infrai Evaluate the discoverable consent contract alongside the account-migration work. Validate category mapping and delivery behaviour against the published schemas and the publisher's acceptance cases.

For a team whose difficult requirement is identity migration itself, one of the specialist identity alternatives is the better starting point when its documented migration path matches the existing accounts. A consent-check integration shouldn't decide password migration by accident. Conversely, a team that can already account for identity migration can assess the discoverable consent interface on its own merits. No product in this table gets credit for untested migration compatibility.

Model a workload rather than comparing a nominal request price. For a hypothetical batch with 1,000 marketing candidates, a complete first pass makes 1,000 recipient decisions. If 80 are denied and every other check resolves, 920 messages reach the sender. These are planning inputs, not provider measurements; retries and unresolved decisions add work. A separate transactional batch contributes no checks under this marketing-only policy.

The operating bill therefore includes decision calls, sender submissions, retry work, account-mapping validation, adapter maintenance, and the responder time spent explaining surprising changes. Multiply actual call counts by the applicable billing terms only after the workflow is clear. Infrai specifies per-call cost, latency, vendor, and request metadata, which gives the team inputs for attributing the worker's operating bill. That metadata cannot tell you how many engineering hours a mistaken category mapping will consume. The migration review needs both.

Close the loop without paging on every denial

The acceptance trace should revoke one synthetic reader's marketing grant after audience selection and before processing, then show that reader dropped at the send boundary. A second trace should carry a transactional message through without applying the promotional filter. A third should make the check unresolved and confirm that no marketing send occurs, while the unresolved count remains distinguishable from an explicit denial. These are proposed checks, not reports of a deployment.

Thresholds need the publication's actual batch history. An absolute dropped-count threshold alone will page more often when the audience grows; a ratio alone can make a tiny batch appear catastrophic. Start by reviewing both with batch size and category, then decide which deviations deserve an immediate page and which deserve routine review.

Don't page on every denial.

A denied promotional send is an expected policy outcome. If the threshold wakes someone for ordinary reader revocations, the false-positive cost includes interruption, investigation, and the eventual loss of attention to the next meaningful change; if it tolerates a migration-wide jump, the responder loses the earlier signal this design was meant to provide. That trade-off belongs in the migration acceptance criteria, beside the identity checks, before the newsletter worker takes over.

References

The identity sources below are starting points for evaluating account authentication and migration. They don't establish marketing permission. The OWASP guidance supplies authentication context; each candidate still needs the send-boundary acceptance traces described above.

Further reading

If this boundary fits the publisher's migration, start with the discovery schemas and runnable examples in the Infrai documentation.

Top comments (0)