What does backend auth actually cost under Auth0, Keycloak and custom code?
The three options shift cost between line items rather than eliminate it. Auth0 is a hosted identity provider: you pay a subscription, and the vendor runs the servers, patches the software and handles uptime. Keycloak is open-source identity software you self-host: there is no license fee, but you own the infrastructure and the operational burden. Custom code means your team implements login, sessions, token issuance, password storage and recovery on its own stack, and owns every part of it.
Comparing license price alone is misleading because the fee is often the smallest line on the self-hosted and custom side, and the most visible one on the hosted side. Keycloak shows "free" on a pricing page while costing engineer-hours every month. Custom auth looks cheap at launch, but security review and incident exposure grow with it. A fair comparison sums the same five categories for each option:
| Cost category | Auth0 (hosted) | Keycloak (self-hosted) | Custom code |
|---|---|---|---|
| Subscription / license | Recurring fee, usually scaled by users or features | None for the software; optional paid support | None |
| Infrastructure | Included in the subscription | Compute, database, backups, multi-region failover | Same as Keycloak, inside your own services |
| Build and integrate | SDK integration and configuration | Deployment, realm setup, theming, integration | Full design and implementation |
| Ongoing operations | Mostly vendor-owned; you monitor integration | Upgrades, patching, on-call, incident response | All of Keycloak's operations work, plus maintaining the auth code |
| Security and compliance | Vendor attestations, with your own configuration review | Hardening, pen tests, audit evidence | Audits, pen tests, full breach exposure |
How does backend authentication work under each option?
Auth0 and Keycloak use the same underlying model: they act as an OpenID Connect (OIDC) provider on top of OAuth 2.0. The flow for a typical web or mobile app looks like this:
- The client redirects the user to the identity provider's authorization endpoint.
- The identity provider authenticates the user with a password, social login, enterprise SSO or MFA, depending on configuration.
- The identity provider redirects back to the application with a short-lived authorization code. Public clients such as single-page and mobile apps should protect this step with PKCE.
- The application exchanges the code at the token endpoint for an ID token, an access token and usually a refresh token.
- The client sends the access token to your backend APIs, usually in the
Authorization: Bearerheader. - Each API validates the token locally. It checks the signature against the provider's public keys (published as a JWKS), then the issuer, audience and expiry. After that it applies its own authorization rules.
Service-to-service calls use the client credentials grant instead. A service authenticates with its own client ID and secret and receives an access token without any user involved.
The difference between the options is who runs which step:
- Auth0: The vendor runs steps 1 through 4 on its infrastructure, including the login page, credential storage, MFA and federation. Your backend only does step 6.
- Keycloak: The same endpoints exist, but they are served by your Keycloak cluster under a realm you configure. You run steps 1 through 4 on your own servers, and your backend still only does step 6.
- Custom code: Your team implements every step. That includes the login UI, password verification, code and token issuance, signing key management, refresh and revocation, and, if you want interoperability, the discovery and JWKS endpoints as well.
Because step 6 is the same for any standards-compliant provider, backend token validation is the most portable part of the system. The later sections on cost and switching rely on that.
How does hosted identity provider pricing work?
Hosted identity providers mostly bill per monthly active user (MAU). The number on the invoice, though, depends on contract terms that matter as much as the unit price.
The core meter: monthly active users
A user usually counts as active if they authenticate at least once during the billing period. The exact rule varies by vendor. Check the following before you model anything:
- Whether a token refresh counts as activity.
- Whether one person who logs in through two applications counts once or twice.
- Whether dormant accounts cost anything.
If your product has seasonal or bursty usage, the MAU count can swing widely from month to month. A growth projection in your business plan turns directly into a growth projection on your auth bill.
What the tiers gate
Plans are usually split by feature rather than by volume. Higher tiers typically unlock:
- Enterprise SSO connections such as SAML and OIDC federation
- Stronger MFA options
- Custom domains for the login page
- Longer log retention
Machine-to-machine tokens are often metered separately, so service-to-service traffic can grow costs without any change in human user counts.
Hidden drivers of a tier jump
The expensive surprises tend to come from sales, not from engineering:
- Enterprise SAML: One large customer who needs a SAML connection can push you onto an enterprise plan.
- B2B multi-tenancy: Per-organization branding, roles or connections may require a higher tier.
- Log export and egress: Shipping auth logs to your SIEM for compliance can require a higher tier or add-on.
Budgeting against moving targets
A budget built on your current tier can be off by a large factor a year later. That happens when the user count grows and one of these features becomes mandatory at the same time. Vendors also revise plans and prices, so check current pricing pages and contract terms rather than relying on any snapshot, including this one.
What does it take to run self-hosted Keycloak in production?
Keycloak has no license fee, but you take on everything a vendor would otherwise operate. That starts with a production database: managed or replicated, sized for session and token traffic, and tuned so that slow queries don't turn into slow logins.
High availability means running several Keycloak nodes behind a load balancer. The nodes share session and authentication state through a distributed cache (Infinispan). Misconfigure cache discovery or replication and users get logged out at random or fail mid-flow when a node restarts.
+----------------+
| Load balancer |
+-------+--------+
+-----------+-----------+
+----v-----+ +-----v----+
| Keycloak |<--------->| Keycloak | distributed cache
| node A | | node B |
+----+-----+ +-----+----+
+-----------+-----------+
+-------v--------+ +-----------+
| Production DB |---->| Backups |
+----------------+ +-----------+
Monitoring: metrics, logs, login-failure alerts
Upgrades are the largest recurring cost. A release can run database migrations and change the APIs that custom authenticator SPIs depend on, and it can break custom themes. Each upgrade therefore needs staging tests and a rollback plan. Teams that skip this work fall behind and end up running old releases without security patches, which is the worst outcome for an identity system.
You also need:
- Backups, plus restore drills, because a backup you have never restored is unproven.
- Alerting on login error rates as well as node health.
- Someone who understands realms, clients and authentication flows well enough to debug a failed login at 2 a.m.
When auth is down, every login is blocked, so Keycloak needs a named on-call owner rather than whoever happens to be awake.
+----------------------+
| Users / clients |
+----------+-----------+
|
+----------v-----------+
| Load balancer |
+----+------------+----+
| |
+-----------v--+ +--v-----------+
| Keycloak |<---->| Keycloak |
| node A | | node B |
| themes, SPIs | | themes, SPIs |
+----+-----+---+ +---+-----+----+
| | | |
| +--v--------------v--+ |
| | Distributed cache | |
| | (Infinispan): | |
| | sessions, flows | |
| +--------------------+ |
| |
+----v--------------------------v----+ +-------------+
| Production database (replicated) |---->| Backups |
| realms, clients, users | | + restore |
+------------------------------------+ | drills |
+-------------+
+------------------------------------------------------------------+
| Monitoring: node health, metrics, logs, login-error-rate alerts |
| --> on-call owner who can debug realms, clients and auth flows |
+------------------------------------------------------------------+
A typical highly available Keycloak deployment: a load balancer in front of multiple nodes sharing session state through a distributed cache, backed by a replicated production database with tested backups and monitoring that pages an on-call owner.
What does custom auth code really include?
Building auth yourself usually starts with a login endpoint that checks a password hash and issues a token. That first version can ship in a sprint, which is why it looks cheap. The real scope shows up later, one requirement at a time.
| Capability | Quick first version | Scope at maturity |
|---|---|---|
| Passwords | Hash with a slow algorithm | Rehash on login when parameters change, breached-password checks |
| Abuse protection | None, or a basic per-IP limit | Per-account lockout, rate limits that resist credential stuffing without locking out real users |
| Email flows | Verification link | Single-use, expiring reset tokens, protection against account enumeration |
| MFA | Not built | TOTP or WebAuthn enrollment, recovery codes, support-assisted recovery |
| Sessions and tokens | Long-lived JWT | Revocation on logout and password change, signing key rotation with overlapping keys |
| Federation | Not built | Social login, plus SAML and OIDC per enterprise tenant |
| Operations | Application logs | Tamper-evident audit trail, admin tooling for support staff |
Every row is a place where a subtle bug becomes a breach. A reset token that never expires, a timing difference that reveals which emails are registered, or a signing key that can't be rotated without logging everyone out are all common in real codebases. None of them show up in feature demos.
That is why custom auth carries the highest security risk and maintenance burden of the three options, even though it looks cheapest at the start. The cost stays hidden until something forces it into view. That might be an incident, a compliance audit asking for login history, or the first enterprise customer's security questionnaire asking about SSO, MFA enforcement and session revocation. At that point the missing rows in the table become roadmap work that blocks revenue.
How do you calculate the crossover point between hosted and self-hosted auth?
Those roadmap items carry a cost, and the cleanest way to compare it against a vendor bill is to reduce both options to a monthly figure and find where they meet.
Illustrative estimate. Every input below is an assumption, not a measured result:
- Fully loaded engineer cost: $180,000/year, or $15,000/month
- Engineer time to operate Keycloak (upgrades, patching, backups, on-call): 0.25 FTE, or $3,750/month
- Infrastructure (HA nodes, managed database, monitoring): $500/month
- Hypothetical hosted price: $0.05 per monthly active user (MAU)
- Starting users: 20,000 MAU, growing 8% per month
Self-hosting is a mostly fixed cost and hosted pricing is mostly variable, so the crossover is:
crossover MAU = (FTE fraction × monthly engineer cost + monthly infra) ÷ per-MAU price
With these inputs, that is $4,250 ÷ $0.05 = 85,000 MAU. At 8% monthly growth you reach it after ln(85,000 ÷ 20,000) ÷ ln(1.08) ≈ 19 months.
| Month | MAU | Hosted ($/mo) | Self-hosted ($/mo) |
|---|---|---|---|
| 0 | 20,000 | 1,000 | 4,250 |
| 12 | ~50,400 | ~2,520 | 4,250 |
| 18 | ~79,900 | ~4,000 | 4,250 |
| 24 | ~126,800 | ~6,340 | 4,250 |
To build this as a spreadsheet, use one row per month with these columns: MAU (previous row × 1.08), hosted cost (MAU × price), and self-hosted cost (fixed). Add step increases to the self-hosted infrastructure cost as you add nodes.
Two caveats affect the result more than any other input:
- Pricing shape. Real vendor pricing is usually tiered, and enterprise features such as SSO are often priced separately rather than linearly per MAU.
- Engineer time. The FTE fraction varies widely between teams. At 0.1 FTE the crossover drops to about 43,000 MAU. At 0.5 FTE it rises to about 160,000 MAU.
There is no universal crossover point. Use your own team's numbers and the vendor's current price sheet.
import math
ENGINEER_COST_MONTHLY = 15_000 # fully loaded, $180k/year (assumed)
FTE_FRACTION = 0.25 # share of one engineer running Keycloak (assumed)
INFRA_MONTHLY = 500 # HA nodes, managed DB, monitoring (assumed)
PRICE_PER_MAU = 0.05 # hypothetical hosted price, linear (assumed)
START_MAU = 20_000
GROWTH = 0.08 # 8% month-over-month (assumed)
MONTHS = 24
def self_hosted_cost(fte=FTE_FRACTION):
# Mostly fixed. Add step increases here if you model extra nodes at higher MAU.
return fte * ENGINEER_COST_MONTHLY + INFRA_MONTHLY
def crossover_mau(fte=FTE_FRACTION):
# The MAU count at which the hosted bill equals the self-hosted cost.
return self_hosted_cost(fte) / PRICE_PER_MAU
x = crossover_mau()
months_to_x = math.log(x / START_MAU) / math.log(1 + GROWTH)
print(f"Crossover: {x:,.0f} MAU, reached after ~{months_to_x:.1f} months")
print(f"{'month':>5} {'MAU':>9} {'hosted':>8} {'self':>8}")
for m in range(0, MONTHS + 1, 6):
mau = START_MAU * (1 + GROWTH) ** m
print(f"{m:>5} {mau:>9,.0f} {mau * PRICE_PER_MAU:>8,.0f} {self_hosted_cost():>8,.0f}")
for fte in (0.1, 0.25, 0.5):
print(f"FTE {fte}: crossover at {crossover_mau(fte):,.0f} MAU")
A small Python model that computes the hosted vs. self-hosted crossover MAU, projects monthly costs under compound growth, and shows how sensitive the result is to the assumed engineer time. All inputs are illustrative and should be replaced with your own figures.
How much does it cost to migrate away from an identity provider?
The crossover calculation leaves out the cost of leaving. Exit cost belongs in total cost of ownership because it grows each month you stay.
Password hashes
Users can only move without a password reset if the hashes come out in a usable form. That means you need the algorithm, the salt and the parameters, and the target system must be able to verify that format. Hosted providers may limit hash export or handle it as a support request rather than a self-service API. Check this before you sign. Keycloak keeps hashes in its own database, so you can read them directly. A custom hashing provider, though, can tie you to that code. If hashes can't move, you either force a reset for every user or run a lazy migration that verifies each user against the old system at their next login. A lazy migration keeps both systems running for months.
User IDs and clients
Downstream tables, audit logs and authorization rules usually key on the sub claim. If the new system issues different IDs, you need a mapping table or a data migration. Every client application also needs a new issuer, new keys, new redirect URIs and new secrets. Every live session has to expire or be revoked, which forces users to log in again.
Vendor risk
While you stay, you are exposed to price changes and features moved to higher plans. You also have no control over outages, and rate limits can throttle your login traffic. A heavily customized Keycloak carries similar risk: themes, SPIs and extensions that only one engineer understands.
Illustrative estimate (assumed numbers, not a benchmark):
Migration cost = (core hours + clients × hours per client) × hourly rate
Assumed inputs:
- 120 core hours
- 25 clients at 6 hours each
- $100 per hour
(120 + 25 × 6) × $100 = $27,000
Re-run this formula with next year's client count rather than today's user count. The client count is what drives exit cost up.
What are the alternatives to Auth0, Keycloak and custom code?
These three options are points on a spectrum, not the only choices. The cost model above applies to each of the alternatives below. What changes is which line items are large.
- Other hosted identity providers. Several vendors sell hosted identity on similar terms, and the large cloud platforms offer their own user-directory and authentication services. Pricing meters, tier boundaries and export policies differ, so run the same MAU, tier-jump and hash-export checks against each. Cloud-platform identity services can be attractive if you already run there. They also tie your login system more closely to that platform.
- Other open-source, self-hosted identity servers. Keycloak is not the only open-source OIDC provider. Alternatives vary in scope. Some are full identity platforms, while others are narrower components that handle only token issuance or only login UI. The operational line items are the same as Keycloak's: database, high availability, upgrades and on-call.
- Managed or supported Keycloak. You can buy commercial support for Keycloak or pay a third party to host it. This keeps the open-source software and its data model while moving some of the operations burden, and some of the cost, back into a subscription.
- Framework auth libraries inside your application. Many web frameworks ship session-based or token-based authentication modules. They cover the "quick first version" column of the custom-code table with tested code. You still own the rest of the table: MFA, federation, key rotation and audit trails.
- Delegating login entirely to external providers. Some products can rely only on social login or on customers' own enterprise IdPs and store no passwords at all. This removes password storage and reset flows. You still need session handling, account linking and a fallback for users who lose access to their external account.
- Hybrid setups. A common pattern is one identity broker, hosted or self-hosted, that federates to customer IdPs, while your backend validates tokens from that one issuer. Teams also run a hosted provider early and plan a move to self-hosting at a known user count, which is where the crossover and exit-cost formulas matter.
How can each option save engineering time?
Engineering hours are usually the largest cost line, so it is worth knowing where each option actually saves time and where it only moves the work.
Hosted providers save operations and protocol time. The vendor owns uptime, patching, scaling, MFA implementations and federation protocols. For a team with no SRE capacity, this removes the on-call rotation and upgrade work described in the Keycloak section. Integration still takes time: tenant configuration, login page customization and testing each client application.
Keycloak saves build time but not operations time. You get standards-compliant OIDC and SAML, MFA, user federation and an admin console without writing them. You still spend recurring hours on upgrades, backups and incident response. To reduce those hours:
- Export realm configuration and keep it in version control, so environments can be rebuilt and compared instead of configured by hand.
- Automate deployments, and run a staging upgrade with your real themes and extensions before every production upgrade.
- Keep custom SPIs and themes to a minimum. Every customization is code you must retest on each release.
- Upgrade on a regular schedule rather than in large, rare jumps that pile up migrations.
Custom code rarely saves time beyond the first sprint. If you build, the time savings come from not building the hard parts. Use vetted libraries for password hashing, token signing and WebAuthn, and keep your own code focused on the flows that make your product different.
Practices that save time under any option:
- One shared token-validation module. Write issuer, audience and algorithm checks once, as in the code at the end of this article, and reuse it in every service. Then each new service doesn't need its own auth review.
- Standard protocols end to end. OIDC and OAuth clients behave the same across providers. Engineers who learn the flow once can debug any service, and a provider change becomes a configuration change.
- Authorization in your own service. When permissions live in your database, adding a role or tenant rule is a normal code change. It doesn't require a change to identity provider configuration that needs separate access and testing.
- Login-failure alerting. Alerting on authentication error rates, not only node health, cuts the time spent finding out whether a login problem is in your code, your configuration or the provider.
When should you buy, self-host Keycloak, or build custom auth?
No single option wins at every stage. The right choice depends on who will operate the system and which constraints you cannot negotiate away.
Buy (Auth0) when you have no platform or SRE capacity and need login, MFA and social sign-in working this quarter. A hosted provider's audit reports can shorten your own compliance work, because you inherit its controls. Avoid it for B2C products with many low-value users, where per-user pricing grows faster than revenue. Avoid it when data must stay in a jurisdiction or network the provider does not serve.
Self-host Keycloak when data residency, air-gapped deployment or a regulator requires the identity store on your infrastructure. It also suits large user counts, where fixed infrastructure costs beat per-user fees. Avoid it if nobody owns upgrades, database backups, and on-call response for login outages. An unpatched identity server is a bigger risk than a monthly invoice.
Build custom only when identity is the product, such as unusual delegation models, or when your login flows set you apart from competitors. Even then, build the domain logic and use vetted libraries for token handling and password hashing. Avoid it whenever auth is plumbing. You take on every future protocol change and security fix yourself.
| Scenario | Recommended option | Why |
|---|---|---|
| Early-stage, small team, no SRE | Auth0 | Lowest operational burden |
| B2B, few high-value tenants, SSO demands | Auth0 | Per-user cost is small relative to contract value |
| B2C, large free tier | Keycloak | Fixed cost scales better than per-user fees |
| Air-gapped or strict residency | Keycloak | Hosting off your infrastructure is not allowed |
| Identity is core differentiation | Custom on standard libraries | Control over flows justifies the maintenance |
How can you keep auth costs and switching costs low under any choice?
Whichever row of that table you land on, a few habits keep the decision reversible and keep engineering hours down.
Keep authorization out of the identity provider
Let the IdP answer "who is this?" and let your own service answer "what may they do?" Roles, tenant membership and resource permissions stored as custom claims or IdP-side rules become migration work later, because every one of them has to be re-modeled in the next system. If permissions live in your database, a token only needs to carry a stable identity.
Code against OIDC and OAuth, not the vendor SDK
Use standard OIDC client and JWT libraries for login flows and token handling. Vendor SDKs are convenient, but their helper methods and claim conventions spread through a codebase and turn a configuration change into a refactor.
Validate tokens through discovery and JWKS
Configure validation with only standard inputs:
- Issuer URL: used to fetch the discovery document and JWKS URI.
- Expected audience: the API identifier the token must be issued for.
- Allowed signing algorithms: pin these explicitly instead of trusting the token header.
- Clock-skew tolerance: a small allowance for drift between servers.
- Key cache refresh on unknown key ID: handles key rotation without a redeploy.
Switching providers then means changing the issuer and audience values, with no code changes.
Map subjects to internal user IDs
Never use the IdP's sub as your primary key. Store a mapping like this:
| internal_user_id | issuer | subject |
|---|---|---|
| your UUID | IdP issuer URL | IdP sub value |
Put a unique constraint on (issuer, subject). During a migration, both the old and new issuers can resolve to the same internal user, and your foreign keys never change.
import { createRemoteJWKSet, jwtVerify } from "jose";
import { Pool } from "pg";
// Switching IdPs means changing these two values. The code stays the same.
// Set the issuer exactly as the IdP reports it, including any trailing slash.
const ISSUER = process.env.OIDC_ISSUER ?? "";
const AUDIENCE = process.env.OIDC_AUDIENCE ?? "";
// Mapping table: CREATE TABLE user_identities (internal_user_id uuid NOT NULL
// REFERENCES users(id), issuer text NOT NULL, subject text NOT NULL,
// PRIMARY KEY (issuer, subject));
const pool = new Pool();
// Find the JWKS URI through standard OIDC discovery instead of hardcoding it.
async function loadJwks() {
const url = `${ISSUER.replace(/\/$/, "")}/.well-known/openid-configuration`;
const res = await fetch(url);
if (!res.ok) throw new Error(`OIDC discovery failed: ${res.status}`);
const meta = await res.json();
if (meta.issuer !== ISSUER) throw new Error("issuer mismatch in discovery");
// jose caches keys and refetches when a token has an unknown kid, so key rotation needs no redeploy.
return createRemoteJWKSet(new URL(meta.jwks_uri));
}
const jwksPromise = loadJwks();
// Returns your internal user ID. Authorization then runs against your own tables.
export async function authenticate(token: string): Promise<string | null> {
const { payload } = await jwtVerify(token, await jwksPromise, {
issuer: ISSUER,
audience: AUDIENCE,
algorithms: ["RS256"], // pinned explicitly; the token header is not trusted
clockTolerance: 30, // seconds of allowed clock skew
});
const { rows } = await pool.query(
"SELECT internal_user_id FROM user_identities WHERE issuer = $1 AND subject = $2",
[payload.iss, payload.sub],
);
return rows[0]?.internal_user_id ?? null; // null means not provisioned yet
}
Vendor-neutral token validation that finds keys through OIDC discovery and JWKS, pins the issuer, audience and algorithm, and resolves the (issuer, subject) pair to an internal user ID through a mapping table.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to auth0 vs keycloak cost, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.