system-design46 min read

How to Design an HR & People Management Platform — A Senior+ Guide | Ayodhyya

How to Design an HR & People Management Platform

A comprehensive system design guide for building platforms like BambooHR, Gusto, and Workday — from architecture to compliance

System Design HR Tech Enterprise SaaS Compliance Payroll

1. Platform Overview & Scope

An HR and People Management Platform is the operational backbone of every organization. It consolidates employee lifecycle management — from recruiting through offboarding — into a single, integrated system. Platforms like BambooHR, Gusto, Workday, and Rippling serve companies ranging from 10-person startups to 100,000+ employee enterprises, and each tier demands fundamentally different architectural trade-offs.

At its core, an HR platform must answer five questions:

  1. Who works here? — Employee directory, profiles, org charts
  2. When do they work? — Time tracking, PTO, scheduling
  3. What do we owe them? — Payroll, benefits, compensation
  4. How are they performing? — Goals, reviews, feedback
  5. Are we compliant? — Tax filings, labor laws, data privacy
Key Insight: The hardest part of building an HR platform is not any single module — it's the cross-module data consistency. A termination must cascade to payroll finalization, benefits COBRA triggers, access revocation, and performance cycle removal, all within a single transaction boundary.

Target Scale

TierEmployee CountCompaniesPeak ConcurrencyData Volume
Startup10–10010,000+~50 concurrent~10 GB
SMB100–1,0002,000+~500 concurrent~200 GB
Enterprise1,000–100,000+200+~10,000 concurrent~10 TB

This guide targets the SMB-to-enterprise transition — a multi-tenant SaaS platform supporting up to 50,000 employees per tenant, with strict compliance requirements for US, EU, and UK labor markets.

2. High-Level Architecture

