Use Case 004: Trial Expiration and Auto-Cleanup

Overview

Property Value
Use Case ID UC-004
Use Case Name Trial Expiration and Auto-Cleanup
Module Identity Management - Trial Lifecycle
Priority High
Status Implemented
Version 1.0
Last Updated January 30, 2026

Description

This use case describes the automated lifecycle management of trial accounts from approaching expiration through final cleanup. The system automatically monitors trial expiration dates, sends proactive warning notifications, enforces access restrictions upon expiration, and performs scheduled cleanup of expired trial data. This process ensures trial users are kept informed about their trial status, provides opportunities for conversion to paid accounts, maintains system security by preventing unauthorized access, and manages data retention in compliance with privacy regulations.

Actors

Actor Description Role
Background Job Service Scheduled task processor that executes trial management operations Primary
Trial User Customer with active or expiring trial account Primary
System Application Manager platform Supporting
Email Service SMTP or AWS SES for sending notifications Supporting
Administrator System admin managing trial extensions and monitoring Secondary
Sales Team Team following up on trial expirations for conversions Secondary

Preconditions

  1. Application Manager is running with background job service enabled
  2. Email service (SMTP or AWS SES) is configured and operational
  3. Trial users exist in the system with defined expiration dates
  4. Trial expiration policies are configured:
    • Warning notification schedule (default: 7, 3, 1 days before expiration)
    • Grace period duration (default: 0 days, configurable up to 30 days)
    • Auto-cleanup delay (default: 30 days after expiration)
    • Cleanup enabled flag (default: true)
  5. Email templates for expiration warnings and notifications are configured
  6. Background job runs on schedule (default: daily at 2:00 AM UTC)

Postconditions

Success Postconditions

  1. Warning emails sent to users approaching trial expiration
  2. Expired trials are marked inactive and access is blocked
  3. Session tokens for expired users are invalidated
  4. Application access grants are marked as expired
  5. Expired trial data is cleaned up after retention period
  6. All lifecycle events are logged in audit trail
  7. Analytics and metrics are updated with expiration data
  8. Administrators and sales team are notified of expirations

Failure Postconditions

  1. Failed operations are logged with detailed error messages
  2. Retry mechanism attempts to process failed items
  3. Administrators are alerted to recurring failures
  4. System continues processing other trial users despite individual failures
  5. Email delivery failures are tracked for manual follow-up

Triggers

  • Scheduled Trigger: Background job runs daily (configurable frequency)
  • Manual Trigger: Administrator initiates immediate trial expiration check
  • Event Trigger: Trial user attempts to access application post-expiration
  • API Trigger: External system requests trial status update

Basic Flow (Happy Path)

sequenceDiagram participant Scheduler as Task Scheduler participant Job as Background Job Service participant DB as Identity Database participant Email as Email Service participant Audit as Audit Log participant Analytics as Analytics Service Note over Scheduler,Job: Daily Execution at 2:00 AM UTC Scheduler->>Job: Trigger trial expiration job Job->>Job: Initialize job context Job->>DB: Query trials expiring in warning periods DB->>Job: Return trials (7-day, 3-day, 1-day warnings) loop For each trial requiring warning Job->>DB: Check if warning already sent alt Warning not yet sent Job->>Email: Send expiration warning email Email-->>Job: Email sent successfully Job->>DB: Mark warning as sent (WarningXDaysSent=true) Job->>Audit: Log warning sent event else Warning already sent Job->>Job: Skip (already notified) end end Job->>DB: Query trials expired today or earlier DB->>Job: Return expired active trials loop For each expired trial Job->>DB: Set IsActive=false Job->>DB: Mark all sessions as expired Job->>DB: Mark application grants as expired Job->>Email: Send trial expired notification Email-->>Job: Email sent successfully Job->>Audit: Log trial expiration event Job->>Analytics: Record expiration metrics end Job->>DB: Query trials eligible for cleanup Note over Job,DB: Cleanup: 30+ days past expiration DB->>Job: Return trials for deletion loop For each trial to cleanup alt Auto-cleanup enabled Job->>DB: Delete user sessions Job->>DB: Delete application grants Job->>DB: Delete or anonymize user data Job->>Audit: Log cleanup event Job->>Job: Increment cleanup counter else Auto-cleanup disabled Job->>Job: Skip cleanup (retention policy) end end Job->>DB: Record job execution statistics Job->>Analytics: Update trial lifecycle metrics Job->>Scheduler: Job completed successfully Note over Job: Metrics: 150 warnings sent<br/>23 trials expired<br/>5 trials cleaned up<br/>Duration: 45 seconds

Detailed Steps

Phase 1: Warning Notifications (7, 3, 1 Days Before Expiration)

  1. Identify Trials Requiring Warnings

    • Calculate warning threshold dates: NOW + 7 days, NOW + 3 days, NOW + 1 day
    • Query database for trials expiring within warning windows
    • Filter for active trials only (IsActive = true)
    • Exclude trials that already received specific warning
  2. Send 7-Day Warning

    • For trials expiring in 7 days:
      • Check Warning7DaysSent flag is false
      • Compose warning email with:
        • Expiration date and time remaining
        • Call-to-action to upgrade or extend trial
        • Contact information for sales team
        • Summary of usage and value received
      • Send email via configured provider
      • Update Warning7DaysSent = true and Warning7DaysSentAt = NOW
      • Log event in audit trail
  3. Send 3-Day Warning

    • For trials expiring in 3 days:
      • Check Warning3DaysSent flag is false
      • Compose urgent warning email with:
        • Emphasized urgency (3 days remaining)
        • Direct link to upgrade or contact sales
        • Reminder of trial benefits
        • Data export instructions (if applicable)
      • Send email via configured provider
      • Update Warning3DaysSent = true and Warning3DaysSentAt = NOW
      • Log event in audit trail
  4. Send 1-Day Final Warning

    • For trials expiring in 1 day:
      • Check Warning1DaySent flag is false
      • Compose final warning email with:
        • Strong urgency messaging (expires tomorrow)
        • Prominent upgrade button/link
        • Phone number for immediate assistance
        • What happens upon expiration (access blocked)
      • Send email via configured provider
      • Update Warning1DaySent = true and Warning1DaysSentAt = NOW
      • Log event in audit trail
      • Notify sales team for follow-up

