Full answer
Illustrative design (example SQL, not run here):
CREATE TABLE setting_defs (
key text PRIMARY KEY,
value_type text NOT NULL CHECK (value_type IN ('int', 'bool', 'text', 'json')),
default_value jsonb NOT NULL,
description text
);
CREATE TABLE tenant_settings (
tenant_id bigint NOT NULL,
key text NOT NULL REFERENCES setting_defs(key),
value jsonb NOT NULL,
updated_by bigint,
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, key)
);
CREATE TABLE tenant_settings_history (
id bigserial PRIMARY KEY, tenant_id bigint, key text,
old_value jsonb, new_value jsonb, changed_by bigint, changed_at timestamptz DEFAULT now()
);Effective value for a tenant and key:
SELECT COALESCE(t.value, d.default_value)
FROM setting_defs d
LEFT JOIN tenant_settings t ON t.key = d.key AND t.tenant_id = 42
WHERE d.key = 'max_upload_mb';Design points: keep keys in a definitions table so typos are rejected by the foreign key and every key has a default and a documented meaning; store values as jsonb or text with a declared type and validate in the service layer, since a CHECK cannot easily validate by type; write history in the same transaction as the change (a trigger guarantees it even for manual edits); cache effective settings per tenant in the application and invalidate on write; and add an additional level, such as plan-level defaults between global and tenant, only when a real need appears, using the same COALESCE chain.
Settings that must be consistent across servers immediately, such as feature kill switches, may need shorter cache lifetimes or a pub-sub invalidation.
Key points
- Definitions with defaults
- Overrides keyed by tenant and key
- COALESCE gives the effective value
- History written in the same transaction
- Cache with invalidation on write
Common mistakes
- Free-form keys with no definitions table
- Changing settings without recording who did it
Follow-ups
- How would you add plan-level defaults between global and tenant?
- How would you roll back a bad settings change?
Tips
- Show the COALESCE read