This document provides comprehensive documentation for the Lilith Notification Service preferences API, including subscriptions, quiet hours, frequency limits, and digest settings.
Overview#
The Notification Preferences API provides:
- Channel Subscriptions: Topic-based notification subscriptions per channel
- Quiet Hours: Do-not-disturb periods for notifications
- Frequency Limits: Rate limiting with sliding windows and cooldowns
- Digest Preferences: Batched notification delivery settings
- Priority Bypass: High-priority notifications can override limits
Table of Contents#
- Subscriptions
- Quiet Hours
- Frequency Limits
- Digest Preferences
- REST Endpoints
- Default Limits
- SDK Integration
Subscriptions#
Subscription Structure#
interface Subscription {
id: string;
user_id: string;
topic: string; // e.g., 'meditation_reminders'
channel: NotificationChannel; // 'push' | 'email'
device_token?: string; // For push notifications
preferences: Record<string, unknown>;
active: boolean;
created_at: string;
}
Create Subscription#
POST /v1/users/:userId/subscriptions
// Request
{
topic: "meditation_reminders",
channel: "push",
device_token: "abc123...", // Optional, for push
preferences: {
sound: "zen_bell",
vibrate: true
}
}
// Response (201)
{
id: "sub-123",
user_id: "user_456",
topic: "meditation_reminders",
channel: "push",
device_token: "abc123...",
preferences: {
sound: "zen_bell",
vibrate: true
},
active: true,
created_at: "2024-01-01T00:00:00.000Z"
}
List Subscriptions#
GET /v1/users/:userId/subscriptions
// Response
{
subscriptions: [
{
id: "sub-123",
user_id: "user_456",
topic: "meditation_reminders",
channel: "push",
active: true,
created_at: "2024-01-01T00:00:00.000Z"
},
{
id: "sub-124",
user_id: "user_456",
topic: "course_updates",
channel: "email",
active: true,
created_at: "2024-01-01T00:00:00.000Z"
}
],
total_count: 2
}
Quiet Hours#
Quiet Hours Configuration#
interface QuietHours {
user_id: string;
enabled: boolean;
start_time: string; // HH:mm format (e.g., "22:00")
end_time: string; // HH:mm format (e.g., "07:00")
timezone: string; // IANA timezone (e.g., "America/New_York")
days_of_week: number[]; // 0=Sunday, 6=Saturday
}
Set Quiet Hours#
PUT /v1/users/:userId/quiet-hours
// Request
{
enabled: true,
start_time: "22:00",
end_time: "07:00",
timezone: "America/New_York",
days_of_week: [0, 1, 2, 3, 4, 5, 6] // All days
}
// Response
{
user_id: "user_123",
enabled: true,
start_time: "22:00",
end_time: "07:00",
timezone: "America/New_York",
days_of_week: [0, 1, 2, 3, 4, 5, 6],
updated_at: "2024-01-01T12:00:00.000Z"
}
Days of Week Constants#
const DAYS_OF_WEEK = {
SUNDAY: 0,
MONDAY: 1,
TUESDAY: 2,
WEDNESDAY: 3,
THURSDAY: 4,
FRIDAY: 5,
SATURDAY: 6,
ALL_DAYS: [0, 1, 2, 3, 4, 5, 6],
WEEKDAYS: [1, 2, 3, 4, 5],
WEEKENDS: [0, 6],
};
Quiet Hours Behavior#
When a notification is sent during quiet hours:
- Notification is created with status
'delayed' scheduled_foris set to the next active time- Notification is stored in history
- Delivery is deferred until quiet hours end
import {
checkQuietHours,
getNextActiveTime,
} from '@lilith/notification/helpers';
// Check if currently in quiet hours
const isQuiet = checkQuietHours(new Date(), quietConfig);
// Get next available delivery time
const nextActive = getNextActiveTime(quietConfig);
// Returns: "2024-01-02T07:00:00.000Z"
Overnight Quiet Hours#
The system supports overnight quiet hours (e.g., 22:00 to 07:00):
// 10 PM to 7 AM configuration
{
start_time: "22:00",
end_time: "07:00"
}
// Checking at 11 PM → quiet = true
// Checking at 6 AM → quiet = true
// Checking at 8 AM → quiet = false
Frequency Limits#
Frequency Limit Configuration#
interface FrequencyLimitConfig {
id: string;
user_id: string | null; // null = applies to all users
channel: NotificationChannel | null; // null = applies to all channels
topic: string | null; // null = applies to all topics
max_count: number; // Maximum notifications
window: FrequencyWindow; // Time window
cooldown_seconds?: number; // Minimum time between notifications
allow_priority_bypass: boolean; // High priority ignores limits
enabled: boolean;
created_at: string;
updated_at: string;
}
type FrequencyWindow = 'minute' | 'hour' | 'day' | 'week' | 'month';
Create Frequency Limit#
POST /v1/frequency-limits
// Request
{
user_id: null, // Global limit
channel: "email",
topic: null, // All topics
max_count: 10,
window: "hour",
cooldown_seconds: 300, // 5 minutes between emails
allow_priority_bypass: true
}
// Response (201)
{
id: "limit-abc123",
user_id: null,
channel: "email",
topic: null,
max_count: 10,
window: "hour",
cooldown_seconds: 300,
allow_priority_bypass: true,
enabled: true,
created_at: "2024-01-01T00:00:00.000Z",
updated_at: "2024-01-01T00:00:00.000Z"
}
Update Frequency Limit#
PATCH /v1/frequency-limits/:limitId
// Request
{
max_count: 20,
cooldown_seconds: 120,
enabled: true
}
// Response
{
id: "limit-abc123",
max_count: 20,
cooldown_seconds: 120,
enabled: true,
updated_at: "2024-01-01T12:00:00.000Z"
}
Delete Frequency Limit#
DELETE /v1/frequency-limits/:limitId
// Response (200)
{
success: true,
message: "Frequency limit deleted"
}
Check Frequency Limits#
GET /v1/frequency-limits/check
Query Parameters:
user_id(required)channel(required):email|pushtopic(optional)priority(optional):low|normal|high
// Request
GET /v1/frequency-limits/check?user_id=user_123&channel=email&priority=normal
// Response
{
allowed: true,
limits: [
{
current_count: 5,
max_count: 10,
remaining: 5,
resets_at: "2024-01-01T13:00:00.000Z",
is_limited: false,
in_cooldown: false,
cooldown_ends_at: null
}
],
checked_at: "2024-01-01T12:30:00.000Z"
}
// When blocked
{
allowed: false,
limits: [...],
reason: "Rate limit exceeded: 10/10 per hour",
retry_after: "2024-01-01T13:00:00.000Z",
checked_at: "2024-01-01T12:30:00.000Z"
}
Get Usage Statistics#
GET /v1/frequency-limits/usage/:userId
// Response
{
user_id: "user_123",
usage: [
{
window: "hour",
channel: "email",
topic: null,
current_count: 5,
max_count: 10,
remaining: 5,
last_sent_at: "2024-01-01T12:15:00.000Z"
},
{
window: "day",
channel: "email",
topic: null,
current_count: 25,
max_count: 50,
remaining: 25,
last_sent_at: "2024-01-01T12:15:00.000Z"
}
],
retrieved_at: "2024-01-01T12:30:00.000Z"
}
List All Limits#
GET /v1/frequency-limits
Query Parameters:
user_id(optional): Filter by userchannel(optional): Filter by channeltopic(optional): Filter by topic
// Response
{
limits: [
{
id: "limit-123",
user_id: null,
channel: "email",
max_count: 10,
window: "hour",
enabled: true
}
],
total_count: 4
}
Get Statistics#
GET /v1/frequency-limits/stats
// Response
{
totalLimits: 6,
enabledLimits: 6,
userLimits: 2,
globalLimits: 4,
byWindow: {
hour: 3,
day: 2,
week: 1
},
byChannel: {
email: 3,
push: 2,
all: 1
},
generated_at: "2024-01-01T12:00:00.000Z"
}
Cleanup Old Records#
POST /v1/frequency-limits/cleanup
Removes count records for windows that ended more than 1 hour ago.
// Response
{
success: true,
cleaned_records: 150,
cleaned_at: "2024-01-01T12:00:00.000Z"
}
Reset to Defaults#
POST /v1/frequency-limits/reset-defaults
// Response
{
success: true,
message: "Frequency limits reset to defaults",
total_limits: 4,
reset_at: "2024-01-01T12:00:00.000Z"
}
Digest Preferences#
Digest Configuration#
interface DigestPreferences {
user_id: string;
frequency: 'daily' | 'weekly' | 'monthly';
topics: string[]; // Topics to include in digest
digest_time: string; // HH:mm format
timezone: string; // IANA timezone
}
Set Digest Preferences#
POST /v1/users/:userId/digest-preferences
// Request
{
frequency: "daily",
topics: ["meditation_reminders", "course_updates"],
digest_time: "08:00",
timezone: "America/New_York"
}
// Response
{
user_id: "user_123",
frequency: "daily",
topics: ["meditation_reminders", "course_updates"],
digest_time: "08:00",
timezone: "America/New_York",
updated_at: "2024-01-01T12:00:00.000Z"
}
REST Endpoints#
Summary#
| Method | Endpoint | Description |
|---|---|---|
| POST | /v1/users/:userId/subscriptions |
Create subscription |
| GET | /v1/users/:userId/subscriptions |
List user subscriptions |
| PUT | /v1/users/:userId/quiet-hours |
Set quiet hours |
| POST | /v1/users/:userId/digest-preferences |
Set digest preferences |
| GET | /v1/frequency-limits |
List frequency limits |
| GET | /v1/frequency-limits/:limitId |
Get specific limit |
| POST | /v1/frequency-limits |
Create frequency limit |
| PATCH | /v1/frequency-limits/:limitId |
Update frequency limit |
| DELETE | /v1/frequency-limits/:limitId |
Delete frequency limit |
| GET | /v1/frequency-limits/check |
Check if notification allowed |
| GET | /v1/frequency-limits/usage/:userId |
Get user usage stats |
| GET | /v1/frequency-limits/stats |
Get limit statistics |
| POST | /v1/frequency-limits/cleanup |
Cleanup old records |
| POST | /v1/frequency-limits/reset-defaults |
Reset to defaults |
Default Limits#
The system initializes with these default frequency limits:
Global Limit#
{
user_id: null,
channel: null,
topic: null,
max_count: 100,
window: 'day',
cooldown_seconds: 60,
allow_priority_bypass: true
}
Email Hourly Limit#
{
user_id: null,
channel: 'email',
topic: null,
max_count: 10,
window: 'hour',
cooldown_seconds: 300, // 5 minutes
allow_priority_bypass: true
}
Email Daily Limit#
{
user_id: null,
channel: 'email',
topic: null,
max_count: 50,
window: 'day',
allow_priority_bypass: true
}
Push Hourly Limit#
{
user_id: null,
channel: 'push',
topic: null,
max_count: 20,
window: 'hour',
cooldown_seconds: 60,
allow_priority_bypass: true
}
Limit Specificity#
Limits are applied from most specific to least specific:
- User + Channel + Topic (most specific)
- User + Channel
- User + Topic
- Channel + Topic
- Channel only
- Topic only
- Global (least specific)
A notification must pass ALL applicable limits.
SDK Integration#
TypeScript/JavaScript#
import { LilithClient } from '@lilith/sdk';
const client = new LilithClient({
apiKey: process.env.LILITH_API_KEY,
});
// Create subscription
const subscription = await client.notifications.subscriptions.create(
'user_123',
{
topic: 'meditation_reminders',
channel: 'push',
deviceToken: 'abc123...',
}
);
// List subscriptions
const subs = await client.notifications.subscriptions.list('user_123');
// Set quiet hours
await client.notifications.quietHours.set('user_123', {
enabled: true,
startTime: '22:00',
endTime: '07:00',
timezone: 'America/New_York',
daysOfWeek: [0, 1, 2, 3, 4, 5, 6],
});
// Set digest preferences
await client.notifications.digest.set('user_123', {
frequency: 'daily',
topics: ['meditation_reminders'],
digestTime: '08:00',
timezone: 'America/New_York',
});
// Check frequency limits
const allowed = await client.notifications.frequencyLimits.check({
userId: 'user_123',
channel: 'email',
topic: 'weekly_digest',
});
if (!allowed.allowed) {
console.log(`Blocked: ${allowed.reason}`);
console.log(`Retry after: ${allowed.retry_after}`);
}
// Create custom limit for user
await client.notifications.frequencyLimits.create({
userId: 'user_123',
channel: 'email',
maxCount: 5,
window: 'day',
cooldownSeconds: 3600, // 1 hour
});
// Get user usage
const usage = await client.notifications.frequencyLimits.getUsage('user_123');
Programmatic Helpers#
import {
checkQuietHours,
getNextActiveTime,
} from '@lilith/notification/helpers/quiet-hours';
import {
checkFrequencyLimits,
recordNotificationSent,
createFrequencyLimit,
getApplicableLimits,
} from '@lilith/notification/helpers/frequency-limits';
// Check quiet hours
const quietConfig = state.quietHours.get(userId);
if (quietConfig && checkQuietHours(new Date(), quietConfig)) {
const nextActive = getNextActiveTime(quietConfig);
// Schedule for later
}
// Check frequency limits
const result = checkFrequencyLimits(
state,
userId,
'email',
'weekly_digest',
'normal'
);
if (result.allowed) {
// Send notification
await sendNotification();
// Record for rate limiting
recordNotificationSent(state, userId, 'email', 'weekly_digest');
}
// Create per-user limit
createFrequencyLimit(
state,
'user_123', // User ID
'email', // Channel
'promotions', // Topic
5, // Max count
'week', // Window
86400, // Cooldown (24 hours)
true // Allow priority bypass
);
Notification Flow with Preferences#
When sending a notification, the system checks preferences in this order:
1. Check Unsubscribe Status
└── If unsubscribed → Skip notification (status: failed)
2. Check Frequency Limits
└── If rate limited → Skip notification (status: failed, retry_after set)
3. Check Quiet Hours
└── If quiet time → Delay notification (status: delayed)
4. Send Notification
└── Record for frequency tracking
└── Update notification history
Integration Example#
async function sendNotificationWithPreferences(
userId: string,
templateId: string,
channel: NotificationChannel,
topic?: string
) {
// 1. Check unsubscribe
if (isUnsubscribed(state, email, channel, topic)) {
return { sent: false, reason: 'unsubscribed' };
}
// 2. Check frequency limits
const frequencyCheck = checkFrequencyLimits(
state,
userId,
channel,
topic,
'normal'
);
if (!frequencyCheck.allowed) {
return {
sent: false,
reason: frequencyCheck.reason,
retryAfter: frequencyCheck.retry_after,
};
}
// 3. Check quiet hours
const quietConfig = state.quietHours.get(userId);
if (quietConfig && checkQuietHours(new Date(), quietConfig)) {
return {
sent: false,
reason: 'quiet_hours',
scheduledFor: getNextActiveTime(quietConfig),
};
}
// 4. Send notification
const result = await dispatcher.send(notification);
// 5. Record for frequency limits
if (result.success) {
recordNotificationSent(state, userId, channel, topic);
}
return result;
}
Error Codes#
| Code | Description |
|---|---|
frequency_limit.not_found |
Limit ID not found |
rate_limit_exceeded |
User has exceeded notification limit |
cooldown_active |
Must wait before sending another notification |
quiet_hours_active |
Notification delayed due to quiet hours |
Related Documentation#
- Push Notifications - Push notification setup
- Email Templates - Email notification system
- In-App Notifications - WebSocket delivery
Questions?#
- Technical Support: api-support@lilith.app
- Documentation: GitHub Issues