Multi-Tenancy And The Concepts Behind It.

Multi-Tenancy And The Concepts Behind It

多租户架构及其核心概念

Introduction

Building a multi-tenant application is one of the most architecturally demanding challenges in backend engineering. It requires deliberate decisions around data isolation, request handling, code organization, and system reliability all working together seamlessly beneath a surface that feels effortless to the end user. This article covers the core concepts behind multi-tenant architecture: how tenant isolation works, how clean architecture organizes the codebase, how the API Gateway and middleware relate to each other, and the supporting engineering principles SSL, encryption, load balancing, idempotency, and dependency injection that make the whole system robust and maintainable.

引言

构建多租户应用程序是后端工程中架构要求最高的挑战之一。它需要在数据隔离、请求处理、代码组织和系统可靠性方面做出深思熟虑的决策,所有这些都需要在用户感觉不到的层面下无缝协作。本文涵盖了多租户架构背后的核心概念:租户隔离的工作原理、整洁架构(Clean Architecture)如何组织代码库、API 网关与中间件之间的关系,以及使整个系统稳健且易于维护的支撑工程原则,如 SSL、加密、负载均衡、幂等性和依赖注入。


What Is A Multi-Tenant Application?

A multi-tenant application is a single software system that serves multiple independent customers called tenants from a shared infrastructure, while guaranteeing complete data isolation between them.

什么是多租户应用程序?

多租户应用程序是一个单一的软件系统,它通过共享的基础设施为多个独立的客户(称为租户)提供服务,同时保证它们之间数据的完全隔离。


Real-Life Example:

Imagine Ikeja City Mall. It is one big mall with many different shops inside. Each shop is a tenant because it rents space in the mall. Although all the shops share the same building, each one has its own products, workers, and customers. A multi-tenant application works the same way: many businesses (tenants) use the same application, but each business has its own users and data.

现实生活中的例子:

想象一下伊凯贾城市购物中心(Ikeja City Mall)。它是一个容纳了许多不同商店的大型商场。每家商店都是一个“租户”,因为它们租用了商场内的空间。尽管所有商店共享同一栋建筑,但每家店都有自己的产品、员工和客户。多租户应用程序的工作方式相同:许多企业(租户)使用同一个应用程序,但每个企业都有自己的用户和数据。


Purpose

Single-TenantMulti-Tenant
InfrastructureSeparate per customerShared across all customers
Cost efficiencyLowHigh
Data isolationNaturalEngineered
Scalability complexityLowHigh
Maintenance overheadHighLow

目的

单租户多租户
基础设施每个客户独立所有客户共享
成本效率
数据隔离自然具备需工程实现
扩展复杂度
维护开销

How Tenants Data Stays Separate

Tenant Isolation: The Core Engineering Challenge Since all tenants share the same infrastructure, isolation must be enforced deliberately at multiple layers. A single point of enforcement is insufficient; defense in depth is the standard approach.

租户数据如何保持独立

租户隔离:核心工程挑战 由于所有租户共享同一基础设施,必须在多个层面上有意地实施隔离。单一的强制执行点是不够的;纵深防御是标准做法。


Real-Life Example:

Think about how the same office building enforces privacy across floors. There is the security guard at the gate, the access card that only opens your floor, the receptionist on each floor who stamps everything with your company name, and the filing cabinet that only opens for the right key. If one layer fails, the next catches it. That is exactly how tenant isolation works: multiple overlapping layers, not a single point of trust.

现实生活中的例子:

想想同一栋办公楼是如何在不同楼层之间实施隐私保护的。大门口有保安,门禁卡只能打开你所在的楼层,每个楼层有前台负责给所有文件盖上公司名称,文件柜也只有对应的钥匙才能打开。如果一层防线失效,下一层会补上。这正是租户隔离的工作方式:多个重叠的层级,而不是单一的信任点。


Approach 1: Separate Database per Tenant

Each tenant gets their own database instance. Maximum isolation, but expensive to operate and difficult to maintain at scale.

方法 1:每个租户独立数据库

每个租户拥有自己的数据库实例。隔离性最高,但运营成本高昂,且在大规模扩展时难以维护。


Approach 2: Separate Schema per Tenant

One database, but each tenant has their own schema (namespace). A middle ground between isolation and operational efficiency.

方法 2:每个租户独立 Schema

使用同一个数据库,但每个租户拥有自己的 Schema(命名空间)。这是隔离性和运营效率之间的折中方案。


Approach 3: Shared Tables with tenant_id (Most Common)

All tenants share the same tables. Every row is tagged with a tenant_id column that identifies ownership. Cheapest to operate but requires the most engineering discipline. Most production multi-tenant systems use this approach. The rest of this article assumes it.

方法 3:共享表并使用 tenant_id(最常用)

所有租户共享相同的表。每一行数据都通过 tenant_id 列进行标记,以标识归属权。运营成本最低,但需要极高的工程规范。大多数生产环境的多租户系统都采用这种方法。本文后续内容将基于此方法展开。


tenant_id: The Foundation of Shared Table Isolation