Phase 2: Trial Expiration Processing

  1. Identify Expired Trials

    • Query database for trials where:
      • TrialExpirationDate <= NOW
      • IsActive = true (not yet processed)
      • Optional: GracePeriodExpirationDate <= NOW (if grace period configured)
    • Sort by expiration date (oldest first)
  2. Deactivate Expired Trial

    • For each expired trial:
      • Set IsActive = false
      • Set DeactivatedAt = NOW
      • Set DeactivationReason = 'TrialExpired'
      • Calculate CleanupEligibleDate = DeactivatedAt + 30 days
  3. Invalidate Sessions

    • Query all active sessions for expired user
    • For each session:
      • Set IsExpired = true
      • Set ExpiredAt = NOW
      • Set ExpirationReason = 'TrialExpired'
    • Force logout from all devices
    • Clear session cache
  4. Expire Application Access Grants

    • Query all application grants for expired user
    • For each grant:
      • Set IsExpired = true
      • Set ExpiredAt = NOW
      • Ensure ExpiresAt reflects actual expiration date
  5. Send Trial Expired Notification

    • Compose expiration email with:
      • Notice that trial has expired
      • Thank you for trying Riptide
      • Clear call-to-action to upgrade
      • What was accomplished during trial
      • Contact information for sales/support
      • Data retention policy (30 days)
    • Send via configured email provider
    • Update ExpirationEmailSentAt = NOW
    • Log email delivery status
  6. Update Analytics

    • Record expiration event with:
      • User ID and email
      • Trial duration actually used
      • Last login date
      • Number of logins during trial
      • Applications accessed
      • Reason for expiration (time-based, manual, etc.)
    • Update aggregate metrics:
      • Total expirations today
      • Expiration rate (%)
      • Conversion opportunities (trials not converted)

Phase 3: Auto-Cleanup Processing

  1. Identify Trials Eligible for Cleanup

    • Query database for trials where:
      • CleanupEligibleDate <= NOW
      • IsActive = false
      • IsDeleted = false
    • Check auto-cleanup is enabled in configuration
    • Sort by cleanup eligible date (oldest first)
  2. Delete Session Data

    • Delete all session records for the trial user
    • Remove session cache entries
    • Log deletion count
  3. Delete Application Access Grants

    • Delete all application grant records
    • Log deletion count
  4. Delete or Anonymize User Data

    • If Data Deletion Enabled:
      • Hard delete user record from database
      • Delete associated audit logs (based on retention policy)
      • Remove from analytics data (or anonymize)
    • If Data Anonymization Preferred (GDPR):
      • Replace email with anonymized value: deleted-user-{GUID}@anonymized.local
      • Replace full name with: [Deleted User]
      • Clear company name, phone, industry
      • Preserve: user ID, trial dates, metrics (anonymized)
      • Set IsDeleted = true and DeletedAt = NOW
    • Log cleanup action
  5. Record Cleanup Event

    • Write to audit log:
      • User ID (before deletion)
      • Email (before deletion)
      • Cleanup reason (auto-cleanup after retention period)
      • Data deletion method (hard delete vs. anonymization)
      • Cleanup timestamp
      • Job execution ID
  6. Update Cleanup Metrics

    • Increment cleanup counter for job run
    • Update aggregate metrics (total cleanups, data deleted)
    • Record compliance event for data protection

Phase 4: Job Completion and Reporting

  1. Generate Job Summary

    • Compile statistics:
      • Warnings sent (breakdown by type: 7-day, 3-day, 1-day)
      • Trials expired
      • Sessions invalidated
      • Cleanups performed
      • Errors encountered
      • Execution duration
      • Next scheduled run
  2. Log Job Execution

    • Write job completion record:
      • Job ID
      • Start time and end time
      • Status (success, partial success, failed)
      • Detailed statistics
      • Any errors or warnings
  3. Send Administrator Report (Optional)

    • If configured, email daily summary to administrators:
      • Overview of trial lifecycle activity
      • Key metrics and trends
      • Action items requiring attention
      • System health indicators
  4. Schedule Next Execution

    • Confirm next scheduled run time
    • Update job state for monitoring
    • Release resources

Alternative Flows

Alt Flow 1: Manual Trial Extension by Administrator

