Skip to main content

Backstage API Technical Specification

Version: 1.0.0 Last Updated: October 26, 2024 Status: Production

Executive Summary

The Backstage API is a unified backend system that powers all internal law firm operations. It consists of two integrated API surfaces working together to provide comprehensive legal practice management functionality:

  • Admin API (34 endpoints) - Provisioning, user management, access control, and system administration
  • User API (37 endpoints) - Day-to-day operations for lawyers, paralegals, and staff

Total: 71 endpoints serving 10,000+ concurrent users across multiple law firms.


Table of Contents

  1. Overview
  2. Admin API
  3. User API
  4. Authentication & Authorization
  5. Data Models
  6. Error Handling
  7. Performance & Scalability
  8. Security & Compliance
  9. Monitoring & Observability
  10. Deployment

1. Overview

1.1 Purpose

The Backstage API provides:

  • For Admins: Complete control over firm provisioning, user management, and access control
  • For Lawyers: Full case lifecycle management, client relationship management, document management
  • For Staff: Time tracking, billing support, appointment scheduling, notifications

1.2 Target Users

User TypePrimary APIUse Cases
System AdminAdmin APIProvision firms, manage users, configure access grants, support access
LawyerUser APIManage cases, clients, documents, track time, view invoices
ParalegalUser APIAssist with cases, manage documents, schedule appointments
StaffUser APITime tracking, billing support, records management

1.3 Architecture Principles

  • Multi-tenant: Row-level security ensures firm-level data isolation
  • Fine-grained RBAC: Role-based + manual access grants + field-level policies
  • API-first: RESTful design, OpenAPI 3.1 specifications
  • Microservices-ready: Modular design allowing future service extraction
  • Event-driven: Async processing via SQS for notifications and workflows
  • Cloud-native: Deployed on AWS with auto-scaling and multi-AZ redundancy

1.4 Technology Stack

LayerTechnology
RuntimeNode.js 20 LTS
FrameworkNestJS 10.x
LanguageTypeScript 5.x
DatabasePostgreSQL 15 (Multi-tenant)
CacheRedis 7 (Cluster mode)
SearchElasticsearch 8
Message QueueAWS SQS
StorageAWS S3
IdentityLogto (OAuth 2.0 / OIDC)

2. Admin API

2.1 Overview

The Admin API provides system administration capabilities for provisioning firms, managing users, configuring access control, and providing support access.

Base URL: https://api.lawfirm.com/admin Total Endpoints: 34 Authentication: JWT (admin roles required)

2.2 API Modules

2.2.1 Law Firms (3 endpoints)

Manage law firm tenants and their configurations.

MethodEndpointDescription
POST/firmsCreate a new law firm tenant
GET/firmsList all law firms (paginated)
GET/firms/\{firmId\}Get law firm details

Key Features:

  • Multi-tenant firm creation with isolated data
  • Logto organization provisioning (optional)
  • Firm-level configuration (billing settings, branding, features)

Example: Create a new firm

POST /admin/firms
Authorization: Bearer <admin-jwt>
Content-Type: application/json

{
"name": "Smith & Associates LLP",
"slug": "smith-associates",
"contactEmail": "admin@smithlaw.com",
"billingPlan": "enterprise",
"createLogtoOrg": true,
"features": {
"timeTracking": true,
"documentManagement": true,
"clientPortal": false
}
}

2.2.2 Users & Lawyers (9 endpoints)

Provision and manage user accounts, including professional credentials for lawyers.

MethodEndpointDescription
GET/users/searchSearch auth users (by email, name, Logto ID)
POST/firms/\{firmId\}/usersProvision a user (identity + profile + roles)
GET/firms/\{firmId\}/usersList user profiles in a firm
GET/users/\{userId\}/credentialsList professional credentials
POST/users/\{userId\}/credentialsAdd a professional credential (bar license, etc.)
DELETE/users/\{userId\}/credentials/\{credId\}Remove a credential

Key Features:

  • Logto identity creation with invitation emails
  • Role assignment (lawyer, paralegal, staff, admin)
  • Professional credential management (bar numbers, jurisdictions)
  • Multi-step provisioning with rollback on failure

