BACK TO SELECTED WORK
CASE STUDYBackend Engineering & Systems

Subscription Tracker

API Architecture, Upstash Workflow Scheduling & Arcjet Security

ROLEBackend Engineer
CORE STACKNode.js / Express 4 /...
YEAR2024
STATUSProduction
EST. READ52 MIN READ

Production-ready REST API for subscription lifecycle management engineered with Express 4, MongoDB Mongoose session transactions, Arcjet bot defense, Upstash Workflow durable step functions, and Nodemailer dispatch.

Core Challenge: Subscription tracking requires coordinating multi-tenant account data, auto-calculating recurring renewal intervals across varied frequencies, orchestrating multi-day reminder schedules without in-memory timer leaks, and protecting public auth surfaces from bot floods.

Node.jsExpress 4MongoDBMongooseJWTbcryptjsArcjetUpstash WorkflowNodemailerDay.js

Subscription Tracking Demands Rigorous Backend Architecture

Subscription tracking looks deceptively simple at the UI layer, but the backend must reliably orchestrate multi-tenant ownership, recurring renewal dates, background scheduling, API defense, and server resilience.

KEY CONSTRAINTS & COORDINATION PROBLEMS7 VECTORS
  • ▸Authenticated user data: Strict JWT resolution on private routes.
  • ▸Subscription ownership: Enforcing matching account IDs on data access.
  • ▸Recurring renewal dates: Pre-save calculation across daily/weekly/monthly/yearly cycles.
  • ▸Lifecycle states: Automatic transition between active, cancelled, and expired.
  • ▸Automated reminders: Decoupling long sleep intervals from request threads.
  • ▸API abuse protection: Guarding routes against bots and rate flooding via Arcjet.
  • ▸Reliable server lifecycle: Dynamic port fallback and graceful process termination.
SUBSCRIPTION DATA FLOW & REMINDER OFFSETS
USER
 │
 ▼
SUBSCRIPTION DATA
 │
 ├── COST
 ├── FREQUENCY (daily / weekly / monthly / yearly)
 ├── RENEWAL DATE (auto-calculated)
 ├── PAYMENT METHOD
 └── STATUS (active / cancelled / expired)
        │
        ▼
AUTOMATED REMINDER (7d / 5d / 2d / 1d)
        │
        ▼
EMAIL (Nodemailer HTML template)

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔

A Resilient, Layered Backend Foundation

Instead of building an ad-hoc CRUD script, the system was designed around five defensive principles: modular domain routing, deterministic data hooks, multi-layered security, durable step functions, and reliable server lifecycle control.

Segregated Express routes, controllers, and middleware across auth, user, subscription, and workflow domains with centralized error handling.

Mongoose pre-save hooks automatically compute next renewal dates across variable billing frequencies and auto-transition lapsed subscriptions to expired.

Arcjet middleware acts as an edge defense layer against bot attacks and rate bursts before requests reach JWT signature verification and ownership checks.

Offloaded reminder schedules to Upstash Workflow step functions, eliminating memory leaks from long-lived timers and fragile in-process cron jobs.

Engineered automatic port conflict resolution (EADDRINUSE retry) and zero-downtime graceful shutdown with connection draining and fallback forced exit.

END-TO-END EXECUTION PIPELINE
CLIENT REQUEST
      │
      ▼
[1. Arcjet Defense]       ──▶ Evaluates IP, Bot Shield & Token Bucket (403/429 if denied)
      │ (allowed)
      ▼
[2. JWT Authentication]   ──▶ Verifies Bearer Token, extracts User payload (401 if invalid)
      │ (authenticated)
      ▼
[3. Domain Controller]    ──▶ Validates payload & runs business logic
      │
      ▼
[4. Mongoose Pre-Save]    ──▶ Auto-calculates renewalDate from startDate + frequency
      │                       Auto-transitions expired subscriptions
      ▼
[5. Database Persistence] ──▶ Atomic write / transaction commit in MongoDB Atlas
      │
      ▼
[6. Upstash Workflow]     ──▶ Schedules durable step function:
      │                       sleepUntil(7d, 5d, 2d, 1d) without holding server memory
      ▼
[7. Nodemailer Delivery]  ──▶ Dispatches personalized HTML reminder email to subscriber

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔

Modular Domain Architecture

Segregated Express routes, controllers, and middleware across auth, user, subscription, and workflow domains with centralized error handling.

Schema-Enforced State & Lifecycle

Mongoose pre-save hooks automatically compute next renewal dates across variable billing frequencies and auto-transition lapsed subscriptions to expired.

Two-Tier Security Pipeline

Arcjet middleware acts as an edge defense layer against bot attacks and rate bursts before requests reach JWT signature verification and ownership checks.

Durable Background Workflows

Offloaded reminder schedules to Upstash Workflow step functions, eliminating memory leaks from long-lived timers and fragile in-process cron jobs.

Production-Grade Process Management

Engineered automatic port conflict resolution (EADDRINUSE retry) and zero-downtime graceful shutdown with connection draining and fallback forced exit.

Multi-Tier Express & Serverless Workflow Architecture

The application decouples immediate synchronous HTTP transaction handling from asynchronous, long-running reminder cycles using durable cloud step functions.

