Backend Design for Employee Records and Payroll Audit System
System DesignModel answerLast updated
Build a backend architecture for managing employee data and payroll changes with strong audit trails, concurrency safety, and regional customization support.
Problem Description
You're building the backend for a workforce management platform. The system tracks employee information, processes salary modifications, and handles time-off approvals. Your architecture must guarantee data integrity, complete audit trails, and flexibility for region-specific requirements.
Design solutions for three interconnected challenges:
1. Data Architecture
Create a database schema supporting Employee and SalaryModification entities. Your design must preserve every historical change—when someone's compensation changes, you need both old and new values, timestamps, and who made the change. Consider: how do you accurately compute paychecks when salary changes mid-period?
2. Concurrent Operations
Two managers might simultaneously approve the same leave request. Your system must prevent duplicate processing—the employee shouldn't lose double the vacation days, and only one approval notification should send. What mechanisms ensure exactly-once semantics?
3. Regional Flexibility
Different locations require different data. California needs state disability insurance codes, while Texas doesn't. European offices track works council membership. How do you support arbitrary location-specific attributes without constant schema changes?
Requirements
- Define REST API endpoints for salary updates
- Explain your auditability strategy (tracking who, what, when for every modification)
- Target system: 100,000 employees with high write traffic during monthly payroll cycles
- Pro-rating example: If salary increases from $96,000 to $120,000 halfway through a pay period, the paycheck must reflect the blended rate accurately
What to Deliver
Provide database schemas, API specifications, concurrency control mechanisms, and extensibility patterns. Explain trade-offs between different approaches and justify your choices with concrete reasoning.
Hints
Hint 1
Think about whether you should update existing records or create new ones when data changes—which approach better supports audit requirements?
Hint 2
Consider what database primitives prevent two transactions from making conflicting changes to the same resource
Hint 3
Evaluate structured vs semi-structured storage for optional fields: what does each approach cost you in query performance and flexibility?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Solution: Workforce Management Backend Design
This problem tests whether you can build systems where financial accuracy and legal compliance trump convenience. The core insight: treat compensation data like financial ledgers—immutable facts you never overwrite, only append to and query from.
1. Requirements Clarification
Before designing, establish these parameters:
- Multi-tenancy: Assume the platform serves multiple companies, requiring
company_idpartitioning throughout - Consistency requirements: Financial and legal data demands strong consistency; a delayed write is acceptable, but data corruption or duplicate payments are not
- Backdating support: HR departments often backdate raises to prior effective dates, requiring historical recalculation
- Scale estimation:
- 100K employees × 2 pay periods/month = 200K payroll calculations monthly
- Each calculation might read 3-5 compensation records and write 8-12 line items
- Peak: ~500-800 writes/second during payroll batch windows
- A properly indexed PostgreSQL instance handles this; the challenge is correctness, not throughput
2. Schema Design
Separate concerns into identity, time-variant facts, and immutable audit trails:
CREATE TABLE employees (
employee_id UUID PRIMARY KEY,
company_id UUID NOT NULL,
full_name VARCHAR(255),
email VARCHAR(255),
location_code VARCHAR(20), -- 'US-CA', 'DE-BE', etc.
metadata JSONB DEFAULT '{}',
record_version INT DEFAULT 1,
created_at TIMESTAMPTZ,
modified_at TIMESTAMPTZ
);
CREATE TABLE salary_history ( -- append-only, never UPDATE
history_id UUID PRIMARY KEY,
employee_id UUID REFERENCES employees,
company_id UUID NOT NULL,
annual_amount_cents BIGINT NOT NULL,
currency_code CHAR(3) NOT NULL,
valid_from DATE NOT NULL,
valid_until DATE, -- NULL means current
recorded_at TIMESTAMPTZ NOT NULL, -- when entered (bi-temporal)
replaced_by UUID, -- points to correction record
changed_by_user_id UUID NOT NULL,
change_reason TEXT,
CHECK (annual_amount_cents >= 0)
);
CREATE TABLE payroll_line_items (
line_id UUID PRIMARY KEY,
employee_id UUID REFERENCES employees,
payroll_batch_id UUID NOT NULL,
item_type VARCHAR(50), -- REGULAR_PAY, BONUS, CORRECTION, DEDUCTION
amount_cents BIGINT NOT NULL,
currency_code CHAR(3),
processing_status VARCHAR(20), -- PENDING, PROCESSED, CANCELLED
deduplication_key VARCHAR(255) UNIQUE,
created_by_user_id UUID,
created_at TIMESTAMPTZ
);
CREATE TABLE change_log ( -- write-only, no UPDATE/DELETE permissions
log_id BIGSERIAL PRIMARY KEY,
company_id UUID,
table_name VARCHAR(100),
record_id UUID,
column_name VARCHAR(100),
previous_value JSONB,
updated_value JSONB,
changed_by_user_id UUID,
transaction_id VARCHAR(100),
timestamp TIMESTAMPTZ DEFAULT NOW()
);
Critical design choices:
- Monetary values as integers: Store cents/pence to avoid floating-point errors
- Bi-temporal modeling:
valid_from/valid_untilcaptures when the data applies;recorded_atcaptures when we learned about it. This distinction lets you recreate what the system "knew" at any past moment - Append-only patterns: Never UPDATE or DELETE salary records. Corrections create new rows that reference originals via
replaced_by - Transactional audit writes: The change_log insert happens in the same transaction as the business data change, guaranteeing consistency
Pro-rating calculation: When salary changes mid-period from $96,000 to $120,000 on day 8 of a 20-business-day period:
- Query salary_history for all rows where
valid_from <= period_end AND (valid_until IS NULL OR valid_until >= period_start) - Calculate weighted contribution:
- First rate: ($96,000 / 260 working days) × 8 days = $2,953.85
- Second rate: ($120,000 / 260 working days) × 12 days = $5,538.46
- Total gross: $8,492.31
If the change was entered after payroll ran but backdated, the next cycle detects the discrepancy and generates a CORRECTION line item for the difference.
3. API Design
Model operations as resource creation, not field mutation:
POST /api/v1/employees/{employee_id}/salary-changes
Headers:
Idempotency-Key: {client-generated-uuid}
If-Match: "{current-record-version}"
Body:
{
"annual_amount_cents": 12000000,
"currency_code": "USD",
"valid_from": "2024-08-01",
"change_reason": "Annual merit increase"
}
Response 201:
{
"history_id": "a7f3...",
"record_version": 9,
"effective_date": "2024-08-01"
}
Response 409: Version mismatch (concurrent modification detected)
Response 422: Validation error (e.g., overlaps locked payroll period)
GET /api/v1/employees/{employee_id}/salary-history?as_of=2024-07-15
GET /api/v1/employees/{employee_id}/audit-trail?field=annual_amount&limit=50
Key implementation details:
- User identity from auth token: Never accept
changed_by_user_idin request body - Idempotency-Key header: Makes retries safe; server returns cached response if key already processed
- If-Match for optimistic locking: Prevents lost updates when multiple users modify the same employee
4. Concurrency Control
For the leave approval scenario, use optimistic locking with conditional updates:
BEGIN;
UPDATE leave_requests
SET status = 'APPROVED',
approved_by_user_id = :user_id,
approved_at = NOW(),
record_version = record_version + 1
WHERE request_id = :id
AND status = 'PENDING'
AND record_version = :expected_version;
-- Check affected rows; if 0, another transaction already processed it
Within the same transaction:
- Update leave balance:
UPDATE leave_balances SET remaining_days = remaining_days - :days WHERE employee_id = :id AND remaining_days >= :days - Write audit record to change_log
- Insert notification event into outbox table for async processing
The second manager's transaction finds zero matching rows (status already changed) and returns HTTP 409.
Pattern comparison:
| Approach | Best For | Trade-offs |
|---|---|---|
| Optimistic locking (version check) | Low-contention admin operations | Clean failure mode; requires client retry logic |
| Pessimistic locking (SELECT FOR UPDATE) | High-contention scenarios, complex multi-row updates | Holds locks longer; risk of deadlocks |
| Unique constraints | Preventing duplicate submissions | Database-enforced; use with idempotency keys |
Critical considerations:
- Never trigger side effects (emails, external APIs) inside the transaction—use the outbox pattern to publish events only after commit succeeds
- Combine idempotency keys (same user resubmitting) with version checks (different users conflicting)
- For batch operations like payroll processing, acquire row-level locks explicitly:
SELECT ... FOR UPDATE SKIP LOCKEDlets parallel workers process different employees safely
5. Regional Customization
Use JSONB with a schema registry approach:
CREATE TABLE custom_field_schemas (
schema_id UUID PRIMARY KEY,
company_id UUID NOT NULL,
location_code VARCHAR(20),
field_key VARCHAR(100) NOT NULL,
data_type VARCHAR(20), -- STRING, NUMBER, BOOLEAN, DATE
required BOOLEAN DEFAULT FALSE,
validation_rules JSONB, -- e.g., {"min": 0, "max": 99999, "pattern": "^[A-Z]{2}\\d{7}$"}
is_sensitive_pii BOOLEAN,
UNIQUE(company_id, location_code, field_key)
);
CREATE INDEX idx_employee_metadata_gin ON employees USING GIN (metadata);
CREATE INDEX idx_ca_tax_code ON employees ((metadata->>'ca_sdi_code'))
WHERE location_code = 'US-CA';
Application logic validates employees.metadata against the schema registry on writes. For frequently queried fields, create expression indexes.
Trade-off analysis:
| Approach | Advantages | Disadvantages |
|---|---|---|
| JSONB column | Single-row reads; flexible schema; good index support | Type safety enforced at app layer; complex queries harder |
| EAV tables | Strongly typed values; granular history per field | Requires complex JOINs; poor query performance at scale |
| ALTER TABLE | Full SQL type system; optimal query performance | Requires migrations; downtime risk; doesn't scale to hundreds of fields |
Recommendation: Start with JSONB. When a field becomes business-critical (e.g., legally required tax identifiers queried in every payroll run), promote it to a real column or dedicated table:
CREATE TABLE employee_tax_profiles (
employee_id UUID PRIMARY KEY REFERENCES employees,
jurisdiction_code VARCHAR(20),
tax_identifier VARCHAR(50),
withholding_config JSONB
);
6. What Distinguishes Strong Responses
Interviewers look for candidates who:
- Recognize append-only patterns for audit-critical data instead of in-place updates
- Make audit logging transactional rather than async to prevent drift
- Apply specific concurrency primitives (optimistic locking, conditional updates) with concrete SQL
- Reason about bi-temporal modeling: distinguishing when facts apply from when you learned them
- Quantify trade-offs numerically: "JSONB gives O(1) row reads but O(n) key scans without indexes"
- Catch correctness issues: noting that floats lose precision, that idempotency alone doesn't prevent concurrent conflicts, or that emitting events before commit risks inconsistency
Weak responses suggest "just use microservices" without addressing the core data modeling challenges, or propose soft-delete flags that make audit reconstruction ambiguous.