Example: Provision a lawyer

POST /admin/firms/123/users
Authorization: Bearer <admin-jwt>
Content-Type: application/json

{
"email": "john.doe@smithlaw.com",
"fullName": "John Doe",
"role": "LAWYER",
"invite": true,
"logtoOrgId": "org_abc123",
"credentials": [
{
"type": "BAR_LICENSE",
"jurisdiction": "CA",
"licenseNumber": "12345",
"issuedDate": "2015-06-01",
"expiresAt": "2025-12-31"
}
]
}

2.2.3 Logto Bridge (8 endpoints)

Sync and manage Logto organizations and memberships.

MethodEndpointDescription
GET/logto/orgsList Logto organizations known to the app
POST/firms/\{firmId\}/logto/syncSync Logto org and memberships
GET/firms/\{firmId\}/logto/membersList org members (locally cached)
POST/firms/\{firmId\}/logto/membersAdd/invite a member to Logto org
GET/firms/\{firmId\}/logto/members/\{memberId\}Get a specific member
DELETE/firms/\{firmId\}/logto/members/\{memberId\}Remove a member from Logto org
PUT/firms/\{firmId\}/logto/members/\{memberId\}/rolesReplace member's org roles
GET/logto/rolesList available Logto org roles

Key Features:

  • Bidirectional sync between Logto and local DB
  • Cached membership data for performance
  • Role management (org-level roles in Logto)
  • Invitation workflow integration

2.2.4 Access Grants (9 endpoints)

Manage manual access grants for resources and subresources.

MethodEndpointDescription
GET/access-control/resource-typesList allowed resource types
GET/access-control/resource-types/\{type\}/subresourcesList allowed subresource types
GET/access-grants/searchSearch access grants (by user, resource, etc.)
GET/resources/\{resourceType\}/\{resourceId\}/grantsList grants for a resource
POST/resources/\{resourceType\}/\{resourceId\}/grantsCreate manual access grant
DELETE/resources/\{resourceType\}/\{resourceId\}/grants/\{grantId\}Revoke access grant
GET/resources/\{resourceType\}/\{resourceId\}/\{subType\}/\{subId\}/grantsList grants for subresource
POST/resources/\{resourceType\}/\{resourceId\}/\{subType\}/\{subId\}/grantsCreate subresource grant
DELETE/resources/\{resourceType\}/\{resourceId\}/\{subType\}/\{subId\}/grants/\{grantId\}Revoke subresource grant

Key Features:

  • Fine-grained resource access control
  • Support for hierarchical resources (case → documents, case → time entries)
  • Grant types: READ, WRITE, DELETE
  • Audit trail for all grant operations

2.2.5 Capabilities (2 endpoints)

Aggregate and resolve user capabilities.

MethodEndpointDescription
GET/firms/\{firmId\}/users/\{userId\}/field-policiesGet effective field policies for a user
GET/firms/\{firmId\}/users/\{userId\}/capabilitiesGet user capabilities (scopes + policies + case sets)

Key Features:

  • Aggregates permissions from roles + manual grants
  • Field-level access policies (e.g., hide client SSN from paralegals)
  • Case ID sets (which cases user has access to)
  • Cached for performance

2.2.6 Support Access (6 endpoints)

Act-as functionality for customer support.

MethodEndpointDescription
POST/support-access/sessionsStart a support access session (act as user)
GET/support-access/sessionsList support access sessions
GET/support-access/sessions/\{sessionId\}Get a support access session
DELETE/support-access/sessions/\{sessionId\}Revoke a support access session
POST/support-access/locksAcquire exclusive admin lock on resource
DELETE/support-access/locks/\{lockId\}Release a lock

Key Features:

  • Time-limited sessions (default: 1 hour)
  • Audit logging of all actions performed as target user
  • Exclusive locks prevent concurrent admin access
  • Automatic session expiration

2.3 Admin API Summary

CategoryEndpointsPurpose
Law Firms3Firm provisioning and management
Users & Lawyers9User lifecycle management
Logto Bridge8Identity provider sync
Access Grants9Fine-grained access control
Capabilities2Permission aggregation
Support Access6Act-as and admin tools
Total34-

