Twelve-Factor App
Twelve-Factor App
A SaaS app development methodology. Twelve principles including configuration, dependencies, and port binding.
Twelve-Factor App
A SaaS app development methodology. Twelve principles including configuration, dependencies, and port binding.
The Twelve-Factor App is a modern SaaS application development methodology proposed by Heroku developers in 2011. It defines 12 principles for building apps that are easy to deploy, scale, and maintain in cloud-native environments. It has become even more important in the era of containers, serverless, and microservices.
Core principles: 1) Codebase - one version-controlled codebase, 2) Dependencies - explicitly declare dependencies, 3) Config - separate configuration using environment variables, 4) Backing Services - treat DBs, caches, etc. as replaceable resources, 5) Build/Release/Run - separate the build and run stages, 6) Processes - run as stateless processes.
Additional principles: 7) Port Binding - expose services by binding to their own port, 8) Concurrency - scale out horizontally by replicating processes, 9) Disposability - fast startup and graceful shutdown, 10) Dev/Prod Parity - keep development and production environments consistent, 11) Logs - treat logs as event streams, 12) Admin Processes - run administrative tasks as one-off processes.
These principles fit naturally with Docker and Kubernetes environments. Environment variable configuration (ConfigMap/Secret), stateless containers, horizontal scaling (HPA), health checks, and log collection (Fluentd) all follow the Twelve-Factor principles.
// Twelve-Factor App ์์น ์ ์ฉ ์์
// 3. Config - ํ๊ฒฝ๋ณ์๋ก ์ค์ ๋ถ๋ฆฌ
// โ ์ํฐํจํด: ํ๋์ฝ๋ฉ
const dbUrl = 'postgres://user:pass@localhost:5432/mydb';
// โ
ํ๊ฒฝ๋ณ์ ์ฌ์ฉ
const config = {
database: {
url: process.env.DATABASE_URL,
pool: parseInt(process.env.DB_POOL_SIZE || '10')
},
redis: {
url: process.env.REDIS_URL
},
port: parseInt(process.env.PORT || '3000'),
logLevel: process.env.LOG_LEVEL || 'info'
};
// ํ์ ํ๊ฒฝ๋ณ์ ๊ฒ์ฆ (์์ ์์ ์)
const required = ['DATABASE_URL', 'REDIS_URL', 'JWT_SECRET'];
for (const key of required) {
if (!process.env[key]) {
console.error(`Missing required env var: ${key}`);
process.exit(1);
}
}
// 4. Backing Services - ๊ต์ฒด ๊ฐ๋ฅํ ๋ฆฌ์์ค
// ํ๊ฒฝ๋ณ์๋ง ๋ฐ๊พธ๋ฉด ๋ก์ปฌ Redis โ AWS ElastiCache ์ ํ ๊ฐ๋ฅ
const redis = new Redis(process.env.REDIS_URL);
// 6. Processes - Stateless ํ๋ก์ธ์ค
// โ ๋ฉ๋ชจ๋ฆฌ์ ์ธ์
์ ์ฅ (์ค์ผ์ผ๋ง ๋ถ๊ฐ)
const sessions = new Map();
// โ
์ธ๋ถ ์ ์ฅ์(Redis)์ ์ธ์
์ ์ฅ
app.use(session({
store: new RedisStore({ client: redis }),
secret: process.env.SESSION_SECRET
}));
// 9. Disposability - Graceful Shutdown
async function gracefulShutdown(signal: string) {
console.log(`Received ${signal}, shutting down gracefully...`);
// 1. ์ ์์ฒญ ๊ฑฐ๋ถ
server.close();
// 2. ์งํ ์ค์ธ ์์
์๋ฃ ๋๊ธฐ
await Promise.all([
redis.quit(),
prisma.$disconnect(),
closeDbPool()
]);
console.log('Cleanup complete, exiting');
process.exit(0);
}
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// 11. Logs - stdout์ผ๋ก ์ถ๋ ฅ (์์ง์ ์ธํ๋ผ๊ฐ ๋ด๋น)
// โ ํ์ผ์ ์ง์ ๋ก๊น
// fs.appendFileSync('/var/log/app.log', message);
// โ
stdout์ผ๋ก ๊ตฌ์กฐํ๋ ๋ก๊ทธ
import pino from 'pino';
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
// JSON ํ์์ผ๋ก stdout ์ถ๋ ฅ โ Fluentd/Datadog์ด ์์ง
});
logger.info({ userId, action: 'login' }, 'User logged in');
// Kubernetes ๋ฐฐํฌ ์์
/*
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: app
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: app-secrets
key: database-url
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: app-config
key: log-level
livenessProbe: # 9. Disposability
httpGet:
path: /health
port: 3000
readinessProbe:
httpGet:
path: /ready
port: 3000
*/
In cloud migration:
"We're trying to move an on-premises app to K8s, but we're running into a lot of problems." - "Check it against Twelve-Factor. If configuration is hardcoded in files, or if state is stored on the local filesystem, containerization is difficult. You need to switch to environment variables and external storage."
In a technical interview:
"What's the most important principle in Twelve-Factor?" - "I'd pick Config and Stateless Processes. If you separate configuration using environment variables, the same code can be deployed anywhere, and stateless processes are the foundation of horizontal scaling and failure recovery."
In incident response:
"The Pod keeps restarting after deployment." - "Did you implement graceful shutdown? When it receives SIGTERM, it needs to finish in-flight requests and clean up DB connections. Otherwise, readiness can fail and it may restart endlessly."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free