Authentication and Registration System Design: End-to-End Practices for Accounts, Permissions, and Quotas
This article explains how to design authentication and registration as a bounded subsystem rather than a few endpoints. It covers the identity, session, authorization, and metering layers; registration uniqueness, password storage, and abuse prevention; session and token models with risk signals; entitlement modeling for subscription tiers; quota, rate limiting, and cost controls; and observability, audit, compliance, and a launch checklist.
1. Why Authentication and Registration Deserve Their Own Subsystem
Login and registration are often implemented hastily as a few endpoints, but they are the trust starting point for almost every product. They determine the uniqueness of user identity, the boundaries of data ownership, the basis for permission decisions, and the anchor for later billing and quota deduction. If the early design is vague, the cost of adding data migration, permission models, and audit trails later will be much higher than getting it right once.
A mature account subsystem usually contains four layers of responsibility:
- Identity layer: registration, login, recovery, account deletion, and multi-factor verification;
- Session layer: token issuance, refresh, revocation, device identification, and anomalous-location detection;
- Authorization layer: roles, resources, subscription tiers, and entitlement decisions;
- Metering layer: call quotas, rate limits, usage aggregation, and budget alerts.
Once these four layers are decoupled, business code depends only on three questions: who the current subject is, what entitlements it has, and how much quota remains. Permission checks no longer scatter across if-else branches.
2. Registration: Uniqueness, Minimization, and Abuse Prevention
2.1 Choosing Account Identifiers
Common identifiers include phone numbers, email addresses, and third-party authorized identities. A recommended model is an internal primary key plus multiple bound identifiers. Use a non-enumerable ID that is unrelated to business data, such as a UUID or snowflake ID, and avoid using a phone number or email address directly as the primary key, which would cause identity changes when the identifier is rebound.
CREATE TABLE account (id BIGINT PRIMARY KEY, -- Internal non-enumerable primary keystatus SMALLINT NOT NULL DEFAULT 0, -- 0 pending activation, 1 active, 2 frozen, 3 deletedcreated_at TIMESTAMP NOT NULL,deleted_at TIMESTAMP NULL);CREATE TABLE account_identity (id BIGINT PRIMARY KEY,account_id BIGINT NOT NULL,type SMALLINT NOT NULL, -- 1 phone, 2 email, 3 third-party authorizationidentifier VARCHAR(128) NOT NULL,verified BOOLEAN NOT NULL DEFAULT FALSE,UNIQUE KEY uk_type_id (type, identifier));
2.2 Password Storage and Verification
Passwords must never be stored in plaintext or with a simple hash. Use a salted slow hash algorithm with an adjustable computational cost, such as bcrypt, scrypt, or argon2. Support recomputation during verification using the parameters stored in the record so that the cost factor can be upgraded smoothly.
# Pseudocode: password handling for registration and logindef register(identifier, raw_password):salt = random_salt(16)digest = kdf(raw_password, salt, cost=DEFAULT_COST) # slow hashstore(identifier, salt, digest, cost=DEFAULT_COST)def verify(identifier, raw_password):rec = load(identifier)if kdf(raw_password, rec.salt, rec.cost) == rec.digest:return Truereturn False
2.3 Abuse Prevention and Data Minimization
The registration endpoint is a high-value target for account farming and credential stuffing. It should at least include CAPTCHA or behavioral challenges, per-IP and per-device rate limiting, short-lived one-time verification codes that expire within 5 minutes with a maximum of 5 failed attempts, and channel tags for registration sources. At the same time, follow the principle of data minimization: collect only fields that the business truly needs, and do not request sensitive information such as contacts or location unless necessary.
3. Login: Sessions, Tokens, and Risk Control
3.1 Choosing a Session Model
- Server-side sessions: centralized state and immediate revocation, suitable for scenarios that require strong control, at the cost of shared storage such as a distributed cache.
- Self-contained tokens: stateless and easy to scale horizontally, but revocation and password-change invalidation require additional mechanisms such as short TTLs plus a blacklist or version number.
A common compromise is to use short-lived access tokens at the minute level and long-lived refresh tokens with one-time rotation. Every refresh validates the device fingerprint and token family lineage. If replay is detected, the entire chain is invalidated.
3.2 Multi-Factor Authentication and Graduated Trust
High-sensitivity operations such as rebinding a phone number, resetting a password, changing a subscription, or exporting data should trigger secondary verification. Record the “last strong authentication time” in the session so that trust can be graduated instead of applied uniformly.
3.3 Login Risk Signals
Common signals for risk decisions include device fingerprint, deviation between IP geolocation and usual location, failure count and failure interval, number of concurrent sessions, and unusual User-Agent combinations. When risk is high, prefer adding verification rather than rejecting outright to reduce false positives.
4. Authorization and Subscription Tiers: Extract Entitlements from Code
Different subscription tiers such as free, individual paid, team, and education are essentially differences in entitlement sets, not branches scattered across business code. A three-layer model of role, entitlement, and resource is recommended:
- Role: such as free / individual / team / edu;
- Entitlement: such as
model.advanced,api.access,seat.count=5; - Decision: a unified policy entry point; business code only calls
can(subject, action, resource).
def can(subject, action, resource):plan = get_plan(subject) # subscription tierif not plan.active or plan.expired: # downgrade immediately on expirationplan = FALLBACK_PLANif action not in plan.entitlements:return Falsereturn quota_left(subject, action) > 0 # entitlement plus quota check
A key design point is to separate entitlement decisions from quota decisions. The former answers “is this allowed?” and the latter answers “how much is left?” Only when they evolve independently can real business scenarios such as mid-cycle upgrades and downgrades, trial conversion, and refund rollback be supported. Downgrade rules must be defined explicitly, such as retaining read-only access, preserving data export, or keeping a limited number of calls, to avoid incidents where paid expiration causes a complete login failure.
5. Metering, Rate Limiting, and Cost Control
For account systems that serve model calls or high-cost resources, cost variables must be part of the design:
- Quota dimensions: meter across three dimensions: subject (account or team), resource (model tier or API), and time window (minute, day, or month).
- Rate-limiting algorithms: token buckets allow bursts, leaky buckets smooth output, and sliding windows provide more precise statistics. Apply coarse-grained rate limiting at the gateway layer and fine-grained quota enforcement at the application layer.
- Budgets and alerts: set a periodic budget for each subject, issue a warning at 80%, and trip the circuit breaker at 100% to prevent a single anomaly from causing runaway billing.
- Usage aggregation: write call logs asynchronously to a message queue, then aggregate them with streaming or batch jobs. Avoid heavy computation on the request path.
Request -> identity verification -> entitlement check -> quota pre-deduction -> business execution -> actual usage write-back (compensation/rollback)
Pre-deduction plus write-back, or eventual-consistency reconciliation, is more effective at preventing concurrent bypass than executing first and charging later.
6. Observability, Audit, and Compliance
- Audit: keep a full trail of login success and failure, permission changes, subscription changes, and key creation and revocation, including subject, source, time, and result.
- Metrics: registration conversion rate, login success rate, secondary verification trigger rate, token refresh failure rate, and quota cap hit rate.
- Alerts: bulk registration, abnormal credential stuffing, abnormal token rotation, and quota spikes.
- Compliance: provide a clear privacy policy and authorization scope, offer self-service account deletion and data deletion channels, encrypt sensitive fields at rest, and redact logs.
When running on cloud infrastructure, you can deploy stateless services on a container platform, store audit archives in object storage, aggregate usage asynchronously with a message queue, and complete the observability loop with logging and monitoring. Cloud platforms that offer these general categories can support this architecture; choose based on your own compliance and cost constraints.
7. Launch Checklist
- Primary keys are non-enumerable, and identifiers are decoupled from identity;
- Passwords use slow hashing with an upgradeable cost factor;
- Refresh tokens rotate once and can revoke the entire chain;
- Sensitive operations require mandatory secondary authentication;
- Entitlements and quotas are separated, and downgrade rules are explicitly defined;
- Quota pre-deduction, usage write-back, and periodic reconciliation are in place;
- Audit, metrics, and alerts are all covered;
- Account deletion and data deletion paths can be completed self-service.
Treat authentication and registration as a subsystem with clear boundaries, metering, and audit. Future permission expansion, commercial tiering, and cost governance then become configuration work rather than rearchitecture.