3. User API

3.1 Overview

The User API provides day-to-day operations for lawyers, paralegals, and staff. It covers the full lifecycle of legal practice management.

Base URL: https://api.lawfirm.com/api Total Endpoints: 37 Authentication: JWT (user roles)

3.2 API Modules

3.2.1 User Profile (2 endpoints)

Manage the current user's profile.

MethodEndpointDescription
GET/meGet current user's profile
PATCH/meUpdate current user's profile

3.2.2 Firm Members (2 endpoints)

View firm members and their profiles.

MethodEndpointDescription
GET/firm/membersList members in user's firm
GET/firm/members/\{userId\}Get a specific member's profile

3.2.3 Cases (7 endpoints)

Full case lifecycle management.

MethodEndpointDescription
GET/casesList cases accessible to current user
POST/casesCreate a new case
GET/cases/\{caseId\}Get case details
PATCH/cases/\{caseId\}Update case details
GET/cases/\{caseId\}/membersList members assigned to a case
POST/cases/\{caseId\}/membersAdd a member to a case
DELETE/cases/\{caseId\}/members/\{userId\}Remove a member from a case

Key Features:

  • Case number auto-generation
  • Status workflow (OPEN → IN_PROGRESS → CLOSED → ARCHIVED)
  • Practice area categorization
  • Team assignment with roles (lead attorney, associate, paralegal)

3.2.4 Clients (4 endpoints)

Client relationship management (CRM).

MethodEndpointDescription
GET/clientsList clients accessible to current user
POST/clientsCreate a new client
GET/clients/\{clientId\}Get client details
PATCH/clients/\{clientId\}Update client details

Key Features:

  • Contact information management
  • Client type (individual, corporation, government)
  • Relationship tracking (primary contact, billing contact)
  • Client portal access configuration

3.2.5 Documents (5 endpoints)

Secure document management with S3 storage.

MethodEndpointDescription
GET/documentsList documents accessible to current user
POST/documentsUpload a new document
GET/documents/\{docId\}Get document metadata and download URL
PATCH/documents/\{docId\}Update document metadata
DELETE/documents/\{docId\}Delete a document (soft delete)

Key Features:

  • Secure upload via presigned S3 URLs
  • Version tracking
  • Document categorization (pleading, contract, correspondence, etc.)
  • Full-text search (OCR integration)
  • Access control inheritance from parent resource

3.2.6 Appointments (6 endpoints)

Calendar and scheduling management.

MethodEndpointDescription
GET/appointmentsList appointments for current user
POST/appointmentsCreate a new appointment
GET/appointments/\{apptId\}Get appointment details
PATCH/appointments/\{apptId\}Update appointment
DELETE/appointments/\{apptId\}Cancel appointment
POST/appointments/\{apptId\}/responsesRespond to appointment invitation

Key Features:

  • Calendar integration (Google Calendar, Outlook)
  • Appointment types (consultation, hearing, meeting, deadline)
  • Attendee management with RSVP
  • Reminders (email, SMS, push notifications)

3.2.7 Time & Billing (6 endpoints)

Billable hours tracking and time entry management.

MethodEndpointDescription
GET/time-entriesList time entries for current user
POST/time-entriesCreate a new time entry
GET/time-entries/\{entryId\}Get time entry details
PATCH/time-entries/\{entryId\}Update time entry
DELETE/time-entries/\{entryId\}Delete time entry
POST/time-entries/\{entryId\}/submitSubmit time entry for approval

Key Features:

  • Timer functionality (start/stop/pause)
  • Activity code tracking
  • Billable vs. non-billable classification
  • Approval workflow
  • Rate calculation based on user's billing rate

3.2.8 Invoices (2 endpoints)

View invoices (read-only for non-admin users).

MethodEndpointDescription
GET/invoicesList invoices accessible to current user
GET/invoices/\{invoiceId\}Get invoice details

Key Features:

  • Invoice line items (time entries, expenses)
  • Payment status tracking
  • PDF generation
  • Integration with accounting systems (QuickBooks)

3.2.9 Notifications (3 endpoints)