sequenceDiagram actor Admin as Administrator participant UI as Admin Web UI participant API as Application Manager API participant DB as Identity Database participant Email as Email Service participant Job as Background Job Admin->>UI: Navigate to trial user details UI->>API: GET /api/v1/trial-users/{id} API->>DB: Fetch user details DB->>API: User data (expiring soon) API->>UI: Display user details UI->>Admin: Show expiration date Admin->>UI: Click "Extend Trial" UI->>Admin: Show extension dialog Admin->>UI: Enter extension days (e.g., +30 days) UI->>API: POST /api/v1/trial-users/{id}/extend API->>DB: Update TrialExpirationDate = current + 30 days API->>DB: Reset warning flags (Warning7DaysSent, etc.) API->>DB: Set ExtendedAt = NOW, ExtendedBy = admin ID API->>DB: Add admin note DB->>API: Update successful API->>Email: Send extension notification to user Email-->>User: "Your trial has been extended" API->>UI: Extension successful UI->>Admin: Show updated expiration date Note over Job: Next job run will skip this user<br/>until new expiration approaches

Steps:

  1. Administrator identifies trial user requiring extension
  2. Administrator navigates to user details in admin panel
  3. Administrator clicks "Extend Trial" button
  4. System displays extension dialog with options:
    • Extension duration (days)
    • Reason for extension
    • Admin notes
  5. Administrator submits extension request
  6. System validates extension request
  7. System updates TrialExpirationDate = CurrentExpirationDate + ExtensionDays
  8. System resets warning flags: Warning7DaysSent = false, Warning3DaysSent = false, Warning1DaySent = false
  9. System records extension metadata:
    • ExtendedAt = NOW
    • ExtendedBy = AdminUserId
    • ExtensionReason = AdminProvidedReason
  10. System sends extension confirmation email to trial user
  11. System logs extension event in audit trail
  12. Background job will respect new expiration date in future runs

Alt Flow 2: Trial Renewal (Upgrade to Paid)

sequenceDiagram actor User as Trial User participant Web as Web Portal participant API as Application Manager API participant DB as Identity Database participant Payment as Payment Service participant Email as Email Service participant Job as Background Job User->>Web: Click "Upgrade to Paid" in warning email Web->>User: Display subscription plans User->>Web: Select plan and enter payment info Web->>Payment: Process payment Payment->>Web: Payment successful Web->>API: POST /api/v1/trial-users/{id}/convert API->>DB: Update user type (trial → paid) API->>DB: Set SubscriptionStartDate = NOW API->>DB: Remove trial expiration constraints API->>DB: Grant full application access DB->>API: Conversion successful API->>Email: Send welcome to paid subscription email Email-->>User: Confirmation and receipt API->>Web: Conversion successful Web->>User: Show success + dashboard access Note over Job: Future job runs will skip this user<br/>(no longer a trial user)

Steps:

  1. Trial user receives expiration warning email
  2. User clicks "Upgrade Now" link in email
  3. System displays subscription plan options
  4. User selects plan and completes payment
  5. Payment service processes transaction
  6. System converts trial user to paid subscriber:
    • Update UserType = 'Paid'
    • Set SubscriptionTier = SelectedPlan
    • Set SubscriptionStartDate = NOW
    • Calculate SubscriptionRenewalDate
    • Remove TrialExpirationDate constraint
    • Set ConvertedFromTrialAt = NOW
  7. System grants full application access (removes trial limitations)
  8. System sends welcome email with:
    • Payment confirmation and receipt
    • Full access details
    • Account management instructions
    • Support contact information
  9. System logs conversion event for analytics
  10. Background job will exclude this user from trial expiration processing

Alt Flow 3: Grace Period Extension

flowchart TD A[Trial expiration date reached] --> B{Grace period configured?} B -->|Yes, grace period enabled| C[Extend access for grace period] B -->|No grace period| D[Immediate expiration] C --> E[Update GracePeriodExpirationDate] C --> F[Send grace period notification] C --> G[Continue allowing access] G --> H[Daily check during grace period] H --> I{Grace period expired?} I -->|No| G I -->|Yes| J[Expire trial and block access] D --> J J --> K[Send final expiration notice] K --> L[Invalidate sessions]

Steps:

  1. Trial reaches expiration date
  2. System checks if grace period is enabled in configuration
  3. If grace period enabled (e.g., 7 days):
    • Calculate GracePeriodExpirationDate = TrialExpirationDate + GracePeriodDays
    • Keep IsActive = true during grace period
    • Mark InGracePeriod = true
    • Send grace period notification email explaining:
      • Trial has technically expired
      • Access extended for X days grace period
      • After grace period, access will be blocked
      • Urgency to upgrade or extend
  4. During grace period:
    • User can continue accessing applications
    • System displays grace period banner in UI
    • Daily reminders sent (optional)
  5. When grace period expires:
    • Proceed with normal expiration flow (Phase 2)
    • Set IsActive = false
    • Invalidate sessions
    • Send final expiration notice

Alt Flow 4: Email Delivery Failure During Warnings

Steps:

  1. Background job attempts to send warning email (Phase 1, steps 2-4)
  2. Email service returns error (SMTP failure, invalid email, rate limit)
  3. System logs email delivery failure:
    • User ID and email
    • Warning type (7-day, 3-day, 1-day)
    • Error message
    • Timestamp
  4. System does NOT mark warning flag as sent (Warning7DaysSent remains false)
  5. System increments EmailFailureCount for this user
  6. If EmailFailureCount > 3:
    • Flag user record as EmailDeliveryIssue = true
    • Notify administrator for manual follow-up
    • Add to admin task queue: "Email delivery failing for user X"
  7. Next job run will retry sending warning (flag still false)
  8. Administrator can:
    • Verify email address is correct
    • Manually contact user via alternative channel
    • Update email address and retry
    • Extend trial to give user time to resolve email issues

Alt Flow 5: Cleanup Failure and Retry

