> ## Documentation Index
> Fetch the complete documentation index at: https://ayakaleaf-pro.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 水平スケーリング

> スティッキーセッション対応のロードバランサーの背後で、複数の Ayakaleaf Pro レプリカを実行します。

レプリカが 1 つの場合、すべてのコンパイルに 1 つのノードの CPU を使用します。2 vCPU のテストノードでは、6 つの同時コンパイルに 1 つの場合の 3 倍の時間がかかり、その間ほかのノードはアイドル状態のままでした。複数のレプリカを使うと、ユーザーとそのコンパイルがノード間に分散されます。

これは Overleaf の [水平スケーリング](https://ayakaleaf-pro.mintlify.site/ja/on-premises/maintenance/horizontal-scaling.md) の設計を Kubernetes に置き換えたものです。

| 要件 | ここでの対応 |
| - | - |
| 共有の MongoDB と Redis | インストール時の `10-mongo.yaml` と `20-redis.yaml` |
| 共有のシークレット | [ステップ 2](https://ayakaleaf-pro.mintlify.site/ja/on-premises/installation/using-kubernetes/2.-create-the-namespace-and-secrets.md) の Secret `overleaf-secrets` にすでに含まれています |
| プロジェクトファイルと履歴は **S3** に保存（NFS ではない） | 任意の S3 サービス。[S3](https://ayakaleaf-pro.mintlify.site/ja/on-premises/configuration/kubernetes/s3.md) を参照してください。クラスター内の例として Garage を使用しています |
| コンパイルとアップロード用に、レプリカごとのローカルディスク | 各ノード上の `hostPath` `/srv/overleaf-ha` |
| 永続的なルーティング、WebSocket、10 分のタイムアウト、50 MB のアップロード | Overleaf のサンプル設定を使用した HAProxy |
| 1 つのレプリカに併設するシングルトンの git-bridge | `overleaf-0` を sibling とする git-bridge |

> [!WARNING]
>
> S3 は最初から計画してください。すでにボリューム上にファイルを保存しているインスタンスでは、先に [S3 への移行](https://ayakaleaf-pro.mintlify.site/ja/on-premises/maintenance/s3-migration.md) が必要です。この構成はステップ 5 の Deployment を置き換えます。StatefulSet を適用する前に、Deployment を削除してください（`kubectl delete -f 40-overleaf.yaml`）。

**1. S3 ストレージ**

[S3](https://ayakaleaf-pro.mintlify.site/ja/on-premises/configuration/kubernetes/s3.md) の説明に従い、お使いの S3 サービスまたはクラスター内の Garage で 3 つのバケットと 2 つのユーザーを設定し、4 つのキーを Secret `overleaf-s3` に格納します。以下の設定では、そのページの Garage の例を使用しています。

**2. 設定**

この ConfigMap は `30-config.yaml` を置き換えます。S3 と git-bridge を追加し、`OVERLEAF_SITE_URL` をロードバランサーに向けます。

```yaml title="60-config.yaml" wrap theme={null}
apiVersion: v1
kind: ConfigMap
metadata:
  name: overleaf-env
  namespace: overleaf
data:
  OVERLEAF_APP_NAME: Ayakaleaf Pro
  OVERLEAF_SITE_URL: http://192.0.2.10:30081      # the load balancer (HAProxy) URL
  OVERLEAF_ADMIN_EMAIL: admin@example.com
  # Emails: add the sender and the SMTP server together, see Email delivery
  OVERLEAF_MONGO_URL: mongodb://mongo-0.mongo:27017,mongo-1.mongo:27017,mongo-2.mongo:27017/sharelatex?replicaSet=overleaf
  OVERLEAF_REDIS_HOST: redis
  REDIS_HOST: redis
  ENABLED_LINKED_FILE_TYPES: project_file,project_output_file,url
  ENABLE_CONVERSIONS: "true"
  EMAIL_CONFIRMATION_DISABLED: "true"
  OVERLEAF_TRUSTED_PROXY_IPS: loopback,10.244.0.0/16   # HAProxy runs in the pod CIDR
  # Sandboxed compiles, node paths: each replica owns /srv/overleaf-ha on its node
  SANDBOXED_COMPILES: "true"
  SANDBOXED_COMPILES_SIBLING_CONTAINERS: "true"
  DOCKER_RUNNER: "true"
  SANDBOXED_COMPILES_HOST_DIR_COMPILES: /srv/overleaf-ha/data/compiles
  SANDBOXED_COMPILES_HOST_DIR_OUTPUT: /srv/overleaf-ha/data/output
  SANDBOXED_COMPILES_HOST_DIR_CACHE: /srv/overleaf-ha/data/cache
  ALL_TEX_LIVE_DOCKER_IMAGES: ghcr.io/ayaka-notes/texlive-full:2026.1
  ALL_TEX_LIVE_DOCKER_IMAGE_NAMES: TeX Live 2026
  TEX_LIVE_DOCKER_IMAGE: ghcr.io/ayaka-notes/texlive-full:2026.1
  # S3 (required for more than one replica); keys are in the Secret overleaf-s3
  OVERLEAF_FILESTORE_BACKEND: s3
  OVERLEAF_FILESTORE_TEMPLATE_FILES_BUCKET_NAME: overleaf-template-files
  OVERLEAF_FILESTORE_S3_ENDPOINT: http://garage:3900
  OVERLEAF_FILESTORE_S3_PATH_STYLE: "true"
  OVERLEAF_FILESTORE_S3_REGION: garage
  OVERLEAF_HISTORY_BACKEND: s3
  OVERLEAF_HISTORY_PROJECT_BLOBS_BUCKET: overleaf-project-blobs
  OVERLEAF_HISTORY_CHUNKS_BUCKET: overleaf-chunks
  OVERLEAF_HISTORY_S3_ENDPOINT: http://garage:3900
  OVERLEAF_HISTORY_S3_PATH_STYLE: "true"
  OVERLEAF_HISTORY_S3_REGION: garage
  # Git integration: one git-bridge, its sibling is overleaf-0
  GIT_BRIDGE_ENABLED: "true"
  GIT_BRIDGE_HOST: 10.96.100.80      # the git-bridge Service's fixed ClusterIP, see 75-git-bridge.yaml
  GIT_BRIDGE_PORT: "8000"
```

**3. レプリカ**

```yaml title="70-overleaf.yaml" wrap theme={null}
apiVersion: v1
kind: Service
metadata:
  name: overleaf-hl
  namespace: overleaf
spec:
  clusterIP: None            # stable DNS per replica: overleaf-0.overleaf-hl, ...
  selector:
    app: overleaf-ha
  ports:
    - {name: http, port: 80}
    - {name: web, port: 3000}       # git-bridge API (sibling only)
    - {name: history, port: 3100}   # history-v1, used by git-bridge via V1_HISTORY_URL
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: overleaf
  namespace: overleaf
spec:
  serviceName: overleaf-hl
  replicas: 3
  # OrderedReady: overleaf-0 runs the migrations alone before the next replica starts
  podManagementPolicy: OrderedReady
  selector:
    matchLabels:
      app: overleaf-ha
  template:
    metadata:
      labels:
        app: overleaf-ha
    spec:
      terminationGracePeriodSeconds: 60
      # Keep the environment to the ConfigMap and Secrets: no REDIS_PORT=tcp://..., GIT_BRIDGE_PORT=tcp://...
      enableServiceLinks: false
      affinity:
        podAntiAffinity:            # one replica per node: each uses that node's Docker and disk
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchLabels:
                  app: overleaf-ha
              topologyKey: kubernetes.io/hostname
      containers:
        - name: sharelatex
          image: ghcr.io/ayaka-notes/overleaf-pro:6.3.2
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            # Each replica hands out history URLs with its own stable name, so git-bridge can reach them
            - name: V1_HISTORY_URL
              value: http://$(POD_NAME).overleaf-hl.overleaf.svc.cluster.local:3100/api
          envFrom:
            - configMapRef: {name: overleaf-env}
            - secretRef: {name: overleaf-secrets}
            - secretRef: {name: overleaf-s3}
          ports:
            - containerPort: 80
          readinessProbe:
            httpGet: {path: /status, port: 80}
            periodSeconds: 10
          resources:
            requests: {cpu: 500m, memory: 1536Mi}
            limits: {memory: 3Gi}
          volumeMounts:
            - {name: local, mountPath: /var/lib/overleaf}
            - {name: docker-sock, mountPath: /var/run/docker.sock}
      volumes:
        # Local disk for ephemeral files (compiles, output, uploads); the HOST_DIR_* paths are under it
        - name: local
          hostPath: {path: /srv/overleaf-ha, type: DirectoryOrCreate}
        - name: docker-sock
          hostPath: {path: /var/run/docker.sock, type: Socket}
```

* \*\*Deployment ではなく StatefulSet。\*\*各レプリカは、ロードバランサーの Cookie と git-bridge が参照する固定の名前（`overleaf-0`、`overleaf-1`、...）を持ちます。また `OrderedReady` により最初に `overleaf-0` だけが起動するため、データベースのマイグレーションを実行するのは 1 つのレプリカだけになります。
* \*\*ノードごとに 1 つのレプリカ。\*\*各レプリカは自身のノードの Docker を通じてコンパイルを開始し、それを自身のノードの `/srv/overleaf-ha` に保持します。
* \*\*レプリカごとの `V1_HISTORY_URL`。\*\*各レプリカは自身の名前を使って履歴リンクを発行するため、git-bridge がそれらに到達できます。

**4. git-bridge**

```yaml title="75-git-bridge.yaml" wrap theme={null}
apiVersion: v1
kind: Service
metadata:
  name: git-bridge
  namespace: overleaf
spec:
  # Fixed ClusterIP (inside the service CIDR): the sharelatex image's nginx proxies /git/ with
  # `resolver 127.0.0.11` (Docker's DNS), which does not exist in Kubernetes, so GIT_BRIDGE_HOST is this IP
  clusterIP: 10.96.100.80
  selector:
    app: git-bridge
  ports:
    - {name: http, port: 8000}
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: git-bridge
  namespace: overleaf
spec:
  serviceName: git-bridge
  replicas: 1
  selector:
    matchLabels:
      app: git-bridge
  template:
    metadata:
      labels:
        app: git-bridge
    spec:
      # Service "git-bridge" would inject GIT_BRIDGE_PORT=tcp://..., which git-bridge reads as its port
      enableServiceLinks: false
      containers:
        - name: git-bridge
          image: ghcr.io/ayaka-notes/overleaf-pro/git-bridge:6.3.2   # same version as the sharelatex image
          command: ["/server-pro-start.sh"]
          securityContext:
            runAsUser: 0
          env:
            - {name: GIT_BRIDGE_API_BASE_URL, value: "http://overleaf-0.overleaf-hl.overleaf.svc.cluster.local:3000/api/v0/"}
            - {name: GIT_BRIDGE_OAUTH2_SERVER, value: "http://overleaf-0.overleaf-hl.overleaf.svc.cluster.local"}
            - {name: GIT_BRIDGE_POSTBACK_BASE_URL, value: "http://git-bridge.overleaf.svc.cluster.local:8000"}
            - {name: GIT_BRIDGE_ROOT_DIR, value: /data/git-bridge}
          ports:
            - containerPort: 8000
          resources:
            requests: {cpu: 100m, memory: 256Mi}
            limits: {memory: 768Mi}
          volumeMounts:
            - {name: data, mountPath: /data/git-bridge}
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: [ReadWriteOnce]
        resources:
          requests:
            storage: 5Gi
```

`GIT_BRIDGE_HOST` が固定 IP アドレスである理由については、[Git 連携](https://ayakaleaf-pro.mintlify.site/ja/on-premises/configuration/kubernetes/integrations/git-integration.md) を参照してください。

**5. ロードバランサー**

HAProxy の設定は、Overleaf のサンプルに 5 つの変更を加えたものです。`/git/` と同様に `/project/<id>/mcp` を `overleaf-0` にルーティングすること（[MCP サーバー](https://ayakaleaf-pro.mintlify.site/ja/on-premises/configuration/kubernetes/integrations/mcp-server.md#several-replicas) を参照）、ポート `8080` での通常の HTTP（イメージは非 root ユーザーで実行されるため、containerd 上ではポート 80 にバインドできません）、クラスター DNS によるサーバーの検出（Pod の IP は再起動のたびに変わります）、すべてのノードが応答するための DaemonSet、そしてデフォルトの `roundrobin` の代わりに `balance leastconn` を使用すること（下記の Q\&A を参照）です。

```yaml title="80-haproxy.yaml" wrap theme={null}
apiVersion: v1
kind: ConfigMap
metadata:
  name: haproxy-config
  namespace: overleaf
data:
  haproxy.cfg: |
    global
      log stdout format raw local0 info

    resolvers kubedns
      parse-resolv-conf
      hold valid 10s

    defaults
      mode                    http
      # New sessions go to the replica with the fewest open connections (editors keep a WebSocket open)
      balance                 leastconn
      option                  httpchk HEAD /status
      http-check              expect status 200
      default-server          check resolvers kubedns init-addr none
      log                     global
      option                  httplog
      # Reroute to a different backend if the sticky one is down
      option                  redispatch 1
      retries                 3
      # Sticky session for 24h of inactivity -- compile output is deleted after 24h
      cookie                  server-pro-ha insert maxidle 24h
      timeout queue           1m
      timeout connect         15s
      timeout client          1m
      # Allow slow compiles -- hard-coded limit in clsi is 10min
      timeout server          10m
      # Disconnect the editor after 23h
      timeout tunnel          23h
      # Lower than NGINX_KEEPALIVE_TIMEOUT (65s) in the sharelatex container
      timeout http-keep-alive 60s

    listen overleaf
      bind :8080
      option forwardfor
      # When TLS ends in front of HAProxy, also pass:  http-request set-header X-Forwarded-Proto https
      # git requests go to the git-bridge sibling
      use-server overleaf-0 if { path_beg /git/ }
      # MCP clients send no cookie: keep compile, log and PDF download on one replica
      use-server overleaf-0 if { path_reg ^/project/[0-9a-f]{24}/mcp(/|$) }
      http-response add-header X-Served-By %s
      stats enable
      stats uri /haproxy
      server overleaf-0 overleaf-0.overleaf-hl.overleaf.svc.cluster.local:80 cookie overleaf-0
      server overleaf-1 overleaf-1.overleaf-hl.overleaf.svc.cluster.local:80 cookie overleaf-1
      server overleaf-2 overleaf-2.overleaf-hl.overleaf.svc.cluster.local:80 cookie overleaf-2
---
apiVersion: apps/v1
# DaemonSet: one HAProxy per node, so the NodePort answers on every node with externalTrafficPolicy
# Local. The cookie holds the replica name, so stickiness works whichever HAProxy a request hits.
kind: DaemonSet
metadata:
  name: haproxy
  namespace: overleaf
spec:
  selector:
    matchLabels:
      app: haproxy
  template:
    metadata:
      labels:
        app: haproxy
      annotations:
        config-hash: "1"   # bump to restart after editing the ConfigMap
    spec:
      containers:
        - name: haproxy
          image: haproxy:lts-alpine
          ports:
            - containerPort: 8080
          resources:
            requests: {cpu: 50m, memory: 32Mi}
            limits: {memory: 256Mi}
          volumeMounts:
            - {name: config, mountPath: /usr/local/etc/haproxy}
      volumes:
        - name: config
          configMap:
            name: haproxy-config
---
apiVersion: v1
kind: Service
metadata:
  name: haproxy
  namespace: overleaf
spec:
  type: NodePort
  externalTrafficPolicy: Local    # keep the client IP (no SNAT); only nodes running HAProxy answer
  selector:
    app: haproxy
  ports:
    - {name: http, port: 80, targetPort: 8080, nodePort: 30081}
```

```bash theme={null}
kubectl delete -f 40-overleaf.yaml --ignore-not-found
kubectl apply -f 60-config.yaml -f 70-overleaf.yaml -f 75-git-bridge.yaml -f 80-haproxy.yaml
kubectl -n overleaf rollout status statefulset/overleaf --timeout=20m
curl -sI http://192.0.2.10:30081/login | grep -i x-served-by
```

`externalTrafficPolicy: Local` により、ユーザーの IP アドレスが `X-Forwarded-For` に保持されます。

**6. TLS**

[TLS プロキシ](https://ayakaleaf-pro.mintlify.site/ja/on-premises/configuration/kubernetes/tls-proxy.md) の説明に従って HAProxy で HTTPS を終端し、`60-config.yaml` で `OVERLEAF_SITE_URL` を `https://` のアドレスに、`OVERLEAF_SECURE_COOKIE: "true"` を設定します。

### 期待される結果

それぞれ 2 vCPU と 4 GB のノード 3 台に 3 つのレプリカを配置し、MongoDB、Redis、Garage、git-bridge、HAProxy も同じノード上で動かしてテストしました。

* 12 人のユーザーが 600 ページの文書を同時にコンパイル：12 人全員がコンパイルして PDF を取得でき、レプリカあたり 4 人でした。1 ラウンドに 8 ～ 18 秒かかりました。各ノードでは少なくとも 1.3 GB のメモリが利用可能なまま保たれました。
* すべてのユーザーは 1 つのレプリカに留まります（Cookie `server-pro-ha`）。コンパイルしたレプリカから取得する必要がある PDF のダウンロードも同様です。エディターの WebSocket を含め、HTTPS でも同じです。
* レプリカが停止すると、HAProxy がそれをダウンと判定するまでの約 15 ～ 20 秒間、そのユーザーにはエラーが発生します。その後、ユーザーは別のレプリカに移動し、セッションが Redis にあるためログインしたままになります。

### Q\&A

> [accordion] なぜ `balance leastconn` を使うのですか？
>
> \*\*回答：\*\*Overleaf のサンプル（`roundrobin`、ノードごとに 1 つの HAProxy）では、テストで 12 人の新規ユーザーが 3 つのレプリカに 8、3、1 人と偏り、最も混雑したレプリカでは最も遅いユーザーが 29 秒待たされました。開いている接続が最も少ないレプリカを優先する `leastconn`（各エディターは WebSocket を開いたままにします）では、同じテストで 4、4、4 人、18 秒となりました。スティッキー性は変わりません。それは Cookie によって実現されています。

> [accordion] HAProxy の代わりに Ingress コントローラーを使用できますか？
>
> \*\*回答：\*\*はい。Cookie によって固定のレプリカにルーティングでき、WebSocket をサポートし、10 分のリクエスト時間と 50 MB のアップロードを許可し、keep-alive タイムアウトを 65 秒未満に保ち、`X-Forwarded-For` と `X-Forwarded-Proto` を送信し、`/git/` と `/project/<id>/mcp` を `overleaf-0` に送る場合は使用できます。すべてのリクエストを分散する Service ではなく、レプリカ自身の名前（`overleaf-N.overleaf-hl`）にルーティングしてください。

> [accordion] 4 つ目のレプリカを追加するには？
>
> \*\*回答：\*\*Docker と TeX Live イメージを備えたノードを追加し、`70-overleaf.yaml` で `replicas: 4` を設定し、HAProxy の設定に `server overleaf-3 ...` の行を追加します（HAProxy が再起動するように `config-hash` も更新してください）。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.