Incoming HTTP request targeting API endpoints (/api/v1/auth, /subscriptions, or /users) hits Express pipeline with JSON parsing and cookie inspection.

aj.protect() checks the client IP against security policies. Bot attacks return 403 Forbidden; rate limit exhaustion triggers 429 Too Many Requests.

Bearer token extracted from Authorization header, verified against JWT_SECRET. The authenticated User document is attached to req.user for downstream handler authorization.

Subscription document is populated. Pre-save middleware auto-calculates renewalDate from frequency and checks if renewal is already expired before persisting to MongoDB.

Controller calls triggerWorkflow(SERVER_URL + /api/v1/workflows/subscription/reminder). Upstash QStash queues the durable execution context.

Step engine uses context.sleepUntil() across 7d, 5d, 2d, and 1d offsets. When reached, context.run triggers Nodemailer to send personalized HTML reminders.

SYSTEM TOPOLOGY & BOUNDARIES
+─────────────────────────────────────────────────────────────────────────────────────────────+
│                                  INCOMING CLIENT TRAFFIC                                    │
│                              Web Clients / Mobile / API Consumers                           │
+─────────────────────────────────────────────────────────────────────────────────────────────+
                                              │
                                              ▼
+─────────────────────────────────────────────────────────────────────────────────────────────+
│                               EXPRESS 4 HTTP PIPELINE (app.js)                              │
│                                                                                             │
│  [express.json()] ──▶ [express.urlencoded()] ──▶ [cookieParser()] ──▶ [arcjetMiddleware()]  │
│                                                                              │              │
│                                         Rate Exceeded / Bot Detected ────────┴──▶ [429 / 403]│
+─────────────────────────────────────────────────────────────────────────────────────────────+
                                              │
                                              ▼
+─────────────────────────────────────────────────────────────────────────────────────────────+
│                               ROUTING & MIDDLEWARE BOUNDARY                                 │
│                                                                                             │
│  ┌───────────────────────┐  ┌───────────────────────┐  ┌─────────────────────────────────┐  │
│  │   /api/v1/auth        │  │   /api/v1/users       │  │   /api/v1/subscriptions         │  │
│  │   • POST /sign-up     │  │   • GET / (admin)     │  │   • POST / (create + trigger)   │  │
│  │   • POST /sign-in     │  │   • GET /:id (jwt)    │  │   • GET /user/:id (ownership)   │  │
│  │   • POST /sign-out    │  │                       │  │   • [staged CRUD endpoints]     │  │
│  └───────────────────────┘  └───────────────────────┘  └─────────────────────────────────┘  │
│                                                                      │                      │
│                                                        authorize middleware (JWT)           │
+─────────────────────────────────────────────────────────────────────────────────────────────+
                                              │
                                              ▼
+───────────────────────────────────────────────┬─────────────────────────────────────────────+
│         DATA PERSISTENCE LAYER                │          DURABLE WORKFLOW ENGINE            │
│                                               │                                             │
│  Mongoose Models & Lifecycle Hooks:           │  Upstash Workflow (/api/v1/workflows):      │
│                                               │                                             │
│  • User Model:                                │  • serve(/subscription/reminder)            │
│    - Email unique index                       │  • context.run('get subscription')          │
│    - Bcrypt password hash                     │  • Reminders loop: [7, 5, 2, 1] days        │
│                                               │  • context.sleepUntil(reminderDate)         │
│  • Subscription Model:                        │  • context.run('triggerReminder')           │
│    - Frequency mapping (1, 7, 30, 365)        │                                             │
│    - Pre-save auto-renewal calculation        │                        │                    │
│    - Auto-expiration status flag              │                        ▼                    │
│                                               │            [NODEMAILER SMTP GATEWAY]        │
│  • MongoDB Atlas Database                     │            Personalized HTML Email Alerts   │
+───────────────────────────────────────────────┴─────────────────────────────────────────────+

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
SYSTEM SUBSYSTEMS & RESPONSIBILITIES6 SUBSYSTEMS SPECIFIED
01Client Dispatches Request

Incoming HTTP request targeting API endpoints (/api/v1/auth, /subscriptions, or /users) hits Express pipeline with JSON parsing and cookie inspection.

02Arcjet Security Evaluation

aj.protect() checks the client IP against security policies. Bot attacks return 403 Forbidden; rate limit exhaustion triggers 429 Too Many Requests.

03JWT Authentication & Route Guard

Bearer token extracted from Authorization header, verified against JWT_SECRET. The authenticated User document is attached to req.user for downstream handler authorization.

04Mongoose Schema Validation & Pre-Save

Subscription document is populated. Pre-save middleware auto-calculates renewalDate from frequency and checks if renewal is already expired before persisting to MongoDB.

05Upstash Durable Workflow Triggering

Controller calls triggerWorkflow(SERVER_URL + /api/v1/workflows/subscription/reminder). Upstash QStash queues the durable execution context.

06Step Sleeping & Email Notification

Step engine uses context.sleepUntil() across 7d, 5d, 2d, and 1d offsets. When reached, context.run triggers Nodemailer to send personalized HTML reminders.

Schema Integrity & Automated Pre-Save Hooks

Mongoose schemas enforce strict type validation, enum restrictions, and reference indexing. Pre-save hooks eliminate manual date math by deterministically computing renewal intervals.

Collection: users