sequenceDiagram participant Job as Background Job participant DB as Identity Database participant Retry as Retry Queue participant Alert as Alert Service participant Admin as Administrator Job->>DB: Delete trial user data DB-->>Job: Error: Foreign key constraint violation Job->>Job: Catch exception Job->>Retry: Add to retry queue Job->>Alert: Log error alt First retry Retry->>DB: Retry deletion (attempt 2) DB-->>Retry: Success Retry->>Job: Cleanup successful else Persistent failure Retry->>DB: Retry deletion (attempt 3) DB-->>Retry: Still failing Retry->>Alert: Critical error Alert->>Admin: Email alert Admin->>DB: Manually investigate end

Steps:

  1. Cleanup process attempts to delete trial user data (Phase 3, step 14)
  2. Database returns error (e.g., foreign key constraint, lock timeout)
  3. System catches exception and logs detailed error:
    • User ID
    • Cleanup operation that failed
    • Database error message
    • Timestamp
  4. System adds failed cleanup to retry queue:
    • Include user ID
    • Retry attempt count = 1
    • Next retry time = 1 hour from now
  5. System continues processing other trials (does not abort entire job)
  6. On next job run or retry cycle:
    • Attempt cleanup again
    • If successful, remove from retry queue
    • If fails again, increment retry count
  7. After 3 failed retry attempts:
    • Flag as critical failure
    • Send alert to administrators
    • Create admin task: "Manual intervention required for user cleanup"
    • Preserve user data until manually resolved
  8. Administrator investigates and resolves:
    • Check for data integrity issues
    • Manually delete orphaned records
    • Update database constraints if needed
    • Manually trigger cleanup once resolved

Alt Flow 6: User Attempts Access Post-Expiration

sequenceDiagram actor User as Trial User (Expired) participant App as Riptide Application participant API as Application Manager API participant DB as Identity Database participant Web as Web Portal User->>App: Attempt to access application App->>API: Validate session token API->>DB: Check user and session status DB->>API: User IsActive=false (expired) API->>App: 401 Unauthorized - Trial expired App->>User: Redirect to expiration notice page User->>Web: View expiration notice Web->>User: Display options:<br/>- Upgrade to paid<br/>- Contact sales<br/>- Request extension alt User chooses to upgrade User->>Web: Click "Upgrade Now" Web->>User: Redirect to subscription flow else User contacts sales User->>Web: Click "Contact Sales" Web->>User: Display contact form / phone end

Steps:

  1. Expired trial user attempts to login or access application
  2. Application validates session with Application Manager API
  3. API queries database and finds IsActive = false
  4. API returns 401 Unauthorized with reason: TrialExpired
  5. Application redirects user to expiration notice page
  6. User sees clear message:
    • "Your trial has expired"
    • Trial duration and expiration date
    • Options to upgrade or contact sales
    • Data retention notice (30 days)
  7. User can choose action:
    • Upgrade: Redirect to subscription/payment flow
    • Contact Sales: Display contact form or phone number
    • Request Extension: Submit extension request to admin review
  8. System logs access attempt for analytics (expired trial engagement)

Business Rules

Rule ID Description Enforcement
BR-001 Background job runs daily at 2:00 AM UTC (configurable) Task scheduler configuration
BR-002 Warning emails sent at 7, 3, and 1 days before expiration Background job logic + database flags
BR-003 Trial expires when TrialExpirationDate <= NOW Database query + background job
BR-004 Expired trials are immediately marked IsActive = false Background job update operation
BR-005 All sessions invalidated upon trial expiration Background job session cleanup
BR-006 Grace period optional (0-30 days), configured globally Configuration setting
BR-007 Auto-cleanup occurs 30 days after expiration (configurable) Background job + retention policy
BR-008 Data deletion must comply with GDPR (anonymization option) Cleanup logic + compliance flag
BR-009 Warning emails not resent if already delivered Database flags prevent duplicates
BR-010 Manual trial extensions reset warning flags Extension API logic
BR-011 Converted paid users excluded from expiration processing User type filter in queries
BR-012 Maximum 3 retry attempts for failed cleanup operations Retry queue configuration
BR-013 Email delivery failures do not block trial expiration Error handling + logging
BR-014 Job must complete within 5 minutes for up to 10,000 trials Performance requirement + monitoring

Data Requirements

Trial User Record Updates

{
  "Id": "uuid-v4",
  "Email": "string",
  "IsActive": "boolean (set to false upon expiration)",
  "TrialExpirationDate": "datetime (UTC)",
  "GracePeriodExpirationDate": "datetime (UTC, optional)",
  "InGracePeriod": "boolean (default: false)",
  
  "Warning7DaysSent": "boolean (default: false)",
  "Warning7DaysSentAt": "datetime (UTC, nullable)",
  "Warning3DaysSent": "boolean (default: false)",
  "Warning3DaysSentAt": "datetime (UTC, nullable)",
  "Warning1DaySent": "boolean (default: false)",
  "Warning1DaysSentAt": "datetime (UTC, nullable)",
  
  "DeactivatedAt": "datetime (UTC, nullable)",
  "DeactivationReason": "string (e.g., 'TrialExpired', 'ManualDeactivation')",
  "ExpirationEmailSentAt": "datetime (UTC, nullable)",
  
  "CleanupEligibleDate": "datetime (UTC, calculated)",
  "IsDeleted": "boolean (default: false)",
  "DeletedAt": "datetime (UTC, nullable)",
  
  "ExtendedAt": "datetime (UTC, nullable)",
  "ExtendedBy": "uuid-v4 (admin user ID, nullable)",
  "ExtensionReason": "string (nullable)",
  
  "ConvertedFromTrialAt": "datetime (UTC, nullable)",
  "_comment": "Note: User types are represented via inheritance (TrialUser, ApplicationUser), not an enum field",
  
  "EmailFailureCount": "integer (default: 0)",
  "EmailDeliveryIssue": "boolean (default: false)"
}