graph TB subgraph Client["Client Layer"] Web["React SPA"] Mobile["React Native Mobile"] Admin["Admin Portal"] end subgraph Gateway["API Gateway"] GW["Kong / Azure APIM"] Auth["Auth Middleware"] RateLimit["Rate Limiter"] end subgraph Services["Microservices"] CoreHR["Core HR Service"] Payroll["Payroll Service"] TimeOff["Time-Off Service"] TimeTrack["Time Tracking Service"] Benefits["Benefits Service"] Perf["Performance Service"] Recruit["Recruiting Service"] LMS["Learning Service"] DocMgmt["Document Service"] Comp["Compensation Service"] Expense["Expense Service"] Notif["Notification Service"] end subgraph Data["Data Layer"] PG["PostgreSQL
(Primary)"] Redis["Redis
(Cache/Sessions)"] ES["Elasticsearch
(Search)"] S3["S3 / Blob Storage
(Documents)"] Kafka["Kafka
(Event Bus)"] end subgraph External["External Integrations"] IRS["IRS / Tax APIs"] Bank["Banking / ACH"] BenefitsVendor["Benefits Vendors"] Slack["Slack / Teams"] IdP["Okta / Azure AD"] end Web & Mobile & Admin --> GW GW --> Auth --> RateLimit RateLimit --> CoreHR & Payroll & TimeOff & TimeTrack & Benefits & Perf & Recruit & LMS & DocMgmt & Comp & Expense CoreHR & Payroll & TimeOff & TimeTrack & Benefits & Perf & Recruit & LMS & DocMgmt & Comp & Expense --> Notif CoreHR & Payroll & TimeOff & TimeTrack & Benefits & Perf --> PG CoreHR & TimeOff --> Redis CoreHR & Recruit --> ES DocMgmt --> S3 CoreHR & Payroll & Benefits --> Kafka

Architecture Principles

  • Multi-tenant isolation: Each company's data is isolated at the database schema level. Shared infrastructure with row-level security as defense-in-depth.
  • Event-driven cascades: Employee lifecycle events (hire, transfer, termination) are published to Kafka and consumed by downstream services to maintain eventual consistency.
  • Modular monolith option: For teams under 20 engineers, a modular monolith with clear domain boundaries is preferable to full microservices.
  • Audit everything: Every data mutation is recorded in an immutable audit log. HR data is legally sensitive — "who changed what, when" must be provable.
  • Idempotent payroll: Payroll runs must be idempotent. A retry of the same pay period must not double-pay employees.

Service Communication Pattern

Text
Sync calls (gRPC):  Client → API Gateway → Service → Service
                    Used for: reads, simple writes, real-time lookups

Async events (Kafka): Service → Topic → Consumer Group
                    Used for: lifecycle cascades, notifications, audit logging
                    Guarantees: at-least-once delivery, idempotent consumers

Outbox pattern:     Service writes to DB + outbox table in same transaction
                    Debezium CDC reads outbox → publishes to Kafka
                    Eliminates dual-write problem
Payroll Criticality: Payroll is the single most regulated and time-sensitive module. It must run on a deterministic schedule, produce audit-trail-ready outputs, handle multi-state tax jurisdictions, and never lose data. Design it with the reliability characteristics of a banking system.

3. Employee Directory & Profiles

The employee directory is the foundational data model from which nearly every other module derives its data. It must handle rich profiles, employment history, custom fields, and document attachments while remaining performant for search-heavy access patterns.

Data Model

C#
public class Employee
{
    public Guid Id { get; set; }
    public Guid TenantId { get; set; }
    public string EmployeeNumber { get; set; }
    public EmployeeStatus Status { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PreferredName { get; set; }
    public string Email { get; set; }
    public string PersonalEmail { get; set; }
    public string PhoneNumber { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Gender { get; set; }
    public string Ethnicity { get; set; }
    public string Pronouns { get; set; }

    public Guid DepartmentId { get; set; }
    public Guid PositionId { get; set; }
    public Guid LocationId { get; set; }
    public Guid ManagerId { get; set; }
    public DateTime HireDate { get; set; }
    public DateTime? TerminationDate { get; set; }
    public EmploymentType EmploymentType { get; set; }
    public string EmploymentClassification { get; set; }

    public decimal AnnualSalary { get; set; }
    public string Currency { get; set; }
    public string PayFrequency { get; set; }

    public Address HomeAddress { get; set; }
    public List<EmergencyContact> EmergencyContacts { get; set; }
    public Dictionary<string, object> CustomFields { get; set; }
}

public class EmployeeProfile : Employee
{
    public string FullName => $"{FirstName} {LastName}";
    public int TenureDays => (DateTime.UtcNow - HireDate).Days;
    public string OrgPath { get; set; }
    public int DirectReportsCount { get; set; }
    public ProfilePhoto Photo { get; set; }
    public List<Skill> Skills { get; set; }
}

Employee Lifecycle State Machine

stateDiagram-v2 [*] --> Candidate Candidate --> PreBoarding: Offer Accepted PreBoarding --> Active: Start Date Active --> OnLeave: Leave Request OnLeave --> Active: Return Active --> Transferred: Internal Transfer Transferred --> Active: Transfer Complete Active --> Terminated: Termination Active --> Resigned: Resignation Resigned --> Offboarding: Notice Period Terminated --> Offboarding: Immediate Offboarding --> [*]

Search & Directory Features

  • Full-text search: Elasticsearch index across name, email, job title, department, skills, location.
  • Filtered views: Filter by department, location, status, manager, hire date range.
  • Directory browsing: Hierarchical org tree view with expand/collapse. Lazy loading for large orgs.
  • Profile completeness: Dashboard widget showing completion percentage to drive self-service data collection.
  • Privacy controls: SSN, salary, personal email visible only to HR admins and the employee themselves.

Indexing Strategy

SQL
CREATE INDEX idx_employee_search ON employees
    USING GIN (
        to_tsvector('english',
            coalesce(first_name, '') || ' ' ||
            coalesce(last_name, '') || ' ' ||
            coalesce(email, '') || ' ' ||
            coalesce(job_title, '')
        )
    )
    WHERE tenant_id = $1 AND status = 'Active';

CREATE INDEX idx_employee_org_path ON employees (tenant_id, org_path)
    WHERE status = 'Active';

CREATE INDEX idx_employee_dashboard ON employees
    (tenant_id, department_id, status, hire_date DESC);

4. Organizational Chart

The org chart visualizes reporting relationships and organizational structure. It must support multiple hierarchy types (solid-line, dotted-line), matrix organizations, and dynamic restructuring without data loss.

Hierarchy Model

C#
public class OrgNode
{
    public Guid Id { get; set; }
    public Guid TenantId { get; set; }
    public Guid EmployeeId { get; set; }
    public Guid? ParentNodeId { get; set; }
    public string OrgPath { get; set; }
    public int Depth { get; set; }
    public string HierarchyType { get; set; }
    public string CostCenter { get; set; }
    public bool IsHeadcount { get; set; }
    public List<OrgNode> Children { get; set; }
    public Employee Employee { get; set; }
    public int SubtreeSize { get; set; }
}

Org Chart Operations

OperationComplexityImplementation
Get direct reportsO(1)WHERE parent_node_id = @nodeId
Get full subtreeO(k)WHERE org_path LIKE @path || '/%'
Move employeeO(n)UPDATE org_path for subtree, reindex
Org chart renderingO(n)Recursive CTE, then build tree in memory
Reporting chainO(depth)Walk parent pointers
Materialized Path Pattern: We use materialized paths (e.g., "/eng/backend/platform") rather than recursive CTEs for most queries. This gives O(1) subtree lookups with a LIKE prefix match and simplifies move operations. The trade-off is that moving a subtree requires updating all descendants' org_path values — acceptable for org restructures that happen a few times per year.

Rendering Considerations

  • Large orgs (1000+ nodes): Render only the visible viewport. Load children lazily on expand. Use virtual scrolling for the list view.
  • Multiple views: Tree view (default), reporting lines, cost center view, location view.
  • Export: PNG, PDF, and interactive HTML exports for board presentations.
  • Historical org charts: Store org structure snapshots to show "what the org looked like on Jan 1, 2024."

5. Onboarding Workflows

Onboarding transforms a signed offer letter into a fully provisioned, productive employee. It spans pre-boarding (before day one), the first week, first 30 days, and first 90 days.

Workflow Engine Design

C#
public class OnboardingWorkflow
{
    public Guid Id { get; set; }
    public Guid TenantId { get; set; }
    public Guid EmployeeId { get; set; }
    public string TemplateId { get; set; }
    public OnboardingStatus Status { get; set; }
    public DateTime StartDate { get; set; }
    public List<OnboardingPhase> Phases { get; set; }
}

public class OnboardingPhase
{
    public string Name { get; set; }
    public int Order { get; set; }
    public int DaysBeforeStart { get; set; }
    public List<OnboardingTask> Tasks { get; set; }
}

public class OnboardingTask
{
    public string Title { get; set; }
    public string TaskType { get; set; }
    public string AssigneeType { get; set; }
    public bool IsRequired { get; set; }
    public bool IsCompleted { get; set; }
    public DateTime? DueDate { get; set; }
    public string DocumentTemplateId { get; set; }
    public List<string> Dependencies { get; set; }
}

Document Collection Checklist

DocumentDue ByRequiredCompliance
I-9 Employment EligibilityDay 1YesUSCIS — must complete within 3 business days
W-4 Tax WithholdingDay 1YesIRS — affects payroll withholding
State Tax FormDay 1YesState-specific
Direct Deposit AuthorizationDay 1RecommendedACH regulations
Emergency Contact FormWeek 1YesSafety compliance
Employee Handbook AcknowledgmentWeek 1YesLegal protection
NDA / IP AssignmentDay 1YesIntellectual property
Benefits Enrollment30 daysYesERISA
Background Check ConsentPre-hireYesFCRA
I-9 Compliance: The I-9 form is the most audit-sensitive document in onboarding. USCIS conducts random audits and penalties range from $252 to $25,076 per form. The system must enforce completion deadlines, store documents securely, and track re-verification dates.

Pre-Building Automation

C#
public class OnboardingOrchestrator
{
    private readonly IEventBus _eventBus;
    private readonly IProvisioningService _provisioning;

    public async Task HandleOfferAccepted(OfferAcceptedEvent e)
    {
        var workflow = await CreateWorkflow(e.OfferId, e.EmployeeId);

        await Task.WhenAll(
            _provisioning.CreateCompanyEmail(e.EmployeeEmail),
            _provisioning.ProvisionLaptop(e.EmployeeId, e.OfficeLocation),
            _provisioning.AddToSlackWorkspace(e.EmployeeEmail),
            _provisioning.CreateGitLabAccount(e.EmployeeEmail),
            _provisioning.ScheduleOrientation(e.StartDate, e.OfficeLocation),
            _provisioning.AssignOnboardingBuddy(e.EmployeeId, e.DepartmentId)
        );

        await _eventBus.Publish(new OnboardingStartedEvent
        {
            EmployeeId = e.EmployeeId,
            StartDate = e.StartDate,
            ManagerId = e.ManagerId
        });
    }
}

6. Time-Off Management

Time-off management is deceptively complex. A typical US company offers 5–10 leave types, each with different accrual rules, carryover limits, eligibility requirements, and legal obligations.

Leave Types & Policies

Leave TypeUS DefaultAccrualCarryoverPaidLegal Basis
PTO (Vacation)10–20 days/yrPer pay periodUp to capYesCompany policy
Sick LeaveVaries by statePer hour workedSome states capYesState/local law
FMLA Leave12 weeks/yrN/AN/ANoFederal (FMLA)
Bereavement3–5 daysN/AN/AYesCompany policy
Jury DutyAs neededN/AN/AVariesState law
Military LeaveAs neededN/AN/ADifferentialUSERRA
Parental Leave0–16 weeksN/AN/AVariesState law / policy

Accrual Engine

C#
public class AccrualCalculator
{
    public AccrualResult Calculate(EmployeeLeaveBalance balance, PayPeriod period)
    {
        var policy = balance.LeavePolicy;
        decimal earned = policy.AccrualMethod switch
        {
            AccrualMethod.PerPayPeriod =>
                policy.AnnualAllowance / policy.PayPeriodsPerYear,
            AccrualMethod.Hourly =>
                period.HoursWorked * policy.AccrualRatePerHour,
            AccrualMethod.FrontLoaded =>
                balance.YearsOfService >= policy.YearsForFrontLoad
                    ? policy.AnnualAllowance
                    : policy.AnnualAllowance / policy.PayPeriodsPerYear,
            _ => policy.AnnualAllowance / 12m
        };

        earned *= GetSeniorityMultiplier(balance.Employee.YearsOfService, policy);

        decimal newBalance = balance.Available + earned;
        if (newBalance > policy.MaxBalance)
        {
            decimal excess = newBalance - policy.MaxBalance;
            newBalance = policy.MaxBalance;
            if (policy.CarryoverEnabled)
            {
                newBalance += Math.Min(excess, policy.MaxCarryover);
            }
        }

        return new AccrualResult
        {
            Earned = earned,
            NewBalance = newBalance,
            CapApplied = newBalance == policy.MaxBalance
        };
    }
}

Approval Workflow

graph LR A[Employee Submits] --> B{Manager Review} B -->|Approved| C{HR Review if >10 days} B -->|Rejected| D[Notify Employee] B -->|Needs Info| A C -->|Approved| E[Block Calendar] C -->|Rejected| D E --> F[Deduct from Balance] F --> G[Update Team Calendar]

Blackout Dates & Conflicts

  • Blackout periods: Configurable per department (e.g., no PTO during Q4 close for finance).
  • Overlap limits: Maximum team members on leave simultaneously (e.g., no more than 20% on the same day).
  • Holiday calendar: Company-wide holidays, configurable by country/state.
  • Half-day support: Allow partial-day requests (half-day, quarter-day, hourly).

7. Timesheet & Time Tracking

Time tracking serves two purposes: (1) compliance with FLSA for non-exempt employees who must be paid overtime, and (2) project-based cost allocation.

Core Data Model

C#
public class TimeEntry
{
    public Guid Id { get; set; }
    public Guid EmployeeId { get; set; }
    public DateTime Date { get; set; }
    public TimeOnly ClockIn { get; set; }
    public TimeOnly? ClockOut { get; set; }
    public decimal RegularHours { get; set; }
    public decimal OvertimeHours { get; set; }
    public decimal DoubleTimeHours { get; set; }
    public string ProjectCode { get; set; }
    public EntryStatus Status { get; set; }
    public bool IsEdited { get; set; }
    public List<TimeEntryAudit> EditHistory { get; set; }
}

public class TimesheetPeriod
{
    public DateOnly PeriodStart { get; set; }
    public DateOnly PeriodEnd { get; set; }
    public decimal TotalRegularHours { get; set; }
    public decimal TotalOvertimeHours { get; set; }
    public decimal TotalDoubleTimeHours { get; set; }
    public TimesheetStatus Status { get; set; }
    public List<TimeEntry> Entries { get; set; }
}
Multi-State Complexity: Federal FLSA requires overtime after 40 hours/week. California requires: (1) overtime after 8 hours/day, (2) double-time after 12 hours/day, (3) overtime on the 7th consecutive workday. The system must detect the employee's work state and apply the correct rule set.

Overtime Calculation

C#
public class OvertimeCalculator
{
    public OvertimeResult Calculate(Employee employee, List<TimeEntry> weekEntries)
    {
        return employee.WorkState switch
        {
            "CA" => CalculateCaliforniaOvertime(weekEntries),
            "AK" => CalculateAlaskaOvertime(weekEntries),
            _ => CalculateFederalOvertime(weekEntries.Sum(e => e.RegularHours))
        };
    }

    private OvertimeResult CalculateFederalOvertime(decimal totalHours)
    {
        return new OvertimeResult
        {
            RegularHours = Math.Min(totalHours, 40),
            OvertimeHours = Math.Max(0, totalHours - 40),
            DoubleTimeHours = 0
        };
    }

    private OvertimeResult CalculateCaliforniaOvertime(List<TimeEntry> entries)
    {
        decimal dailyOvertime = 0, dailyDoubleTime = 0;
        foreach (var entry in entries)
        {
            decimal dayTotal = entry.RegularHours + entry.OvertimeHours;
            if (dayTotal > 12) dailyDoubleTime += dayTotal - 12;
            if (dayTotal > 8) dailyOvertime += dayTotal - 8;
        }
        decimal weekTotal = entries.Sum(e => e.RegularHours + e.OvertimeHours);
        decimal weeklyOvertime = Math.Max(0, weekTotal - 40);
        decimal totalOT = Math.Max(dailyOvertime + dailyDoubleTime, weeklyOvertime);
        return new OvertimeResult
        {
            RegularHours = Math.Min(weekTotal, 40),
            OvertimeHours = totalOT - dailyDoubleTime,
            DoubleTimeHours = dailyDoubleTime
        };
    }
}

Geofencing & Kiosk Mode

  • Geofencing: Mobile app restricts clock-in to within a configurable radius of the worksite.
  • Kiosk mode: Shared tablet at worksite. Employees clock in/out with PIN or biometric.
  • Break compliance: Auto-prompt for meal/rest breaks per state law (e.g., California: 30-min meal break before 5th hour).
  • GPS tagging: Optional GPS coordinates stored with each clock event for remote/mobile workers.

8. Payroll Processing

Payroll is the most critical and regulated module. Employees must be paid accurately and on time. Errors create legal liability, tax penalties, and trust erosion.

Payroll Run Pipeline

graph TD A[Initiate Payroll Run] --> B[Collect Time & Attendance] B --> C[Apply Earning Rules] C --> D[Apply Deduction Rules] D --> E[Calculate Tax Withholding] E --> F[Calculate Employer Taxes] F --> G[Generate Pay Stubs] G --> H{Manager/HR Review} H -->|Approved| I[Generate ACH File] H -->|Rejected| J[Correct & Re-run] I --> K[Submit to Bank] K --> L[Generate Tax Deposits] L --> M[File Tax Returns] M --> N[Archive & Audit Log]

Gross-to-Net Calculation

C#
public class PayrollCalculator
{
    public Paystub CalculatePaystub(Employee employee, PayPeriod period,
        List<TimeEntry> timeEntries, List<EarningLine> additionalEarnings,
        List<DeductionLine> deductions)
    {
        var paystub = new Paystub();

        paystub.RegularPay = CalculateRegularPay(employee, timeEntries);
        paystub.OvertimePay = CalculateOvertimePay(employee, timeEntries);
        paystub.DoubleTimePay = CalculateDoubleTimePay(employee, timeEntries);
        paystub.BonusPay = additionalEarnings.Where(e => e.Type == "Bonus").Sum(e => e.Amount);
        paystub.CommissionPay = additionalEarnings.Where(e => e.Type == "Commission").Sum(e => e.Amount);
        paystub.GrossPay = paystub.RegularPay + paystub.OvertimePay + paystub.DoubleTimePay
            + paystub.BonusPay + paystub.CommissionPay;

        paystub.PreTaxDeductionsTotal = employee.Benefits.HealthInsurancePreTax
            + employee.Benefits.DentalVisionPreTax
            + employee.Benefits.HSAContribution
            + employee.Benefits.FSAContribution
            + employee.Benefits.Retirement401kPreTax;

        paystub.TaxableIncomeFederal = paystub.GrossPay - paystub.PreTaxDeductionsTotal;

        paystub.FederalIncomeTax = CalculateFederalWithholding(
            employee.W4Info, paystub.TaxableIncomeFederal, employee.PaidFrequency);
        paystub.StateIncomeTax = CalculateStateWithholding(
            employee.WorkState, paystub.TaxableIncomeFederal, employee.PaidFrequency);

        paystub.SocialSecurityTax = Math.Min(
            paystub.TaxableIncomeFederal * 0.062m, 168_600m * 0.062m / employee.PayPeriodsPerYear);
        paystub.MedicareTax = paystub.TaxableIncomeFederal * 0.0145m;
        if (paystub.TaxableIncomeFederal > 200_000m)
            paystub.MedicareTax += (paystub.TaxableIncomeFederal - 200_000m) * 0.009m;

        paystub.NetPay = paystub.GrossPay - paystub.PreTaxDeductionsTotal
            - paystub.PostTaxDeductionsTotal - paystub.TotalTaxes;

        paystub.TotalEmployerCost = paystub.GrossPay
            + paystub.SocialSecurityTax
            + paystub.MedicareTax
            + CalculateFUTA(paystub, employee)
            + CalculateSUTA(employee.WorkState, paystub);

        return paystub;
    }
}

Direct Deposit & ACH

ComponentDetail
ACH File FormatNACHA CCDB format, batched by payment date
Split DepositsUp to 10 bank accounts per employee with fixed or percentage splits
Same-Day ACHOptional same-day processing for last-minute corrections
ReversalsHandle ACH returns (R01 insufficient funds, R03 invalid account) within 2 banking days
Pay CardsPrepaid Visa/Mastercard for unbanked employees
Payroll Idempotency: Each payroll run is identified by a unique RunId + PayPeriodId combination. The bank submission is idempotent — retrying the same run does not create duplicate payments. Enforced through a database unique constraint.

Tax Filing Automation

  • Federal 941: Quarterly Form 941 filing via IRS e-file.
  • State quarterly returns: Automated filing for all 50 states + DC.
  • W-2 generation: Annual W-2 creation, SSA e-filing, and employee portal access by January 31.
  • 1099-NEC: Contractor payment tracking and 1099 generation for payments over $600.
  • New hire reporting: Automated reporting to state directories within 20 days of hire.

9. Benefits Administration

Benefits administration manages the enrollment lifecycle for health insurance, retirement plans, and other employee benefits.

Benefits Data Model

C#
public class BenefitsPlan
{
    public Guid Id { get; set; }
    public string PlanName { get; set; }
    public string PlanType { get; set; }
    public string Carrier { get; set; }
    public decimal EmployeePremium { get; set; }
    public decimal EmployerPremium { get; set; }
    public decimal Deductible { get; set; }
    public List<BenefitTier> Tiers { get; set; }
    public bool IsPreTax { get; set; }
}

public class BenefitEnrollment
{
    public Guid EmployeeId { get; set; }
    public Guid PlanId { get; set; }
    public EnrollmentStatus Status { get; set; }
    public string EnrollmentType { get; set; }
    public DateTime EffectiveDate { get; set; }
    public string Tier { get; set; }
    public List<Beneficiary> Beneficiaries { get; set; }
    public Guid? LifeEventId { get; set; }
}

Life Events & Qualifying Events

graph LR A[Life Event Occurs] --> B{Event Type} B -->|Marriage| C[Add Spouse] B -->|Birth| D[Add Child] B -->|Divorce| E[Remove Spouse] B -->|Relocation| F[Change Plan Region] C & D & E & F --> G[Special Enrollment Window] G --> H[Employee Selects Coverage] H --> I[Verify Documentation] I --> J[Notify Carrier via EDI 834]

COBRA Administration

  • Trigger: Termination, reduction in hours, divorce, dependent aging out.
  • Timeline: Employer notifies COBRA admin within 30 days. Notice to employee within 14 days. Employee has 60 days to elect.
  • Duration: 18 months (standard), 36 months (disability), 29 months (qualifying disability).
  • Premium: 102% of total plan cost. Employee pays directly.
ACA Compliance: ALEs with 50+ FTE employees must offer affordable health coverage to 95% of FT employees and generate Forms 1094-C and 1095-C annually.

10. Performance Management

Performance management encompasses goal setting (OKRs), continuous feedback, formal reviews (360-degree), calibration sessions, and performance improvement plans.

Performance Cycle Template

C#
public class PerformanceCycle
{
    public string Name { get; set; }
    public CycleType Type { get; set; }
    public DateTime GoalSettingStart { get; set; }
    public DateTime GoalSettingEnd { get; set; }
    public DateTime SelfReviewStart { get; set; }
    public DateTime SelfReviewEnd { get; set; }
    public DateTime ManagerReviewStart { get; set; }
    public DateTime ManagerReviewEnd { get; set; }
    public DateTime PeerReviewStart { get; set; }
    public DateTime CalibrationStart { get; set; }
    public int PeerReviewersPerEmployee { get; set; }
    public List<RatingScale> RatingScale { get; set; }
}

public class PerformanceReview
{
    public Guid EmployeeId { get; set; }
    public string SelfAssessment { get; set; }
    public decimal SelfRating { get; set; }
    public string ManagerAssessment { get; set; }
    public decimal ManagerRating { get; set; }
    public decimal ManagerCalibratedRating { get; set; }
    public List<PeerReview> PeerReviews { get; set; }
    public string FinalRating { get; set; }
    public bool CalibrationAdjusted { get; set; }
}

OKR Framework

LevelExampleMetricOwner
Company ObjectiveAchieve product-market fitRevenue, retentionCEO
Department Key ResultReduce onboarding timeDays to completeVP Eng
Team Key ResultShip self-serve provisioning% onboarded without CSMEng Mgr
Individual Key ResultComplete API documentationCoverage %Individual

360 Review Workflow

sequenceDiagram participant HR participant Employee participant Manager participant Peers participant Calibrator HR->>Employee: Review cycle started Employee->>Employee: Complete self-assessment HR->>Peers: Request peer feedback Peers->>Employee: Submit anonymous feedback Manager->>Manager: Complete manager assessment Manager->>HR: Submit for calibration HR->>Calibrator: Calibration session Calibrator->>HR: Calibrated ratings HR->>Manager: Final ratings Manager->>Employee: Performance conversation Employee->>HR: Acknowledge review

Performance Improvement Plans

  • Duration: 30, 60, or 90 days with defined milestones.
  • Documentation: All PIP documents stored in personnel file with restricted access.
  • Check-ins: Scheduled check-in reminders at configurable intervals.
  • Outcomes: Successful completion, extension, or termination — each triggers different downstream workflows.

11. Compensation Management

Compensation management encompasses salary structures, equity grants, bonuses, and total rewards.

Salary Band Structure

C#
public class SalaryBand
{
    public string JobFamily { get; set; }
    public string Level { get; set; }
    public string Geography { get; set; }
    public decimal MinSalary { get; set; }
    public decimal Midpoint { get; set; }
    public decimal MaxSalary { get; set; }
    public string Currency { get; set; }
    public int BandVersion { get; set; }
    public DateTime EffectiveDate { get; set; }
}

// Compa-Ratio: Employee Salary / Band Midpoint
// Below 0.8 = Underpaid, 0.8-1.0 = Developing, 1.0 = At Market, 1.0-1.2 = Above Market

Compensation Review Cycle

graph TD A[Budget Allocation] --> B[Manager Nominations] B --> C[HR Analysis] C --> D[Comp Review Committee] D --> E{Approval} E -->|Approved| F[Generate Letters] E -->|Rejected| G[Revise & Resubmit] F --> H[Manager Delivery] H --> I[Update Payroll]

Equity Management

Grant TypeVestingTax TreatmentTracking
ISO4-year, 1-year cliffAMT at exercise, LTCG at saleExercise price, 409A valuation
NSO4-year, 1-year cliffOrdinary income at exerciseW-2 reporting
RSU4-year, 1-year cliffOrdinary income at vestingVesting schedule, sell-to-cover
PSU3-year, performance conditionsOrdinary income at vestingPerformance metrics
ESPP6-month offering periodsDiscount is ordinary incomeLook-back price

Pay Equity Analysis

  • Compensation ratio analysis: Compare pay across gender, race, and other protected categories.
  • Regression analysis: Statistical analysis controlling for legitimate factors.
  • Banding compliance: Flag employees paid above or below band for review.
  • Pay transparency: States like CO, CA, NY require salary ranges in job postings.
Pay Transparency Laws: As of 2024, 8+ US states and several countries require salary range disclosure in job postings or upon request. The compensation module must expose salary bands to the recruiting system while maintaining access controls.

12. Recruiting Pipeline

The recruiting module (ATS) manages the funnel from job requisition to offer acceptance, integrating seamlessly with Core HR.

Pipeline Stages

graph LR A[Job Requisition] --> B[Job Posting] B --> C[Application] C --> D[Screening] D --> E[Phone Screen] E --> F[Technical Interview] F --> G[Final Round] G --> H[Reference Check] H --> I[Offer] I -->|Accepted| J[Pre-boarding] I -->|Rejected| K[Nurture]

Data Model

C#
public class JobRequisition
{
    public string Title { get; set; }
    public Guid DepartmentId { get; set; }
    public Guid HiringManagerId { get; set; }
    public Guid RecruiterId { get; set; }
    public int Headcount { get; set; }
    public string SalaryRangeId { get; set; }
    public RequisitionStatus Status { get; set; }
}

public class Candidate
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Source { get; set; }
    public Guid? ReferredByEmployeeId { get; set; }
    public PipelineStage CurrentStage { get; set; }
    public List<Interview> Interviews { get; set; }
    public List<Scorecard> Scorecards { get; set; }
    public string ResumeUrl { get; set; }
    public bool IsDiversityCandidate { get; set; }
}

public class Interview
{
    public string InterviewType { get; set; }
    public List<Interviewer> Interviewers { get; set; }
    public DateTime ScheduledAt { get; set; }
    public InterviewStatus Status { get; set; }
    public Scorecard Scorecard { get; set; }
}

ATS Integration Features

  • Job board syndication: Post to LinkedIn, Indeed, Glassdoor via XML feed / API.
  • Resume parsing: Extract structured data from uploaded resumes using NLP.
  • Interview scheduling: Calendar sync with automated availability collection and timezone handling.
  • Referral tracking: Employee referral portal with bonus tracking.
  • Diversity metrics: Pipeline diversity reporting. Anonymized screening mode to reduce bias.
  • EEOC compliance: Voluntary self-identification data stored separately from hiring decisions.
Seamless Handoff: When a candidate accepts an offer, the system automatically creates an employee record, triggers onboarding, and provisions IT resources. No re-keying of data.

13. Learning Management

The LMS handles training assignments, compliance training, course catalogs, and learning paths. Compliance training is particularly critical.

Training Types

TrainingFrequencyAudienceCompliance
Sexual Harassment PreventionAnnualAll employeesCA, NY, IL mandatory
Cybersecurity AwarenessAnnualAll employeesSOC 2, HIPAA
Workplace Safety (OSHA)At hire + refresherOn-site workersOSHA 29 CFR 1910
HIPAA PrivacyAnnualHealthcare clients staffHIPAA §164.530
Code of ConductAnnualAll employeesSarbanes-Oxley
DEI TrainingAnnualAll employeesCompany policy

LMS Data Model

C#
public class TrainingAssignment
{
    public Guid EmployeeId { get; set; }
    public Guid CourseId { get; set; }
    public AssignmentSource Source { get; set; }
    public DateTime AssignedDate { get; set; }
    public DateTime DueDate { get; set; }
    public DateTime? CompletedDate { get; set; }
    public AssignmentStatus Status { get; set; }
    public decimal Progress { get; set; }
    public decimal? Score { get; set; }
    public bool Passed { get; set; }
    public DateTime? CertificateExpiration { get; set; }
}

public class Course
{
    public string Title { get; set; }
    public string ContentType { get; set; }
    public int DurationMinutes { get; set; }
    public bool IsCompliance { get; set; }
    public bool Recurring { get; set; }
    public int RecurrenceDays { get; set; }
    public decimal PassingScore { get; set; }
}

SCORM & xAPI Integration

  • SCORM 1.2 / 2004: Embed SCORM content in an iframe. Track completion, score, and time.
  • xAPI (Experience API): Send detailed learning statements to a Learning Record Store.
  • Overdue escalation: Automated reminders at 7 days, 3 days, and 1 day before due. Manager escalation when overdue.

14. Employee Self-Service Portal

The self-service portal empowers employees to manage their own HR data without submitting tickets.

Portal Features Matrix

FeatureEmployeeManagerHR Admin
View/Edit personal infoOwn profileDirect reportsAll
Request time offSubmitApprove / DenyOverride
View pay stubsOwnAll
Benefits enrollmentEnroll / ChangeManage plans
Submit timesheetOwnApproveOverride
Performance reviewSelf-assessmentTeam reviewsCalibration
TrainingAssigned + catalogTeam progressAll progress
Expense reportsSubmitApproveOverride

Mobile-First Design

  • Clock in/out: One-tap with GPS verification. Widget for quick access.
  • Time-off requests: Calendar view with team availability overlay.
  • Push notifications: Approvals pending, pay day reminders, training due dates.
  • Biometric auth: Fingerprint and Face ID for mobile app access.
  • Offline mode: Cache pay stubs and policy documents for offline viewing.
Self-Service ROI: Companies implementing self-service HR portals report 40-60% reduction in HR ticket volume. Employees spend 70% less time on routine HR tasks.

15. Manager Dashboard

The manager dashboard provides a unified view of everything a manager needs to lead their team.

Dashboard Widgets

C#
public class ManagerDashboard
{
    public int TeamSize { get; set; }
    public int OpenPositions { get; set; }
    public List<PendingAction> PendingActions { get; set; }
    public TeamOverview Overview { get; set; }
    public List<UpcomingEvent> UpcomingEvents { get; set; }
    public PerformanceSnapshot PerformanceSnapshot { get; set; }
    public List<FlightRisk> FlightRisks { get; set; }
    public CompSnapshot CompSnapshot { get; set; }
}

public class PendingAction
{
    public string Type { get; set; }
    public string Title { get; set; }
    public int Count { get; set; }
    public string Url { get; set; }
    public DateTime? DueDate { get; set; }
}

Manager-Specific Workflows

  • Bulk approvals: Approve multiple requests in a single action.
  • Team calendar: Overlay of PTO, holidays, and events. Drag to create.
  • 1:1 meeting support: Agenda builder with talking points from performance and goals.
  • Compensation planning: View compa-ratio, performance ratings, and proposed merit increases.
  • Org chart editing: Drag-and-drop team restructuring (requires HR approval).

16. Analytics & Reporting

HR analytics transforms raw people data into actionable intelligence.

Key Metrics

MetricDefinitionTargetAlert
HeadcountTotal active employeesPer budget>10% over budget
Voluntary TurnoverVol exits / avg headcount × 12<10% annually>15% annualized
Time to FillDays from req open to offer<30 days>60 days
Cost per HireTotal recruiting spend / hires<$5,000>$10,000
Offer Accept RateOffers accepted / sent>85%<70%
Training CompletionCompleted / assigned100%<95%
Engagement ScoreSurvey rating (1-5)>4.0<3.5

DEI Metrics

graph TD A[DEI Dashboard] --> B[Representation by Gender, Race, Age] A --> C[Hiring Funnel Diversity] A --> D[Pay Equity Gap Analysis] A --> E[Promotion Rate by Demographic] A --> F[Retention Rate by Demographic] A --> G[Leadership Pipeline Diversity]

Report Types

C#
public class ReportEngine
{
    public static readonly string[] StandardReports = new[]
    {
        "Headcount Summary (daily snapshot)",
        "Turnover Report (weekly)",
        "New Hires Report (weekly)",
        "Payroll Summary (per pay period)",
        "Benefits Enrollment Status",
        "Training Compliance Dashboard (monthly)",
        "Diversity Report (quarterly)",
        "Compensation Band Analysis (quarterly)",
        "Headcount Forecast (monthly)",
        "Exit Interview Summary (monthly)"
    };
}

Data Warehouse Architecture

  • ETL pipeline: CDC from PostgreSQL → Kafka → Spark dbt transformations → Snowflake/BigQuery.
  • BI tools: Embedded Metabase or Superset for self-service analytics.
  • Export: CSV, Excel, PDF for all reports. Scheduled email delivery.
  • Anonymization: Small team suppression to prevent individual identification.

17. Document Management

HR generates enormous volumes of documents requiring version control, e-signatures, retention policies, and secure access.

Document Categories

CategoryExamplesRetentionAccess
EmploymentOffer letter, contract, NDADuration + 7 yearsEmployee + HR
Tax FormsW-4, W-9, I-9, W-27 years (IRS)Employee + Payroll
BenefitsEnrollment forms, claims6 years (ERISA)Employee + Benefits
PerformanceReviews, PIPs, goals3 yearsEmployee + Manager + HR
DisciplinaryWarnings, terminations7 yearsHR only
PoliciesHandbook, code of conductCurrent + supersededAll employees

E-Signature Workflow

C#
public class DocumentSignatureRequest
{
    public Guid DocumentId { get; set; }
    public List<Signer> Signers { get; set; }
    public string SigningOrder { get; set; }
    public DateTime ExpirationDate { get; set; }
    public string CallbackUrl { get; set; }
}

public class Signer
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Role { get; set; }
    public SigningStatus Status { get; set; }
    public DateTime? SignedAt { get; set; }
    public string SignatureData { get; set; }
    public string IPAddress { get; set; }
}
I-9 Document Storage: I-9 supporting documents must be stored separately from the I-9 form and cannot be retained longer than 3 business days after start date (for E-Verify employers). Automated purging enforced.

18. Expense Management

Expense management handles submission, receipt capture, approval workflows, and reimbursement processing.

Expense Workflow

graph LR A[Employee Submits] --> B[Auto-Validate Policy] B --> C{Total > $500?} C -->|No| D[Manager Approve] C -->|Yes| E[Manager + Finance] D --> F[Finance Process] E --> F F --> G[Reimburse via Payroll] G --> H[GL Posting]

Policy Engine

C#
public class ExpensePolicy
{
    public Dictionary<string, decimal> CategoryLimits { get; set; }
    public decimal ReceiptRequiredThreshold { get; set; } = 25;

    public ExpenseValidationResult Validate(ExpenseLineItem item)
    {
        var violations = new List<PolicyViolation>();
        if (item.Amount > GetCategoryLimit(item.Category))
            violations.Add(new PolicyViolation("EXCEEDS_LIMIT"));
        if (item.Amount >= ReceiptRequiredThreshold && item.ReceiptUrl == null)
            violations.Add(new PolicyViolation("MISSING_RECEIPT"));
        if (item.Date > DateTime.UtcNow.AddDays(60))
            violations.Add(new PolicyViolation("LATE_SUBMISSION"));
        return new ExpenseValidationResult { IsValid = !violations.Any(v => v.Severity == "Hard") };
    }
}

Receipt Processing

  • OCR extraction: Camera → OCR (Google Vision / Azure Form Recognizer) → extract merchant, date, amount.
  • Per diem support: GSA per diem rates by location.
  • Mileage tracking: Google Maps API for route-based calculation. IRS rate (67 cents/mile).
  • Currency conversion: Real-time exchange rates with historical lookup.
  • Duplicate detection: ML-based detection of duplicate receipts.

19. Org-Wide Announcements

The announcement system enables leadership to communicate company-wide, department-specific, or targeted messages.

Announcement Features

FeatureDetail
TargetingAll, department, location, level, custom groups
SchedulingPublish immediately or schedule for future date
Read ReceiptsTrack who has read (opt-in per company)
AcknowledgmentRequire explicit "I acknowledge" for policy updates
PriorityNormal, Important, Urgent (push notification + email)
ChannelsIn-app banner, email, Slack/Teams, mobile push
CommentsOptional comment thread for Q&A
C#
public class Announcement
{
    public string Title { get; set; }
    public string Content { get; set; }
    public string Priority { get; set; }
    public TargetAudience Audience { get; set; }
    public DateTime? ScheduledAt { get; set; }
    public DateTime? ExpiresAt { get; set; }
    public bool RequiresAcknowledgment { get; set; }
    public List<string> DistributionChannels { get; set; }
}

20. Monitoring & Observability

HR platforms carry unique monitoring requirements. Payroll failures are P0 incidents. Data access anomalies may indicate insider threats.

Monitoring Stack

graph TD subgraph Application["Application Layer"] AppLogs["Structured Logs - Serilog to ELK"] AppMetrics["Metrics - Prometheus to Grafana"] AppTraces["Distributed Traces - Jaeger"] end subgraph Infrastructure["Infrastructure"] HostMetrics["CPU, Memory, Disk"] DBMetrics["PostgreSQL Metrics"] KafkaMetrics["Kafka Lag"] end subgraph Business["Business Metrics"] PayrollHealth["Payroll Run Status"] OnboardingRate["Onboarding Completion"] APIErrors["API Error Rates"] end subgraph Alerting["Alerting"] PagerDuty["PagerDuty P0/P1"] Slack["Slack P2/P3"] end AppLogs & AppMetrics & AppTraces --> HostMetrics & DBMetrics & KafkaMetrics HostMetrics & DBMetrics & KafkaMetrics --> PayrollHealth & OnboardingRate & APIErrors PayrollHealth & OnboardingRate & APIErrors --> PagerDuty & Slack

Critical Alerts

AlertSeverityThresholdAction
Payroll run failureP0Any failure during payroll windowPage on-call + payroll lead
Payroll run delayP1Not completed by T+4 hoursPage on-call
Tax calculation errorP0Any tax exceptionHalt payroll, page lead
Auth service downP05xx > 1% for 5 minutesPage on-call
DB replication lagP1Lag > 30 secondsPage DBA
Unusual data accessP1User accessing >100 records/minSecurity alert + block
Bulk export detectedP1Export >1000 recordsAlert security team

Audit Logging

C#
public class AuditLogEntry
{
    public string EntityType { get; set; }
    public Guid EntityId { get; set; }
    public string Action { get; set; }
    public string UserId { get; set; }
    public string IpAddress { get; set; }
    public Dictionary<string, object> OldValues { get; set; }
    public Dictionary<string, object> NewValues { get; set; }
    public DateTime Timestamp { get; set; }
    public bool IsSensitiveData { get; set; }
}
Sensitive Data Auditing: Access to SSN, salary, health records, and immigration status must generate audit log entries regardless of whether data was modified. The audit log itself must be immutable — append-only.

21. Security & Access Control

HR platforms are treasure troves for attackers: SSNs, salary data, bank account details, health information, and home addresses.

Authentication & SSO

C#
public class AuthenticationConfig
{
    public SsoConfig SSO { get; set; }
    public MfaPolicy Mfa { get; set; }
    public SessionConfig Sessions { get; set; }
    public PasswordPolicy Passwords { get; set; }
}

public class RoleBasedAccessControl
{
    public static readonly Dictionary<string, List<string>> RolePermissions = new()
    {
        ["Employee"] = new()
        {
            "profile:read:own", "profile:update:own:limited",
            "timeoff:request", "timeoff:read:own",
            "paystub:read:own", "timesheet:read:own:submit",
            "documents:read:own", "training:read:own:complete"
        },
        ["Manager"] = new()
        {
            "timeoff:approve:direct_reports",
            "timesheet:approve:direct_reports",
            "performance:review:direct_reports",
            "team:read:direct_reports"
        },
        ["HRAdmin"] = new()
        {
            "employee:read:all", "employee:create", "employee:update",
            "payroll:read:all", "payroll:process",
            "benefits:admin", "reports:read:all", "audit:read"
        },
        ["PayrollAdmin"] = new()
        {
            "payroll:read:all", "payroll:process", "payroll:approve",
            "tax:admin", "banking:admin"
        },
        ["SuperAdmin"] = new() { "*:*:*" }
    };
}

Data Encryption

LayerMechanismDetail
TransitTLS 1.3All HTTP traffic, gRPC, database connections
At RestAES-256Database encryption, S3 SSE-KMS
Field-LevelAES-256-GCMSSN, bank account, salary — per-tenant keys
Key ManagementAWS KMS / Azure Key VaultAutomatic rotation every 90 days

Security Controls

  • Data masking: SSN as ***-**-1234. Salary visible only to HR admin and employee.
  • IP allowlisting: Optional IP whitelist for HR admin access.
  • Session recording: Record HR admin sessions for sensitive operations.
  • Penetration testing: Quarterly third-party pen tests. Bug bounty program.
  • SOC 2 Type II: Annual audit with continuous monitoring.

22. Compliance & Regulatory

HR compliance is a multi-jurisdictional minefield. The platform must enforce rules from federal, state, local, and international regulations simultaneously.

Key Regulations

RegulationJurisdictionScopePenalty
FLSAFederal (US)Minimum wage, overtime, child labor$220–$2,194/violation
FMLAFederal (US)12 weeks unpaid leaveLiquidated damages
ACAFederal (US)Health coverage for ALEs$2,880/employee/year
EEOCFederal (US)Anti-discrimination, EEO-1Back pay + damages
GDPREU/EEAData privacy, consent€20M or 4% revenue
CCPA/CPRACaliforniaConsumer data rights$2,500–$7,500/violation
Section 409AFederal (US)Deferred compensation20% penalty + interest
COBRAFederal (US)Health coverage continuation$100/day
ADAFederal (US)Disability accommodationBack pay + damages

Compliance Automation

C#
public class ComplianceEngine
{
    public async Task<ComplianceCheckResult> RunComplianceChecks(Guid tenantId)
    {
        var results = new List<ComplianceCheck>();
        results.Add(await CheckFlsaCompliance(tenantId));
        results.Add(await CheckI9Compliance(tenantId));
        results.Add(await CheckOshaCompliance(tenantId));
        results.Add(await CheckAcaCompliance(tenantId));
        results.Add(await CheckPayEquity(tenantId));
        results.Add(await CheckLeaveAccruals(tenantId));
        results.Add(await CheckStateCompliance(tenantId));

        return new ComplianceCheckResult
        {
            Checks = results,
            OverallStatus = results.All(r => r.Status == ComplianceStatus.Compliant)
                ? ComplianceStatus.Compliant
                : ComplianceStatus.ActionRequired,
            CriticalFindings = results.Where(r => r.Severity == "Critical").ToList()
        };
    }
}

GDPR Compliance for HR

  • Lawful basis: Employment contract (Art. 6(1)(b)) for most HR processing.
  • Data minimization: Collect only what's necessary.
  • Right to access: Employees can request all their data within 30 days.
  • Right to erasure: Limited for HR data due to legal retention requirements.
  • DPIA: Required for high-risk processing like performance monitoring.
  • Cross-border transfers: Standard Contractual Clauses for EU→US transfers.
Multi-State Complexity: A company with employees in California, New York, and Texas must simultaneously comply with CA paid sick leave, NY salary transparency, and TX no state income tax. The system must maintain state-specific rule engines.

23. Database Design

Multi-Tenant Schema Strategy

SQL
CREATE SCHEMA tenant_acme;
CREATE SCHEMA tenant_globex;

ALTER TABLE employees ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON employees
    USING (tenant_id = current_setting('app.current_tenant')::uuid);

SET app.current_tenant = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';

Core Schema

SQL
CREATE TABLE employees (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    employee_number VARCHAR(20) NOT NULL,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    status VARCHAR(20) NOT NULL DEFAULT 'Active',
    department_id UUID REFERENCES departments(id),
    manager_id UUID REFERENCES employees(id),
    hire_date DATE NOT NULL,
    termination_date DATE,
    employment_type VARCHAR(20) NOT NULL,
    org_path TEXT,
    org_depth INT DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE payroll_runs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    pay_period_id UUID NOT NULL,
    status VARCHAR(20) NOT NULL,
    total_gross DECIMAL(12,2),
    total_net DECIMAL(12,2),
    idempotency_key VARCHAR(100) UNIQUE NOT NULL
);

CREATE TABLE paystubs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    payroll_run_id UUID REFERENCES payroll_runs(id),
    employee_id UUID REFERENCES employees(id),
    gross_pay DECIMAL(12,2) NOT NULL,
    net_pay DECIMAL(12,2) NOT NULL,
    federal_tax DECIMAL(12,2),
    state_tax DECIMAL(12,2),
    social_security DECIMAL(12,2),
    medicare DECIMAL(12,2)
);

