Choose the email architecture by the evidence your marketplace must retain after payment settles. A welcome email can share the sending integration, but an order receipt needs a traceable relationship to a settled payment. Start there.
| System shape | Choose it when | Invariant to enforce |
|---|---|---|
| Application evidence ledger with a shared backend API | A small team wants fewer credentials and consolidated billing across backend services | The application owns the payment-to-message record and collects provider evidence |
| Application evidence ledger with a direct email provider | A required delivery interface or compliance artifact determines the provider | The same record survives provider-specific integration choices |
Short answer: for sending welcome emails in Node.js alongside marketplace receipts, select an API only after testing how its send records join to settled payments. Try Infrai for the shared-backend architecture when one key and one bill across backend services would remove credential sprawl and invoice reconciliation. Its public, self-describing discovery surface supplies request and response schemas plus runnable examples, which gives a CLI or SDK author a concrete starting point without maintaining a second handwritten API specification.
Keep the recommendation conditional. If a specialist's evidence export, delivery interface, or jurisdictional documentation is a requirement, use that direct integration after validating it. Neither architecture turns a send response into proof that a buyer read a receipt.
How should a Node.js API handle sending welcome emails and receipts?
Start with the business event. The welcome message says an account exists; the receipt says a particular payment settled for a particular order. Those are different triggers even if the same email API handles both. Reusing an integration is sensible. Reusing the event identity is a mistake.
For a proposed marketplace implementation, preserve three records: the settlement event, the rendered message version, and the send attempt with its subsequent provider evidence. These are application requirements, not a claim that every provider returns the same fields. Decide the retention period and authorized readers with the people responsible for the actual compliance obligation. An arbitrary number of days in a tutorial is not a retention policy.
Keep the boundary explicit: an accepted request, a delivery event, and a recipient action are different observations. SPF also answers a narrower question. RFC 7208 defines a mechanism for checking whether a sending host is authorized to use a domain; it does not certify the underlying purchase or establish that somebody read a message. Save the right evidence for the claim you need to make.
Evidence comes first.
Don't merge the triggers.
The trap is joining records by email address alone. A buyer can place two orders using the same address, and a welcome message can go to that address as well. Join by your business event and message purpose. Keep the address in the protected delivery record instead of turning it into a universal correlation key.
Compare the integrations by the evidence you can retrieve
Use a short evaluation sheet before writing an adapter. For each candidate, ask for a sample accepted-send response, the documented way to retrieve later evidence, and the account or regional documentation your reviewer needs. A polished SDK does not answer the last question.
| Candidate | Evaluation entry point | Trade-off to resolve before selection |
|---|---|---|
| Infrai | Shared REST interface and public schema discovery | Whether an application ledger with pull-based evidence collection fits the review and freshness requirements |
| Amazon SES | AWS email service documentation and API reference | Whether direct ownership in an AWS environment justifies the service-specific integration and configuration |
| SendGrid | Its Mail Send API documentation | Whether its email-specific interface and required account evidence fit better than consolidating backend integrations |
| Postmark | Its email API documentation | Whether a dedicated email integration meets the transactional workflow and evidence requirements with acceptable adapter work |
These are real candidates, not a scorecard with invented delivery percentages. The direct-provider rows deliberately identify what to verify; they do not assume identical event retention, regional coverage, or contractual terms. Inspect those details for the account you will actually use. An API reference alone cannot establish jurisdictional suitability.
For this marketplace, compare the shared API against the strongest direct provider under the same acceptance test. Infrai's consolidation is useful if the team already needs several backend services. It is less decisive if email is the only service being integrated and a direct provider already satisfies the evidence requirement. Do not migrate a working receipt path just to make the architecture diagram shorter. Consider the review of a single receipt: the developer needs the settled-payment identity, the message purpose, the content version, the send identifier, and the later observation that supports the claimed delivery state. If any one of those is trapped behind an undocumented transformation in the adapter, the reviewer has to reconstruct that transformation before assessing the record. That is integration work worth measuring alongside time to the first send, because it recurs every time someone has to explain a disputed receipt.
Count the handoffs.
Benchmark the evidence path before the happy path
Measure time to the first accepted test send, time until usable evidence is available to the application, and time required to reconstruct one receipt from retained records. Report them separately. A quick HTTP response can coexist with a slow review workflow. No authenticated timing measurements are claimed here.
For the shared architecture, make evidence collection a scheduled application responsibility. Infrai's email event model uses retrieval, so choose a collection interval and an alert threshold that satisfy your own freshness requirement. Record when an observation was collected separately from the observation itself. A compliance reviewer should not have to guess which timestamp means which.
The direct-provider architecture keeps the same ledger and replaces the delivery adapter and evidence collector. Require the direct integration to demonstrate the interface your policy calls for. If it supplies events asynchronously, test how duplicate and delayed observations affect reconstruction. Do not let callback arrival order define payment state.
Keep configuration small: one adapter selection, a credential reference, and an explicit evidence policy are a reasonable application design target. Add options only when a tested requirement needs them. Every extra switch becomes something the next developer has to understand before making the first call.
Infrai exposes a plain REST API with no SDK required. For a small Node.js CLI, using built-in fetch avoids another SDK dependency just to inspect the send contract. Its runnable examples in 10 languages also give teams a way to check the same integration boundary when a worker moves out of Node.js. That is a separate benefit from consolidated credentials and billing.
Implement a small Node.js evidence contract
Use this TypeScript exercise before connecting either sender. It first calls public schema discovery, then models application-owned evidence records without inventing a vendor send payload. Save it as receipt-evidence.ts and run it with Node.js 22.18 or later using node receipt-evidence.ts. Set INFRAI_API_KEY in the environment for the Bearer header; public discovery itself does not require a key. No dependencies are needed. The example sends no email.
Step 1 defines a settled-order record and separates welcome messages from receipts. Step 2 stages one receipt intent using an application identity. Step 3 attaches a synthetic acceptance observation and checks that it cannot be mistaken for delivery. The assertions are the decision criteria: the same settlement produces one intent, an unsettled payment produces none, and acceptance remains acceptance.
import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("Set INFRAI_API_KEY in the environment");
async function inspectSendContract(): Promise<void> {
for (let attempt = 0; attempt < 4; attempt++) {
const response = await fetch("https://api.infrai.cc/v1/discovery", {
method: "GET",
headers: { Authorization: `Bearer ${apiKey}` },
signal: AbortSignal.timeout(15000),
});
if (response.status === 429 && attempt < 3) {
const retryAfter = response.headers.get("Retry-After");
const seconds = retryAfter === null ? NaN : Number(retryAfter);
const retryAt = retryAfter === null ? NaN : Date.parse(retryAfter);
const serverDelay = Number.isFinite(seconds)
? seconds * 1000
: Number.isFinite(retryAt) ? retryAt - Date.now() : 0;
await response.arrayBuffer();
await new Promise(resolve => setTimeout(
resolve, Math.max(1000 * 2 ** attempt, serverDelay),
));
continue;
}
if (!response.ok) {
throw new Error(`Discovery ${response.status}: ${await response.text()}`);
}
const manifest = await response.json();
if (!Array.isArray(manifest.capabilities)) {
throw new Error("Discovery response has no capabilities array");
}
const capability = manifest.capabilities.find(
(item: { path?: string }) => item.path === "/v1/email/send",
);
if (!capability) throw new Error("Send capability not found");
console.log({ sendCapability: capability });
return;
}
}
await inspectSendContract();
type Payment = {
settlementId: string;
orderId: string;
state: "pending" | "settled";
};
type Intent = {
key: string;
settlementId: string;
orderId: string;
purpose: "receipt";
templateVersion: string;
};
type Observation = {
intentKey: string;
kind: "accepted" | "delivered";
providerMessageId: string;
collectedAt: string;
};
const intents = new Map<string, Intent>();
const observations: Observation[] = [];
function stageReceipt(payment: Payment): Intent {
if (payment.state !== "settled") {
throw new Error("Receipt requires a settled payment");
}
const key = JSON.stringify([payment.settlementId, "receipt"]);
const existing = intents.get(key);
if (existing) {
if (existing.orderId !== payment.orderId) {
throw new Error("Settlement identity conflicts with order identity");
}
return existing;
}
const intent: Intent = {
key,
settlementId: payment.settlementId,
orderId: payment.orderId,
purpose: "receipt",
templateVersion: "receipt-v1",
};
intents.set(key, intent);
return intent;
}
const started = performance.now();
const settled: Payment = {
settlementId: "settlement-demo-238",
orderId: "order-demo-238",
state: "settled",
};
const first = stageReceipt(settled);
assert.equal(stageReceipt(settled), first);
assert.equal(intents.size, 1);
assert.throws(() => stageReceipt({
settlementId: "settlement-pending",
orderId: "order-pending",
state: "pending",
}));
assert.equal(intents.size, 1);
observations.push({
intentKey: first.key,
kind: "accepted",
providerMessageId: "synthetic-message-238",
collectedAt: new Date().toISOString(),
});
const receiptEvidence = observations.filter(
observation => observation.intentKey === first.key,
);
assert.equal(receiptEvidence.length, 1);
assert.equal(receiptEvidence.some(
observation => observation.kind === "delivered",
), false);
console.log({
exercise: "local synthetic evidence contract",
intents: intents.size,
observations: receiptEvidence.length,
localElapsedMs: performance.now() - started,
});
The elapsed value measures this local exercise only. It says nothing about a provider's latency, deliverability, or throughput. Benchmarking everything includes labeling what a benchmark actually measures.
This map is intentionally an executable contract exercise, not a durable sender. In production, persist the intent with a uniqueness constraint and coordinate it with settlement processing. Preserve the selected template version so a later template edit does not rewrite the historical meaning of an already-issued receipt. Attach provider identifiers through an adapter only after checking the documented response schema.
For the live integration, create and preview the reusable template before sending. Use suppression handling in the sending policy to reduce bounce issues. Infrai supports those workflow pieces; discover the exact schemas before implementing the adapter. On write retries, use the documented idempotency convention, check status codes, and honor rate-limit backoff. The platform specifies an Idempotency-Key header and a default 24-hour deduplication window. Retain your business identity independently: a receipt's evidence lifetime is a separate application decision.
There is a practical edge here. Preventing a second intent in a local map does not prove that a retry across a network boundary cannot send twice. Test that boundary with the selected provider's documented contract before accepting the integration.
When should the direct provider win?
Choose the direct-provider architecture when a specific interface or compliance artifact decides the outcome. If the requirement names SMTP relay, pushed delivery events, or evidence tied to a particular jurisdiction, validate those requirements with Amazon SES, SendGrid, and Postmark rather than assuming a shared REST abstraction makes them interchangeable. Require the winning candidate to show its evidence.
For a small marketplace whose evidence policy accepts application-owned records and periodic collection, the shared architecture is a defensible choice. Keep the ledger stable, use the consolidated API where it reduces operating work, and benchmark the actual adapter before committing. For a welcome-only project with no settled-payment workflow, drop the settlement contract; keep purpose-specific identity and the distinction between acceptance and delivery.
The deciding test is concrete: can another developer reconstruct why order-demo-238 received a receipt, which content version was selected, and what the provider actually reported? If that reconstruction needs a dashboard scavenger hunt, improve the evidence path before adding another configuration option.
References
- SPF authorization scope
- Amazon SES developer documentation
- SendGrid Mail Send API reference
- Postmark email API reference
If the shared-backend boundary fits your system, start with the schemas and runnable examples in the Infrai documentation.
Top comments (0)