๐Ÿ—๏ธ Architecture

Twelve-Factor App

Twelve-Factor App

A SaaS app development methodology. Twelve principles including configuration, dependencies, and port binding.

๐Ÿ“– Detailed Explanation

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.

๐Ÿ’ป Code Example

// 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
*/

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

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

โš ๏ธ Cautions

๐Ÿ”— Related Terms

Kubernetes Container CI/CD Microservice Cloud Native

๐Ÿ“š Learn More

๐Ÿ“„ 12factor.net - Official Site (Korean) ๐Ÿ“„ Red Hat - Introduction to Twelve-Factor App ๐Ÿ“„ Google Cloud - Twelve-Factor on GCP