# Deployment This page covers putting a Cylinder app into production: finding the webapps, WSGI and ASGI servers, reverse proxies, and serving more requests at once. [Operations](operations.md) covers reloading, logging, streaming, and sharing state between requests. A Cylinder app is a standard WSGI application, so anything that can host one can host it. ## Find the webapps without relying on the working directory A relative `site_dir` is resolved against the directory the process was started from. Started from another, it leads nowhere, and every request is a `500` whose log line names the path that is not a directory. In production, where a service manager chooses that directory, return an absolute path: ```python import pathlib WEBAPPS = pathlib.Path(__file__).parent / "my_webapps" def app_map(request): return WEBAPPS, "webapp1" ``` ## Expose the app for a WSGI server Servers such as Gunicorn and uWSGI import a module and look for the application object, so create it at module level: ```python # cylinder_main.py import logging import pathlib import cylinder WEBAPPS = pathlib.Path(__file__).parent / "my_webapps" def app_map(request): return WEBAPPS, "webapp1" app = cylinder.get_app(app_map, log_level=logging.INFO, request_id_header="X-Request-ID") ``` and point the server at it, for example `gunicorn cylinder_main:app`. Name a `request_id_header` only where [a proxy sets that header](operations.md#request-ids) on every request, as the nginx example below does, and leave the option out with no proxy. ## Behind a reverse proxy Behind nginx, a load balancer, or a CDN, the address and scheme the app sees are the proxy's. The proxy sends the original ones in headers such as `X-Forwarded-For`. Once the app is told to believe them, `request.remote_addr`, `request.scheme`, and `request.host` reflect the original request. Under Waitress, name the proxy and the headers it sets: ```python waitress.serve( app, host="127.0.0.1", port=8080, trusted_proxy="127.0.0.1", trusted_proxy_headers="x-forwarded-for x-forwarded-proto x-forwarded-host", ) ``` `trusted_proxy` is the address the proxy connects from. Waitress believes the headers only on connections from that address. From any other, and from every connection when no proxy is named, it removes them before the app sees them, which is why `ProxyFix` has no effect under Waitress. Under another server, wrap the app in Werkzeug's [`ProxyFix`](https://werkzeug.palletsprojects.com/en/stable/middleware/proxy_fix/): ```python from werkzeug.middleware.proxy_fix import ProxyFix app = ProxyFix(cylinder.get_app(app_map), x_for=1, x_proto=1, x_host=1) ``` Set each number to the count of proxies you actually run that set that header. Trusting a header that no proxy of yours sets lets a client forge it. ## Many slow requests at once A request holds a worker thread until its response is complete, including the time its handler spends waiting on a database or on another service. When every thread is busy, new requests wait for one. Waitress starts with 4 threads. If your handlers spend their time waiting, give it more: ```python waitress.serve(app, host="127.0.0.1", port=8080, threads=100, connection_limit=200) ``` - `threads` is how many requests can be in progress at once. A waiting thread costs little, so a few hundred is reasonable. - `connection_limit` is how many connections Waitress holds open. It defaults to 100, and it counts the idle connections that browsers keep open as well as requests in progress, so set it higher than `threads`. Connections past the limit wait in the operating system's queue until Waitress accepts them. **On Windows, keep `connection_limit` at 500 or below.** Waitress watches its connections with `select()`, which takes at most 512 sockets on Windows. With a higher limit, Waitress stops with `ValueError: too many file descriptors in select()` when more connections than that are idle at once. So one Waitress process on Windows serves about 500 requests at a time. On other systems the limit is 1024, and passing [`asyncore_use_poll=True`](https://docs.pylonsproject.org/projects/waitress/en/stable/arguments.html) removes it. Other servers have the same setting under another name: - Gunicorn starts with one worker that handles one request at a time. `gunicorn --threads 100 cylinder_main:app` gives it 100 threads. - Under [an ASGI server](#running-under-an-asgi-server), the threads belong to the adapter. It starts with 10 threads, and `WSGIMiddleware(app, workers=100)` gives it 100 threads. ## A process for each core More threads help handlers that wait. They do not help handlers that compute: in the standard build of Python, only one thread in a process runs Python code at a time, so a process uses one core however many threads it has. To use every core, run a process for each and share the requests among them. Gunicorn, which does not run on Windows, can do this by itself with `--workers 4`. Waitress runs as a single process, so start it once for each core, each on its own port: ```python # cylinder_main.py import sys import cylinder import waitress def main(): app = cylinder.get_app(app_map) waitress.serve(app, host="127.0.0.1", port=int(sys.argv[1])) def app_map(request): return "my_webapps", "webapp1" if __name__ == "__main__": main() ``` Run `python cylinder_main.py 8081`, and again for `8082`, `8083`, and `8084`. Then have nginx share the requests among them, with this in the `http` block of its configuration: ```nginx upstream cylinder { least_conn; server 127.0.0.1:8081; server 127.0.0.1:8082; server 127.0.0.1:8083; server 127.0.0.1:8084; } server { listen 80; location / { proxy_pass http://cylinder; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; # the app above names this header as its request ID, so a client must not be the one to set it proxy_set_header X-Request-ID $request_id; } } ``` `least_conn` sends each request to the process with the fewest in progress, which suits requests that take different lengths of time. The three headers are the ones to trust [behind a reverse proxy](#behind-a-reverse-proxy), so add the `trusted_proxy` settings from that section to the `waitress.serve()` call. A few things change with more than one process: - **Each process has its own memory.** A lock, a cache, or a counter in one is not seen by the others. [Thread safety](operations.md#thread-safety) has more on this. - **A handler edit still needs no restart.** Every process loads handler files as requests arrive. A change to a module needs every process restarted. - **Give each process its own log file.** Python's logging does not support several processes writing to one file, so put the port in the file name. - **nginx on Windows is limited.** nginx calls [its Windows build](https://nginx.org/en/docs/windows.html) a beta that should not be expected to scale, so a busy site is better served by a proxy on Linux. ## Running under an ASGI server Cylinder is a WSGI framework, and it also runs under any ASGI server through an adapter. That lets you use servers such as Uvicorn or Hypercorn, deploy to hosting that expects ASGI, and run a Cylinder site in the same process as async code. Install [a2wsgi](https://pypi.org/project/a2wsgi/) and wrap the app: ```python # cylinder_main.py import cylinder from a2wsgi import WSGIMiddleware def app_map(request): return "my_webapps", "webapp1" app = cylinder.get_app(app_map) asgi_app = WSGIMiddleware(app) ``` Then point the ASGI server at the wrapped app, for example `uvicorn cylinder_main:asgi_app`. The adapter runs each request on a worker thread, so nothing about your handlers changes. These were checked with a2wsgi 1.10 on Uvicorn 0.55: pages, form and JSON posts, `abort()` and redirects, static files with conditional and range requests, `HEAD`, responses streamed a piece at a time, and [cleanup callbacks](composition.md#cleaning-up-after-a-request). ### Next to async code The main reason to do this is to put a Cylinder site beside something that needs async, such as a WebSocket endpoint. Mount the wrapped app inside an async framework. With [Starlette](https://www.starlette.io/): ```python import cylinder from a2wsgi import WSGIMiddleware from starlette.applications import Starlette from starlette.routing import Mount, WebSocketRoute def app_map(request): return "my_webapps", "webapp1" async def echo(websocket): await websocket.accept() async for message in websocket.iter_text(): await websocket.send_text(f"echo: {message}") cylinder_app = cylinder.get_app(app_map) asgi_app = Starlette( routes=[ WebSocketRoute("/ws", echo), Mount("/", app=WSGIMiddleware(cylinder_app)), ] ) ``` `/ws` is handled by the async endpoint, and every other URL goes to Cylinder. ### What the adapter does not change - **Handlers are still synchronous.** A handler cannot be `async def`. Each request in progress occupies a worker thread, so this brings no extra concurrency. To serve more requests at once, give the adapter [more threads](#many-slow-requests-at-once). - **Cylinder itself does not handle WebSockets.** They belong to the async app you mount it in. - **A request body sent without a `Content-Length` arrives empty.** Werkzeug only reads a chunked body when the server says the input stream ends cleanly, and the adapter does not say so. It does end cleanly, so you can say it yourself: ```python def input_terminated(environ, start_response): environ["wsgi.input_terminated"] = True return app(environ, start_response) asgi_app = WSGIMiddleware(input_terminated) ``` Browsers and most clients send a `Content-Length`, so this only matters for clients that stream an upload. ## Static files in production Cylinder serves static files in chunks without reading them into memory. It [answers conditional and range requests](static-files.md#caching-and-partial-downloads), so browsers revalidate cheaply and downloads can resume. By default a browser checks with the server before reusing a cached file. For assets whose URL changes whenever their content does, set a long `Cache-Control` in the handler that serves them, as [Changing what is sent](static-files.md#changing-what-is-sent) shows. For a very busy site, serve static files from your proxy or a CDN. A range is read from its first byte, wherever in the file that is, so seeking around a file of several gigabytes costs no more than reading its start. ## Before you go live [Security](security.md) is a short checklist of things to confirm before an app faces the internet.