
Summary
Key points of this document
- Requirement to add a service usable without invitation to an invitation-based platform.
- Constraint: Localize exceptions without changing shared authentication.
- Technology Stack
Overview
The existing B2B multi-tenant platform's authentication is designed on the premise that users invited to an organization start using it after administrator approval. If we add a B2C subscription service that can be used immediately without invitation, we cannot rebuild the existing authentication model for each tenant. Here, we will organize the design adopted to change the behavior for only one exceptional tenant without breaking the overall platform's authentication model, along with the decision-making process.
Requirement to add a service usable without invitation to an invitation-based platform.
The existing multi-tenant business SaaS platform bundles business systems like attendance management and sales management, which are contracted by organizational units, and where organizational administrators invite users to start using them. Under this premise, new users are in a "pending" state until invited, and can only use the service after being activated by the organization's administrator. The order is fixed: an organization unit exists, and users start using the service after belonging to an organization.
A requirement arose to add a B2C subscription service where users input learning topics and AI generates and delivers content. This type of service inherently lacks the concept of an "organization," and users are expected to start using it immediately upon logging in with their Google account. Applying the existing invitation-based authentication model as is would make the service unviable.
There were two options. One was to modify the shared authentication platform itself to add a "user type that can be used immediately without an organization." The other was to leave the existing shared authentication untouched and prepare a separate mechanism to allow exceptional behavior for only this one tenant. We chose the latter because modifications to shared authentication would affect all tenants.
Constraint: Localize exceptions without changing shared authentication.
The shared authentication platform is a foundational component that many other B2B tenants depend on. If we were to write a conditional branch like "only this tenant is automatically activated" into the application code, a single oversight in that branch could affect the authentication behavior of other tenants. We initially set the constraint to express exceptions at the configuration or infrastructure layer, without changing the shared platform's code.
At the same time, we also decided that this consumer-facing service should not be within the Cookie scope of the shared Single Sign-On (SSO). If the shared SSO session cookie has a scope valid for both the invitation-based business systems and the invitation-free consumer service, there is a risk that a session incident in one could propagate to the other.
Technology Stack
The backend is built with Bun + Hono, using Stripe for payments and multiple generative AI APIs (text generation and audio/media generation) for content creation. The frontend is an SPA with React Router 8. Initially, we also prepared desktop app shells with Electron and mobile app shells with Expo, but for reasons described later, we shifted our strategy to focus on PWAs.
The escape route: separation of authentication realms.
The adopted design involves creating a new "authentication realm" specifically for this tenant within the shared authentication platform, and enabling the "automatically activate on first login" setting only within that realm. This setting is not part of the application logic but is expressed as a flag scoped only to this specific realm within the infrastructure provisioning definition (IaC). The shared authentication code itself remains untouched.
Furthermore, this realm operates with a dedicated authentication backend and a dedicated Cookie domain, completely separating it from the shared SSO Cookie scope used by existing B2B tenants. Because the scope is divided at the domain level, due to the browser's same-origin policy, it is structurally impossible for session cookies from the consumer service to be sent to the business systems, or vice versa.
The key point of this design is not to "write code that allows exceptions," but to "segregate with infrastructure so that exceptions can structurally only exist within this scope." If exceptions are expressed with if statements in application code, there remains a risk that another developer in the future might touch it without understanding the meaning of that branch. By expressing it as an infrastructure boundary, breaking the boundary requires explicitly changing the infrastructure definition, making accidents less likely.
- The auto-activate flag is scoped only to this realm on IaC, not in application code.
- Completely separate from the shared SSO scope using a dedicated authentication backend and dedicated Cookie domain.
- Express it not as "code that allows exceptions," but as "an infrastructure boundary where only exceptions can exist."
Persistent Job + Bounded Step API Worker Pattern
The process of generating content from learning topics is an asynchronous process that calls multiple external AI APIs sequentially and takes tens of seconds to several minutes. In serverless environments like Cloud Run, which have execution time limits per request, the entire generation process cannot be completed within a single HTTP request.
Therefore, we designed it to persist the entire generation process as a "job" in the DB, and execute each step of the job (topic expansion, material generation, post-processing, etc.) as independent, bounded HTTP calls. Each HTTP request advances only one step, updates the job status upon completion, and then finishes. The next step is triggered as another HTTP request (a call from an internal worker).
For job concurrency control, we adopted a skip method using row locks (a method that proceeds to the next candidate without waiting if the target row is locked) to prevent multiple worker instances from processing the same job twice. Additionally, we record a heartbeat (a timestamp for liveness check) at the start of each step, and jobs whose heartbeats are not updated for a certain period are considered "stalled" and can be automatically re-acquired and resumed. This ensures that even if an instance crashes midway, the job does not remain permanently stalled and self-heals without manual intervention.
- Store the entire generation process as a persistent job in the DB, and decompose each step into bounded HTTP calls.
- Prevent duplicate processing by multiple workers using a row-lock skip method.
- Self-heal without manual intervention through automatic detection and re-acquisition of stalled jobs via heartbeats.
Global Concurrency Control using DB Count Method
For the most costly and resource-intensive step in content generation (media generation API calls), it was necessary to set a global concurrency limit across multiple Cloud Run instances. While there was an option to build a dedicated queue service or message broker, we judged that the operational cost would not be justified at this scale and adopted a lighter alternative.
We adopted a simple counting method: query the DB for the number of jobs in the "currently running" state, and if the limit is reached, make new executions wait. State sharing across instances was entrusted to the existing shared resource, the database, without adding new middleware. Since the DB itself guarantees consistency through transactions, the implementation is relatively simple.
While this method cannot provide true fair queuing or throughput guarantees, it was sufficient to prevent the most undesirable situation: "running too many concurrently and hitting external API rate limits, or causing costs to skyrocket." This was a decision to choose a lightweight solution appropriate for the scale, understanding the trade-offs of not having a dedicated queue service.
Idempotency Design for Two-Stage Stripe Payments
Payments are divided into two stages: estimation (the stage where the user is presented with how much the generation will cost) and actual charging (the stage where generation actually begins). Since the cost of generation varies depending on the topic's depth (options like lightweight, standard, in-depth), it was necessary to present an estimate to the user before charging and only charge after obtaining consent.
By dividing it into two stages, we thoroughly implemented request design using idempotency keys to prevent double charging even if network retries occur at each stage. Even if the same operation is unintentionally sent multiple times, Stripe treats it as the same operation, preventing duplicate charges. For irreversible operations like payments, we prioritized ensuring idempotency on the server side rather than relying solely on UI prevention measures (like double-click prevention).
Automatically post daily/monthly reports based on JST to operations chat.
Operationally important metrics such as sales, refunds, external API costs, and gross profit are aggregated in daily buckets based on Japan Standard Time (JST) and automatically posted to the operations chat at a fixed time every morning. A monthly summary is also posted at the beginning of each month. The aim is to shorten the time it takes to notice anomalies by having the necessary figures delivered proactively, rather than requiring operators to open a dashboard each time to check.
Since these types of reports can span multiple currencies and multiple billing paths, the aggregation logic is encapsulated within the report generation process and implemented as an internal worker API for daily batches. By making it a path that only accepts authenticated internal calls, it is not an endpoint that can be arbitrarily accessed from the outside.
Separate delivery expiration from data retention period.
Generated content is stored in object storage like GCS, and signed URLs are used for delivery to users. After a certain retention period (e.g., 1 year), we designed it to stop issuing signed URLs and return a 410 (Gone) upon access, but the records themselves in the DB are retained for audit purposes without deletion.
We intentionally separated "the period users can access" and "the period the business retains records" because their purposes differ. If the latter were deleted along with the former, we would lose the means to track what happened if inquiries or troubleshooting arose later. As a design to balance storage costs and audit requirements, we decided not to stop delivery and delete data at the same time.
Decision to forgo native app distribution and lean towards PWA.
Initially, we also prepared desktop apps with Electron and mobile app shells with Expo, but as development progressed, we shifted our strategy to focus on PWAs (Progressive Web Apps). One reason was that the authentication flow using Google login conflicted with a security policy that blocks OAuth authentication from environments running within embedded browsers (WebView), such as Electron.
While technical means exist to circumvent this restriction (e.g., launching an external browser to complete authentication), they increase implementation and maintenance complexity. Furthermore, distributing as a native app to stores incurs continuous operational costs for review processes and update distribution. PWAs, which are self-contained within a browser and accessible without installation, can avoid these types of constraints and operational costs.
For a service launched by a small team, the operational costs unique to native apps are a significant burden that cannot be ignored. We decided to prioritize PWAs in the initial phase, with the premise that we would reconsider native apps when experiences unique to them (such as push notifications and the quality of offline playback) become absolutely necessary for the business.
Verification points: Confirming the impact of realm separation and load testing for concurrency limits.
When establishing a new authentication realm, our top priority was to ensure that there would be absolutely no impact on the login and session behavior of existing B2B tenants. Specifically, we confirmed through actual browser behavior that existing tenant cookies are not sent to the new realm's domain, and that new realm cookies do not leak to the existing shared SSO domain.
For global concurrency control, load tests confirmed that new requests are correctly queued when the limit is reached, that pending requests are processed after the limit is released, and that the total number of concurrent executions does not exceed the limit even when multiple instances are running simultaneously. Since the DB count method is simpler to implement, it is more prone to race conditions at boundary values, so we focused heavily on this verification.
Conditions where this design is not suitable.
This design is effective when the authentication model of the existing shared infrastructure cannot be changed, and the number of exceptional tenants is limited to a few. If the number of tenants with similar exceptions increases, the cost of individual handling for each realm will accumulate, and at some point, it will become cheaper to undertake a modification to "formally add the concept of user types to the shared authentication infrastructure itself." Localized exception handling is an effective shortcut only as long as the exceptions are few.
Furthermore, if the frequency and scale of calls increase further, the DB count method for global concurrency control is an area where migration to a dedicated queue service should be considered. For the current scale, the additional load on the database was acceptable, but the premise changes if the scale changes.
Summary: Change behavior only for exceptional tenants without breaking the existing authentication model.
Consistent throughout this topic was the decision to "localize exceptions without changing the shared mechanism that many existing tenants depend on." The separation of authentication realms, the dedicated worker pattern, and the DB count method for concurrency control were all implemented in a way that avoids the cost and risk of modifying the shared infrastructure itself, by confining the scope to a single tenant.
When adding a new type of tenant to an existing multi-tenant infrastructure, the question that arises, even before how to implement the features, is the demarcation of how much of the existing assumptions (in this case, "users are invited to an organization") should be preserved, and where they can be locally broken. If implementation proceeds with this demarcation being ambiguous, the complexity of the shared infrastructure will increase without limit.


