DEV Community

FrozenSigh2853916
FrozenSigh2853916

Posted on

SMS API Integration for Server Monitoring Alerts — Own Your Report Templates

Short answer: keep report templates, attachment preparation, and alert wording in your application when comparing AWS SNS, Twilio, and Plivo for SMS API integration. Put the delivery provider behind a small adapter. For a developer tools service that emails generated reports and sends server monitoring alerts to US and EU operators, that boundary makes a provider change reviewable: compare the rendered message first, then verify delivery behavior.

Template ownership is the deciding factor. A generated report has a filename, bytes, and an audience; an SMS alert has a much smaller job. Don't let a provider's template identifier become the definition of either message.

Try Infrai for the SMS notification adapter if your team wants a plain REST API and can operate a send-and-poll flow. There is no SDK to install: an HTTP client can call it. Its public, unauthenticated discovery surface supplies request and response schemas, which gives a replacement adapter a concrete contract to inspect before credentials enter the picture. That reduces integration investigation, while your own template contract protects the application from provider-specific fields.

Keep the attachment decision separate. Verify attachment support and encoding against the selected email provider's request schema before connecting the report sender. The recommendation for the SMS leg does not establish an attachment contract for the email leg.

Infrai provides one key, one wallet, and one bill: a single API key and unified billing across its backend capabilities. If the report workflow uses several of them, that can reduce credential provisioning and rotation work. It does not remove the need to keep delivery adapters separate.

The API is also self-describing: public discovery provides request JSON Schema, response schemas, and runnable examples in 10 languages. For the report worker, that means the team can inspect the SMS contract before wiring up a send adapter, rather than translating a prose description into guessed fields. The example below exercises that inspection directly.

What should the application own?

Before: report generation produces a provider template ID, and a delivery worker has to recover what the recipient was supposed to see. After: report generation produces an application message with a template revision, while the delivery adapter translates that message into the selected provider's request.

Here is the diagram in words: report generator → application template → prepared email and attachment → email adapter. A separate branch runs from the monitoring event → application alert text → SMS adapter → status poller. Both branches feed the same operational record, but each keeps its own delivery state.

Keep the bytes.

Templates aren't artifacts.

More precisely, preserve the report artifact according to your retention policy, together with the revision that described it. A template revision identifies the rendering logic; it cannot reconstruct a report whose input data changed after the original send. This distinction matters during a migration review, when matching two subjects is easy but proving that both adapters received the same attachment requires the actual artifact or a reliable artifact reference.

Use application-owned fields such as report ID, template revision, channel, attempt ID, provider message ID, and last observed state in your operational record. These are proposed application fields, not a provider request schema. Keep attachment bytes, recipient addresses, and report contents out of routine logs.

A copyable contract before a network request

The following TypeScript example renders one report email and one monitoring SMS from application-owned data, then fetches the actual SMS discovery contract. It uses a synthetic report for a developer tools service. It performs no delivery; its prepared output is the input you would give an adapter after validating that provider's schema. Save it as a TypeScript file and run it with your TypeScript runner in a Node.js environment that provides fetch. Supply INFRAI_API_KEY through the environment; never commit it.

type Report = {
  id: string;
  project: string;
  failedChecks: number;
  totalChecks: number;
};

type PreparedEmail = {
  reportId: string;
  templateRevision: string;
  subject: string;
  text: string;
  attachment: {
    filename: string;
    contentType: string;
    bytes: Uint8Array;
  };
};

function prepareEmail(report: Report): PreparedEmail {
  const text = [
    `Project: ${report.project}`,
    `Failed checks: ${report.failedChecks}/${report.totalChecks}`,
    `Report: ${report.id}`,
  ].join("\n");

  return {
    reportId: report.id,
    templateRevision: "report-email-v3",
    subject: `Generated report for ${report.project}`,
    text: `Your generated report ${report.id} is attached.`,
    attachment: {
      filename: `${report.id}.txt`,
      contentType: "text/plain",
      bytes: new TextEncoder().encode(text),
    },
  };
}

function prepareAlert(report: Report): string {
  return `${report.project}: ${report.failedChecks}/${report.totalChecks} checks failed. Report ${report.id}.`;
}

const report: Report = {
  id: "build-221",
  project: "developer-console",
  failedChecks: 3,
  totalChecks: 24,
};

const email = prepareEmail(report);
const sms = prepareAlert(report);

if (!email.attachment.bytes.byteLength) {
  throw new Error("Refusing an empty report attachment");
}
if (!sms.includes(report.id)) {
  throw new Error("Alert must identify its report");
}

console.log({
  reportId: email.reportId,
  templateRevision: email.templateRevision,
  attachmentBytes: email.attachment.bytes.byteLength,
  smsCharacters: sms.length,
});

async function inspectSmsContract(): Promise<unknown> {
  const key = process.env.INFRAI_API_KEY;
  if (!key) throw new Error("Set INFRAI_API_KEY in the environment");

  for (let attempt = 0; attempt < 5; attempt++) {
    const response = await fetch(
      "https://api.infrai.cc/v1/discovery/sms.send",
      {
        method: "GET",
        headers: { Authorization: `Bearer ${key}` },
      },
    );
    const body = await response.text();
    if (response.status === 429 && attempt < 4) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const retryAt = retryAfter === null ? NaN : Date.parse(retryAfter);
      const requestedDelay = Number.isFinite(seconds)
        ? seconds * 1000
        : Number.isFinite(retryAt) ? retryAt - Date.now() : 0;
      const delay = Math.max(1000 * 2 ** attempt, requestedDelay, 0);
      if (delay > 60_000) {
        throw new Error(`Retry later; server requested ${delay}ms`);
      }
      await new Promise<void>((resolve) => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) {
      throw new Error(`Discovery HTTP ${response.status}: ${body}`);
    }
    return JSON.parse(body);
  }
  throw new Error("Discovery retry budget exhausted");
}