In-app notification center.

MethodEndpointDescription
GET/notificationsList notifications for current user
POST/notifications/\{notifId\}/readMark notification as read
POST/notifications/mark-all-readMark all notifications as read

Key Features:

  • Real-time notifications via WebSocket
  • Notification types (case update, document upload, appointment reminder, etc.)
  • Unread count badge
  • Notification preferences

3.2.10 Collaboration (4 endpoints)

Unified commenting system across all resources.

MethodEndpointDescription
GET/\{resourceType\}/\{resourceId\}/commentsList comments on a resource
POST/\{resourceType\}/\{resourceId\}/commentsAdd a comment to a resource
PATCH/comments/\{commentId\}Edit a comment
DELETE/comments/\{commentId\}Delete a comment

Key Features:

  • Comments on cases, documents, clients, appointments, time entries
  • @mentions for tagging team members
  • Rich text formatting (Markdown)
  • File attachments

3.3 User API Summary

ModuleEndpointsPurpose
Profile2User profile management
Firm Members2View team members
Cases7Case lifecycle management
Clients4CRM functionality
Documents5Document management
Appointments6Scheduling
Time & Billing6Billable hours tracking
Invoices2Invoice viewing
Notifications3Activity feed
Collaboration4Commenting system
Total37-

4. Authentication & Authorization

4.1 Authentication (Logto Integration)

Identity Provider: Logto (OAuth 2.0 / OIDC)

Authentication Flow

1. User initiates login in web/mobile app
2. App redirects to Logto authorization endpoint
3. User authenticates (email/password, SSO, MFA)
4. Logto issues authorization code
5. App exchanges code for tokens (access token + refresh token)
6. App includes access token in API requests: Authorization: Bearer <jwt>
7. API validates JWT signature and claims
8. API resolves user permissions and processes request

JWT Token Structure

{
"iss": "https://lawfirm.logto.app",
"sub": "logto_user_abc123",
"aud": "https://api.lawfirm.com",
"exp": 1698765432,
"iat": 1698761832,
"scope": "openid profile email",
"client_id": "app_client_xyz",
"email": "john.doe@smithlaw.com",
"email_verified": true
}

Token Validation

All API requests must include a valid JWT token. The API validates:

  1. Signature: RSA256 signature verification using Logto's public keys (JWKS)
  2. Expiration: exp claim must be in the future
  3. Audience: aud claim must match API audience
  4. Issuer: iss claim must match Logto issuer URL

4.2 Authorization (RBAC + Access Grants)

4.2.1 Role-Based Access Control (RBAC)

RoleAdmin APIUser APIDescription
SYSTEM_ADMIN✅ Full access✅ Read-onlyPlatform administrators
LAWYER✅ Full accessAttorneys with case ownership
PARALEGAL✅ Limited accessLegal assistants (no billing access)
STAFF✅ Limited accessSupport staff (billing, records)
CLIENT❌ (Future)External clients (portal access only)

4.2.2 Permission Scopes

Admin API Scopes:

  • firms:create, firms:read, firms:update
  • users:create, users:read, users:update, users:delete
  • access-grants:create, access-grants:read, access-grants:revoke
  • support-access:create, support-access:read, support-access:revoke

User API Scopes:

  • cases:create, cases:read, cases:update, cases:delete
  • clients:create, clients:read, clients:update, clients:delete
  • documents:create, documents:read, documents:update, documents:delete
  • time-entries:create, time-entries:read, time-entries:update, time-entries:submit
  • invoices:read

4.2.3 Access Grant Model

In addition to role-based permissions, users can be granted explicit access to specific resources:

interface AccessGrant {
id: string;
userId: string;
firmId: string;
resourceType: 'CASE' | 'CLIENT' | 'DOCUMENT' | 'TIME_ENTRY';
resourceId: string;
action: 'READ' | 'WRITE' | 'DELETE';
grantedBy: string;
grantedAt: Date;
expiresAt: Date | null;
revokedAt: Date | null;
}

Example: Grant a paralegal read access to a specific case:

POST /admin/resources/CASE/case_123/grants
Content-Type: application/json