Guaranteed uniqueness via unique index. Lowercased, whitespace trimmed, and validated against standard email regex format.

Minimum 6 characters. Never stored in plaintext; salted and hashed via bcryptjs.hash() during registration transactions.

Auto-generates ISO-8601 createdAt and updatedAt metadata.

Collection: subscriptions

Indexed foreign key referencing User. Enables O(log N) lookup speeds when querying /subscriptions/user/:id.

Strict enums prevent malformed inputs: currencies (USD, EUR, GBP), frequencies (daily, weekly, monthly, yearly), and categories (8 distinct domains).

Custom validator rejects future start dates (startDate <= new Date()) and verifies renewal occurs after start.

MONGOOSE ENTITY RELATIONSHIP MODEL
┌───────────────────────────────────────┐
│              User Model               │
├───────────────────────────────────────┤
│ _id: ObjectId (PK, auto)              │
│ name: String (2-50 chars, trim)       │
│ email: String (unique, trim, regex)   │ ──┐
│ password: String (bcrypt hash, min 6) │   │
│ createdAt: Date                       │   │ 1 : N Reference
│ updatedAt: Date                       │   │
└───────────────────────────────────────┘   │
                                            │
                                            ▼
┌────────────────────────────────────────────────────────────────────────┐
│                          Subscription Model                            │
├────────────────────────────────────────────────────────────────────────┤
│ _id: ObjectId (PK, auto)                                               │
│ user: ObjectId (FK ──▶ User._id, indexed: true, required)             │
│ name: String (2-100 chars, trim)                                       │
│ price: Number (min: 0, max: 1000)                                      │
│ currency: String (enum: ['USD', 'EUR', 'GBP'], default: 'USD')         │
│ frequency: String (enum: ['daily', 'weekly', 'monthly', 'yearly'])     │
│ category: String (enum: sports, tech, entertainment, finance, ...)     │
│ paymentMethod: String (required, trim)                                 │
│ status: String (enum: ['active', 'cancelled', 'expired'])              │
│ startDate: Date (required, validation: <= current date)               │
│ renewalDate: Date (auto-calculated via pre-save hook)                  │
│ createdAt: Date, updatedAt: Date                                       │
└────────────────────────────────────────────────────────────────────────┘

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
SYSTEM SUBSYSTEMS & RESPONSIBILITIES2 SUBSYSTEMS SPECIFIED
01User Schema (user.model.js)

Collection: users

02Subscription Schema (subscription.model.js)

Collection: subscriptions

Pre-Save Lifecycle Hook (subscription.model.js)
subscriptionSchema.pre('save', function (next) {
  // 1. Auto-calculate renewal date if not explicitly supplied
  if (!this.renewalDate) {
    const renewalPeriods = {
      daily: 1,
      weekly: 7,
      monthly: 30,
      yearly: 365,
    };
    this.renewalDate = new Date(this.startDate);
    this.renewalDate.setDate(this.renewalDate.getDate() + renewalPeriods[this.frequency]);
  }

  // 2. Automatically mark subscription as expired if renewal period has lapsed
  if (this.renewalDate < new Date()) {
    this.status = 'expired';
  }

  next();
});

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
SYSTEM SUBSYSTEMS & RESPONSIBILITIES2 SUBSYSTEMS SPECIFIED
01User Schema (user.model.js)

Collection: users

02Subscription Schema (subscription.model.js)

Collection: subscriptions

Architectural Bottlenecks in Recurring Systems

Recurring subscription management introduces operational edge cases that simple CRUD scaffolding cannot withstand. Here are the five core engineering challenges addressed.

01 CHALLENGE

Fragile Timers vs Durable Scheduling

SCHEDULING & CONCURRENCY
PROBLEM

In-memory setTimeout or local node-cron instances drop pending reminder states whenever the server restarts, and scaling to multi-instance setups causes duplicate email dispatching.

IMPACT

Missed renewal notifications or redundant spam to paying users.

02 CHALLENGE

Atomic Registration Without Orphan Records

DATA INTEGRITY & TRANSACTIONS
PROBLEM

User creation requires validation, duplicate checking, bcrypt hashing, and database writes. Any downstream failure could leave inconsistent partial state without transactional isolation.

IMPACT

Corrupted auth tables and phantom accounts that block subsequent registration attempts.

03 CHALLENGE

Renewal Date Drift Across Billing Cycles

STATE & LIFECYCLE
PROBLEM

Subscriptions span daily, weekly, monthly, and yearly cadences. Relying on client payloads allows malicious or drift-prone renewal dates, keeping expired items active indefinitely.

IMPACT

Mismatched billing cycles and invalid reminder trigger windows.

04 CHALLENGE

API Abuse & Credential Stuffing at the Edge

EDGE SECURITY & RATE LIMITS
PROBLEM

Public authentication and subscription creation routes are vulnerable to automated bot scans, credential stuffing, and rapid burst flooding before application logic executes.

IMPACT

Database connection pool exhaustion and unauthorized API utilization.

05 CHALLENGE

Port Collisions & Abrupt Process Termination

RUNTIME & PROCESS RELIABILITY
PROBLEM

Node servers crash on EADDRINUSE if another service binds the target port. Furthermore, unhandled SIGINT/SIGTERM abruptly severs active HTTP connections without closing database handles.