Note: See UC-001 for complete user data model. The system uses inheritance-based user types (TrialUser : User, ApplicationUser : User) rather than a UserType enum field.

Background Job Execution Record

{
  "JobExecutionId": "uuid-v4",
  "JobName": "TrialExpirationAutoCleanup",
  "StartedAt": "datetime (UTC)",
  "CompletedAt": "datetime (UTC)",
  "Duration": "timespan",
  "Status": "enum ('Success', 'PartialSuccess', 'Failed')",
  
  "Statistics": {
    "trialsProcessed": "integer",
    "warning7DaysSent": "integer",
    "warning3DaysSent": "integer",
    "warning1DaySent": "integer",
    "trialsExpired": "integer",
    "sessionsInvalidated": "integer",
    "trialsCleanedUp": "integer",
    "emailsSent": "integer",
    "emailsFailed": "integer",
    "errors": "integer"
  },
  
  "Errors": [
    {
      "userId": "uuid-v4",
      "operation": "string (e.g., 'SendWarningEmail', 'CleanupData')",
      "errorMessage": "string",
      "timestamp": "datetime (UTC)"
    }
  ],
  
  "NextScheduledRun": "datetime (UTC)"
}

Audit Log Entry

{
  "AuditLogId": "uuid-v4",
  "EventType": "enum ('TrialWarningXDaysSent', 'TrialExpired', 'TrialCleanedUp', 'TrialExtended')",
  "TrialUserId": "uuid-v4",
  "TrialUserEmail": "string",
  "Timestamp": "datetime (UTC)",
  "Details": {
    "warningType": "string (e.g., '7-day', '3-day', '1-day')",
    "expirationDate": "datetime (UTC)",
    "emailSent": "boolean",
    "cleanupMethod": "string (e.g., 'HardDelete', 'Anonymize')",
    "extendedBy": "uuid-v4 (admin user ID)",
    "extensionDays": "integer"
  },
  "JobExecutionId": "uuid-v4 (if from background job)"
}

Email Templates

7-Day Expiration Warning Email

Subject: Your Riptide Trial Expires in 7 Days

Body:

Hello [Full Name],

Your Riptide trial is approaching its expiration date.

Trial Details:
• Expiration Date: [Expiration Date]
• Days Remaining: 7 days
• Applications: [List of Applications]

During your trial, you've:
• Logged in [Login Count] times
• Accessed [App Count] applications
• [Other usage highlights]

Don't Lose Access!
Upgrade to a paid subscription to continue enjoying Riptide applications without interruption.

[Upgrade Now Button]

Need More Time?
If you need additional time to evaluate Riptide, contact our sales team at [Sales Contact].

Questions?
Our support team is here to help: [Support Contact]

Thank you for trying Riptide!

Best regards,
The Riptide Team

---
This is an automated message. Please do not reply to this email.

3-Day Expiration Warning Email

Subject: ⚠️ Your Riptide Trial Expires in 3 Days

Body:

Hello [Full Name],

⚠️ URGENT: Your Riptide trial expires in just 3 days!

Trial Expiration: [Expiration Date] at [Time]
Time Remaining: 3 days

After expiration, you will lose access to:
• [Application 1]
• [Application 2]
• [Application 3]

Act Now to Maintain Access
Don't let your work be interrupted. Upgrade today to continue using Riptide.

[Upgrade to Paid Subscription Button]

Need Assistance?
Our team is ready to help you choose the right plan:
• Call us: [Phone Number]
• Email: [Sales Email]
• Schedule a demo: [Demo Link]

Already upgraded? Please disregard this message.

Best regards,
The Riptide Team

---
This is an automated message. Please do not reply to this email.

1-Day Final Warning Email

Subject: 🚨 FINAL WARNING: Your Riptide Trial Expires Tomorrow

Body:

Hello [Full Name],

🚨 FINAL NOTICE: Your Riptide trial expires tomorrow!

Trial Expires: [Expiration Date] at [Time]
Time Remaining: Less than 24 hours

What Happens Next?
• Tomorrow at [Time], your trial access will be blocked
• You will no longer be able to login to Riptide applications
• Your data will be retained for 30 days, then permanently deleted

Don't Let Your Trial End!
Upgrade right now to maintain uninterrupted access.

[UPGRADE NOW - Large Button]

Need Help Deciding?
Call us now for immediate assistance: [Phone Number]
Our team is standing by to answer your questions.

Alternative Options:
• Request a trial extension: [Extension Request Link]
• Schedule a call with sales: [Calendar Link]
• View pricing plans: [Pricing Page Link]

Important: Data Retention
After expiration, your trial data will be retained for 30 days. After that, it will be permanently deleted in compliance with our data protection policies.

Don't wait! Act now to continue your Riptide experience.

Best regards,
The Riptide Team

URGENT: This is your final notification before trial expiration.

---
This is an automated message. Please do not reply to this email.

Trial Expired Notification Email

Subject: Your Riptide Trial Has Expired

Body:

Hello [Full Name],

Your Riptide trial has expired as of [Expiration Date].

What This Means:
• You can no longer access Riptide applications
• Your login credentials have been deactivated
• Your trial data will be retained for 30 days