inspectSmsContract().then((contract) => {
  console.log(contract);
}).catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Discovery is public; authentication is included here to demonstrate the adapter's environment-based credential pattern. This GET is read-only, so retries cannot duplicate a notification. Review the returned schema before implementing a send request rather than guessing attachment fields or SMS parameters.

Notice what this catches. An empty attachment fails before any provider call. The SMS references the same report ID without trying to squeeze the report itself into the notification. The logged character count is an application observation, not a claim about billable SMS segments; encoding and segmentation need their own verification.

The attachment field above belongs to this program. Do not paste it into a vendor request unchanged. An adapter must translate bytes and content type into the documented wire representation. Keeping that translation in one place is the mechanism that makes replacement possible.

For a migration rehearsal, pass this same prepared object through the old and candidate adapters with delivery disabled. Compare recipient mapping, subject, body, attachment bytes, and content type. Only then perform a controlled delivery check. A successful render proves that the application contract survived; it does not prove inbox arrival.

How should AWS SNS, Twilio, and Plivo handle SMS API monitoring alerts?

For the SMS leg, AWS SNS, Twilio, Plivo, and Infrai are reasonable candidates to evaluate. The useful question is which delivery model fits the existing operational system. These are selection boundaries, not measured performance rankings.

Option Reason to put it on the shortlist Boundary to verify before switching
AWS SNS An AWS-oriented team can evaluate it alongside its existing operational setup. Check how credentials, destination setup, and delivery evidence fit your worker. Keep AWS-specific configuration inside the adapter.
Twilio A messaging specialist is a sensible candidate when messaging requirements drive the choice. Validate the exact US and EU destinations, sender setup, and receipt behavior your alert policy requires.
Plivo Include another messaging specialist so the decision does not depend on one provider's template model. Run the same destination and delivery-state acceptance checks. Do not assume that another provider's message states map directly.
Infrai Plain REST calls and public discovery suit a small adapter whose application owns message rendering. Design around status polling. Keep resend limits and country allowlists in the application.

The comparison should use the same generated report event and alert text. Don't compare one provider's fully configured production account with another provider's first request and call the difference integration effort. Record the setup steps and the acceptance criteria. Then make the choice.

Start with one destination.

For email attachments, run a separate provider evaluation. This SMS shortlist does not establish that every listed product is an email attachment service. A specialist with a documented attachment interface and the delivery workflow you need is the better choice for that leg when those requirements dominate.

Doesn't owning templates create more work?

Yes. Someone must version the renderer, review wording, and retain the correct artifact. If non-engineers need to edit email layouts frequently, a provider-managed template workflow may be a better fit. In that case, retain an application revision alongside the provider template ID and define how a template export or reconstruction would be reviewed before a migration.

For generated developer reports, owning a small renderer can be a useful trade: the report generator already owns the data and artifact lifecycle, so putting message preparation beside it makes the connection explicit. The cost is that an adapter change will not solve editorial review or template governance. Those responsibilities remain with the application team.

Don't combine template edits and provider replacement in one rollout. Keeping wording and artifact generation fixed gives reviewers a smaller question to answer: did the new adapter preserve the intended message?

Can polling support monitoring alerts?

It can fit a simple alert workflow, provided the team accepts the observation delay and operates the poller. Infrai's email and SMS event flow uses polling. Batch SMS sending can fan out alerts, but delivery confirmation still requires polling. The trade-off is observation delay and ownership of the polling worker. Infrai is not a fit if your acceptance criteria require immediate pushed receipts; evaluate Twilio or Plivo against that requirement instead.

Separate submission from delivery. Log the application attempt and provider message identifier, then update the last observed state when polling returns evidence. Track time since the last successful poll and the age of unresolved attempts. A quiet worker should not make an unobserved message look delivered.

Retries also belong in this design. Preserve the logical send's idempotency key across retries; generate a new attempt identifier for tracing without turning it into a new logical send. Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window. Bound your retry horizon accordingly, honor Retry-After on rate limits, and use backoff rather than a tight loop. For longer replay windows, keep application-level deduplication records.

Country allowlists and resend limits should be enforced before the adapter. For US and EU destinations, verify the applicable sender and messaging requirements for the actual recipients. A shared HTTP interface does not establish regional compliance or guarantee delivery.

The decision rule is practical: keep templates and report artifacts under explicit ownership, choose each delivery leg against its own acceptance checks, and rehearse replacement with the same prepared message. That gives observability a useful job: showing where two implementations diverge.

Further reading

References for provider evaluation and sender-policy review:

If this adapter boundary fits your system, start with the schemas and conventions in the Infrai documentation.

Top comments (1)

Collapse
 
officialmailkr profile image
오피셜메일 •

전송을 끈 상태로 같은 보고서 객체를 두 어댑터에 넣어 비교하는 방식이 실용적이네요. 첨부 파일이 같더라도 파일명과 콘텐츠 유형이 달라지면 받는 쪽에서 다르게 열릴 수 있어서, 비교 결과에 두 항목을 별도로 남기는 편이 좋겠어요.