Short answer: a housing society platform is a multi-tenant SaaS with three demanding users: a guard who needs an answer in seconds, a resident who doesn't want to be called on the intercom, and a committee that changes every year and still needs an audit trail. The architecture that serves all three is one Next.js codebase over one Postgres database. Row-level security keyed on society_id isolates every tenant. Realtime pushes go to a private channel per flat, gate passes are redeemed in a single atomic UPDATE, and an append-only audit log can't be edited from the app.
A note on scope before the detail. This is our reference architecture for resident-security and society-management products, not a write-up of one client's results. Its core patterns (role checks in Postgres, HMAC-verified webhooks, UPI reconciliation in integer paise, append-only logs) run in production in our own client platform today. The figures in this article are design budgets we build and test against, and each one is labelled that way.
The challenge: four workflows held together by paper and WhatsApp groups
Walk into most gated communities and the "system" is a combination of tools nobody chose:
- The visitor register. A paper book or a shared tablet at the gate. The guard writes a name, calls the flat on the intercom, waits, and calls again if nobody picks up. Couriers queue. At night, nobody wants the call at all.
- Resident communication. Notices go to a WhatsApp group where they're buried in an hour. There's no read receipt that means anything and no way to target one tower.
- Maintenance collection. Residents pay by bank transfer, cheque or UPI to a personal-looking VPA. The treasurer then matches payments to flats in a spreadsheet by squinting at transaction notes.
- Records. Committees rotate annually. The register, the spreadsheet and the WhatsApp history leave with the outgoing members, so disputes about who entered, who paid and who approved have no source of truth.
Underneath those workflows sit the engineering constraints that make the product hard:
- Tenant isolation is a safety property, not a feature. A resident of one society seeing another society's visitor log is a breach, not a bug.
- The gate has bad connectivity. Guard devices sit in concrete cabins and basements, so the app has to work offline and reconcile later without double-counting.
- Visitor data is personal data. Phone numbers and photos collected at the gate fall under India's Digital Personal Data Protection Act, 2023: collect for a stated purpose, keep only as long as that purpose needs.
- Notifications are the product. If a resident's approval takes thirty seconds to reach the gate, the guard has already rung the intercom and the app has failed.
The architecture: isolation in the database, speed at the edges
1. One schema, every society, isolated by row-level security
Every tenant-owned table carries a society_id. Membership (which user belongs to which society and flat, and in what role) lives in one table. A small security definer helper resolves the caller's societies once per statement, so policies stay fast and can't recurse through their own RLS:
-- Roles a person can hold inside one society.
create type public.society_role as enum ('resident', 'guard', 'committee');
create table public.memberships (
user_id uuid not null references auth.users (id) on delete cascade,
society_id uuid not null references public.societies (id) on delete cascade,
unit_id uuid references public.units (id) on delete cascade, -- null for guards
role public.society_role not null,
active boolean not null default true,
primary key (user_id, society_id, role)
);
-- private schema: never exposed through the API. Empty search_path: hijack-proof.
create or replace function private.my_society_ids()
returns uuid[]
language sql stable security definer set search_path = ''
as $$
select coalesce(array_agg(m.society_id), '{}')
from public.memberships m
where m.user_id = (select auth.uid()) and m.active;
$$;
alter table public.visits enable row level security;
-- Guards and committee see their society's gate log; residents see their own flat.
create policy visits_select on public.visits
for select to authenticated
using (
society_id = any ((select private.my_society_ids()))
and (
exists (
select 1 from public.memberships m
where m.user_id = (select auth.uid())
and m.society_id = visits.society_id
and m.role in ('guard', 'committee')
and m.active
)
or unit_id in (
select m.unit_id from public.memberships m
where m.user_id = (select auth.uid()) and m.active
)
)
);
Two details carry most of the weight. First, (select auth.uid()) and (select private.my_society_ids()) are wrapped in sub-selects so Postgres evaluates them once per statement instead of once per row. On a gate log with tens of thousands of rows, that's the difference between an index scan and a timeout. Second, the application never filters by society. A Server Component queries visits under the caller's JWT and the database returns only what that person may see. A forgotten where clause leaks nothing.
Isolation gets a test, not a promise. This pgTAP check runs in CI against a seeded database with two societies:
-- supabase/tests/tenant_isolation.test.sql
begin;
select plan(1);
set local role authenticated;
set local request.jwt.claims = '{"sub": "00000000-0000-0000-0000-00000000000a"}'; -- resident of society A
select is(
(select count(*) from public.visits where society_id = '00000000-0000-0000-0000-0000000000b0'),
0::bigint,
'a resident of society A reads zero rows from society B'
);
select * from finish();
rollback;
2. Visitor approval: one transaction, then a push
The guard's check-in is a Server Action that inserts a visits row with status waiting. A trigger publishes the change to the flat's private Realtime topic and to the gate's topic. Because Supabase delivers database broadcasts from the write-ahead log, a message only goes out after the transaction commits. A rolled-back check-in never rings anyone's phone.
create or replace function private.broadcast_visit()
returns trigger
language plpgsql security definer set search_path = ''
as $$
begin
-- Resident's flat and the gate both hear about it; nobody else can subscribe.
perform realtime.broadcast_changes(
'unit:' || new.unit_id::text, tg_op, tg_op, tg_table_name, tg_table_schema, new, old
);
perform realtime.broadcast_changes(
'gate:' || new.society_id::text, tg_op, tg_op, tg_table_name, tg_table_schema, new, old
);
return null;
end;
$$;
create trigger visits_broadcast
after insert or update on public.visits
for each row execute function private.broadcast_visit();
-- Private channels are authorised by RLS on realtime.messages.
create policy unit_topic_read on realtime.messages
for select to authenticated
using (
realtime.topic() like 'unit:%'
and exists (
select 1 from public.memberships m
where m.user_id = (select auth.uid())
and m.active
and m.unit_id::text = split_part(realtime.topic(), ':', 2)
)
);
When the resident taps Approve, a second Server Action updates the visit and appends an audit_log row in the same transaction, so the status and its history can't disagree. The guard's screen updates from the gate topic. If nobody answers within 60 seconds, the request escalates to the intercom. The app is the fast path, not the only path.
3. Pre-approved gate passes, redeemed atomically
Most visits are predictable: the cook at 7am, a parent on Sunday, a delivery window. For those, the resident issues a pass in advance and the server signs it. The QR code carries payload.signature, where the payload holds the pass id, and the signature is an HMAC-SHA256 over it with a server-only secret. Verification never trusts the QR's contents beyond the id:
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyPassToken(token: string, secret: string): string | null {
const [payload, signature] = token.split(".");
if (!payload || !signature) return null;
const expected = createHmac("sha256", secret).update(payload).digest();
const given = Buffer.from(signature, "base64url");
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
const { passId } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
return typeof passId === "string" ? passId : null;
}
The redemption itself is a single statement. The time window, remaining uses and society scope are checked and the use is consumed atomically, so two guards scanning the same pass at two gates can't both admit it. A per-scan idempotency key makes offline replays safe:
create or replace function public.redeem_gate_pass(p_pass_id uuid, p_scan_id uuid)
returns public.gate_passes
language plpgsql security invoker set search_path = ''
as $$
declare
v_pass public.gate_passes;
begin
-- An offline guard device may replay the same scan: count it once.
insert into public.gate_pass_scans (scan_id, pass_id) values (p_scan_id, p_pass_id)
on conflict (scan_id) do nothing;
if not found then
select * into v_pass from public.gate_passes where id = p_pass_id;
return v_pass;
end if;
update public.gate_passes
set uses_remaining = uses_remaining - 1
where id = p_pass_id
and now() between valid_from and valid_until
and uses_remaining > 0
returning * into v_pass; -- RLS on gate_passes already scopes this to the guard's society
if not found then
raise exception 'pass expired, exhausted or not valid at this society' using errcode = 'P0002';
end if;
return v_pass;
end;
$$;
The guard PWA queues scans in IndexedDB when the cabin loses signal and replays them on reconnect. The idempotency key means a replayed scan never consumes a second use. The guard sees "verified offline, pending sync" rather than a false green.
4. Maintenance billing that reconciles itself
Society dues are predictable, which makes them ideal for automation. Each billing run generates one invoice per flat. Each invoice carries a UPI payment link whose transaction reference (tr) is the invoice id. When the society's payment provider reports a credit, a signed webhook matches it on that reference and compares amounts in integer paise, never floating-point rupees. The pattern is the same one that runs our own client billing. It also rejects any callback whose HMAC signature fails or whose timestamp is more than five minutes old, which bounds replay attacks.
The treasurer stops matching transaction notes in a spreadsheet. The committee console shows paid, pending and overdue per flat, and reminders go out on WhatsApp with the payment link attached.
5. Records that outlive the committee
Every privileged change (approvals, pass issuance, billing adjustments, role changes) writes to an audit_log table that no API role can update or delete. A before update or delete trigger raises an exception, so even an accidental edit from the SQL editor fails. Incoming committees inherit a complete, tamper-evident history instead of a handover WhatsApp chat.
Visitor personal data gets the opposite treatment: a scheduled job purges visitor phone numbers and photos after a retention window the committee sets (we default to 90 days). The aggregate entry record is kept, which serves the security purpose without keeping personal data past it.
Design budgets and how we hold them
| Budget | Target | How it's enforced |
|---|---|---|
| Commit-to-resident notification | ≤ 2 s at p95 | Broadcast from the WAL after commit; measured from visits.created_at to client receipt and alerted on regression |
| Cross-society reads | 0 rows | RLS on every tenant table, plus the pgTAP isolation test in CI |
| Gate pass redemption | 1 atomic statement | redeem_gate_pass() checks window, uses and scope in one UPDATE |
| Duplicate offline scans counted | 0 | Unique scan_id per scan, on conflict do nothing |
| Visitor PII retention | 90 days (default) | Scheduled purge, configurable per society |
| Unanswered approval | 60 s, then escalate | Gate timer falls back to the intercom |
These are budgets, not results. When we deploy this architecture for a society, we report against this table from production telemetry: approval latency, the share of visitors entering on pre-approved passes, and on-time maintenance collection. Those are the numbers worth publishing, and they belong to the client.
Build checklist
- Model membership first. One person can be a resident in one society and committee in another. Roles belong to the membership, not the user.
- Put isolation in policies, then test it. If a query needs a
where society_id = …to be safe, the policy is wrong. - Broadcast after commit. Never notify from application code before the write is durable.
- Make every gate action idempotent. Assume the guard device will retry.
- Decide retention on day one. Purging later is a migration; purging from the start is a cron job.
Our web engineering team builds on exactly this stack, and the billing side reuses our custom invoicing and UPI reconciliation work.
Frequently asked questions
How do you keep each housing society's data separate in a multi-tenant app?
Give every tenant-owned table a society_id column and enforce isolation with Postgres row-level security, so the database itself returns only rows from the caller's societies. A security definer helper resolves the caller's memberships once per statement, and a CI test signs in as a resident of one society and asserts zero rows are visible from another. Filtering in application code alone is not enough, because one missed where clause leaks data.
How does real-time visitor approval work in a society management app?
The guard's check-in inserts a visit with status waiting. A database trigger broadcasts the change to that flat's private realtime channel, which is only delivered after the transaction commits. The resident approves with one tap, the status update and an audit record are written in the same transaction, and the guard's screen updates. If nobody responds within a set time, typically 60 seconds, the request falls back to the intercom.
How long should a housing society app keep visitor phone numbers and photos?
Only as long as the security purpose requires. India's Digital Personal Data Protection Act, 2023 expects personal data to be collected for a stated purpose and erased once that purpose is served. A practical design keeps the aggregate entry record but purges visitor phone numbers and photos on a schedule, with a default such as 90 days that the committee can change. Confirm the policy with your society's legal adviser.