{
"userId": "user_456",
"action": "READ",
"expiresAt": "2024-12-31T23:59:59Z"
}

4.2.4 Field-Level Policies

Control which fields are visible/editable per role:

interface FieldPolicy {
resourceType: string;
field: string;
role: string;
read: boolean;
write: boolean;
}

Example: Hide client SSN from paralegals

{
"resourceType": "CLIENT",
"field": "ssn",
"role": "PARALEGAL",
"read": false,
"write": false
}

4.3 Multi-Tenancy

All data is scoped to a firmId. Row-level security (RLS) in PostgreSQL ensures:

  • Users can only access data within their firm
  • Cross-firm queries are blocked at the database level
  • Firm IDs are automatically injected into all queries

5. Data Models

5.1 Core Entities

5.1.1 Law Firm

interface LawFirm {
id: string; // UUID
name: string; // "Smith & Associates LLP"
slug: string; // "smith-associates" (unique)
logtoOrgId: string | null; // Logto organization ID
contactEmail: string;
billingPlan: 'starter' | 'professional' | 'enterprise';
features: {
timeTracking: boolean;
documentManagement: boolean;
clientPortal: boolean;
advancedReporting: boolean;
};
createdAt: Date;
updatedAt: Date;
}

5.1.2 User

interface User {
id: string; // UUID
firmId: string; // Foreign key to LawFirm
logtoUserId: string | null; // Logto user ID
email: string; // Unique within firm
fullName: string;
role: 'SYSTEM_ADMIN' | 'LAWYER' | 'PARALEGAL' | 'STAFF';
isLawyer: boolean;
isActive: boolean;
createdAt: Date;
updatedAt: Date;
}

5.1.3 Case

interface Case {
id: string; // UUID
firmId: string;
clientId: string;
caseNumber: string; // Auto-generated: "2024-00123"
title: string; // "Smith v. Johnson - Personal Injury"
description: string;
caseType: 'CIVIL' | 'CRIMINAL' | 'FAMILY' | 'CORPORATE' | 'IMMIGRATION' | 'OTHER';
status: 'OPEN' | 'IN_PROGRESS' | 'CLOSED' | 'ARCHIVED';
practiceArea: string; // "Personal Injury", "Employment Law", etc.
openedAt: Date;
closedAt: Date | null;
createdBy: string;
createdAt: Date;
updatedAt: Date;
}

5.1.4 Client

interface Client {
id: string; // UUID
firmId: string;
type: 'INDIVIDUAL' | 'CORPORATION' | 'GOVERNMENT' | 'NON_PROFIT';
fullName: string; // For individuals
companyName: string | null; // For organizations
email: string;
phone: string;
address: {
street: string;
city: string;
state: string;
zip: string;
country: string;
};
createdBy: string;
createdAt: Date;
updatedAt: Date;
}

5.1.5 Document

interface Document {
id: string; // UUID
firmId: string;
resourceType: 'CASE' | 'CLIENT' | 'GENERAL';
resourceId: string | null; // case_123, client_456, or null for general docs
fileName: string;
fileSize: number; // Bytes
mimeType: string;
s3Key: string; // S3 object key
s3Bucket: string;
category: 'PLEADING' | 'CONTRACT' | 'CORRESPONDENCE' | 'EVIDENCE' | 'OTHER';
version: number; // Version tracking
uploadedBy: string;
uploadedAt: Date;
deletedAt: Date | null; // Soft delete
}

5.1.6 Time Entry

interface TimeEntry {
id: string; // UUID
firmId: string;
userId: string;
caseId: string;
activityCode: string; // "RESEARCH", "DRAFTING", "COURT_APPEARANCE", etc.
description: string;
durationMinutes: number;
isBillable: boolean;
billingRate: number; // USD per hour
totalAmount: number; // Calculated: (durationMinutes / 60) * billingRate
status: 'DRAFT' | 'SUBMITTED' | 'APPROVED' | 'REJECTED' | 'INVOICED';
workDate: Date;
submittedAt: Date | null;
approvedBy: string | null;
approvedAt: Date | null;
createdAt: Date;
updatedAt: Date;
}