IMPACT

Deployment boot failures and dropped in-flight client requests.

Implementation Deep-Dives

Examining the concrete code implementations that solved distributed scheduling, database concurrency, schema-driven lifecycle transitions, and API authorization.

01 CHALLENGE

Durable Workflow Scheduling vs Ephemeral Timers

PROBLEM

Traditional Node.js timers (setTimeout/setInterval) tie schedule states directly to server process memory. Any container restart, redeploy, or crash wipes pending timers. Conversely, polling cron jobs cause high O(N) database load even when no renewals are due.

SOLUTION

Implemented Upstash Workflow step functions (/api/v1/workflows/subscription/reminder). The workflow executes context.run('get subscription'), iterates through [7, 5, 2, 1] day reminder intervals, and executes context.sleepUntil(reminderDate). Schedule state is durably offloaded to QStash.

controllers/workflow.controller.js
// controllers/workflow.controller.js
export const sendReminders = serve(async (context) => {
  const { subscriptionId } = context.requestPayload;
  const subscription = await fetchSubscription(context, subscriptionId);
  if (!subscription || subscription.status !== 'active') return;

  const renewalDate = dayjs(subscription.renewalDate);
  for (const daysBefore of REMINDERS) {
    const reminderDate = renewalDate.subtract(daysBefore, 'day');
    if (reminderDate.isAfter(dayjs())) {
      await sleepUntilReminder(context, `Reminder ${daysBefore} days before`, reminderDate);
    }
    if (dayjs().isSame(reminderDate, 'day')) {
      await triggerReminder(context, `${daysBefore} days before reminder`, subscription);
    }
  }
});

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
02 CHALLENGE

Atomic User Registration with Mongoose Transactions

PROBLEM

Standard Mongoose save operations are non-transactional by default. If duplicate validation, password hashing, or downstream token creation throws an error midway, partial state could leave orphaned records or corrupted account collections.

SOLUTION

Enforced Mongoose session transactions in auth.controller.js. The controller opens a session with mongoose.startSession(), executes validation and user creation within session.startTransaction(), and guarantees a complete session.abortTransaction() upon any thrown error.

controllers/auth.controller.js
// controllers/auth.controller.js
export const signUp = async (req, res, next) => {
  const session = await mongoose.startSession();
  session.startTransaction();
  try {
    const { name, email, password } = req.body;
    const existingUser = await User.findOne({ email }).session(session);
    if (existingUser) {
      const error = new Error('User already exists');
      error.statusCode = 409;
      throw error;
    }
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    const newUsers = await User.create([{ name, email, password: hashedPassword }], { session });
    const token = jwt.sign({ userId: newUsers[0]._id }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });

    await session.commitTransaction();
    session.endSession();
    res.status(201).json({ success: true, data: { token, user: newUsers[0] } });
  } catch (error) {
    await session.abortTransaction();
    session.endSession();
    next(error);
  }
};

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
03 CHALLENGE

Deterministic Date Calculation via Pre-Save Hooks

PROBLEM

Relying on frontend clients to pass both startDate and renewalDate invites drift, timezone confusion, or deliberate tampering. Manually calculating renewal dates in controllers leads to duplicated code across creation and update handlers.

SOLUTION

Centralized all renewal logic into a Mongoose pre-save lifecycle hook. It maps frequency strings (daily: 1, weekly: 7, monthly: 30, yearly: 365) to day offsets and sets renewalDate automatically. It also inspects if renewalDate < current date, auto-transitioning the status to 'expired'.

models/subscription.model.js
// models/subscription.model.js
subscriptionSchema.pre('save', function (next) {
  if (!this.renewalDate) {
    const renewalPeriods = {
      daily: 1,
      weekly: 7,
      monthly: 30,
      yearly: 365,
    };
    this.renewalDate = new Date(this.startDate);
    this.renewalDate.setDate(
      this.renewalDate.getDate() + renewalPeriods[this.frequency]
    );
  }

  // Auto-expire subscriptions whose renewal has already lapsed
  if (this.renewalDate < new Date()) {
    this.status = 'expired';
  }

  next();
});

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
04 CHALLENGE

Two-Tier Security: Edge Protection & Resource Ownership

PROBLEM

Authentication alone is insufficient: attackers can flood auth endpoints with credential stuffing bots, or authenticated users can query other tenants' subscription IDs if ownership is not explicitly verified.

SOLUTION

Configured Arcjet middleware globally with bot detection and token-bucket rate limiting before application routes execute. On private routes, JWT middleware validates bearer tokens and controllers explicitly verify that req.user._id matches req.params.id.

middlewares/arcjet.middleware.js
// middlewares/arcjet.middleware.js
const arcjetMiddleware = async (req, res, next) => {
  try {
    const decision = await aj.protect(req, { requested: 1 });
    if (decision.isDenied()) {
      if (decision.reason.isRateLimit()) return res.status(429).json({ error: 'Rate limit exceeded' });
      if (decision.reason.isBot()) return res.status(403).json({ error: 'Bot detected' });
      return res.status(403).json({ error: 'Access denied' });
    }
    next();
  } catch (error) {
    next(error);
  }
};

// controllers/subscription.controller.js (Ownership Guard)
if (req.user.id !== req.params.id) {
  const error = new Error('You are not the owner of this account');
  error.status = 401;
  throw error;
}

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔

