Skip to content

Design Requirements Document: Communication Service on Cloudflare Workers

Version: 2.0

Date: August 24, 2025

Authors: Grok (based on user discussion)

Status: Draft


1. Overview

1.1 Purpose

This document outlines the design requirements for the Communication Service, a microservice responsible for sending user-facing email notifications in the StratIQX microservices architecture. The service supports email notification types (welcome_email, otp_email, payment_email, contact_email) using static templates defined in a TypeScript configuration class, adhering to the StratIQX Email Template Guidelines v2.0. It is hosted on Cloudflare Workers for serverless deployment, integrates with Resend for email delivery (ported from an existing worker), and implements the X-Service authentication pattern for secure service-to-service communication, as per the StratIQX Email System Troubleshooting & Integration Guide. The design leverages the Error-Driven Design Pattern (EDDP) for robust error handling and is accessible at comm.stratiqx.ai/send.

1.2 Scope

  • In Scope:
    • Email sending via Resend with guideline-compliant templates.
    • Service-to-service authentication using X-Service headers.
    • Static template management via TypeScript configuration.
    • Error handling with EDDP.
    • API endpoint for sending communications.
  • Out of Scope:
    • SMS support (planned for future iterations; otp_email used instead of otp_sms).
    • Database or Workers KV storage for templates (static only for now).
    • Advanced features like webhooks or queuing (future enhancements).
  • Assumptions:
    • Resend is implemented in an existing Cloudflare Worker and can be ported seamlessly.
    • The Identity Server (auth.stratiqx.ai) supports X-Service authentication.
    • TypeScript is the standard for development, aligning with existing conventions.
    • The stratiqx.ai domain is verified in Resend with proper DNS records.

1.3 Key Stakeholders

  • Development Team: Implements and maintains the service.
  • Operations Team: Manages Cloudflare Workers deployment and secrets.
  • Product Team: Defines notification types and template content.
  • Design Team: Ensures compliance with StratIQX Email Template Guidelines.
  • Security Team: Validates X-Service authentication integration.

2. Functional Requirements

2.1 Core Functionality

  • Service Name: Communication Service.
  • Subdomain/Endpoint: Exposed at comm.stratiqx.ai/send via a POST API.
  • Input: Accepts a JSON payload (CommunicationPayload) containing:
    • communication_type: Identifies the notification type (e.g., welcome_email, otp_email).
    • user_id: Required for logging and tracking.
    • email: Recipient email address (required).
    • Dynamic template data (e.g., name, otp, amount, message).
  • Output: Sends the email via Resend and returns a success response (HTTP 200) or error details (HTTP 400/401/500).
  • Channel Supported: Email only (via Resend). SMS support is planned for the future.
  • Notification Types:
    • welcome_email: Service activation email with welcome message (from welcome@stratiqx.ai).
    • otp_email: OTP verification email (from auth@stratiqx.ai).
    • payment_email: Payment confirmation email with transaction details (from billing@stratiqx.ai).
    • contact_email: Acknowledgment of user contact request (from welcome@stratiqx.ai).
    • Extensible for additional email types.
  • Authentication: Requests must include Authorization: Bearer <admin-token> and X-Service: stratiqx-<service-name> headers, validated against the Identity Server.

2.2 Template Management

  • Storage: Templates are defined statically in a TypeScript configuration class (CommunicationTemplateConfig).
  • Template Structure: Each template complies with the StratIQX Email Template Guidelines v2.0 and includes:
    • communicationType: Unique identifier (e.g., welcome_email).
    • channel: email (SMS not supported yet).
    • subject: Email subject (e.g., "Welcome to StratIQX Intelligence Services").
    • content: HTML content with Handlebars placeholders (e.g., , ), using:
      • Inter font via Google Fonts.
      • Inline SVG Lucide icons for visual elements.
      • Theme-specific colors (Success Green, Security Blue, Payment Amber).
      • Components: Header, Hero, Service Activation Card, Information Card, Analyst Contact Card, CTA, Support, Footer.
  • Rendering: Use Handlebars to merge payload data with templates.
  • Future: SMS templates (e.g., for otp_sms) will be added when SMS support is implemented.