5.2 Database Schema Reference

Complete ERD: See Database Schema Documentation for full schema with 23 slices and 100+ tables.

Key schema slices:

  • AUTH: Users, roles, sessions
  • FIRMS: Law firms, settings
  • CASES: Cases, case assignments, case status history
  • CLIENTS: Clients, contacts
  • DOCUMENTS: Documents, document versions
  • APPOINTMENTS: Appointments, attendees, reminders
  • TIME_TRACKING: Time entries, billing rates, activity codes
  • INVOICES: Invoices, line items, payments
  • NOTIFICATIONS: Notifications, notification preferences
  • COMMENTS: Comments (polymorphic association)
  • ACCESS_CONTROL: Access grants, field policies
  • AUDIT_LOGS: Audit trails

6. Error Handling

6.1 Error Response Format

All API errors follow this structure:

{
"error": {
"code": "RESOURCE_NOT_FOUND",
"message": "The requested case could not be found",
"details": {
"resourceType": "Case",
"resourceId": "case_123"
},
"timestamp": "2024-10-26T10:30:00Z",
"requestId": "req_abc123"
}
}

6.2 HTTP Status Codes

Status CodeMeaningUsage
200 OKSuccessSuccessful GET, PATCH, DELETE
201 CreatedCreatedSuccessful POST
204 No ContentSuccess (no body)Successful DELETE with no response body
400 Bad RequestClient errorInvalid request body, missing required fields
401 UnauthorizedAuthentication failureMissing or invalid JWT token
403 ForbiddenAuthorization failureUser lacks required permissions
404 Not FoundResource not foundRequested resource doesn't exist
409 ConflictConflictResource already exists, concurrent modification
422 Unprocessable EntityValidation errorRequest body fails validation rules
429 Too Many RequestsRate limit exceededToo many requests from client
500 Internal Server ErrorServer errorUnexpected server-side error
503 Service UnavailableService downTemporary service unavailability

6.3 Error Codes Catalog

Authentication & Authorization

CodeHTTP StatusDescription
AUTH_TOKEN_MISSING401No Authorization header provided
AUTH_TOKEN_INVALID401JWT token is malformed or invalid
AUTH_TOKEN_EXPIRED401JWT token has expired
PERMISSION_DENIED403User lacks required permission
FIRM_ACCESS_DENIED403User cannot access this firm's data

Validation

CodeHTTP StatusDescription
VALIDATION_ERROR422Request body validation failed
REQUIRED_FIELD_MISSING400Required field is missing
INVALID_FIELD_FORMAT400Field format is invalid
INVALID_ENUM_VALUE400Enum value is not recognized

Resources

CodeHTTP StatusDescription
RESOURCE_NOT_FOUND404Requested resource doesn't exist
RESOURCE_ALREADY_EXISTS409Resource with this identifier already exists
RESOURCE_CONFLICT409Concurrent modification detected

Business Logic

CodeHTTP StatusDescription
CASE_ALREADY_CLOSED400Cannot modify a closed case
TIME_ENTRY_ALREADY_INVOICED400Cannot edit invoiced time entry
DOCUMENT_UPLOAD_FAILED500S3 upload failed
LOGTO_SYNC_FAILED502Logto API call failed

Rate Limiting

CodeHTTP StatusDescription
RATE_LIMIT_EXCEEDED429Too many requests from this client

7. Performance & Scalability

7.1 Performance Targets

MetricTargetCurrent
API Response Time (p50)< 100ms~80ms
API Response Time (p95)< 200ms~150ms
API Response Time (p99)< 500ms~400ms
Database Query Time (p95)< 100ms~80ms
Cache Hit Rate> 80%~85%
Throughput5,000 req/sec~3,500 req/sec
Concurrent Users10,000+~8,000

7.2 Caching Strategy

Redis Cache Layers

LayerTTLKeys
User permissions5 minperm:\{userId\}:\{action\}:\{resourceType\}:\{resourceId\}
User profile15 minuser:\{userId\}
Case details10 mincase:\{caseId\}
Client details10 minclient:\{clientId\}
Firm settings30 minfirm:\{firmId\}:settings
Session data24 hrssession:\{sessionId\}