Verified Implementation Matrix

Every architecture choice is grounded in the actual codebase. This matrix details the exact mechanisms protecting data consistency, server resources, and API boundaries.

Architectural AreaRepository ImplementationEngineering Defense & RigorSource File
Database TransactionalityMongoose Session TransactionsUses startSession() and startTransaction() during user sign-up. Guarantees ACID atomicity and explicit rollback via abortTransaction() if bcrypt hashing or user creation fails.controllers/auth.controller.js
Lifecycle AutomationMongoose Pre-Save Schema HooksAutomatically calculates renewalDate based on frequency mapping (daily: 1, weekly: 7, monthly: 30, yearly: 365). Automatically flips status to 'expired' if renewalDate has lapsed.models/subscription.model.js
Durable Background TasksUpstash Workflow Step FunctionsReplaced volatile in-memory setTimeout with QStash-backed durable step functions. context.sleepUntil() suspends execution across days without thread blocking or memory leaks.controllers/workflow.controller.js
Edge Threat MitigationArcjet Bot & Rate DefensePre-middleware executes aj.protect() on all inbound traffic. Discerns rate limits (429) from bot attacks (403) before requests consume database or server resources.middlewares/arcjet.middleware.js
Authorization & OwnershipJWT Middleware + Ownership GuardBearer token signature verification via jsonwebtoken. Controllers cross-examine req.user.id against route parameters to reject multi-tenant data leaks.middlewares/auth.middleware.js
Process StabilityPort Probing & Graceful TeardownTests port availability across 10 sequential attempts to recover from EADDRINUSE collisions. Intercepts SIGINT/SIGTERM, drains active sockets, and forces exit after 8000ms.app.js

Why These Technologies?

Engineering trade-offs made to ensure scalability, data integrity, and operational simplicity without unnecessary infrastructure overhead.

DECISION 01 • ARCHITECTURAL DECISION

Node.js (ESM) + Express 4

WHY / RATIONALE

Delivers a lightweight, un-opinionated middleware pipeline with minimal bootstrap latency and native async/await error propagation.

TRADE-OFF ACCEPTED

NestJS or Fastify was considered, but Express allowed tighter custom middleware composition with Arcjet and Upstash.

OUTCOME / IMPACT

Standardized on native ES Modules ('type': 'module') with Express 4.21.2.

DECISION 02 • ARCHITECTURAL DECISION

MongoDB Atlas + Mongoose 8

WHY / RATIONALE

Subscriptions exhibit varying metadata (categories, frequencies, currencies). Mongoose pre-save hooks centralize date math, and sessions guarantee ACID atomicity on registration.

TRADE-OFF ACCEPTED

PostgreSQL was evaluated, but MongoDB's schema flexibility and rapid document referencing provided faster iteration with zero migration friction.

OUTCOME / IMPACT

Document data model with Mongoose schema validation, indexes, and session transactions.

DECISION 03 • ARCHITECTURAL DECISION

Upstash Workflow Step Engine

WHY / RATIONALE

Replaces fragile local cron jobs or in-memory setTimeout. Workflow state persists across container restarts and sleeps multi-day durations with zero server CPU/RAM usage.

TRADE-OFF ACCEPTED

BullMQ or Celery requires dedicated Redis infrastructure and worker daemon orchestration; Upstash is fully serverless and durable.

OUTCOME / IMPACT

Integrated @upstash/workflow/express for serverless durable step functions.

DECISION 04 • ARCHITECTURAL DECISION

Arcjet Edge Security Layer

WHY / RATIONALE

Protects signup, login, and creation routes from bot floods and rate exhaustion before any expensive database queries or hashing operations are invoked.

TRADE-OFF ACCEPTED

Custom express-rate-limit with Redis requires maintaining cache instances and lacks intelligent bot fingerprinting.

OUTCOME / IMPACT

Configured @arcjet/node middleware to intercept all inbound HTTP traffic.

DECISION 05 • ARCHITECTURAL DECISION

Nodemailer SMTP Transporter

WHY / RATIONALE

Direct SMTP integration allows immediate, customized transactional email dispatch containing subscription name, price, renewal date, and days remaining.

TRADE-OFF ACCEPTED

Third-party transactional APIs (SendGrid/Resend) introduce vendor lock-in; SMTP transporter provides portable email delivery.

OUTCOME / IMPACT

Configured Nodemailer with dynamic HTML template generation.

Deterministic State Transitions & Cycle Intervals

A subscription moves through a finite state machine governed by user actions, pre-save schema evaluation, and time expiration checks.

Assigned upon initial creation. Pre-save hook calculates the initial renewalDate. Upstash Workflow queues automated reminder step functions.

Triggered when a subscriber flags a service for cancellation. Workflow step functions verify state prior to dispatch and safely abort reminder delivery.

Automatically flipped when renewalDate lapses (renewalDate < new Date()). Prevents outdated subscriptions from clogging active queries.

Micro-subscriptions, short passes, daily news feeds

Meal prep boxes, weekly software licenses, trial extensions

Standard SaaS subscriptions, cloud servers, streaming media

Annual enterprise tooling, domain renewals, annual memberships