2.3 API Specification

  • Method: POST /send.
  • Request Headers:
    • Authorization: Bearer <admin-token>: Service token from Identity Server.
    • X-Service: stratiqx-<service-name>: Identifies calling service (e.g., stratiqx-payment).
  • Request Body: JSON CommunicationPayload:
    typescript
    interface CommunicationPayload {
      communication_type: string;
      user_id: string;
      email: string;
      name?: string;
      [key: string]: any; // e.g., otp, amount, transactionId, message
    }
  • Response:
    • Success: { "message": "Communication sent" } (HTTP 200).
    • Error: { "error": { "name": "ErrorName", "message": "Details" } } (HTTP 400/401/500).
  • Rate Limiting: Handle Resend rate limits (HTTP 429) with retries.

2.4 Extensibility

  • Support new email types by adding templates to CommunicationTemplateConfig.
  • Plan for SMS integration (e.g., Twilio HTTP API) in the future.
  • Allow dynamic template storage in Workers KV in future iterations.
  • Support Resend webhooks for email event tracking (e.g., delivered, bounced).

3. Non-Functional Requirements

3.1 Performance

  • Latency: < 500ms for processing and sending (excluding Resend delays).
  • Throughput: Handle up to 100 requests/second, scalable via Cloudflare Workers.
  • Template Rendering: Handlebars rendering < 50ms per request.

3.2 Security

  • Authentication:
    • Require Authorization and X-Service headers for all requests.
    • Validate tokens against the Identity Server (auth.stratiqx.ai).
    • Store AUTH_ADMIN_TOKEN and RESEND_API_KEY in Workers Secrets.
  • Input Validation: Sanitize payloads to prevent injection (e.g., validate email format).
  • Data Privacy: Handle sensitive data (e.g., email, name) per GDPR/CCPA.
  • CORS: Restrict X-Service header to Workers (not browser clients).

3.3 Reliability and Error Handling (EDDP)

  • Error-Driven Design Pattern:
    • Custom error classes:
      • InvalidPayloadError: Missing or invalid payload fields.
      • TemplateNotFoundError: Invalid communication_type.
      • ChannelError: Unsupported channel (future-proof for SMS).
      • EmailProviderError: Resend API failures.
      • UnauthorizedError: Failed X-Service authentication.
    • Centralized error handling: Log errors with context (user_id, communication_type, timestamp) via handleError.
    • Propagate errors to the caller with HTTP status codes:
      • 400: Client errors (e.g., invalid payload, missing template).
      • 401: Authentication failures.
      • 500: Server or provider errors.
    • Logging: Use console.error for Cloudflare logs; plan for external logging (e.g., Sentry via fetch).
  • Retries: Implement exponential backoff for Resend rate limits (HTTP 429).
  • Fail-Fast: Validate inputs and environment variables at startup.

3.4 Maintainability

  • Tech Stack: TypeScript, Handlebars, raw fetch for Resend (or SDK if compatible).
  • Dependencies: Minimal; Handlebars for rendering, no Node.js-specific modules.
  • Testing:
    • Unit tests: Template rendering, authentication, error handling.
    • Integration tests: Resend API calls, end-to-end flow.
  • Monitoring: Use Cloudflare dashboards and wrangler tail for logs.

3.5 Deployment

  • Platform: Cloudflare Workers (serverless, V8 runtime).
  • Configuration: wrangler.toml for vars/routes; secrets for API keys.
  • Domain: comm.stratiqx.ai mapped via Cloudflare Routes.
  • CI/CD: Deploy with wrangler deploy.

4. Architecture

4.1 High-Level Diagram

[Client Services (e.g., Payments Service)] --> POST /send (JSON Payload, X-Service Headers) --> Cloudflare Worker (comm.stratiqx.ai)

Worker Runtime:
- Fetch Handler: Validates X-Service headers, parses payload.
- CommunicationService: Validates payload, renders template, sends email.
  - CommunicationTemplateConfig: Static templates, Handlebars rendering.
  - sendEmail: Fetch to Resend API.