Every table in the system carries a tenant_id column. Think of it like a name tag on every file in a shared archive room. The archive staff will only hand you folders that carry your company’s name — no matter what you ask for, no matter how you ask.

tenant_id:共享表隔离的基础

系统中的每个表都包含一个 tenant_id 列。可以把它想象成共享档案室里每个文件上的姓名标签。档案管理员只会交给你带有你公司名称的文件夹——无论你要求什么,无论你如何要求。

idtenant_idpolicy_holderamount
1ioa_retailJohn Doe₦50,000
2ioa_corporateioa Group₦5,000,000
3ioaJane Smith₦30,000

Advantages Of A Multitenant App

  • Lower Development Cost
  • Easier Maintenance
  • Faster Feature Rollout
  • Better Scalability
  • Faster Customer Onboarding

多租户应用程序的优势

  • 更低的开发成本
  • 更易于维护
  • 更快的功能发布
  • 更好的可扩展性
  • 更快的客户入驻

CRUD

CRUD is the four basic operation, you can perform on data in any application. C-Create, R-Read, U-Update, D-Delete.

CRUD

CRUD 是你在任何应用程序中对数据执行的四种基本操作: C-创建 (Create)、R-读取 (Read)、U-更新 (Update)、D-删除 (Delete)。


Monolithic and Microservice App

A Monolithic app is when the entire application is built as one single unit. Everything—the user interface, the business logic, the database connection—is all bundled together in one codebase.

单体与微服务应用

单体应用是指整个应用程序构建为一个单一单元。所有内容——用户界面、业务逻辑、数据库连接——都捆绑在一个代码库中。


Real-Life Example:

Think of it like a restaurant in Ikeja City Mall in Lagos. One shop does everything: They cook the food, they serve it, they collect the money, they wash the plates. Everything happens in one place by one operation. If the gas cooker breaks down, the whole restaurant stops because everything depends on everything else.

现实生活中的例子:

把它想象成拉各斯伊凯贾城市购物中心的一家餐厅。一家店包办所有事情:他们做饭、上菜、收钱、洗盘子。所有事情都在一个地方由一个团队完成。如果燃气灶坏了,整个餐厅就会停业,因为所有环节都相互依赖。


A Microservice is when you break your application into smaller independent services where each service does one specific job and does it well.

微服务是指将应用程序拆分为更小的独立服务,每个服务只负责一项特定的工作,并将其做好。


Real-Life Example:

Think of it like a restaurant in Ikeja City Mall in Lagos. One shop handles only payments, another handles only user login, another handles only notifications. If the notifications shop has a problem, payments and login keep working fine.

现实生活中的例子:

把它想象成拉各斯伊凯贾城市购物中心的一家餐厅。一家店只负责支付,另一家只负责用户登录,还有一家只负责通知。如果通知店出了问题,支付和登录功能依然可以正常工作。


API Gateway

An API gateway is a single entry point that sits in front of all the backend services and manages every request coming into your system. Instead of clients talking directly to multiple services, they talk to one gateway and the gateway handles the rest.

API 网关

API 网关是一个单一的入口点,位于所有后端服务之前,管理进入系统的每一个请求。客户端不再直接与多个服务通信,而是与一个网关通信,由网关处理其余事务。


Real-Life Example: API Gateway = The Receptionist at the main entrance

When you walk into a company’s building, the receptionist at the front desk:

  • Checks your ID — who are you? Are you authorized to be here? (authentication)
  • Checks your appointment — do you have a valid reason to be here? (authorization)
  • Directs you to the right floor — claims department is floor 3, underwriting is floor 7 (routing)
  • Controls the crowd — if too many people come at once, she manages the queue (rate limiting)
  • Logs every visitor — signs you into the visitor’s book (logging) She handles everyone that walks through the front door. No one bypasses her. She is the single entry point to the entire building. That is the API Gateway.

现实生活中的例子:API 网关 = 主入口的前台接待员

当你走进一家公司的办公楼时,前台接待员会:

  • 检查你的证件——你是谁?你是否有权进入这里?(身份验证)
  • 检查你的预约——你是否有正当理由来这里?(授权)
  • 指引你去正确的楼层——理赔部在 3 楼,承保部在 7 楼(路由)
  • 控制人流——如果同时来的人太多,她会管理排队(限流)
  • 记录每位访客——让你在访客登记簿上签名(日志记录) 她处理每一个走进前门的人。没有人能绕过她。她是整个建筑的单一入口点。这就是 API 网关。

What an API gateway does:

  • Routing
  • Authentication
  • Rate limiting
  • Load balancing
  • Logging
  • SSL Termination

API 网关的功能:

  • 路由
  • 身份验证
  • 限流
  • 负载均衡
  • 日志记录
  • SSL 卸载

Middleware

Middleware is a code that sits between the request and response, it runs automatically every time a user makes a request to server before the request reaches its final destination.

中间件

中间件是位于请求和响应之间的代码,每当用户向服务器发出请求时,它都会在请求到达最终目的地之前自动运行。


Real-Life Example: Middleware = The security personnel on each floor

After the receptionist clears you and you take the elevator…

现实生活中的例子:中间件 = 每个楼层的安保人员

在前台接待员放行并你乘坐电梯后……