FINITE STATE TRANSITION MACHINE
                  [ POST /api/v1/subscriptions ]
                                │
                                ▼ (Pre-save hook calculates renewalDate)
                 ┌─────────────────────────────┐
                 │       status: 'active'      │
                 └──────────────┬──────────────┘
                                │
         ┌──────────────────────┼──────────────────────┐
         │                      │                      │
         ▼ (User cancellation)  ▼ (renewalDate < now)  ▼ (Workflow execution)
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────────────────────┐
│ status:         │    │ status:         │    │  Validate status === 'active'   │
│   'cancelled'   │    │   'expired'     │    │  If inactive ──▶ Abort Reminder │
└─────────────────┘    └─────────────────┘    └─────────────────────────────────┘

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
DEFAULT STATE

status: 'active'

Assigned upon initial creation. Pre-save hook calculates the initial renewalDate. Upstash Workflow queues automated reminder step functions.

USER TERMINATED

status: 'cancelled'

Triggered when a subscriber flags a service for cancellation. Workflow step functions verify state prior to dispatch and safely abort reminder delivery.

AUTO DETECTED

status: 'expired'

Automatically flipped when renewalDate lapses (renewalDate < new Date()). Prevents outdated subscriptions from clogging active queries.

Durable Step Functions with Upstash Workflow

Instead of holding memory-heavy timers or continuously querying the database with cron jobs, the system leverages durable serverless step functions to coordinate multi-day sleep cycles.

Early advance notice: allows user to budget or review upcoming charge.

Decision window: subscriber can update card info or plan cancellation.

Urgent warning: final reminder before payment gateway locks order.

Imminent renewal: final transactional confirmation alert.

SCHEDULED REMINDER TIMELINE ([7, 5, 2, 1] DAYS)
SUBSCRIPTION CREATED (startDate)
       │
       ▼
[Upstash Workflow Initialized] ──▶ context.run('get subscription')
       │
       ├───────────────────────────────────────────┐
       ▼ (sleepUntil: 7 days before)               ▼
┌───────────────┐                           ┌────────────────────────────────────┐
│   T - 7 DAYS  │ ──▶ context.run() ──────▶ │ Nodemailer: "7 Days Before" Email  │
└──────┬────────┘                           └────────────────────────────────────┘
       ▼ (sleepUntil: 5 days before)
┌───────────────┐                           ┌────────────────────────────────────┐
│   T - 5 DAYS  │ ──▶ context.run() ──────▶ │ Nodemailer: "5 Days Before" Email  │
└──────┬────────┘                           └────────────────────────────────────┘
       ▼ (sleepUntil: 2 days before)
┌───────────────┐                           ┌────────────────────────────────────┐
│   T - 2 DAYS  │ ──▶ context.run() ──────▶ │ Nodemailer: "2 Days Before" Email  │
└──────┬────────┘                           └────────────────────────────────────┘
       ▼ (sleepUntil: 1 day before)
┌───────────────┐                           ┌────────────────────────────────────┐
│   T - 1 DAY   │ ──▶ context.run() ──────▶ │ Nodemailer: "1 Day Before" Email   │
└──────┬────────┘                           └────────────────────────────────────┘
       ▼
RENEWAL DATE REACHED (Auto-transition or next billing cycle)

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
Workflow Controller Engine (workflow.controller.js)
const REMINDERS = [7, 5, 2, 1];

export const sendReminders = serve(async (context) => {
  const { subscriptionId } = context.requestPayload;
  
  // Step 1: Memoized fetch & active status check
  const subscription = await fetchSubscription(context, subscriptionId);
  if (!subscription || subscription.status !== 'active') return;

  const renewalDate = dayjs(subscription.renewalDate);

  // Step 2: Iterate through reminder intervals
  for (const daysBefore of REMINDERS) {
    const reminderDate = renewalDate.subtract(daysBefore, 'day');

    if (reminderDate.isAfter(dayjs())) {
      // Remote sleep until target date: 0 node process memory held
      await sleepUntilReminder(context, `Reminder ${daysBefore} days before`, reminderDate);
    }

    if (dayjs().isSame(reminderDate, 'day')) {
      // Trigger transactional email via Nodemailer
      await triggerReminder(context, `${daysBefore} days before reminder`, subscription);
    }
  }
});

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
Step 1 of 4

7 Days Before

Early advance notice: allows user to budget or review upcoming charge.

Step 2 of 4

5 Days Before

Decision window: subscriber can update card info or plan cancellation.

Step 3 of 4

2 Days Before

Urgent warning: final reminder before payment gateway locks order.

Step 4 of 4

1 Day Before

Imminent renewal: final transactional confirmation alert.

Session Transactions & JWT Verification

Authentication pairs MongoDB replica-set transactions with bcrypt password salting and stateless JWT bearer tokens for secure private route resolution.

REGISTRATION & LOGIN AUTHENTICATION SEQUENCE
[ SIGN-UP PIPELINE ]
Client POST /api/v1/auth/sign-up { name, email, password }
       │
       ▼
[1. Start Mongoose Session] ──▶ session.startTransaction()
       │
       ▼
[2. Email Collision Check]  ──▶ User.findOne({ email }).session(session)
       │                        (Throws 409 Conflict if already exists)
       ▼
[3. Bcrypt Hash Generation] ──▶ bcrypt.genSalt(10) ──▶ bcrypt.hash(password, salt)
       │
       ▼
