Employee directory and permissions
Design an employee directory with an org chart and permissions, where access depends on role, department and manager chain.
- 1A check walks up the tree and a list walks down. Depth is small, so lists and moves decide the hierarchy model.
- 2Rules are ordered, and each one is a role, an attribute or a relationship. The first that decides ends the walk.
- 3Filter in SQL with one index scan per rule. One check per row gives the same answer at one round trip per person.
- 4A reorganisation adds 1 to the org version. Cache keys name the version, so nobody computes which decisions changed.
"Design an employee directory with an org chart and permissions, where access depends on role, department and manager chain."
| question | answer 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. |
| requirement | target |
|---|---|
| Peak reads | 11,574 profiles a second |
| One check | Under 5 ms |
| List for a large manager | Under 100 ms |
| Access after a move | Correct at the next read |
| Tenant isolation | Enforced by the database |
| Correctness | Equal 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.
- 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.
| call | result |
|---|---|
| GET /employees/:id | 200 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/reports | 200 people under this manager. |
| GET /me/visible?field=comp | 200 everyone the caller can see in this class. |
| POST /checks | 200 one decision and its rule, for other services. |
| POST /reorganisations | 200 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.
- 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.
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)
);- 1Only public fields are searchable, so a query cannot probe a hidden value.
- 2A separate table: reading a salary needs a join someone wrote on purpose.
- 3Roles are data. A grant can carry a department as its scope.
- 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.
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.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Postgres | Row-level security | A forgotten filter returns no rows, not another tenant's people. | Any shared table |
| Postgres | Byte-ordered text index | Path: a subtree is one key range. | Prefix search |
| Postgres | Composite primary key range | Closure: all descendants of one person, in one scan. | Time series by key |
| Postgres | WITH RECURSIVE | Adjacency: walk the tree with no extra table. | Bills of materials |
| Postgres | UNION of index scans | One 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 |
| Postgres | Generated tsvector, GIN index | Text search in the same statement as the permission filter. | Small search needs |
| Postgres | GRANT per table | The access log takes INSERT and SELECT, nothing else. | Ledgers |
| Redis | GET, SET with a TTL | Decisions by version; old keys expire on their own. | Sessions |
| Service | A plain evaluator in memory | The 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.
| model | rows | size | check p50 | list, 14,891 reports | move 1,004 people |
|---|---|---|---|---|---|
| adjacency | 100,010 | 9 MB | 0.7 ms | 38 ms | 0.6 ms |
| path | 100,010 | 19 MB | 0.3 ms | 25 ms | 7.8 ms |
| closure | 752,991 | 92 MB | 0.3 ms | 24 ms | 49 ms |
| method | status |
|---|---|
| Adjacency list, recursive query | Small companies |
| Materialised path | Approved |
| Closure table | Queries by level |
| Load the tree into app memory | Not approved |
| A graph database for one tree | Not approved |
| list by viewer | reports | visible | adjacency | path | closure |
|---|---|---|---|---|---|
| individual contributor | 0 | 1 | 1.2 ms | 1.2 ms | 1.2 ms |
| team manager | 11 | 10 | 1.4 ms | 1.3 ms | 1.3 ms |
| director | 1,003 | 988 | 4.0 ms | 3.2 ms | 3.0 ms |
| division head | 14,891 | 14,589 | 38 ms | 25 ms | 24 ms |
| move | adjacency | path | closure |
|---|---|---|---|
| 10 people | 1 row, 1.9 ms | 10 rows, 1.5 ms | 70 rows, 1.9 ms |
| 1,004 people | 1 row, 0.6 ms | 1,004 rows, 7.8 ms | 5,020 rows, 49 ms |
| 8,851 people | 1 row, 0.7 ms | 8,851 rows, 71 ms | 26,553 rows, 136 ms |
-- 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 || '~';- 1Up: the row already lists its ancestors.
- 2Down: one range of the byte-ordered index.
- 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.
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- 1RBAC: a grant row, with no relationship needed.
- 2A relationship rule: the tree answers it.
- 3An attribute that denies. Its place in the list means the chain still passes.
- 4A role scoped by an attribute: the grant names a department.
- 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
// 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"
}
-- 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;| model | handles | status |
|---|---|---|
| Roles only | HR admin. Not "my reports". | Not approved |
| Attributes only | Department. The chain needs a query, not an attribute. | Not approved |
| ACL row per viewer and target | Everything, at N × N rows, rebuilt on each move. | Not approved |
| Relation tuples in a separate service | Many apps sharing one model. | Many services |
| Ordered rules: role, attribute, relationship | This prompt, in SQL next to the data. | Approved |
| form of the rules | how it is tested |
|---|---|
| Evaluator in memory, parent pointers | It is the readable specification. |
| SQL check, one per model | Compared rule name by rule name. |
| SQL list, one per model | Compared 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.
| method | time | status |
|---|---|---|
| One check per person, 100,000 people | about 26 s | Not approved |
| One statement, OR of all rules | 219 ms | Not approved |
| One statement, UNION of one scan per rule | 2.6 ms | Approved |
| Precomputed list per viewer | not measured | Rebuild on every move |
| planner fact | what 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.
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- 1Each branch uses its own index. UNION removes people who match twice.
- 2The hierarchy model only changes this one branch.
- 3A deny rule becomes a filter on the branches after it.
Tested source SQL: list
-- 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.
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- 1Old decisions become unreachable the moment the version changes.
- 2A move under your own report would cut the subtree off the tree.
- 3It commits with the move, so the version never lags the tree in Postgres.
- 4If this step fails, the version key expires and the next read loads it from Postgres.
Tested source Go: cache · Go: reorganise
// 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
}
// 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
}
| invalidation | after a move | status |
|---|---|---|
| TTL only | Old access lasts until the TTL ends; the test saw it. | Not approved |
| Find and delete affected keys | Moved people × their viewers. | Not approved |
| Version in the key | Correct at the next read; cold cache for the tenant. | Approved |
| No cache | Correct always. | Approved |
| one decision | p50 | p99 |
|---|---|---|
| Statement in its transaction | 0.3 ms | 0.5 ms |
| Cache hit: version, then decision | 0.2 ms | 0.4 ms |
| Cache miss: reads, statement, store | 0.7 ms | 1.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.
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- 1One decision per class, so a viewer can get public fields and no salary.
- 2A denied viewer never loads the value, so a bug cannot return it.
- 3In the same transaction: no read without a record.
Tested source Go: read
// 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 visibility | status |
|---|---|
| Hide the field in the browser | Not approved |
| Load every field, strip them in the API | One bug leaks |
| Decide per class; read only what is allowed | Approved |
| Row policy with the chain on salaries | Subquery per row |
| search "staff engineer", page of 10 | kept | time | status |
|---|---|---|---|
| Search index, top 10, then filter | 0 | 12 ms | Not approved |
| Search index, top 1,000, then filter | 18 | not timed | Fails for narrow viewers |
| Filter inside the query, in Postgres | 10 | 33 ms | Approved |
| Search engine with department tokens per document | not built | not built | Reindex 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.
| class | fields | who sees it, beyond self and HR admins |
|---|---|---|
| public | name, title, department | Every active colleague |
| contact | phone, city | Chain, department, HR partner |
| comp | salary, grade | Chain; 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.
- 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
- → Same tenantrow-level securityboth are in this tenant
- → Own recordrelationshipcy is not di
- → HR adminrolecy does not have the role hr_admin
- → Target activeattributedi is active
- ✓ Manager chainrelationshipmanager chain: cy > di
- · Confidentialattributenot reached
- · HR partnerrole + attributenot reached
- · Same departmentattributenot reached
- · Public fieldsdefaultnot reached
Pick any viewer and target. The first rule that decides ends the walk, and a move changes the answer at the next read.
| event | result | why it is safe | saved by |
|---|---|---|---|
| A query forgets the tenant filter | Other tenants return no rows. | The policy applies to every statement of the service role. | RLS |
| Transaction has no tenant set | No rows at all. | NULL matches nothing, so a missing setting fails closed. | RLS |
| A move names a person in another tenant | 404. | Row-level security hides the row, so the move stops. | RLS |
| A move puts a manager under a report | 409. | The new parent's ancestors contain the moved person. | Cycle check |
| A move fails halfway | Nothing changes. | Tree, department and version commit together. | Transaction |
| Publishing the version to Redis fails | Old decisions for up to 5 minutes. | The version key has a TTL, so a later read loads it from Postgres. | TTL |
| Redis is down | Reads go to Postgres. | The cache only saves time; the statement stays the truth. | Statement |
| Someone is terminated | Access 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 fails | The read fails. | Same transaction: no salary leaves without a row. | Transaction |
| A manager leaves with reports under them | The chain above still works. | The record stays in the tree, marked inactive, until HR moves the reports. | Tree |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One 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. |
| 2 | Read 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. |
| 3 | Shards 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. |
| 4 | Search 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.
| question | answer | deeper |
|---|---|---|
| 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 |
0 of 10 known
What is the difference between a check and a list?
Why not build a list by calling the check for each person?
Why UNION per rule and not one WHERE with OR?
Why does the closure table cost so much on a move?
Which model would you pick for a company of 100,000?
A manager moves to another team. How do cached decisions stop being wrong?
Should you cache a single check?
Search returns the top 10, then the app drops what the viewer cannot see. What goes wrong?
Why not put salary in the search index?
Why log denied reads?
- 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.