Cache Invalidation

  • Write-through: Updates invalidate cache immediately
  • Event-driven: SQS events trigger cache invalidation across instances
  • TTL-based: All cache entries have expiration

7.3 Pagination

All list endpoints support cursor-based pagination:

GET /api/cases?cursor=eyJpZCI6ImNhc2VfMTIzIn0&limit=20

Response:

{
"data": [...],
"pagination": {
"nextCursor": "eyJpZCI6ImNhc2VfMTQzIn0",
"hasMore": true,
"total": 156
}
}

Parameters:

  • cursor: Opaque cursor for next page (base64-encoded JSON)
  • limit: Items per page (default: 20, max: 100)

7.4 Rate Limiting

Client TypeRate LimitBurst
Web App1,000 req/min1,200 req/min
Mobile App500 req/min600 req/min
Admin Portal2,000 req/min2,400 req/min

Rate Limit Headers:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 843
X-RateLimit-Reset: 1698765432

7.5 Scaling Strategy

ComponentScaling MethodTrigger
Admin APIHorizontal (ECS tasks)CPU > 70% or Latency > 300ms
User APIHorizontal (ECS tasks)CPU > 70% or Latency > 300ms
PostgreSQLVertical + Read replicasCPU > 75% or Connections > 80%
RedisHorizontal (cluster nodes)Memory > 80% or Hit rate < 70%
ElasticsearchHorizontal (data nodes)CPU > 70% or Query latency > 200ms

8. Security & Compliance

8.1 Security Features

FeatureImplementation
AuthenticationOAuth 2.0 / OIDC via Logto
AuthorizationRBAC + Access Grants + Field Policies
Encryption (Transit)TLS 1.3
Encryption (Rest)AES-256 (RDS, S3)
Field-Level EncryptionApplication-level (PII fields)
Row-Level SecurityPostgreSQL RLS (multi-tenant isolation)
Audit LoggingAll API calls logged to CloudWatch
Rate LimitingAPI Gateway + Redis
CSRF ProtectionSameSite cookies + CSRF tokens
XSS ProtectionContent Security Policy (CSP) headers

8.2 Compliance

8.2.1 GDPR (General Data Protection Regulation)

  • Right to Access: GET /me endpoint provides user data export
  • Right to Erasure: DELETE /users/{userId} (soft delete with retention policy)
  • Right to Portability: Data export in JSON format
  • Data Minimization: Only collect necessary fields
  • Consent Management: Cookie consent banner, email preferences

8.2.2 SOC 2 Type II

  • Security: Encryption, access controls, audit logging
  • Availability: Multi-AZ deployment, auto-scaling, 99.9% SLA
  • Processing Integrity: Input validation, error handling
  • Confidentiality: Data classification, encryption at rest
  • Privacy: GDPR compliance, privacy policy

8.2.3 HIPAA (Health Insurance Portability and Accountability Act)

For law firms handling health-related cases:

  • PHI Encryption: Application-level encryption for health data
  • Audit Trails: Comprehensive logging of PHI access
  • Access Controls: Role-based access to health information
  • Business Associate Agreements (BAA): Required for third-party services

8.2.4 ABA Model Rules of Professional Conduct

  • Confidentiality (Rule 1.6): Client data encryption, access controls
  • Competence (Rule 1.1): Secure technology implementation
  • Safeguarding Property (Rule 1.15): Secure document storage

8.3 Data Retention

Data TypeRetention PeriodDeletion Method
Active casesDuration + 7 yearsSoft delete → Hard delete
Closed cases10 years after closureSoft delete → Archive → Hard delete
User accountsDuration + 30 days after terminationSoft delete → Anonymization
Audit logs7 yearsArchive to S3 Glacier
Time entriesLinked to case retentionArchive with case data
DocumentsLinked to case retentionS3 Glacier → Delete

9. Monitoring & Observability

9.1 Metrics

MetricToolAlert Threshold
API Latency (p95)CloudWatch> 500ms
Error RateCloudWatch> 1%
Database CPUCloudWatch> 80%
Database ConnectionsCloudWatch> 80% of max
Cache Hit RateRedis< 70%
Queue DepthSQS> 1,000 messages
Disk I/OCloudWatch> 90% utilization