[4. User Persistence]       ──▶ User.create([{ name, email, password: hash }], { session })
       │
       ▼
[5. JWT Token Generation]   ──▶ jwt.sign({ userId }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN })
       │
       ▼
[6. Commit & Response]      ──▶ session.commitTransaction() ──▶ Return 201 Created
       │
       └─(If error anywhere)──▶ session.abortTransaction() ──▶ 100% Rollback (Zero Orphan Records)


[ SIGN-IN PIPELINE ]
Client POST /api/v1/auth/sign-in { email, password }
       │
       ▼
[1. User Lookup]            ──▶ User.findOne({ email }) (Returns 404 if not found)
       │
       ▼
[2. Password Verification]  ──▶ bcrypt.compare(password, user.password) (Returns 401 if mismatch)
       │
       ▼
[3. JWT Token Generation]   ──▶ jwt.sign({ userId: user._id }, JWT_SECRET, { expiresIn })
       │
       ▼
[4. Authorized Session]     ──▶ Returns { success: true, token, user }

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
Bearer Token Guard (middlewares/auth.middleware.js)
const authorize = async (req, res, next) => {
  try {
    let token;
    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
      token = req.headers.authorization.split(' ')[1];
    }
    if (!token) return res.status(401).json({ message: 'Unauthorized' });

    const decoded = jwt.verify(token, JWT_SECRET);
    const user = await User.findById(decoded.userId);
    if (!user) return res.status(401).json({ message: 'Unauthorized' });

    req.user = user;
    next();
  } catch (error) {
    res.status(401).json({ message: 'Unauthorized', error: error.message });
  }
};

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔

RESTful API Endpoints & Routing Topology

To maintain transparency, this breakdown distinguishes between active production endpoints with verified controller implementations and scaffolded router placeholders in the repository.

Implemented Production Endpoints6 ENTRIES
MethodEndpoint PathAuthorization & GuardDescription
POST/api/v1/auth/sign-upPublic / ArcjetRegisters new account within a Mongoose session transaction; hashes password with bcrypt and issues JWT.
POST/api/v1/auth/sign-inPublic / ArcjetValidates email and password hash; returns authenticated user profile and signed bearer token.
POST/api/v1/auth/sign-outPublic / ArcjetTerminates client auth session and confirms logout state.
POST/api/v1/subscriptionsBearer JWTCreates subscription, executes pre-save renewal calculation hook, and triggers Upstash reminder workflow.
GET/api/v1/subscriptions/user/:idBearer JWT (Ownership)Returns subscriptions for a specific user ID. Strictly checks req.user.id === req.params.id to block tenant leaks.
POST/api/v1/workflows/subscription/reminderUpstash SignatureDurable step function endpoint; orchestrates 7d, 5d, 2d, 1d sleep cycles and dispatches Nodemailer alerts.
Scaffolded Router Definitions in Repo7 ENTRIES
MethodEndpoint PathStatus in CodebaseIntended Functionality
GET/api/v1/subscriptionsRouter DefinedGlobal query endpoint for administrative subscription filtering.
GET/api/v1/subscriptions/:idRouter DefinedRetrieve granular details for a single subscription document.
PUT/api/v1/subscriptions/:idRouter DefinedUpdate subscription metadata (price, paymentMethod, frequency).
DELETE/api/v1/subscriptions/:idRouter DefinedPurge subscription record from database.
PUT/api/v1/subscriptions/:id/cancelRouter DefinedExplicit user endpoint to transition status to 'cancelled'.
GET/api/v1/subscriptions/upcoming-renewalsRouter DefinedQuery filter for subscriptions renewing within a given timeframe.
GET/api/v1/users & /:idRouter DefinedUser query endpoints for administrative and profile management.

Dynamic Port Fallback & Graceful Shutdown

Node applications often fail in development and containerized production due to port conflicts (EADDRINUSE) or severed connections during rolling deployments. The server bootstrap solves both.

EADDRINUSE Recovery

Instead of crashing when the default port (5500) is occupied by a lingering process or another service, the bootstrap spins up transient test servers to probe sequential ports until an open socket is secured.

SIGINT / SIGTERM Interceptor

Intercepts termination signals from orchestrators (Docker/Kubernetes). Stops accepting new inbound requests, allows in-flight responses to complete cleanly, and triggers a safety timeout to prevent hung processes.

