System Design

C27

Employee directory and permissions

Design an employee directory with an org chart and permissions, where access depends on role, department and manager chain.

Not startedSaved in this browser only.
  1. 1A check walks up the tree and a list walks down. Depth is small, so lists and moves decide the hierarchy model.
  2. 2Rules are ordered, and each one is a role, an attribute or a relationship. The first that decides ends the walk.
  3. 3Filter in SQL with one index scan per rule. One check per row gives the same answer at one round trip per person.
  4. 4A reorganisation adds 1 to the org version. Cache keys name the version, so nobody computes which decisions changed.
C27
    A

    The prompt and requirements

    questions first, then numbers
    "Design an employee directory with an org chart and permissions, where access depends on role, department and manager chain."
    questionanswer assumed
    How many tenants and people?10,000 companies, 1,000 people on average, the largest 100,000.
    What is sensitive?Three classes: public, contact, compensation.
    Who sees salaries?The person, their manager chain, HR partners of the department, HR admins.
    Are some records closed?Yes: a confidential flag hides compensation from HR partners, not from the chain.
    How often does the tree change?Small moves daily; a large reorganisation a few times a year.
    May rules differ per company?Not at first. One rule set; grants and attributes are data.
    What needs an audit?Every read of compensation, allowed or denied.
    rulekinddecides when✕ 1 Tenantrow-level securityviewer or target not in this tenant✓ 2 Selfrelationshipviewer is the target✓ 3 HR adminroleviewer has the role✕ 4 Inactiveattributetarget has left✓ 5 Manager chainrelationshipviewer is above target; contact, comp✕ 6 Confidentialattributetarget is flagged; comp✓ 7 HR partnerrole + attributetarget in viewer's department scope✓ 8 Departmentattributesame department; contact✓ 9 Everyonedefaultpublic fields of active peopleNo rule decides: deny.Rule 5 comes before rule 6, so a confidential record stays open to its chain.
    requirementtarget
    Peak reads11,574 profiles a second
    One checkUnder 5 ms
    List for a large managerUnder 100 ms
    Access after a moveCorrect at the next read
    Tenant isolationEnforced by the database
    CorrectnessEqual to a brute-force evaluator

    Two questions drive the design: can A see this field of B, and who can A see. They run in opposite directions on the tree.

    B

    Estimates

    arithmetic shown
    people
    10,000 × 1,000 = 10 million employees
    reads
    10 million × 20 lookups a day = 200 million a day
    average
    200 million ÷ 86,400 s ≈ 2,315 a second
    peak
    2,315 × 5 in work hours ≈ 11,574 a second
    checks
    11,574 × 3 classes ≈ 34,722 a second
    path
    192 bytes an employee × 10 million ≈ 2 GB
    closure
    921 bytes an employee × 10 million ≈ 9 GB

    Bytes per employee were measured on the seeded company, with indexes, at an average depth of 6.5.

    A directory is read-heavy: about 11,574 profiles a second at peak, each one 3 checks. Writes are rare, but one move can touch thousands of rows.

    C

    API

    methods, bodies, status codes
    callresult
    GET /employees/:id200 with the allowed fields. 404 unknown or other tenant.
    GET /employees?q=&field=200 ranked page, inside what the viewer can see.
    GET /employees/:id/reports200 people under this manager.
    GET /me/visible?field=comp200 everyone the caller can see in this class.
    POST /checks200 one decision and its rule, for other services.
    POST /reorganisations200 new version. 409 a cycle. 404 unknown person. Takes a request key.

    Tenant and viewer come from the token, never from the query or the body.

    A hidden field is absent from the response, not null with a reason. A person in another tenant is 404.

    D

    Data model

    entities, then SQL
    employeesPKtenant_idPKidname, titlepublicphone, citycontactFKdept_idattributeactiveattributeconfidentialattributeRLS: tenant_idsalariesPKtenant_idPKemployee_idbase_centscompgradecompapart, so a join is a choicerole_grantsPKemployee_idPKrolePKdept_id0: allRBAC, with a scopeorg_pathPKidpathbyte orderids only; joined to employeesorg_versionsPKtenant_idversion+1 a movenames the cached decisionsaccess_logPKtenant_idPKidviewer, targetclass, ruleINSERT and SELECT only
    tenancy
    tenant_id leads every key, and a policy filters every data table.
    tree tables
    They hold ids only. Each read joins employees, where the policy applies.
    attributes
    Department, active and confidential are columns the rules read.
    search
    The text column holds name and title, which every colleague may see.
    employees, salaries, grants, versions, logsql
    CREATE TABLE departments (
      tenant_id bigint NOT NULL REFERENCES tenants (id),
      id        bigint NOT NULL,
      name      text   NOT NULL,
      PRIMARY KEY (tenant_id, id)
    );
    
    -- Fields any colleague may see, plus the attributes the rules read.
    CREATE TABLE employees (
      tenant_id    bigint  NOT NULL REFERENCES tenants (id),
      id           bigint  NOT NULL,
      name         text    NOT NULL,
      title        text    NOT NULL,
      dept_id      bigint  NOT NULL,
      city         text    NOT NULL,
      phone        text    NOT NULL,
      active       boolean NOT NULL DEFAULT true,
      confidential boolean NOT NULL DEFAULT false,
      -- Only fields every colleague may see go into the search column.
      tsv          tsvector GENERATED ALWAYS AS (to_tsvector('english', name || ' ' || title)1) STORED,
      PRIMARY KEY (tenant_id, id),
      FOREIGN KEY (tenant_id, dept_id) REFERENCES departments
    );
    CREATE INDEX employees_dept ON employees (tenant_id, dept_id);
    CREATE INDEX employees_tsv ON employees USING gin (tsv);
    
    -- Sensitive fields live apart, so a query for the directory cannot touch them by accident.
    CREATE TABLE salaries2 (
      tenant_id   bigint NOT NULL,
      employee_id bigint NOT NULL,
      base_cents  bigint NOT NULL CHECK (base_cents > 0),
      grade       text   NOT NULL,
      PRIMARY KEY (tenant_id, employee_id),
      FOREIGN KEY (tenant_id, employee_id) REFERENCES employees
    );
    
    -- RBAC. An hr_admin grant covers the tenant; an hr_partner grant names one department.
    CREATE TABLE role_grants (
      tenant_id   bigint NOT NULL,
      employee_id bigint NOT NULL,
      role        text   NOT NULL CHECK (role IN ('hr_admin', 'hr_partner'))3,
      dept_id     bigint NOT NULL DEFAULT 0,   -- 0 for a role with no department
      PRIMARY KEY (tenant_id, employee_id, role, dept_id)
    );
    
    -- One row per tenant. A reorganisation adds 1, and cached decisions name the version they used.
    CREATE TABLE org_versions4 (
      tenant_id bigint PRIMARY KEY,
      version   bigint NOT NULL DEFAULT 1
    );
    
    -- Append-only: who asked to see what, and the rule that answered.
    CREATE TABLE access_log (
      tenant_id bigint      NOT NULL,
      id        bigint      GENERATED ALWAYS AS IDENTITY,
      at        timestamptz NOT NULL DEFAULT now(),
      viewer    bigint      NOT NULL,
      target    bigint      NOT NULL,
      class     text        NOT NULL,
      rule      text        NOT NULL,
      allowed   boolean     NOT NULL,
      PRIMARY KEY (tenant_id, id)
    );
    1. 1Only public fields are searchable, so a query cannot probe a hidden value.
    2. 2A separate table: reading a salary needs a join someone wrote on purpose.
    3. 3Roles are data. A grant can carry a department as its scope.
    4. 4One counter per tenant. It invalidates cached decisions in O(1).

    Salaries sit in their own table, so a directory query cannot touch them by accident. Row-level security scopes every table to the tenant.

    E

    The architecture

    click a step; its path lights up
    Employeesbrowser, HR toolsDirectory APIN, no stateRedisdecisions, by versionPostgrespeople, tree, RLSAudit exportsecurity team

    Step 1: Sign in

    • The token names the tenant and the viewer.
    • The service starts a transaction with that tenant set.

    If it fails

    The token is bad: 401, and no query runs.

    The API holds no state. Postgres answers both questions with one statement each, and Redis is optional.

    F

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    PostgresRow-level securityA forgotten filter returns no rows, not another tenant's people.Any shared table
    PostgresByte-ordered text indexPath: a subtree is one key range.Prefix search
    PostgresComposite primary key rangeClosure: all descendants of one person, in one scan.Time series by key
    PostgresWITH RECURSIVEAdjacency: walk the tree with no extra table.Bills of materials
    PostgresUNION of index scansOne scan per rule, not one predicate per row.OR across columns
    Postgres= ANY (ARRAY(subquery))The chain is known before planning, so the join uses the primary key.Sets of unknown size
    PostgresGenerated tsvector, GIN indexText search in the same statement as the permission filter.Small search needs
    PostgresGRANT per tableThe access log takes INSERT and SELECT, nothing else.Ledgers
    RedisGET, SET with a TTLDecisions by version; old keys expire on their own.Sessions
    ServiceA plain evaluator in memoryThe specification the SQL is tested against.Any rule engine

    Postgres gives me row-level security, range scans on a path and index scans I can union. Redis gives me a version-keyed cache if I need one.

    G

    Deep dive: the org tree

    100,000 employees, depth up to 7
    org chartanaboguscyadjacency: 4 rowsana parent -bo parent anagus parent anacy parent bopath: 4 rowsana /ana/bo /ana/bo/gus /ana/gus/cy /ana/bo/cy/closure: 8 rowsana ana 0 bo bo 0ana bo 1 bo cy 1ana gus 1 gus gus 0ana cy 2 cy cy 0Check walks upIs ana above cy? At most one row per level.List walks downWho is under ana? One row per report.
    modelrowssizecheck p50list, 14,891 reportsmove 1,004 people
    adjacency100,0109 MB0.7 ms38 ms0.6 ms
    path100,01019 MB0.3 ms25 ms7.8 ms
    closure752,99192 MB0.3 ms24 ms49 ms
    methodstatus
    Adjacency list, recursive querySmall companies
    Materialised pathApproved
    Closure tableQueries by level
    Load the tree into app memoryNot approved
    A graph database for one treeNot approved
    list by viewerreportsvisibleadjacencypathclosure
    individual contributor011.2 ms1.2 ms1.2 ms
    team manager11101.4 ms1.3 ms1.3 ms
    director1,0039884.0 ms3.2 ms3.0 ms
    division head14,89114,58938 ms25 ms24 ms
    moveadjacencypathclosure
    10 people1 row, 1.9 ms10 rows, 1.5 ms70 rows, 1.9 ms
    1,004 people1 row, 0.6 ms1,004 rows, 7.8 ms5,020 rows, 49 ms
    8,851 people1 row, 0.7 ms8,851 rows, 71 ms26,553 rows, 136 ms
    path: up, down, movesql
    -- The path already lists them.
    SELECT unnest(string_to_array(trim(BOTH '/' FROM path), '/')1)::bigint AS id
    FROM cat_path WHERE id = $1 ORDER BY id;
    
    -- One range scan: every path that starts with the node's path. '~' sorts after '/' and digits.
    SELECT c.id
    FROM cat_path c, (SELECT path FROM cat_path WHERE id = $1) s
    WHERE c.path >= s.path AND c.path < s.path || '~'2
    ORDER BY c.id;
    
    -- Every row in the subtree gets a new prefix.
    UPDATE cat_path c
    SET path =3 (SELECT path FROM cat_path WHERE id = $2) || substr(c.path, length(m.parent_path) + 1)
    FROM (SELECT path, left(path, length(path) - length(id::text) - 1) AS parent_path
          FROM cat_path WHERE id = $1) m
    WHERE c.path >= m.path AND c.path < m.path || '~';
    1. 1Up: the row already lists its ancestors.
    2. 2Down: one range of the byte-ordered index.
    3. 3A move rewrites 1 row per moved person.

    Comp class, median of 15 runs, with the models taking turns. Row counts of every move matched the formula. The models and statements come from the data modeling sheet.

    With depth 7, path reads match closure, at a fifth of the storage and with cheaper moves. So I pick path, and I add closure only for queries by level.

    H

    Deep dive: the permission model

    roles, attributes, relationships
    decidepseudo code
    decide(viewer, target, class):
      not both in this tenant, or viewer left:   DENY   tenant
      viewer = target:                           ALLOW  self
      viewer has role hr_admin1:                  ALLOW  admin
      target has left:                           DENY   inactive
      class <> public AND viewer above target2:   ALLOW  chain
      class = comp AND target.confidential3:      DENY   confidential
      class <> public AND viewer is HR partner
        for target's department4:                 ALLOW  partner
      class = contact AND same department:       ALLOW  department
      class = public:                            ALLOW  everyone
      otherwise:                                 DENY   none5
    1. 1RBAC: a grant row, with no relationship needed.
    2. 2A relationship rule: the tree answers it.
    3. 3An attribute that denies. Its place in the list means the chain still passes.
    4. 4A role scoped by an attribute: the grant names a department.
    5. 5Deny by default: a new field class is closed until a rule opens it.
    Tested source Go: the brute-force evaluator · SQL: one statement per check
    Go: the brute-force evaluatorgo
    
    // decide runs the rules in order, in plain Go, by walking the tree one parent at a time. It is the
    // brute-force evaluator: slow, and simple enough to read as the specification. With a non-nil
    // trace it also records why each rule passed on the request.
    func (c *Company) decide(viewer, target int64, class string, trace *[]security.Check) string {
      note := func(name, result string, detail func() string) {
        if trace != nil {
          *trace = append(*trace, security.Check{Name: name, Result: result, Detail: detail()})
        }
      }
      v, okV := c.Get(viewer)
      t, okT := c.Get(target)
      if !okV || !okT || !v.Active {
        note("tenant", "fail", func() string { return "the viewer or the target is not an active member of this tenant" })
        return "tenant"
      }
      note("tenant", "pass", func() string { return "both are in this tenant" })
    
      if viewer == target {
        note("self", "allow", func() string { return "people see all of their own record" })
        return "self"
      }
      note("self", "pass", func() string { return fmt.Sprintf("%s is not %s", v.Name, t.Name) })
    
      if c.Admins[viewer] {
        note("admin", "allow", func() string { return v.Name + " has the role hr_admin" })
        return "admin"
      }
      note("admin", "pass", func() string { return v.Name + " does not have the role hr_admin" })
    
      if !t.Active {
        note("inactive", "deny", func() string { return t.Name + " has left; only HR admins see the record" })
        return "inactive"
      }
      note("inactive", "pass", func() string { return t.Name + " is active" })
    
      if class != Public {
        if c.Reaches(viewer, target) {
          note("chain", "allow", func() string { return "manager chain: " + c.path(viewer, target) })
          return "chain"
        }
        note("chain", "pass", func() string { return fmt.Sprintf("%s is not above %s", v.Name, t.Name) })
      }
    
      if class == Comp {
        if t.Confidential {
          note("confidential", "deny", func() string { return t.Name + " is confidential: the chain only" })
          return "confidential"
        }
        note("confidential", "pass", func() string { return t.Name + " is not confidential" })
      }
    
      if class != Public {
        if has(c.Partners[viewer], t.Dept) {
          note("partner", "allow", func() string { return fmt.Sprintf("%s is HR partner for %s", v.Name, c.Depts[t.Dept]) })
          return "partner"
        }
        note("partner", "pass", func() string { return fmt.Sprintf("%s is not HR partner for %s", v.Name, c.Depts[t.Dept]) })
      }
    
      if class == Contact {
        if v.Dept == t.Dept {
          note("department", "allow", func() string { return "both are in " + c.Depts[t.Dept] })
          return "department"
        }
        note("department", "pass", func() string { return fmt.Sprintf("%s and %s are in different departments", v.Name, t.Name) })
      }
    
      if class == Public {
        note("everyone", "allow", func() string { return "any active employee sees public fields" })
        return "everyone"
      }
      note("none", "deny", func() string { return "no rule allows this" })
      return "none"
    }
    
    SQL: one statement per checksql
    -- One statement, one decision. $1 target, $2 viewer, $3 field class. The rules run in order.
    WITH chain AS ({ancestors})
    SELECT CASE
      WHEN v.id IS NULL OR t.id IS NULL OR NOT v.active THEN 'tenant'
      WHEN v.id = t.id THEN 'self'
      WHEN EXISTS (SELECT 1 FROM role_grants g WHERE g.employee_id = v.id AND g.role = 'hr_admin') THEN 'admin'
      WHEN NOT t.active THEN 'inactive'
      WHEN $3::text <> 'public' AND EXISTS (SELECT 1 FROM chain c WHERE c.id = v.id) THEN 'chain'
      WHEN $3::text = 'comp' AND t.confidential THEN 'confidential'
      WHEN $3::text <> 'public' AND EXISTS (SELECT 1 FROM role_grants g
             WHERE g.employee_id = v.id AND g.role = 'hr_partner' AND g.dept_id = t.dept_id) THEN 'partner'
      WHEN $3::text = 'contact' AND v.dept_id = t.dept_id THEN 'department'
      WHEN $3::text = 'public' THEN 'everyone'
      ELSE 'none'
    END
    FROM (SELECT 1) one
    LEFT JOIN employees v ON v.id = $2
    LEFT JOIN employees t ON t.id = $1;
    modelhandlesstatus
    Roles onlyHR admin. Not "my reports".Not approved
    Attributes onlyDepartment. The chain needs a query, not an attribute.Not approved
    ACL row per viewer and targetEverything, at N × N rows, rebuilt on each move.Not approved
    Relation tuples in a separate serviceMany apps sharing one model.Many services
    Ordered rules: role, attribute, relationshipThis prompt, in SQL next to the data.Approved
    form of the ruleshow it is tested
    Evaluator in memory, parent pointersIt is the readable specification.
    SQL check, one per modelCompared rule name by rule name.
    SQL list, one per modelCompared set by set.

    Tested at 100,000 people, and at 4,000 people before and after a reorganisation, in all three models. Every pair of the 10-person cast matched too.

    I keep a short ordered rule list that mixes a role, attributes and the manager chain. Each rule is a line I can explain to an auditor.

    I

    Deep dive: filter in SQL, not row by row

    a director who sees 988 people
    methodtimestatus
    One check per person, 100,000 peopleabout 26 sNot approved
    One statement, OR of all rules219 msNot approved
    One statement, UNION of one scan per rule2.6 msApproved
    Precomputed list per viewernot measuredRebuild on every move
    planner factwhat to do
    A cached generic plan cannot see how many people a viewer manages.Plan each list for its parameters.
    A join to a subquery of unknown size can choose a full scan.Fold the chain into an array first.

    Row by row, derived: 0.3 ms median over 2,000 checks × 100,000 people. Before those two fixes, a full scan put every list above 50 ms, whatever the viewer's size.

    listpseudo code
    list(viewer, class):                 // one statement
      me = viewer's department, roles, partner departments
      UNION of one index scan per rule1:
        the viewer
        everyone                    IF me is hr_admin
        people under the viewer2     IF class <> public
        people in partner departments, not confidential for comp3
        people in my department     IF class = contact
        every active person         IF class = public
    1. 1Each branch uses its own index. UNION removes people who match twice.
    2. 2The hierarchy model only changes this one branch.
    3. 3A deny rule becomes a filter on the branches after it.
    Tested source SQL: list
    SQL: listsql
    -- Everyone the viewer can see in one field class. Each rule is one index scan, joined by UNION.
    -- $1 viewer, $2 field class.
    WITH chain AS ({subtree}),
    me AS (
      SELECT v.dept_id,
             EXISTS (SELECT 1 FROM role_grants g WHERE g.employee_id = v.id AND g.role = 'hr_admin') AS admin,
             ARRAY(SELECT g.dept_id FROM role_grants g WHERE g.employee_id = v.id AND g.role = 'hr_partner') AS partner_of
      FROM employees v WHERE v.id = $1 AND v.active
    )
    SELECT $1::bigint AS id FROM me
    UNION
    SELECT e.id FROM employees e, me WHERE me.admin
    UNION
    SELECT e.id FROM employees e, me
    WHERE $2::text <> 'public' AND e.active AND e.id = ANY (ARRAY(SELECT id FROM chain))
    UNION
    SELECT e.id FROM me, unnest(me.partner_of) AS d (id) JOIN employees e ON e.dept_id = d.id
    WHERE $2::text <> 'public' AND e.active AND ($2::text = 'contact' OR NOT e.confidential)
    UNION
    SELECT e.id FROM employees e, me
    WHERE $2::text = 'contact' AND e.active AND e.dept_id = me.dept_id
    UNION
    SELECT e.id FROM employees e, me
    WHERE $2::text = 'public' AND e.active
    ORDER BY id;

    The same 988 rows took 2.6 ms as a union of scans and 219 ms as one big OR. Row by row, the company takes 26 s.

    J

    Deep dive: caching and reorganisations

    version the key; do not chase the entries
    cached check and reorganisepseudo code
    check(viewer, target, class):
      version = org version of the tenant
      key = tenant : version1 : viewer : target : class
      IF key is in Redis: RETURN it
      rule = run the statement; store it for 5 minutes
    
    reorganise(node, parent):
      BEGIN
        check both people are in this tenant; refuse a cycle2
        move the subtree in the tree tables
        version = version + 13
      COMMIT
      publish version to Redis4
    1. 1Old decisions become unreachable the moment the version changes.
    2. 2A move under your own report would cut the subtree off the tree.
    3. 3It commits with the move, so the version never lags the tree in Postgres.
    4. 4If this step fails, the version key expires and the next read loads it from Postgres.
    Tested source Go: cache · Go: reorganise
    Go: cachego
    
    // Check returns the cached decision, or runs the statement and stores it. It reports a cache hit.
    func (c *Cache) Check(ctx context.Context, tenant int64, model string, viewer, target int64, class string) (string, bool, error) {
      version := int64(0)
      if !c.NoVersion {
        var err error
        if version, err = c.version(ctx, tenant); err != nil {
          return "", false, err
        }
      }
      key := fmt.Sprintf("dec:%d:%d:%d:%d:%s", tenant, version, viewer, target, class)
      rule, err := c.RDB.Get(ctx, key).Result()
      if err == nil {
        return rule, true, nil
      }
      if !errors.Is(err, redis.Nil) {
        return "", false, fmt.Errorf("read decision: %w", err)
      }
      if rule, err = c.D.Check(ctx, tenant, model, viewer, target, class); err != nil {
        return "", false, err
      }
      if err := c.RDB.Set(ctx, key, rule, c.TTL).Err(); err != nil {
        return "", false, fmt.Errorf("store decision: %w", err)
      }
      return rule, false, nil
    }
    
    // version reads the tenant's org version from Redis, and from Postgres when the key has gone.
    func (c *Cache) version(ctx context.Context, tenant int64) (int64, error) {
      v, err := c.RDB.Get(ctx, versionKey(tenant)).Int64()
      if err == nil {
        return v, nil
      }
      if !errors.Is(err, redis.Nil) {
        return 0, fmt.Errorf("read version: %w", err)
      }
      err = c.D.scoped(ctx, tenant, func(tx pgx.Tx) error {
        return tx.QueryRow(ctx, q["read_version"]).Scan(&v)
      })
      if err != nil {
        return 0, fmt.Errorf("read org version: %w", err)
      }
      if err := c.RDB.Set(ctx, versionKey(tenant), v, c.TTL).Err(); err != nil {
        return 0, fmt.Errorf("store version: %w", err)
      }
      return v, nil
    }
    
    // Publish stores the version a reorganisation returned, right after its commit.
    func (c *Cache) Publish(ctx context.Context, tenant, version int64) error {
      if err := c.RDB.Set(ctx, versionKey(tenant), version, c.TTL).Err(); err != nil {
        return fmt.Errorf("publish version: %w", err)
      }
      return nil
    }
    
    Go: reorganisego
    
    // Reorganise moves a subtree under a new parent in one transaction, in every hierarchy model. It
    // checks the move inside the tenant, changes the department when one is given, and adds 1 to the
    // org version, which makes every cached decision of the tenant unreachable. It returns the new
    // version.
    func (d *Directory) Reorganise(ctx context.Context, tenant, node, parent, dept int64) (int64, error) {
      var version int64
      if node == parent {
        return 0, fmt.Errorf("move %d under itself: %w", node, ErrCycle)
      }
      err := d.scoped(ctx, tenant, func(tx pgx.Tx) error {
        var known int
        if err := tx.QueryRow(ctx, q["known"], []int64{node, parent}).Scan(&known); err != nil {
          return fmt.Errorf("look up people: %w", err)
        }
        if known != 2 {
          return ErrUnknown
        }
        rows, err := tx.Query(ctx, modeling.Q("tree", "ancestors_closure"), parent)
        if err != nil {
          return fmt.Errorf("ancestors of %d: %w", parent, err)
        }
        above, err := pgx.CollectRows(rows, pgx.RowTo[int64])
        if err != nil {
          return fmt.Errorf("read ancestors of %d: %w", parent, err)
        }
        if slices.Contains(above, node) {
          return ErrCycle
        }
        if dept != 0 {
          if _, err := tx.Exec(ctx, q["move_department"], node, dept); err != nil {
            return fmt.Errorf("move department: %w", err)
          }
        }
        for _, s := range []struct {
          name string
          args []any
        }{
          {"move_adjacency", []any{node, parent}},
          {"move_path", []any{node, parent}},
          {"move_closure_unlink", []any{node}},
          {"move_closure_link", []any{node, parent}},
        } {
          if _, err := tx.Exec(ctx, modeling.Q("tree", s.name), s.args...); err != nil {
            return fmt.Errorf("%s: %w", s.name, err)
          }
        }
        return tx.QueryRow(ctx, q["bump_version"]).Scan(&version)
      })
      if err != nil {
        return 0, fmt.Errorf("move %d under %d: %w", node, parent, err)
      }
      return version, nil
    }
    
    invalidationafter a movestatus
    TTL onlyOld access lasts until the TTL ends; the test saw it.Not approved
    Find and delete affected keysMoved people × their viewers.Not approved
    Version in the keyCorrect at the next read; cold cache for the tenant.Approved
    No cacheCorrect always.Approved
    one decisionp50p99
    Statement in its transaction0.3 ms0.5 ms
    Cache hit: version, then decision0.2 ms0.4 ms
    Cache miss: reads, statement, store0.7 ms1.0 ms
    whole move
    1,004 people, all models, department, version: 86 ms in one transaction.
    when to cache
    When a check crosses the network to a separate service, or runs many statements.

    A move invalidates a set of decisions I cannot list cheaply, so I change the key. Here I would not cache one check, because the statement is as fast.

    K

    Deep dive: field visibility, search and audit

    decide per class; filter inside the search
    read one profilepseudo code
    read(viewer, target):                // one transaction
      rules = decide(viewer, target, class) for each class1
      fields = public and contact fields the rules allow
      IF rules[comp] allows: read the salaries row2
      write access_log3: viewer, target, rule, allowed
      RETURN only those fields
    1. 1One decision per class, so a viewer can get public fields and no salary.
    2. 2A denied viewer never loads the value, so a bug cannot return it.
    3. 3In the same transaction: no read without a record.
    Tested source Go: read
    Go: readgo
    
    // Read returns the fields the viewer may see. It decides per field class, reads salaries only when
    // the rule allows them, and logs every decision on sensitive fields, allowed or not.
    func (d *Directory) Read(ctx context.Context, tenant int64, model string, viewer, target int64) (Profile, error) {
      var p Profile
      err := d.scoped(ctx, tenant, func(tx pgx.Tx) error {
        rules := map[string]string{}
        for _, class := range Classes {
          var rule string
          if err := tx.QueryRow(ctx, sql("check", model), target, viewer, class).Scan(&rule); err != nil {
            return fmt.Errorf("check %s: %w", class, err)
          }
          rules[class] = rule
        }
        if rules[Public] == "tenant" {
          return ErrUnknown
        }
        var name, title, city, phone string
        if Allows(rules[Public]) || Allows(rules[Contact]) {
          if err := tx.QueryRow(ctx, q["profile"], target).Scan(&name, &title, &city, &phone); err != nil {
            return fmt.Errorf("read employee: %w", err)
          }
        }
        if Allows(rules[Public]) {
          p.Name, p.Title = &name, &title
        }
        if Allows(rules[Contact]) {
          p.City, p.Phone = &city, &phone
        }
        if Allows(rules[Comp]) {
          var base int64
          var grade string
          if err := tx.QueryRow(ctx, q["salary"], target).Scan(&base, &grade); err != nil {
            return fmt.Errorf("read salary: %w", err)
          }
          p.BaseCents, p.Grade = &base, &grade
        }
        _, err := tx.Exec(ctx, q["log_access"], viewer, target, Comp, rules[Comp], Allows(rules[Comp]))
        return err
      })
      if err != nil {
        return Profile{}, fmt.Errorf("read %d as %d: %w", target, viewer, err)
      }
      return p, nil
    }
    
    field visibilitystatus
    Hide the field in the browserNot approved
    Load every field, strip them in the APIOne bug leaks
    Decide per class; read only what is allowedApproved
    Row policy with the chain on salariesSubquery per row
    search "staff engineer", page of 10kepttimestatus
    Search index, top 10, then filter012 msNot approved
    Search index, top 1,000, then filter18not timedFails for narrow viewers
    Filter inside the query, in Postgres1033 msApproved
    Search engine with department tokens per documentnot builtnot builtReindex on moves
    matches
    8,373 people match the query; the viewer sees 988 people in the comp class.
    oracle
    Never index a field the searcher may not see. A match on it reveals the value.
    audit
    The service role can INSERT and SELECT the log. A DELETE fails with a permission error.
    classfieldswho sees it, beyond self and HR admins
    publicname, title, departmentEvery active colleague
    contactphone, cityChain, department, HR partner
    compsalary, gradeChain; HR partner unless confidential

    Filtering after the search kept 0 of 10 results, so I filter inside it. Every read of compensation writes a log row in the same transaction.

    L

    See it: the rule path

    every decision matched SQL in all three models
    viewer
    target
    fields
    org chart
    • anaExecutive · Chief Executiveconfidential
    • boEngineering · VP Engineeringconfidential
    • cyEngineering · Engineering Manager
    • diEngineering · Engineer
    • edEngineering · Engineer (left)
    • fayEngineering · Staff Engineerconfidential
    • gusSales · VP Salesconfidential
    • halSales · Account Executive
    • ivyPeople · HR Partnerhr_partner, Engineering
    • joPeople · HR Adminhr_admin
    1. → Same tenantrow-level securityboth are in this tenant
    2. → Own recordrelationshipcy is not di
    3. → HR adminrolecy does not have the role hr_admin
    4. → Target activeattributedi is active
    5. ✓ Manager chainrelationshipmanager chain: cy > di
    6. · Confidentialattributenot reached
    7. · HR partnerrole + attributenot reached
    8. · Same departmentattributenot reached
    9. · Public fieldsdefaultnot reached
    ✓ allowedcy sees salary, grade of di. Decided by: Manager chain.

    Pick any viewer and target. The first rule that decides ends the walk, and a move changes the answer at the next read.

    M

    Failure cases

    what breaks, and why access stays correct
    eventresultwhy it is safesaved by
    A query forgets the tenant filterOther tenants return no rows.The policy applies to every statement of the service role.RLS
    Transaction has no tenant setNo rows at all.NULL matches nothing, so a missing setting fails closed.RLS
    A move names a person in another tenant404.Row-level security hides the row, so the move stops.RLS
    A move puts a manager under a report409.The new parent's ancestors contain the moved person.Cycle check
    A move fails halfwayNothing changes.Tree, department and version commit together.Transaction
    Publishing the version to Redis failsOld decisions for up to 5 minutes.The version key has a TTL, so a later read loads it from Postgres.TTL
    Redis is downReads go to Postgres.The cache only saves time; the statement stays the truth.Statement
    Someone is terminatedAccess ends at the next request.The tenant rule reads active in the same statement. A cached decision needs a version change too.Rule 1
    The access log write failsThe read fails.Same transaction: no salary leaves without a row.Transaction
    A manager leaves with reports under themThe chain above still works.The record stays in the tree, marked inactive, until HR moves the reports.Tree
    N

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One Postgres, path column2+ read replicas3+ shards by tenant4+ search engine, permission servicemore load →
    Capacity against the peak1001k10k100k1MDemand, peak checks: 34,722 checks per secondDemand, peak checks34,722One Postgres, 8 clients: 18,710 checks per secondOne Postgres, 8 clients18,7104 replicas, derived: 74,840 checks per second4 replicas, derived74,840checks per second, log scale
    stepaddit handlesmove up when you see
    1One Postgres, path column, no cache.About 18,710 checks a second with 8 clients: a large share of tenants, not all of them.CPU near its limit at peak.
    2Read replicas for checks and lists.Rates add per replica. After a move, read the primary until the replica passes that version.Moves or audit writes pass one primary.
    3Shards by tenant. A tree never crosses a tenant.Each shard adds its own rate. The largest tenants get their own.Search needs ranking or typo handling that Postgres does not give.
    4Search engine and a shared permission service.Department tokens in the index; a permission API for other products.Top of the ladder.

    Demand, derived: 200 million reads a day ÷ 86,400 s × 5 × 3 ≈ 34,722 checks a second. Replica capacity is multiplied, not measured.

    One Postgres takes about 18,710 checks a second, and the peak for all tenants is 34,722. So replicas or tenant shards arrive early, and the design splits cleanly.

    O

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How do the three tree models compare in general?Adjacency is cheap to move, path is one range scan, and closure answers queries by level at the highest write cost.D3
    How do you enforce tenant isolation?tenant_id leads every key, and row-level security filters each statement. Very large tenants can move to their own cell.O6
    Where do authentication and object checks fit?The token proves who is calling. The rules run on every object after that, because a missing object check is the classic access bug.O5
    How does ranked search work under the filter?An inverted index gives candidates and a score. Here the permission set joins before the page is cut, so ranking only sees allowed people.B8
    Why a version in the key and not delete by key?Affected keys are moved people × their viewers, and no index lists them. A version change costs one write.B4
    How do you feed search from the database?Write changes to a log in the same transaction, and let an indexer apply them with versions. A dual write loses updates on a crash.B6
    How does an approval chain find the requester's manager?It reads the parent at step entry and stores the person on the task, so a later move does not change a running approval.C26
    How do you run a large reorganisation safely?Apply it as many small moves, each in its own transaction. Hold the plan in a table, so a failed run can resume.O4
    P

    Drill

    predict, then reveal

    0 of 10 known

    1. What is the difference between a check and a list?

    2. Why not build a list by calling the check for each person?

    3. Why UNION per rule and not one WHERE with OR?

    4. Why does the closure table cost so much on a move?

    5. Which model would you pick for a company of 100,000?

    6. A manager moves to another team. How do cached decisions stop being wrong?

    7. Should you cache a single check?

    8. Search returns the top 10, then the app drops what the viewer cannot see. What goes wrong?

    9. Why not put salary in the search index?

    10. Why log denied reads?

    Q

    Numbers to say

    measured in the lab
    check
    0.3 ms median, 0.5 ms p99, path model.
    rate
    About 18,710 checks a second with 8 clients.
    list
    988 people in 3.2 ms; 14,589 in 25 ms.
    row by row
    About 26 s for 100,000 people.
    storage
    Path 19 MB; closure 92 MB, 752,991 rows.
    move
    1,004 people: 1,004 path rows, 5,020 closure rows, 1 adjacency row.
    depth
    7 at most, 6.5 on average.

    Postgres 16 on an 8-core laptop, 100,000 seeded employees, row-level security on. The rate, the cache and the OR test used the closure model. Other workloads shared the machine, so use these as orders of magnitude.