9.2 Logging

Log Levels:

  • ERROR: Application errors, exceptions
  • WARN: Validation failures, deprecated API usage
  • INFO: API requests, business events
  • DEBUG: Detailed execution flow (dev/staging only)

Log Structure:

{
"timestamp": "2024-10-26T10:30:00Z",
"level": "INFO",
"message": "Case created successfully",
"context": {
"userId": "user_123",
"firmId": "firm_456",
"caseId": "case_789",
"requestId": "req_abc123"
}
}

Log Destinations:

  • CloudWatch Logs: Real-time logging, 30-day retention
  • Elasticsearch: Long-term storage, full-text search
  • S3: Archive for compliance (7-year retention)

9.3 Distributed Tracing

AWS X-Ray integration:

  • Trace ID propagation across services
  • Service maps showing dependencies
  • Latency breakdown by operation
  • Error rate tracking

9.4 Alerting

AlertTriggerChannel
High Error RateError rate > 1% for 5 minPagerDuty + Slack
High Latencyp95 > 500ms for 10 minSlack
Database IssuesCPU > 80% or Connections > 80%PagerDuty
Service DownHealth check fails 3 timesPagerDuty (immediate)
Queue BacklogSQS depth > 1,000 for 15 minSlack

10. Deployment

10.1 Infrastructure

Cloud Provider: AWS Deployment Method: ECS Fargate (Containerized) Multi-AZ: Yes (2 availability zones)

ComponentServiceConfiguration
Load BalancerAWS ALBHTTPS only, TLS 1.3
Admin APIECS Fargate2-10 tasks, 2 vCPU, 4 GB RAM
User APIECS Fargate4-20 tasks, 4 vCPU, 8 GB RAM
PostgreSQLRDSr6g.xlarge, Multi-AZ, Automated backups
RedisElastiCachecache.r6g.large, Cluster mode, 2 replicas
ElasticsearchAmazon ESr6g.large.search, 3-node cluster
Object StorageS3Standard storage class, versioning enabled
Message QueueSQSFIFO queues for ordered processing
CDNCloudFrontEdge caching, WAF integration

10.2 Environments

EnvironmentURLPurposeAuto-Scaling
Productionapi.lawfirm.comLive trafficYes (4-20 tasks)
Stagingapi-staging.lawfirm.comPre-production testingLimited (2-4 tasks)
Developmentapi-dev.lawfirm.comFeature developmentNo (2 tasks)

10.3 CI/CD Pipeline

Tools: GitHub Actions, AWS CodePipeline, AWS CodeDeploy

Pipeline Stages:

  1. Build: Compile TypeScript, run linters
  2. Test: Unit tests, integration tests (Jest)
  3. Security Scan: Dependency scanning (Snyk), SAST (SonarQube)
  4. Build Docker Image: Multi-stage Docker build
  5. Push to ECR: AWS Elastic Container Registry
  6. Deploy to Staging: Blue/green deployment
  7. Run E2E Tests: Automated end-to-end tests
  8. Deploy to Production: Blue/green deployment with traffic shifting

Deployment Strategy: Blue/green with gradual traffic shifting (10% → 50% → 100% over 30 minutes)

10.4 Disaster Recovery

MetricTarget
RTO (Recovery Time Objective)2 hours
RPO (Recovery Point Objective)15 minutes

Backup Strategy:

  • Database: Automated daily backups, 30-day retention, point-in-time recovery
  • S3 Documents: Versioning enabled, cross-region replication
  • Secrets: AWS Secrets Manager with automatic rotation

Disaster Recovery Plan:

  1. Multi-AZ deployment ensures automatic failover
  2. Database snapshots stored across regions
  3. Infrastructure as Code (Terraform) for rapid environment recreation
  4. Runbook for manual failover procedures

API Documentation

Architecture Documentation

Data & Schema

Getting Started


Document Version: 1.0.0 Last Updated: October 26, 2024 Maintained By: Platform Engineering Team Next Review: January 2025