Dynamic Port Probing
const findAvailablePort = async (startPort, maxAttempts = 10) => {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const port = startPort + attempt;
    const isAvailable = await probePort(port);
    if (isAvailable) return port;
  }
  throw new Error(`No port available after ${maxAttempts} tries`);
};

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
Graceful Teardown
const gracefulShutdown = (signal) => {
  server.close(() => {
    console.log('HTTP server closed cleanly');
    process.exit(0);
  });
  // Force exit after 8000ms if connections stall
  setTimeout(() => process.exit(1), 8000);
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔

Three-Tier Defensive Perimeter

Security is enforced in depth: automated bot threats are stopped at the edge, invalid tokens are rejected at the route level, and cross-tenant access is blocked at the controller.

middlewares/arcjet.middleware.js

Intercepts all requests before route matching. Detects automated scrapers, malicious bots, and rate limit exhaustion, returning 403 or 429 without database touch.

middlewares/auth.middleware.js

Guards private API routes by verifying Bearer JWT signatures against JWT_SECRET. Confirms cryptographic integrity and user existence before proceeding.

controllers/subscription.controller.js

Enforces strict tenant isolation by checking that the authenticated req.user.id strictly matches the URL resource parameter req.params.id.

DEFENSIVE PIPELINE TOPOLOGY
INCOMING REQUEST
       │
       ▼
┌─────────────────────────────────────────────────────────────┐
│ TIER 1: ARCJET EDGE SHIELD (Global Middleware)             │
│ • Bot Detected?         ──▶ 403 Forbidden                   │
│ • Rate Limit Exceeded?  ──▶ 429 Too Many Requests           │
└──────────────────────────────┬──────────────────────────────┘
                               │ (Allowed)
                               ▼
┌─────────────────────────────────────────────────────────────┐
│ TIER 2: JWT BEARER AUTHENTICATION (Route Guard)             │
│ • Missing Bearer Token? ──▶ 401 Unauthorized                │
│ • Invalid Signature?    ──▶ 401 Unauthorized                │
│ • User Not Found?       ──▶ 401 Unauthorized                │
└──────────────────────────────┬──────────────────────────────┘
                               │ (Authenticated: req.user attached)
                               ▼
┌─────────────────────────────────────────────────────────────┐
│ TIER 3: RESOURCE OWNERSHIP (Domain Controller)              │
│ • req.user.id !== req.params.id? ──▶ 401 Unauthorized       │
│ • Valid Owner?          ──▶ Proceed to Database Query       │
└─────────────────────────────────────────────────────────────┘

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔
TIER 01

Arcjet Edge Defense

middlewares/arcjet.middleware.js

TIER 02

Stateless JWT Authentication

middlewares/auth.middleware.js

TIER 03

Multi-Tenant Ownership Guard

controllers/subscription.controller.js

Verified Implementation Metrics

Grounded directly in the codebase: concrete specifications verifying architecture resilience, scheduling accuracy, and system stability without synthetic benchmarks.

4
API Route Domains

Segregated domain routers: /auth, /users, /subscriptions, /workflows.

4
Staged Reminder Offsets

Pre-scheduled step notices dispatched at 7, 5, 2, and 1 day(s) before renewal.

3
Discrete Lifecycle States

Schema-enforced FSM: active, cancelled, and auto-computed expired.

0
In-Memory Timer Leaks

100% durable serverless step functions; zero memory held during multi-day sleep.

10
Port Conflict Retries

Dynamic EADDRINUSE probing recovers from local port collisions automatically.

8000ms
Graceful Shutdown Guard

Socket draining window on SIGINT/SIGTERM before forced process exit.

From Request to Reminder: Architectural Synthesis

A recap of how modern backend engineering principles transform simple recurring subscription tracking into a robust, tamper-resistant system.

By delegating multi-day reminder intervals to Upstash Workflow step functions, the API eliminated in-memory timers and heavy recurring cron queries.

Mongoose pre-save hooks automate date math and expiration transitions directly at the schema layer, guaranteeing that business rules cannot be bypassed.

Using MongoDB session transactions during registration ensures that partially written accounts are cleanly rolled back if hashing or token creation encounters errors.

Combining Arcjet edge bot mitigation, JWT route protection, dynamic port recovery, and graceful socket draining yields a production-ready API foundation.

COMPLETE REQUEST-TO-REMINDER EXECUTION PATH
+──────────────────+      +──────────────────+      +──────────────────────────+
│  Client Request  │ ──▶  │  Arcjet Shield   │ ──▶  │  JWT Auth & Ownership    │
│  (REST API Call) │      │  (Bot/Rate 429)  │      │  (Token & User Verify)   │
+──────────────────+      +──────────────────+      +─────────────┬────────────+
                                                                  │
                                                                  ▼
+──────────────────+      +──────────────────+      +──────────────────────────+
│  Nodemailer SMTP │ ◀──  │ Upstash Workflow │ ◀──  │  Mongoose Pre-Save Hook  │
│  (HTML Dispatch) │      │ (QStash Sleeps)  │      │  (Date Math & Expire)    │
+──────────────────+      +──────────────────+      +──────────────────────────+

Authoritative system flow and architecture topology spec.

HORIZONTAL SCROLL ON MOBILE ↔

Decoupled Time from Compute

By delegating multi-day reminder intervals to Upstash Workflow step functions, the API eliminated in-memory timers and heavy recurring cron queries.

Defensive Data Layer

Mongoose pre-save hooks automate date math and expiration transitions directly at the schema layer, guaranteeing that business rules cannot be bypassed.

Zero-Orphan ACID Guarantees

Using MongoDB session transactions during registration ensures that partially written accounts are cleanly rolled back if hashing or token creation encounters errors.

Hardened Gateway & Server Lifecycle

Combining Arcjet edge bot mitigation, JWT route protection, dynamic port recovery, and graceful socket draining yields a production-ready API foundation.

NEXT PRODUCTION SYSTEM • CASE STUDY

RunStack

Distributed Job Execution & Application Orchestration Platform

EXPLORE SYSTEM
BACK TO SELECTED WORKENGINEERING DOSSIER • TUSHAR KANTI DEY