- Error Handling: Custom errors, centralized logging, response mapping.

External Integrations:
- Resend API: Email delivery (welcome@stratiqx.ai, auth@stratiqx.ai, billing@stratiqx.ai).
- Identity Server (auth.stratiqx.ai): Token validation.

4.2 Components

  • CommunicationTemplateConfig: Static class for guideline-compliant email templates.
  • CommunicationService: Handles payload processing, authentication, and email sending.
  • Fetch Handler: Processes HTTP requests, validates X-Service headers.
  • Env Interface: Accesses secrets/vars (RESEND_API_KEY, AUTH_ADMIN_TOKEN, AUTH_BASE_URL).

4.3 Data Flow

  1. Receive POST request with Authorization, X-Service, and CommunicationPayload.
  2. Validate X-Service headers (EDDP: Throw UnauthorizedError if invalid).
  3. Validate payload (EDDP: Throw InvalidPayloadError if invalid).
  4. Retrieve and render template (EDDP: Throw TemplateNotFoundError if missing).
  5. Send email via Resend (EDDP: Throw EmailProviderError on failure).
  6. Log errors centrally and return HTTP response.

5. Integration Details

5.1 Resend Integration

  • Porting: Use existing Resend implementation from another Worker.
  • API Calls: Use fetch to Resend's /emails endpoint for Workers compatibility.
  • Configuration:
    • From addresses: welcome@stratiqx.ai, auth@stratiqx.ai, billing@stratiqx.ai.
    • Tags: Include communication_type for tracking.
    • Verify domain in Resend (DKIM/SPF/DMARC).
  • Error Handling: Wrap API errors in EmailProviderError; handle rate limits with retries.

5.2 X-Service Authentication

  • Headers:
    • Authorization: Bearer <admin-token>: Service token from Identity Server.
    • X-Service: stratiqx-<service-name>: Identifies calling service.
  • Validation: Check headers in fetch handler; optionally validate tokens via auth.stratiqx.ai.
  • Error Handling: Return HTTP 401 with UnauthorizedError for invalid headers/tokens.
  • Logging: Log authentication failures per the troubleshooting guide.

5.3 Template Guidelines Compliance

  • Structure: Follow Welcome Email layout with components (Header, Hero, Service Activation, Information Card, Analyst Contact, CTA, Support, Footer).
  • Branding:
    • Logo: Strat<span style="color: #2563eb;">IQ</span><span style="color: #06b6d4;">X</span>.
    • Tagline: "Strategic Intelligence Amplified".
    • Font: Inter via Google Fonts.
  • Themes:
    • welcome_email, contact_email: Success Green (#10b981).
    • otp_email: Security Blue (#2563eb).
    • payment_email: Payment Amber (#f59e0b).
  • Icons: Use inline SVG Lucide icons (e.g., Rocket, Shield Check, Receipt).
  • Accessibility: Include alt text for icons, ensure screen reader compatibility.

5.4 Future Enhancements

  • SMS support with plain text templates (e.g., otp_sms).
  • Dynamic templates via Workers KV.
  • Resend webhooks for email events.
  • Queuing via Cloudflare Queues for high volume.

6. Risks and Mitigations

  • Risk: Email client compatibility issues. Mitigation: Test templates in Gmail, Outlook, Apple Mail using Litmus.
  • Risk: Authentication misconfiguration. Mitigation: Validate X-Service headers strictly; log failures.
  • Risk: Resend rate limits. Mitigation: Implement retries with exponential backoff.
  • Risk: Template updates require redeployment. Mitigation: Plan for Workers KV in future iterations.

7. Approval and Sign-Off

  • Approved By: [Pending Stakeholder Review]
  • Date: [TBD]

This updated document incorporates the StratIQX Email Template Guidelines v2.0 for compliant email templates, the X-Service authentication pattern for secure service-to-service communication, and the shift to otp_email (removing SMS support for now). It aligns with Cloudflare Workers, Resend, EDDP, and static templates. If you need further refinements, a prototype implementation, or assistance with stakeholder review, let me know!

Strategic Intelligence Hub Documentation