
Summary
Key points of this document
- Decide owners between clouds before layering code
- Separate from common infrastructure to customer-specific UX in 4 layers
- Determine placement by Control Plane and Data Plane, not by product name
Overview
When operating multiple customer applications on a common infrastructure, simply dividing code into layers does not stabilize responsibility boundaries. In addition to deciding which functions to standardize, it's necessary to determine which cloud holds the authoritative data, how to authenticate cross-boundary communication, and what to continue in the event of a failure on one side. This article summarizes the decision-making criteria for a design that uses a 4-layer model to organize application responsibilities, treating Cloudflare as the Data Plane closer to the customer and Google Cloud as the common Control Plane.
Decide owners between clouds before layering code
When attempting to deploy multiple customer applications from a single codebase, the scope of commonality continuously expands. If not only cross-cutting concerns like authentication, notifications, and auditing, but also screens, menus, input fields, and business workflows start to be absorbed by configuration, the common part becomes a giant conditional branch, and a single change affects unrelated customer applications.
To address this problem, the 4-layer model serves as a tool to separate the ability to standardize from the experience of individual implementation. However, even if application code is classified into four layers, if the same data or responsibilities remain in both Cloudflare and Google Cloud, operational boundaries will remain ambiguous. Humans will have to decide which state is correct for every incident response, permission change, backup, deletion, and audit.
Therefore, a single Owner is determined for all Compute, Data, Secrets, and APIs. While treating Cloudflare as the execution plane closer to the customer and Google Cloud as the control plane for the shared infrastructure is a strong initial hypothesis, it is not a rule that prohibits exceptions. We only adopt configurations where the reason for crossing boundaries can be explained, after reviewing the authoritative data, processing location, performance, security, cost, and operational structure.
- Layers organize code dependencies, while cloud boundaries organize ownership and operational responsibility.
- Evaluate boundaries by whether the reason for change and the scope of impact align, not by the amount of commonality.
- Even when exceptions are allowed, do not leave Owner, System of Record, communication contracts, and recovery procedures ambiguous.
Separate from common infrastructure to customer-specific UX in 4 layers
L0 Platform is a common infrastructure that can function without knowledge of business domains. Candidates include Identity, Tenant, RBAC, Notifications, Billing, Usage, AI Gateway, Auditing, Jobs, and Observability. If specific screen names or business procedures start to appear here, it's likely that responsibilities from higher layers are leaking, and it's no longer just a Platform.
L1 Shared Shell is the minimal framework for securely launching customer applications. It provides authentication integration, tenant context, permission guards, API clients, error boundaries, design systems, routing, and accessibility. Primitives placed in the same L1 are stable fundamental concepts like Money, Quantity, DateRange, and Attachment. Volatile business models should not be moved to Primitives merely because they are referenced from multiple places.
L2 Domain Engine is the layer that extracts business capabilities like billing, inventory, and reservations into reusable units. Calculations without side effects are provided as libraries, stateful business capabilities as Domain APIs, and capabilities spanning multiple domains as Platform Services. L3 Client Application contains customer-specific screens, user flows, input fields, menus, and business workflows. The basic approach is to not incorporate unnecessary features from the start, rather than hiding them with permissions or feature flags.
- L0 handles the common infrastructure unaware of business, while L1 handles the application launch framework and stable concepts.
- L2 divides reusable business capabilities into libraries, APIs, and Platform Services based on statefulness and cross-domain nature.
- L3 holds customer-specific differences as explicit code, rather than pushing them into a giant configuration mechanism.
// 4-Layer Responsibilities
L0 Platform
Identity / Tenant / RBAC / Notification / Audit / Job
L1 Shared Shell / Primitives
Auth integration / API client / Design system / Money / DateRange
L2 Domain Engines / APIs
Pure logic library / Stateful Domain API
L3 Client Applications
Client-specific UI / UX / Workflow / DataDetermine placement by Control Plane and Data Plane, not by product name
Cloudflare is responsible for the entry point of customer applications, including DNS, CDN, WAF, rate limiting, static delivery, and Cloudflare Workers. Data that needs to be self-contained per customer and handled with low latency is a candidate for D1, R2, KV, and Durable Objects. However, the storage location is not determined all at once; consistency, transactions, capacity, read/write patterns, retention periods, backup, and deletion requirements are evaluated for each entity.
Google Cloud is responsible for core capabilities shared across all customer applications. Tenant Registry, billing, usage, central auditing, AI Gateway, shared Domain API, heavy batch processing, long-running jobs, and overall policies are candidates. Cloud Run, Cloud Run Jobs, Cloud Tasks, Pub/Sub, Secret Manager, etc., are selected only as needed to fulfill these responsibilities. We do not design to move all services to Cloud Run just because they are on Google Cloud.
The core of the decision is the Control Plane and Data Plane. States that control contracts, permissions, available features, and overall policies are placed in the Control Plane, while states that process actual customer operations, customer-specific documents, and individual workflows are placed in the Data Plane. However, Data Gravity, processing near the data, is also considered. If D1 is the source of truth, computations are also on the Cloudflare side; if Google Cloud data is the source of truth, heavy processing is also placed on the same side to avoid unnecessary cloud round trips.
- Cloudflare candidates: Edge, Client Application Runtime, per-customer Data Plane, low-latency processing.
- Google Cloud candidates: Platform, Control Plane, shared Domain Service, heavy processing, central governance.
- Avoid round trips like CF → GCP → CF → GCP, and place processing near the source of truth data.
Decide on a single System of Record and avoid synchronous Dual Write.
The most important task in stabilizing cloud boundaries is to determine the System of Record for each major entity. We create a table for Owner, source of truth, execution location, backup, retention period, and deletion responsibility, eliminating situations where the same source of truth exists in both Cloudflare and Google Cloud. If data is placed in another location, it is explicitly stated whether it is Authoritative, Replica, Cache, or Derived.
Synchronous Dual Write, where the browser writes to D1 and the Google Cloud side DB simultaneously, loses consistency if only one succeeds. Rather than expecting complete atomicity across two transactions, it is easier to maintain ownership by writing to a single SoR, sending the result as an event, and asynchronously generating a projection on the other side.
Asynchronization does not eliminate consistency issues. Design for idempotency, duplicate delivery, order, retries, poison events, DLQ, and reprocessing procedures by including event_id, schema_version, tenant_id, occurred_at, and correlation_id. If the screen and operations cannot tolerate Replica or Derived data being out of date, then that processing should not be asynchronous, and the boundary itself needs to be re-evaluated.*Place a single boundary API and do not expose internal services and long-term private keys externally.*If Cloudflare's Client Application individually knows Google Cloud internal services, the boundary contract increases with every service addition or division. Consolidate external entry points into a Platform Boundary API, providing stable contracts for Identity, notifications, AI, billing, and shared Domains. Internal Cloud Run services are classified as PUBLIC, EDGE-ONLY, INTERNAL, or PRIVATE, and only necessary entry points are given access paths.*Boundary contracts are version-controlled with OpenAPI or JSON Schema, defining request, response, error, pagination, idempotency key, and correlation ID. Specifically, do not trust tenant_id solely from the body; determine the authorization target from verified machine identity and user context. Perform authentication, authorization, rate limiting, and schema validation at the boundary, and do not return internal service names or exception details as is.*Include event_id, schema_version, tenant_id, occurred_at, and correlation_id, and design for idempotency, duplicate delivery, order, retries, poison events, DLQ, and reprocessing procedures. If the screen and operations cannot tolerate Replica or Derived data being out of date, then that processing should not be asynchronous, and the boundary itself needs to be re-evaluated.
// Example of Data Ownership Record
Entity Owner System of Record Secondary copy
Tenant policy Platform Google Cloud Edge cache
Client workflow Client app Cloudflare D1 Audit projection
Client document Client app Cloudflare R2 Backup replica
Usage aggregate Platform Google Cloud Derived dashboard// Cross-boundary Updates
System of Record
-> Outbox / Event
-> Retryable delivery
-> Idempotent consumer
-> Replica / Cache / Derived projectionPlace a single boundary API and do not expose internal services and long-term private keys externally.
If the Cloudflare Client Application individually knows Google Cloud internal services, the boundary contract increases with every service addition or division. Consolidate external entry points into a Platform Boundary API, providing stable contracts for Identity, notifications, AI, billing, and shared Domains. Internal Cloud Run services are classified as PUBLIC, EDGE-ONLY, INTERNAL, or PRIVATE, and only necessary entry points are given access paths.
Boundary contracts are version-controlled with OpenAPI or JSON Schema, defining request, response, error, pagination, idempotency key, and correlation ID. Specifically, do not trust tenant_id solely from the body; determine the authorization target from verified machine identity and user context. Perform authentication, authorization, rate limiting, and schema validation at the boundary, and do not return internal service names or exception details as is.
For machine authentication from Cloudflare to Google Cloud, static Service Account Keys are not the first choice. Short-lived credentials using OIDC and Workload Identity Federation are considered, and token lifetime, audience, clock skew, replay protection, key rotation, and the delay and operational load during exchange are measured. Even if the short-lived credential method does not meet requirements, the reasons for adopting an alternative method, secret storage location, update procedure, and revocation procedure are documented in the design records.
- The Client Application does not directly depend on internal Cloud Run URLs or service configurations.
- The boundary API establishes not only authentication but also tenant context, authorization, rate limits, schema, and request ID.
- Before distributing long-term keys, verify the feasibility of short-lived credentials, latency, re-acquisition during failures, and operational load.
Choose between immediate response, events, and jobs based on user waiting time.
If all cross-boundary processes are synchronous APIs, delays or failures on the Google Cloud side will propagate to the entire screen on the Cloudflare side. On the other hand, if everything is changed to events, operations where users require immediate results will become eventually consistent, complicating retries and status display. The communication method is chosen not by technical preference, but by when the user needs the result.
Processes that require immediate results, such as permission checks and instant AI responses, are candidates for synchronous APIs. Processes that do not require waiting for results, such as audit projections, external notifications, and usage aggregation, are sent to events or queues. Large file processing and long-running AI processes are accepted as jobs, with a contract allowing progress to be checked via a job ID.
Synchronous paths have a timeout per hop and an overall latency budget. Retries are limited to idempotent operations, and idempotency keys are used for writes. Asynchronous paths separate acceptance and completion; business processing is not displayed as complete merely upon entry into a queue. The API contract defines what states are visible to the user and which failures can be retried.
// Communication Method Selection
Immediate result required -> Synchronous API
Result can arrive later -> Event / Queue
Heavy or long-running work -> Job + status API
External notification -> Event / QueuePrevent failures on one side from spreading to a complete shutdown; determine degradation methods for each function.
A configuration where the entire customer application stops when Google Cloud is unavailable extends the failure scope of the shared infrastructure to all Data Planes. Browsing and updates that can be completed solely with the authoritative data on the Cloudflare side continue, and functions that can be safely decided with in-date cache utilize the cache. Operations that are dangerous to proceed with old information, such as permissions and billing, are explicitly stopped.
Each function is classified into four categories: continuable, read-only, evacuated to queue, and complete stop. For example, it is decided in advance that customer local drafts can continue, but publishing operations requiring central entitlement checks will stop. It is made clear whether a failure returns 200 with old results, accepts with 202, or stops with 503.
Degraded operation also requires a recovery procedure. Updates evacuated to a queue are processed for order and duplication after recovery, and the final result is shown to the user. Caches are given an expiration date and source, and the acceptable staleness during a failure is set per function. During fault injection tests, communication to Google Cloud is blocked to verify key customer local functions, the stopping of dangerous writes, and reprocessing after recovery.
// Google Cloud Outage Classification
Client-local operation -> Continue
Safe cached read -> Continue within TTL
Non-critical write -> Queue and show pending
Policy-dependent operation -> Fail explicitly
Critical cross-cloud write -> Stop; never pretend successMake tenant isolation, auditing, and distributed tracing common specifications for boundaries.
In a multi-tenant configuration, isolation is not solely entrusted to application filters. A single issuer for tenant context is designated, signatures and audiences are validated at the boundary API, and within Google Cloud, dedicated Service Accounts and Least Privilege are applied. Whether D1 and R2 are separated per customer or shared is decided by comparing not only transactions but also permissions, backup, deletion, migration, and failure scope.
Since logs are separated between Cloudflare and Google Cloud, identifiers are needed to track browser, Worker, Boundary API, Cloud Run, queue, and job as a single process. Propagate trace_id, request_id, tenant_id, client_app, service, operation, and correlation_id. However, personal information or body content should not be used as identifiers; only necessary context should be structured and recorded.*Propagate trace_*id, request_*id, tenant_*id, client_app, service, operation, and correlation_id. However, personal information or body content should not be used as identifiers; only necessary context should be structured and recorded.
Application Logs and Audit Logs have different purposes. The former is used for diagnosing defects and performance, while the latter tracks who, when, tenant, action, resource, and result. Even when collecting events for central auditing, we do not use a path that rewrites the authoritative source in the Data Plane. We decide whether to halt customer operations due to an audit-side failure or to hold and send later via an outbox, based on regulations and business requirements.
- The tenant_id is determined from a verified authentication context, not from user input.
- Restrict East-West communication with dedicated Service Accounts and IAM, and do not unnecessarily expose anything public outside of boundary entry points.
- Separate Application Logs, Distributed Traces, and Audit Logs, and link them with the same correlation ID.
- Data sent for AI processing should be minimized to the context required for that processing, not the entire customer DB.
Reflect layers and owners in deployment units and migrate incrementally.
Even if responsibilities are logically separated, deploying everything simultaneously leaves a scope for failure. Organize Platform API, Domain API, Shared Shell package, Client Application, schema, and Infrastructure as Code as independent units of change, and release them in a compatible order. Map environment names, projects, domains, DBs, queues, and secrets using the same rules, preventing validation environments from referencing production resources.
Migration should not be a Big Bang Rewrite. First, inventory current Compute, Data, Secret, communication, and deployment paths. Next, define inter-cloud responsibilities, System of Record, and boundary contracts. Then, extract Platform and Shared Shell, separate customer-specific features and potential Domain Engines, and finally proceed with data migration and infrastructure separation.
Each stage should have an objective, scope, data migration, API change, dependency, risk, security impact, cost impact, rollback, and completion criteria. First, make contracts compatible, observe both paths, then switch traffic. The old path will be deprecated after a period during which recovery is possible. Completion criteria include not only the new configuration working but also the ability to revert to the old path, consistency of record counts and integrity of authoritative sources, and the ability to trace across boundaries.
- Proceed in the order of Inventory → Responsibility Boundaries → System of Record → Boundary Contracts → Platform/Shell Extraction → Data/Infrastructure Migration.
- Maintain backward compatibility for API and event schemas, allowing migration without simultaneous updates to producers and consumers.
- Assign one owner per resource for Infrastructure as Code, and do not manage the same resource from multiple stacks.
- Record switchover, validation, rollback, and old path deletion as separate completion criteria.
If everything is forced into a single approach, boundaries actually become weaker.
This design is not a proposal to convert everything to microservices, Cloud Run, Cloudflare Workers, D1, APIs, and event-driven architectures. Small, stable pure logic is better as a library, as it doesn't increase operational overhead, and processes requiring strong transactions are clearer when confined to a single DB and service. Each time a boundary is added, the costs of authentication, contracts, monitoring, retries, versioning, and incident response increase.
Customer-specific DBs clarify deletion and fault isolation but increase the scope of migration and monitoring. Shared DBs reduce operational overhead but broaden the impact of filter omissions and resource contention. Cloudflare Tunnel is powerful for private networks and management paths, but unconditionally adding it to standard HTTPS communication from Workers to Cloud Run can sometimes only increase paths and operational complexity.
The priorities for evaluation are Security, Simplicity, Clear ownership, Data isolation, Failure isolation, Low coupling, Explicit contracts, Operational simplicity, Cost, Performance, Reusability, and Future extensibility. In particular, current ownership should not be ambiguous to enhance future reusability. If commonality makes boundaries difficult to explain, we judge that such commonality is premature.
The key decision-making criterion to take away is not the amount of commonality, but the clarity of ownership.
In the 4-layer model, Platform and Shared Shell are made common, Domain capability is reused as an Engine or API, and customer-specific UX and workflows are left to the Client Application. This separation allows improvements to the foundation to be delivered to multiple applications while making it difficult for individual business changes to propagate to unrelated applications.
At the cloud boundary, Cloudflare is seen as the Data Plane closer to the customer, and Google Cloud as the shared Control Plane. However, the placement is not determined by name. We check the System of Record, Data Gravity, communication frequency, required consistency, behavior during failures, and operational owner for each entity and process.
What ultimately needs to be confirmed is simple: Is there a single owner for each Compute, Data, Secret, and API? Can the reasons and contracts for crossing boundaries be explained? Can the state when one side stops be correctly shown to users? And can it be rolled back incrementally? Only when these four points are met does a configuration using two clouds become a single maintainable system.