Ready to Continue?
We'd love to have you as a customer! Upgrade now to restore your access.

[Upgrade to Paid Subscription Button]

Your Trial Summary:
• Trial Duration: [Duration] days
• Applications Used: [List]
• Total Logins: [Count]
• Last Access: [Date]

Thank you for trying Riptide. We hope you enjoyed the experience!

Want to Discuss Your Options?
Contact our sales team:
• Email: [Sales Email]
• Phone: [Phone Number]
• Schedule a call: [Calendar Link]

Data Retention Policy:
Your trial data will be securely retained for 30 days. After that, it will be permanently deleted in accordance with GDPR and data protection regulations.

We hope to hear from you soon!

Best regards,
The Riptide Team

---
This is an automated message. Please do not reply to this email.

Trial Extended Notification Email

Subject: Good News! Your Riptide Trial Has Been Extended

Body:

Hello [Full Name],

Great news! Your Riptide trial has been extended.

Extended Trial Details:
• New Expiration Date: [New Expiration Date]
• Additional Days: [Extension Days] days
• Reason: [Extension Reason, if applicable]

You can continue enjoying full access to:
• [Application 1]
• [Application 2]
• [Application 3]

No action is required on your part. Simply continue using Riptide as before.

Make the Most of Your Extended Trial:
[Link to Getting Started Guide]
[Link to Documentation]
[Link to Support Resources]

Have Questions?
Our team is here to help:
• Email: [Support Email]
• Phone: [Phone Number]

Thank you for your continued interest in Riptide!

Best regards,
The Riptide Team

---
This is an automated message. Please do not reply to this email.

Background Job Configuration

Job Settings (appsettings.json)

{
  "BackgroundJobs": {
    "TrialExpirationJob": {
      "Enabled": true,
      "Schedule": "0 2 * * *",
      "Description": "Daily at 2:00 AM UTC",
      "TimeZone": "UTC",
      "MaxExecutionTimeMinutes": 10,
      "BatchSize": 100,
      "EnableParallelProcessing": true,
      "MaxDegreeOfParallelism": 4,
      
      "WarningSchedule": {
        "Warning7Days": true,
        "Warning3Days": true,
        "Warning1Day": true,
        "CustomWarnings": []
      },
      
      "GracePeriod": {
        "Enabled": false,
        "DurationDays": 0,
        "SendGracePeriodNotification": true
      },
      
      "AutoCleanup": {
        "Enabled": true,
        "RetentionDays": 30,
        "Method": "Anonymize",
        "DeleteSessions": true,
        "DeleteGrants": true,
        "DeleteAuditLogs": false
      },
      
      "Notifications": {
        "SendWarningEmails": true,
        "SendExpirationEmails": true,
        "NotifyAdministrators": true,
        "NotifySalesTeam": true,
        "AdminEmailRecipients": ["admin@company.com"],
        "SalesEmailRecipients": ["sales@company.com"]
      },
      
      "ErrorHandling": {
        "ContinueOnError": true,
        "MaxRetries": 3,
        "RetryDelayMinutes": 60,
        "AlertOnFailure": true
      }
    }
  }
}

Cron Schedule Examples

Schedule Cron Expression Description
Daily at 2 AM 0 2 * * * Once per day (recommended)
Every 12 hours 0 */12 * * * Twice per day
Every 6 hours 0 */6 * * * Four times per day
Hourly 0 * * * * Every hour (high frequency)
Weekly on Sunday 0 2 * * 0 Once per week

Performance Requirements

Metric Target Critical Threshold
Job execution time (1,000 trials) < 60 seconds < 120 seconds
Job execution time (10,000 trials) < 5 minutes < 10 minutes
Database query performance < 2 seconds per batch < 5 seconds
Email send rate 50 emails/minute 20 emails/minute
Memory usage < 500 MB < 1 GB
CPU usage during job < 30% < 60%
Concurrent email sends Up to 10 At least 5
Retry processing delay 1 hour 4 hours
Job scheduling accuracy ± 5 minutes ± 15 minutes

Scalability Considerations

  • Batch Processing: Process trials in batches (default: 100) to manage memory
  • Parallel Processing: Use parallel execution for independent operations (warnings, cleanups)
  • Database Indexing: Ensure indexes on:
    • TrialExpirationDate
    • IsActive
    • IsDeleted
    • Warning7DaysSent, Warning3DaysSent, Warning1DaySent
    • CleanupEligibleDate
  • Email Throttling: Respect email service rate limits
  • Monitoring: Track job duration trends to detect performance degradation

Security Considerations

Data Deletion and Privacy

  • GDPR Compliance:

    • Right to erasure honored through auto-cleanup
    • Data retained for minimum necessary period (30 days)
    • Anonymization option for audit trail preservation
    • User can request immediate deletion (separate API)
  • Data Anonymization:

    • Replace PII with anonymized values
    • Preserve analytical data for business intelligence
    • Irreversible process (cannot restore original data)
    • Audit trail maintained for compliance
  • Secure Deletion:

    • Hard delete removes all records (if configured)
    • Database transaction ensures atomicity
    • Backup retention policy separate from live data
    • Deletion logs maintained for compliance audit

Access Control

  • Background Job Security:

    • Job runs with service account credentials
    • Limited database permissions (read trial users, write status)
    • Email service credentials securely stored
    • Job logs do not contain sensitive data (tokens, passwords)
  • Administrator Actions:

    • Manual extensions require admin authentication
    • All admin actions logged in audit trail
    • Role-based access control (RBAC) enforced
    • Approval workflow for bulk extensions (optional)