CREATE TABLE audit_log (
    id BIGSERIAL PRIMARY KEY,
    tenant_id UUID NOT NULL,
    entity_type VARCHAR(50) NOT NULL,
    entity_id UUID NOT NULL,
    action VARCHAR(20) NOT NULL,
    user_id UUID NOT NULL,
    old_values JSONB,
    new_values JSONB,
    is_sensitive BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE RULE no_update_audit AS ON UPDATE TO audit_log DO INSTEAD NOTHING;
CREATE RULE no_delete_audit AS ON DELETE TO audit_log DO INSTEAD NOTHING;

Indexing Strategy

TableIndexPurpose
employeesComposite (tenant_id, status, department_id)Dashboard queries
employeesGiST on org_pathSubtree queries
paystubsComposite (employee_id, period_start)Pay stub retrieval
time_off_requestsComposite (employee_id, status, start_date)Calendar views
audit_logComposite (tenant_id, entity_type, entity_id)Audit trail queries

24. API Design

REST API Overview

Text
Base URL: https://api.hrplatform.com/v1
Authentication: Bearer JWT (SSO IdP)
Tenant isolation: X-Tenant-Id header
Pagination: Cursor-based
Rate limits: 1000 req/min per tenant

GET    /employees                     List employees
GET    /employees/:id                 Get employee
POST   /employees                     Create employee
PATCH  /employees/:id                 Update employee
GET    /employees/:id/org-path        Get reporting chain
GET    /employees/search?q=           Full-text search

GET    /time-off/balances/:empId      Get leave balances
POST   /time-off/requests             Submit request
PATCH  /time-off/requests/:id/approve Approve
GET    /time-off/calendar             Team calendar

POST   /payroll/runs                  Initiate payroll
GET    /payroll/runs/:id              Get status
POST   /payroll/runs/:id/approve      Approve
POST   /payroll/runs/:id/submit-ach   Submit to bank

GET    /benefits/plans                List plans
POST   /benefits/enrollments          Enroll
POST   /benefits/life-events          Report life event

GET    /performance/cycles/:id/reviews/:empId  Get review
POST   /performance/cycles/:id/calibrate       Calibrate

GET    /analytics/headcount           Dashboard data
GET    /analytics/turnover            Metrics
GET    /analytics/diversity           DEI data

GraphQL Schema

GraphQL
type Employee {
    id: ID!
    fullName: String!
    email: String!
    department: Department!
    position: Position!
    manager: Employee
    directReports: [Employee!]!
    hireDate: Date!
    status: EmployeeStatus!
    leaveBalances: [LeaveBalance!]!
    currentReview: PerformanceReview
}

type Query {
    employee(id: ID!): Employee
    employees(filter: EmployeeFilter, pagination: PaginationInput): EmployeeConnection!
    teamCalendar(departmentId: ID!, startDate: Date!, endDate: Date!): [TimeOffEntry!]!
    orgChart(rootEmployeeId: ID, maxDepth: Int): OrgTreeNode!
}

input EmployeeFilter {
    departmentId: ID
    locationId: ID
    status: EmployeeStatus
    search: String
}

Webhook Events

EventUse Case
employee.hiredTrigger Slack welcome, provision accounts
employee.terminatedRevoke access, initiate COBRA
timeoff.approvedUpdate external calendar
payroll.completedUpdate accounting system
benefits.enrollment_changedNotify carrier, update deductions

25. Cost Estimation

Infrastructure Costs (10,000 Employee SaaS)

ServiceSpecificationMonthly Cost
Application Servers4x c6g.xlarge (4 vCPU, 8 GB)$560
PostgreSQL (RDS)db.r6g.xlarge, Multi-AZ, 500 GB$700
Read Replicas2x db.r6g.large$460
Rediscache.r6g.large, cluster mode$240
Elasticsearch3x m6g.large.search$450
Kafka (MSK)3x kafka.m5.large$540
S3 Storage500 GB$15
CDN1 TB transfer/month$90
MonitoringInfra + APM + Logs$500
Total Infrastructure$3,555

Third-Party Service Costs

ServicePurposeMonthly Cost
Stripe ConnectACH processing$0.80/transaction
DocuSignE-signatures$250/mo
Azure Form RecognizerReceipt OCR$1.50/1000 pages
TwilioSMS (MFA)$0.0079/SMS
SendGridEmail delivery$90/mo
Total Third-Party~$1,500

Team Cost Estimate

RoleHeadcountAnnual Cost
Backend Engineers (Sr.)4$720,000
Frontend Engineers (Sr.)3$480,000
DevOps / SRE1$180,000
QA Engineer2$260,000
Product Manager1$170,000
UX Designer1$140,000
Total Team12$1,950,000
Revenue Model: HR SaaS platforms typically charge $6–$15 per employee per month. At 500 customers averaging 200 employees at $8/employee/month: annual revenue = $9.6M. Infrastructure costs of ~$65K/year represent less than 1% of revenue.

26. Testing Strategy

HR platforms require exceptionally rigorous testing because errors directly impact employee paychecks, tax filings, and legal compliance.

Testing Pyramid

graph TD A["E2E Tests - Playwright - 100 tests"] --> B["Integration Tests - xUnit + TestContainers - 500 tests"] B --> C["Unit Tests - xUnit + Moq - 5000+ tests"] style A fill:#f78166,stroke:#f78166,color:#0d1117 style B fill:#58a6ff,stroke:#58a6ff,color:#0d1117 style C fill:#7ee787,stroke:#7ee787,color:#0d1117

Payroll Test Scenarios

C#
public class PayrollCalculatorTests
{
    [Theory]
    [InlineData("CA", 45, 5, 0)]   // California daily OT
    [InlineData("NY", 45, 5, 0)]   // New York weekly only
    [InlineData("TX", 50, 10, 0)]  // Texas weekly only
    public void CalculateOvertime_MultiState(string state, decimal hours, decimal expectedOT, decimal expectedDT)
    {
        var employee = CreateEmployee(workState: state);
        var entries = CreateWeekEntries(totalHours: hours);
        var result = _calculator.CalculateOvertime(employee, entries);
        Assert.Equal(expectedOT, result.OvertimeHours);
    }

    [Fact]
    public void Paystub_NetPay_NeverNegative()
    {
        var employee = CreateEmployee(salary: 30_000m);
        var paystub = _payrollCalculator.CalculatePaystub(employee);
        Assert.True(paystub.NetPay >= 0, "Net pay should never be negative");
    }

    [Fact]
    public void PayrollRun_Idempotent_SameResultOnRetry()
    {
        var run = CreatePayrollRun();
        var result1 = _payrollService.ExecutePayroll(run.Id);
        var result2 = _payrollService.ExecutePayroll(run.Id);
        Assert.Equal(result1.TotalNet, result2.TotalNet);
    }
}

Test Categories

CategoryScopeToolsCoverage
UnitCalculation engines, validatorsxUnit, Moq90%+
IntegrationDB queries, Kafka, APIsTestContainers, WireMock80%+
E2EHire→Pay→TerminatePlaywrightAll critical paths
Payroll ReconciliationCompare against known-good runsCustom tool100% edge cases
LoadPeak usage (pay day, OE)k6, Gatling<200ms p95
SecurityOWASP Top 10, RBAC bypassZAP, BurpZero critical
Payroll Parallel Test: Before each production run, execute the same run against a parallel test environment using anonymized data. Compare results to catch regressions — the same practice banks use before deploying rate changes.

27. Interview Q&A

Q: How would you design payroll for 10,000 employees across 50 states?

A: The payroll system uses a pipeline architecture with idempotent stages. Each employee's pay calculation is independent and parallelized. The pipeline: (1) collect time data, (2) calculate earnings, (3) calculate deductions, (4) calculate taxes via a state-specific rule engine, (5) generate paystub, (6) aggregate for ACH file. Each stage is a Kafka consumer processing employees in batches of 100. The state-specific tax engine loads rules from a configuration store, using a strategy pattern where each state implements ITaxCalculator. New states are added by implementing the interface. The entire run is wrapped in a saga with compensation for rollback. Idempotency is enforced through a unique constraint on (RunId, PayPeriodId).

Q: How do you ensure data consistency when a termination cascades across services?

A: We use the saga pattern with compensation. Termination: (1) Core HR updates status in a transaction, (2) publishes EmployeeTerminatedEvent via the outbox pattern, (3) Payroll service finalizes current pay run and calculates PTO payout, (4) Benefits service initiates COBRA, (5) Document service archives personnel file, (6) Access service revokes all system access. If any step fails, the saga compensates — e.g., if benefits COBRA fails, we retry rather than rolling back the termination. The termination itself is the only step that must be committed; downstream services must be eventually consistent.

Q: How do you handle multi-tenant data isolation?

A: Three layers: (1) Schema-per-tenant for strong logical isolation — each tenant gets its own PostgreSQL schema, (2) Row-Level Security as defense-in-depth — even if application code has a bug, the database layer enforces tenant boundaries, (3) Application-level tenant context set per-request from the JWT token and propagated through all service calls via HTTP headers and Kafka message headers. We test isolation with dedicated integration tests that attempt cross-tenant data access.

Q: How would you migrate a company from BambooHR to your platform?

A: We build a migration toolkit: (1) BambooHR API connector pulls all employee data, time-off history, and documents, (2) Data transformation layer maps BambooHR fields to our schema, handling field mismatches and enrichment, (3) Validation engine runs compliance checks on migrated data, (4) Dry-run mode lets the customer preview everything before committing, (5) Delta sync during the transition period keeps both systems in sync until go-live. Typical migration for 1,000 employees takes 2-4 weeks including validation and UAT.

Q: How do you handle payroll during daylight saving time transitions?

A: Payroll calculations use UTC internally and only convert to local time for display. Pay periods are defined by calendar dates (not hours), so DST transitions don't affect period boundaries. Time entries store local date + local clock-in/out times, and the overtime calculator converts to total duration in decimal hours regardless of DST. We have explicit test cases for the "spring forward" and "fall back" weekends to ensure no double-counting or gaps.

Q: Design the notification system for a platform serving 500 companies.

A: The notification service is a standalone microservice consuming from Kafka. Events are categorized by priority: P0 (payroll failure — page via PagerDuty), P1 (approval pending — push notification + email), P2 (training reminder — email + in-app). Each tenant configures their notification preferences (which channels, quiet hours, digest frequency). The service maintains a notification queue per user with deduplication (no more than one approval reminder per hour). Templates are stored as Handlebars templates with tenant-specific branding. Delivery is retried with exponential backoff, and failed deliveries are logged for manual follow-up.

Q: How do you handle benefits eligibility rules that vary by state and employment type?

A: We model benefits eligibility as a rule engine with composable predicates. Each benefits plan has an eligibility configuration specifying which employment types, departments, locations, and tenure thresholds qualify. For state-specific rules (like California's mandated paid family leave or New York's disability insurance), we maintain a regulatory ruleset that overlays federal defaults. The rules engine evaluates eligibility at enrollment time and re-evaluates on life events. When a regulation changes, we update the ruleset configuration — not application code — allowing compliance updates without redeployment. The system also tracks which employees are affected by a rule change and generates proactive notifications.

Q: How would you design the system to handle a company acquisition — migrating 5,000 employees from another platform?

A: A phased migration approach over 8-12 weeks. Phase 1 (Weeks 1-2): Extract data from the source system via API or flat file export. Map field schemas, identify data quality issues, and generate a migration report. Phase 2 (Weeks 3-4): Transform and cleanse data — normalize department structures, reconcile salary bands, align leave policies. Run data validation rules to flag anomalies. Phase 3 (Weeks 5-6): Load into staging environment with full tenant isolation. Customer runs parallel operations on both systems for one pay period. Phase 4 (Week 7): Validate payroll reconciliation — every employee's pay stub must match between old and new systems. Phase 5 (Week 8): Go-live cutover with real-time delta sync for any remaining transitions. Post-migration support for 30 days including a dedicated Slack channel with the engineering team.

Q: How do you prevent and detect payroll fraud?

A: Multiple layers of defense: (1) Separation of duties — the person who initiates a payroll run cannot approve it; two-person authorization required, (2) Anomaly detection — automated alerts when any employee's pay changes by more than 15% without a documented compensation event, (3) Ghost employee detection — cross-reference active employee count with badge access and network login data, (4) Payroll run comparison — compare each run against the previous run and flag any unexplained changes, (5) Bank account change monitoring — flag and require re-verification when an employee's bank details change within 48 hours of a payroll run, (6) Audit logging — every payroll action is logged with the acting user's identity, IP address, and timestamp. Monthly reconciliation reports are generated automatically and sent to the CFO.

Q: How would you handle a system that needs to support both a 20-person startup and a 20,000-person enterprise on the same codebase?

A: Feature flags and tiered service plans. The core data model and services are the same for all tenants. Differences are handled through: (1) Feature flags — smaller tenants get simplified views (no org chart drag-and-drop, no calibration workflow), (2) Tenant configuration — accrual rules, approval chains, and notification preferences are configurable per-tenant rather than hard-coded, (3) Performance tiering — small tenants share a database pool; enterprise tenants get dedicated read replicas, (4) Onboarding templates — startups use a simple 5-step onboarding; enterprises use the full multi-phase workflow with custom tasks. The key principle is that the codebase is always the same; only configuration and resource allocation differ. This avoids the "two products" trap that plagues many SaaS companies.

Q: Describe how you would implement real-time pay stub generation vs. batch generation.

A: During normal operations, pay stubs are generated as part of the batch payroll run — this is the reliable, auditable path. However, we also support real-time on-demand generation for two scenarios: (1) Employee self-service "what-if" calculator — shows estimated next paycheck based on current elections and hours, useful during benefits open enrollment, (2) Off-cycle payment requests — a manager can request an off-cycle payment (e.g., commission payout) that generates a pay stub immediately. Both paths use the same PayrollCalculator class, ensuring consistency. The on-demand path writes to a shadow table marked as "preview" and doesn't trigger bank submissions. Only the batch payroll run produces official, filed pay stubs.

Q: How do you handle international employees and global payroll?

A: For an initial US-focused platform expanding internationally, we use a hub-and-spoke model. The core platform handles US payroll natively. For other countries, we integrate with local payroll providers via API (e.g., Papaya Global, Remote.com, or local providers like Xero for UK). The integration layer normalizes data between our internal model and the local provider's format. Each country gets a "payroll adapter" that handles local tax calculations, statutory deductions, and filing requirements. Employee data flows from our Core HR service to the local payroll provider; pay results flow back for reporting and analytics. This lets us support 30+ countries without building local payroll expertise in-house.

28. Glossary & Key Terminology

HR technology is a domain dense with acronyms and specialized terminology. This glossary covers the most important terms encountered when designing and building an HR platform, organized by domain.

Employment & HR General

TermDefinition
FLSAFair Labor Standards Act — federal law governing minimum wage, overtime, and child labor in the US. Establishes the 40-hour workweek and overtime requirements.
FMLAFamily and Medical Leave Act — provides eligible employees up to 12 weeks of unpaid, job-protected leave per year for qualifying family and medical reasons.
EEOCEqual Employment Opportunity Commission — federal agency enforcing anti-discrimination laws. Employers with 100+ employees must file EEO-1 reports annually.
I-9Employment Eligibility Verification form required by USCIS for every new hire in the US. Must be completed within 3 business days of start date.
ADAAmericans with Disabilities Act — requires employers to provide reasonable accommodations to qualified individuals with disabilities.
Exempt / Non-ExemptFLSA classification. Exempt employees are not eligible for overtime pay. Non-exempt employees must be paid overtime for hours over 40/week. Classification depends on salary level and job duties.
HeadcountThe total number of active employees in an organization at a given point in time. Distinct from FTE (Full-Time Equivalent), which normalizes part-time employees.
FTEFull-Time Equivalent — a unit of measurement equal to the number of hours worked by one full-time employee (typically 2,080 hours/year). A half-time employee equals 0.5 FTE.
Org ChartA visual representation of an organization's internal structure, showing reporting relationships and hierarchy from executives to individual contributors.
Compa-RatioCompensation ratio — an employee's salary divided by the midpoint of their salary band. A compa-ratio of 1.0 means the employee is paid exactly at the market midpoint.

Payroll & Compensation

TermDefinition
FICAFederal Insurance Contributions Act — the combined Social Security (6.2%) and Medicare (1.45%) taxes withheld from employee paychecks, matched by the employer.
FUTAFederal Unemployment Tax Act — employer-only tax of 6.0% on the first $7,000 of each employee's wages, reduced by a 5.4% credit for state unemployment taxes paid. Effective rate: 0.6%.
SUTAState Unemployment Tax Act — state-level unemployment tax paid by employers. Rates vary by state and employer's experience rating (how many former employees filed unemployment claims).
ACHAutomated Clearing House — electronic bank-to-bank payment network used for direct deposit payroll. NACHA governs the ACH network rules.
Gross PayTotal earnings before any deductions — includes base salary, overtime, bonuses, commissions, and other taxable income.
Net PayThe amount an employee actually receives after all deductions (taxes, benefits, garnishments) are subtracted from gross pay. Also known as "take-home pay."
GarnishmentA court-ordered deduction from an employee's paycheck to pay a debt — child support, tax levies, student loans, or creditor judgments.
W-4Employee's Withholding Certificate — form employees complete to tell their employer how much federal income tax to withhold from their paycheck.
W-2Wage and Tax Statement — form provided to employees and the IRS annually showing total wages earned and taxes withheld during the calendar year.
409AIRS Section 409A — governs nonqualified deferred compensation. Violations result in immediate taxation plus a 20% penalty and interest.

Benefits & Insurance

TermDefinition
ERISAEmployee Retirement Income Security Act — federal law governing private-sector employee benefit plans (health insurance, retirement plans). Sets minimum standards for plan administration.
ACAAffordable Care Act — federal law requiring ALEs (50+ employees) to offer affordable health coverage. Mandates reporting via Forms 1094-C and 1095-C.
COBRAConsolidated Omnibus Budget Reconciliation Act — allows employees and dependents to continue group health coverage for 18-36 months after a qualifying event (termination, reduction in hours, etc.).
HSAHealth Savings Account — tax-advantaged savings account for medical expenses, available with high-deductible health plans. Contributions are pre-tax, growth is tax-free, and qualified withdrawals are tax-free.
FSAFlexible Spending Account — pre-tax account for eligible healthcare or dependent care expenses. Unlike HSAs, FSAs have a use-it-or-lose-it provision (with limited carryover).
PPO / HMO / EPOTypes of health insurance networks. PPO offers more flexibility in provider choice. HMO requires primary care referrals. EPO combines features of both.
Open EnrollmentThe annual period (typically 2-4 weeks) when employees can change their benefits elections. Outside of open enrollment, changes are only allowed with a qualifying life event.
Qualifying Life EventA change in status (marriage, birth, divorce, relocation) that triggers a special enrollment period allowing benefits changes outside open enrollment.

Performance & Development

TermDefinition
OKRObjectives and Key Results — goal-setting framework where objectives describe what to achieve and key results define measurable outcomes. Popularized by Google and Intel.
360 ReviewA performance evaluation method gathering feedback from an employee's manager, peers, direct reports, and sometimes customers. Provides a holistic view of performance.
CalibrationThe process where managers compare and adjust performance ratings across teams to ensure consistency and fairness. Prevents rating inflation in some teams vs. deflation in others.
PIPPerformance Improvement Plan — a structured document outlining specific performance issues, improvement goals, and a timeline (typically 30-90 days). Failure to improve may result in termination.
9-Box GridA talent management tool plotting employees on a 3×3 matrix of performance (low/medium/high) vs. potential (low/medium/high) to guide succession planning and development decisions.

Compliance & Data Privacy

TermDefinition
GDPRGeneral Data Protection Regulation — EU regulation governing the processing of personal data. Requires lawful basis for processing, data minimization, right to access, and right to erasure.
CCPA / CPRACalifornia Consumer Privacy Act / California Privacy Rights Act — grants California residents rights over their personal data, including the right to know, delete, and opt out of the sale of personal information.
SOC 2Service Organization Control 2 — an auditing standard for service providers managing customer data. Based on five Trust Service Criteria: security, availability, processing integrity, confidentiality, and privacy.
PIIPersonally Identifiable Information — any data that could be used to identify a specific individual. In HR: SSN, date of birth, home address, bank account details.
PHIProtected Health Information — health-related data protected under HIPAA. In HR context: health insurance enrollment data, medical leave records, disability accommodations.
RBACRole-Based Access Control — restricting system access based on a user's role within the organization. Ensures employees only see data relevant to their function.

Technology & Architecture

TermDefinition
CDCChange Data Capture — a pattern that tracks and captures changes made to data in a database, enabling real-time data integration and event-driven architectures. Debezium is a popular CDC tool.
Outbox PatternA reliability pattern where a service writes both the business event and an outbox record in the same database transaction, then a separate process publishes outbox records to the message broker. Eliminates the dual-write problem.
Saga PatternA design pattern for managing distributed transactions across multiple services. Each step has a corresponding compensation action that can undo the step if a later step fails.
Materialized PathA tree storage pattern where each node's full path from root is stored (e.g., "/eng/backend/platform"). Enables efficient subtree queries using prefix matching.
SCORMSharable Content Object Reference Model — a set of standards for e-learning software interoperability. Defines how learning content communicates with learning management systems.
xAPIExperience API (Tin Can API) — a specification for tracking learning experiences across platforms. Uses "Actor-Verb-Object" statements stored in a Learning Record Store (LRS).
EDIElectronic Data Interchange — standardized electronic communication between organizations. In HR/benefits: EDI 834 (benefits enrollment), EDI 820 (payment orders).
Study Tip: For HR system design interviews, the most commonly tested terms are: FLSA/FMLA (employment law), FICA/FUTA/SUTA (payroll taxes), COBRA/ACA (benefits), GDPR/SOC 2 (compliance), and the saga/outbox patterns (architecture). Understanding these 10 concepts will cover 80% of domain-specific questions.

29. Conclusion

Building an HR and People Management Platform is one of the most complex SaaS endeavors. It requires deep domain expertise across payroll, benefits, compliance, and employment law — areas where bugs don't just cause downtime, they cause employees to receive incorrect paychecks, companies to face regulatory penalties, and organizations to lose the trust of their workforce.

The key architectural takeaways are:

  1. Start with the employee as the central entity. Every module connects back to the employee record. Get this data model right and the rest follows.
  2. Design for compliance from day one. Retroactive compliance is exponentially harder than building it in. Audit logging, retention policies, and data isolation are non-negotiable foundations.
  3. Payroll must be treated as a financial system. Idempotency, reconciliation, audit trails, and failure recovery are not optional features — they are requirements.
  4. Event-driven architecture for lifecycle cascades. A single employee action (termination, transfer, promotion) touches 10+ services. Async events with the outbox pattern ensure consistency without tight coupling.
  5. Multi-tenancy with strong isolation. Schema-per-tenant plus row-level security provides defense-in-depth. Never rely on application code alone for tenant boundaries.
  6. Invest in testing infrastructure. Payroll calculation tests, compliance rule tests, and migration validation tests are worth their weight in gold. A single miscalculation can cascade to thousands of employees.

The HR tech market continues to grow as companies recognize that people operations are strategic, not administrative. The platforms that win will be those that combine deep compliance expertise with modern developer experience, beautiful employee-facing design, and the reliability that payroll and benefits demand.

Final Thought: The best HR platforms disappear into the background. Employees get paid correctly, on time, every time. Managers approve time off with a tap. HR teams focus on strategy instead of spreadsheets. That seamlessness is the result of thousands of carefully engineered details — and that's what this guide has aimed to cover.

HR & People Management Platform — Senior+ Guide | Ayodhyya