Email Security

  • Token Protection:

    • Tokens never included in warning emails (only in welcome email)
    • Links in emails use secure HTTPS
    • Unsubscribe link included for compliance
    • Email content sanitized (no script injection)
  • Email Authentication:

    • SPF, DKIM, DMARC configured for sending domain
    • TLS/SSL for SMTP connections
    • Email service credentials rotated regularly
    • Rate limiting prevents abuse

Testing Scenarios

Test Case 1: 7-Day Warning Email Sent Successfully

Given: Active trial expiring in 7 days, warning not yet sent
When: Background job executes
Then: 7-day warning email sent, flag updated, audit log entry created
Verify: Email delivered, Warning7DaysSent = true, Warning7DaysSentAt timestamp set

Test Case 2: Multiple Warnings Sent in Sequence

Given: Active trial expiring in 7 days
When: Job runs on day -7, -3, -1
Then: Three separate warning emails sent
Verify: All warning flags true, correct email content for each, no duplicate sends

Test Case 3: Trial Expiration and Access Revocation

Given: Active trial expiring today
When: Background job executes
Then: User marked inactive, sessions invalidated, expiration email sent
Verify: IsActive = false, cannot login, expiration email received, audit log entry

Test Case 4: Auto-Cleanup After 30 Days

Given: Trial expired 30+ days ago
When: Background job executes
Then: User data deleted or anonymized
Verify: Data removed/anonymized, audit log entry, cannot query original email

Test Case 5: Manual Trial Extension Resets Warnings

Given: Trial expiring in 5 days, 7-day warning already sent
When: Admin extends trial by 30 days
Then: Expiration date updated, warning flags reset
Verify: New expiration date, all warning flags false, extension email sent

Test Case 6: Grace Period Delays Expiration

Given: Grace period enabled (7 days), trial expires today
When: Background job executes
Then: User remains active during grace period
Verify: IsActive = true, InGracePeriod = true, grace period notification sent
When: Grace period expires
Then: Normal expiration flow executes
Verify: IsActive = false, sessions invalidated

Test Case 7: Email Delivery Failure and Retry

Given: Email service unavailable
When: Job attempts to send warning email
Then: Email failure logged, flag not set, user added to retry queue
Verify: Error logged, Warning7DaysSent = false, admin notified
When: Job runs again (email service restored)
Then: Warning email sent successfully
Verify: Email delivered, flag now true

Test Case 8: Cleanup Failure and Manual Resolution

Given: Database constraint prevents user deletion
When: Cleanup process executes
Then: Error logged, user added to retry queue
Verify: User not deleted, error in job log, admin alert sent
After 3 retries: Admin investigates and manually resolves
Verify: Issue resolved, user eventually cleaned up

Test Case 9: User Access Attempt Post-Expiration

Given: Trial expired yesterday
When: User attempts to login
Then: Authentication fails with trial expired message
Verify: 401 Unauthorized, redirect to upgrade page, access attempt logged

Test Case 10: Converted User Excluded from Expiration

Given: Trial user upgrades to paid subscription
When: Background job executes (even if trial date passed)
Then: User excluded from expiration processing
Verify: User remains active, no expiration email sent, not in cleanup queue

Test Case 11: Job Performance with Large Dataset

Given: 10,000 active trial users with various expiration dates
When: Background job executes
Then: Job completes within 5 minutes
Verify: All eligible warnings sent, all expirations processed, no timeouts

Test Case 12: Warning Not Resent if Already Delivered

Given: 7-day warning already sent (flag true)
When: Job runs again (still 7 days to expiration)
Then: Warning email not sent again
Verify: Email not sent, flag remains true, no duplicate email

Monitoring and Analytics

Key Metrics to Track

Metric Description Alert Threshold
Job Execution Success Rate Percentage of successful job runs < 95%
Job Execution Duration Time to complete job > 5 minutes (10k trials)
Warning Emails Sent Count per warning type (7-day, 3-day, 1-day) N/A (informational)
Email Delivery Failure Rate Failed emails / Total emails > 5%
Trials Expired Today Count of expirations per day N/A (informational)
Trial Expiration Rate Expired trials / Total trials > 80% (low conversion)
Cleanup Success Rate Successful cleanups / Total cleanup attempts < 98%
Cleanup Volume Number of users cleaned up per run N/A (informational)
Grace Period Utilization Users in grace period N/A (informational)
Trial Extensions Manual extensions by admins N/A (informational)
Conversion Rate Trials converted to paid / Total expired < 10% (opportunity)
Average Trial Duration Used Actual days used vs. available N/A (engagement metric)
Last Login Before Expiration Days between last login and expiration > 7 days (low engagement)

Dashboard Visualizations

  • Trial Lifecycle Funnel:

    • Active trials
    • Trials expiring this week
    • Trials in grace period
    • Expired trials (pending cleanup)
    • Trials cleaned up
  • Expiration Timeline:

    • Daily expiration count (7-day trend)
    • Weekly expiration count (12-week trend)
    • Monthly expiration rate
  • Email Performance:

    • Warning emails sent (breakdown by type)
    • Email delivery success rate
    • Email open rate (if tracking enabled)
    • Click-through rate on upgrade links
  • Conversion Opportunities:

    • Expired trials not converted
    • Trials extended by admins
    • Grace period conversions
    • Upgrade paths taken
  • Job Health:

    • Last execution timestamp
    • Execution duration trend
    • Error rate trend
    • Next scheduled run

Alerts Configuration

Alert Condition Severity Recipients
Job Execution Failed Status = Failed Critical Admins, DevOps
Job Duration Excessive Duration > 10 minutes Warning DevOps
Email Delivery Issues Failure rate > 5% Warning Admins
Cleanup Failures Retry count > 3 Critical Admins
High Expiration Rate Daily expirations > threshold Info Sales Team
Low Conversion Rate Conversion < 10% Warning Sales, Product
Database Performance Query time > 5 seconds Warning DevOps, DBA

Analytics Queries

Expiration Rate by Month

SELECT 
  DATE_TRUNC('month', DeactivatedAt) AS Month,
  COUNT(*) AS TotalExpired,
  COUNT(*) FILTER (WHERE ConvertedFromTrialAt IS NOT NULL) AS Converted,
  ROUND(100.0 * COUNT(*) FILTER (WHERE ConvertedFromTrialAt IS NOT NULL) / COUNT(*), 2) AS ConversionRate
FROM TrialUsers
WHERE DeactivationReason = 'TrialExpired'
GROUP BY DATE_TRUNC('month', DeactivatedAt)
ORDER BY Month DESC;

Average Trial Duration Used

SELECT 
  AVG(EXTRACT(DAY FROM (DeactivatedAt - TrialStartDate))) AS AvgDaysUsed,
  AVG(TrialDurationDays) AS AvgDaysAvailable,
  ROUND(100.0 * AVG(EXTRACT(DAY FROM (DeactivatedAt - TrialStartDate))) / AVG(TrialDurationDays), 2) AS UtilizationRate
FROM TrialUsers
WHERE DeactivatedAt IS NOT NULL;

Trials Expiring This Week

SELECT 
  Id,
  Email,
  FullName,
  TrialExpirationDate,
  Warning7DaysSent,
  Warning3DaysSent,
  Warning1DaySent,
  LastLoginAt
FROM TrialUsers
WHERE 
  IsActive = true
  AND TrialExpirationDate BETWEEN NOW() AND NOW() + INTERVAL '7 days'
ORDER BY TrialExpirationDate ASC;

Cleanup Eligible Trials

SELECT 
  Id,
  Email,
  DeactivatedAt,
  CleanupEligibleDate,
  EXTRACT(DAY FROM (NOW() - DeactivatedAt)) AS DaysSinceExpiration
FROM TrialUsers
WHERE 
  IsActive = false
  AND IsDeleted = false
  AND CleanupEligibleDate <= NOW()
ORDER BY CleanupEligibleDate ASC;
  • UC-001: Trial User Self-Registration and Access

    • Provides the initial trial creation that this use case manages
    • Expiration date set during registration
  • UC-002: Trial User Login and Session Management

    • Sessions invalidated upon trial expiration
    • Session validation checks trial status
  • UC-003: Trial User Application Access Validation

    • Application access grants expired by this use case
    • Access denied for expired trials
  • UC-005: Administrator Trial User Management

    • Admins can manually extend trials (alternative flow)
    • Admins monitor expiration metrics and reports
  • UC-006: Trial to Paid Subscription Conversion

    • Conversion during warning period prevents expiration
    • Converted users excluded from expiration processing
  • UC-007: Trial User Metrics and Reporting

    • Expiration data feeds into analytics and reporting
    • Conversion funnel includes expiration stage
  • UC-008: Email Notification Management

    • Warning and expiration emails use email service
    • Email templates managed centrally
  • UC-009: Background Job Monitoring and Management

    • Trial expiration job monitored with other background jobs
    • Job health and performance tracked

Notes and Assumptions

  1. Daily Job Frequency: Job runs once daily by default; more frequent execution increases load but provides finer-grained control

  2. Warning Schedule Flexibility: 7/3/1 day warnings are standard; additional custom warnings can be configured

  3. Grace Period Optional: Grace period disabled by default; enable for industries requiring additional evaluation time

  4. Cleanup Method: Anonymization preferred over hard deletion for compliance and analytics; configurable

  5. Email Reliability: Assumes email service is reliable; warning flags prevent duplicate sends even if job runs multiple times

  6. Time Zone Handling: All dates stored in UTC; job runs in UTC; emails display dates in user's local time zone (if known)

  7. Manual Extensions: Unlimited manual extensions allowed; admin discretion for sales opportunities or support cases

  8. Conversion Tracking: Trial-to-paid conversion tracked for analytics; conversion rate is key business metric

  9. Data Retention: 30-day retention standard; can be adjusted for compliance requirements (e.g., 90 days, immediate deletion)

  10. Performance Scaling: Job designed to handle 10,000 trials; for larger scale, consider sharding or distributed processing

  11. Retry Logic: Automatic retry for transient failures; manual intervention for persistent issues

  12. Sales Integration: Expiration events can trigger CRM workflows for sales follow-up (integration point)

  13. Monitoring Critical: Job health monitoring essential; silent failures could result in expired trials continuing access

  14. Testing in Non-Production: Thoroughly test with non-production email addresses; avoid sending test emails to real users

  15. Compliance Requirements: GDPR right-to-erasure satisfied by auto-cleanup; other regulations (CCPA, etc.) may require additional handling

Revision History

Version Date Author Changes
1.0 2026-01-30 System Analyst Initial use case documentation

Document Owner: Platform Architecture Team
Stakeholders: Product Management, Engineering, Customer Success, Sales, Legal/Compliance
Review Cycle: Quarterly or as needed for major changes