Deployment
How to get your app running in production
Before deploy
Before deployment, we’ve found an issue in production with the new content security policy headers. Basically, you need to add wss://... and your domain to the :content_security_policy default_src array, like below.
config :my_app, :content_security_policy, %{
default_src: [
....
"wss://yourdomain.com",
"wss://yourdomain.com/live/websocket"
]
}
Read more:
Removing CSP
If you don’t care about content security policies, you can remove this config and then in router.exs change:
# Change this:
plug(:put_secure_browser_headers, %{
"content-security-policy" =>
ContentSecurityPolicy.serialize(
struct(ContentSecurityPolicy.Policy, PetalPro.config(:content_security_policy))
)
})
# To this:
plug :put_secure_browser_headers
Faker dependency and the Landing Page
The landing page and seeders use Faker, so mix.exs already pulls it in for every environment ({:faker, "~> 0.17"}). Nothing to change for prod. Once you’ve replaced the landing page you can scope it back to only: [:test, :dev] if nothing else in prod uses it.
A word on environment variables
In production, Petal Pro requires the following environment variables to be set:
-
SECRET_KEY_BASE -
DATABASE_URL -
PHX_HOST -
PORT -
RESEND_API_KEY— transactional email via Resend
Optional but recommended:
-
SENTRY_DSN— error tracking auto-activates when set -
MCP_ADMIN_TOKEN— bearer token for the admin MCP API
If you’re deploying to Fly.io, the core variables should be automatically taken care of. However, if you’re testing prod on your dev machine or using a different deployment mechanism, you’ll need to set these yourself.
SECRET_KEY_BASE and DATABASE_URL are secrets and need to be protected. Follow best practices for managing secrets on the platform you are deploying to.
Docker
Petal Pro v4 ships a production-ready Dockerfile in the repo root. It uses a multi-stage build: a builder stage compiles the Elixir release (including npm asset pipeline), and a lean Debian runner stage contains only the compiled release.
Build the image
docker build -t myapp .
Run locally
docker run -p 4000:4000 \
-e SECRET_KEY_BASE="your_secret_key_base" \
-e DATABASE_URL="ecto://user:pass@host/db" \
-e PHX_HOST="localhost" \
-e PORT="4000" \
-e RESEND_API_KEY="re_..." \
myapp
Key runtime environment variables
| Variable | Required | Notes |
|---|---|---|
SECRET_KEY_BASE |
Yes |
Generate with mix phx.gen.secret |
DATABASE_URL |
Yes | PostgreSQL connection string |
PHX_HOST |
Yes |
Your domain (no https://) |
PORT |
Yes |
Usually 4000 |
RESEND_API_KEY |
Yes | Transactional email |
SENTRY_DSN |
No | Error tracking |
MCP_ADMIN_TOKEN |
No | Admin AI tool access |
CLIENT_IP_HEADER |
No |
Unset by default. A header your proxy overwrites on every request: fly-client-ip on Fly, cf-connecting-ip behind Cloudflare |
TRUSTED_PROXY_HOPS |
No |
Defaults to 0. How many trailing x-forwarded-for entries your proxies append (1 behind a single nginx or Caddy). Must be a whole number, or the release fails to boot |
FORCE_SSL |
No |
On in prod when unset, true or 1. Any other value turns off the https redirect, HSTS and Secure cookies |
The last three arrived in 4.5.0. Behind a proxy, set CLIENT_IP_HEADER or TRUSTED_PROXY_HOPS, or every sign-in records the proxy’s address, and since 4.5.2 browser and passkey sign-in have no limit per address (see Limits per Address). Step 5 of the 4.4.0 to 4.5.0 upgrade guide covers when to set each one.
The Dockerfile targets Elixir 1.19.5 / OTP 27.3.4 on Debian Bookworm slim. To change versions, update the ARG lines at the top of the file (Pro needs Elixir 1.19 or later).
Deployment with Fly.io
To deploy to Fly.io, use the following guide: Deploy to Fly.io
Error Tracking
Petal Pro uses Sentry for error tracking. It auto-activates when the SENTRY_DSN environment variable is set — no code changes required.
How It Works
Sentry is configured in config/runtime.exs:
if sentry_dsn = System.get_env("SENTRY_DSN") do
config :sentry, dsn: sentry_dsn
end
A Sentry logger handler is attached at application startup, which captures errors logged via Elixir’s Logger:
:logger.add_handler(:sentry_handler, Sentry.LoggerHandler, %{
config: %{metadata: [:file, :line]}
})
In development, if SENTRY_DSN is not set, errors go to your local logs and nothing is sent to Sentry. Set the DSN in dev if you want to test the integration.
Setup
1. Create a Sentry project
- Sign up or log in at sentry.io
- Create a new project — select Elixir as the platform
-
Copy the DSN from the project settings (looks like
https://abc123@o123456.ingest.sentry.io/789)
2. Set the DSN in production
Fly.io:
fly secrets set SENTRY_DSN=https://your-dsn@sentry.io/project-id
Other platforms: Set SENTRY_DSN as an environment variable in your deployment configuration.
That’s it. Deploy and Sentry will start receiving errors.
What Gets Captured Automatically
- Unhandled exceptions in controllers and LiveViews
- LiveView crash reports
-
Any
Logger.error/2orLogger.warning/2calls - Errors from Oban workers
- Anything that bubbles up through the OTP supervision tree
-
Request context on every event: URL, method, headers and the client address (the same one sign-ins record, so set
CLIENT_IP_HEADERorTRUSTED_PROXY_HOPSbehind a proxy). Since 4.5.0 this comes fromPetalProWeb.SentryContextPlug, which masks sign-in secrets first: passwords, the TOTP code, the PIN andsign_in_token, passkey assertions, the OAuthcodeandstate, and the token in confirm, reset-password and confirm-email links. If you care about what goes to Sentry, that’s the plug to tune.
Adding Custom Context
Setting user context
Call this when a user authenticates to attach their identity to all subsequent errors in that process:
Sentry.Context.set_user_context(%{
id: user.id,
email: user.email,
name: user.name
})
A good place to do this is in your auth hooks or controller plugs.
Capturing custom messages
For non-exception events you want to track:
Sentry.capture_message("Billing webhook received unexpected event type",
level: :warning,
extra: %{event_type: event_type, payload: payload}
)
Capturing exceptions manually
try do
risky_operation()
rescue
e ->
Sentry.capture_exception(e, stacktrace: __STACKTRACE__, extra: %{context: "my_function"})
reraise e, __STACKTRACE__
end
Verifying It Works
The easiest test is to trigger an error from IEx on your production instance and confirm it appears in Sentry within a minute or two.
From a Fly.io console:
fly ssh console --app your-app-name
/app/bin/your_app remote
Then in IEx:
Sentry.capture_message("Test error from IEx", level: :error)
Check your Sentry project — the event should appear shortly.
You can also check that the DSN is loaded correctly:
Application.get_env(:sentry, :dsn)
If this returns nil, SENTRY_DSN isn’t set in the environment.
Environment Behavior
| Environment |
SENTRY_DSN set? |
Behavior |
|---|---|---|
| Production | Yes | Errors sent to Sentry |
| Production | No | Errors logged only (misconfiguration — set the DSN) |
| Dev/Test | No | Errors logged locally, nothing sent to Sentry |
| Dev/Test | Yes | Errors sent to Sentry (useful for testing the integration) |
Rate Limiting
Petal Pro uses Hammer with an ETS backend for rate limiting. It’s applied to the endpoints in the table below out of the box and is straightforward to add anywhere else.
What’s Rate Limited by Default
| What | Key | Limit | What starts it again | A refusal |
|---|---|---|---|---|
Browser password sign-in (POST /auth/sign-in), per account |
The account (web_sign_in_account:<user_id>). An email with no account: web_sign_in_unknown:<email> |
10 per 10 minutes | A correct password counted on it, and a password reset | Back to the sign-in page with a flash |
| Browser password sign-in, from a browser that has signed in to the account before |
The browser’s cookie (web_sign_in_device:<nonce>) |
10 per 10 minutes, then counted on the account like any other browser | Each successful sign-in gives the browser a new nonce, so a new count | Back to the sign-in page with a flash |
| Browser password sign-in, per address (only with a client address set, see below) |
Client address (web_sign_in:<ip>) |
100 failures per 10 minutes, across every account | A successful sign-in gives back its own hit, never more | Back to the sign-in page with a flash |
API sign-in (POST /api/sign-in) |
Client address (api_sign_in:<ip>) |
5 per minute | Nothing | A 429 |
| API sign-in, per account |
The account (api_sign_in_account:<user_id>). An email with no account: api_sign_in_unknown:<email> |
10 per 10 minutes | A successful sign-in, and a password reset | A 429 |
API registration (POST /api/register) |
Client address (api_register:<ip>) |
3 per hour | Nothing | A 429 |
Passkey sign-in (POST /auth/sign-in/passkey, only with a client address set) |
Client address (passkey_auth:<ip>) |
10 per minute | Nothing | Back to the sign-in page with a flash |
Two-factor code, TOTP or backup (POST /app/users/totp) |
User (totp:<user_id>) |
5 per 5 minutes | A correct code | A 429 and the code form |
| Passwordless pin request, first send and “Resend” |
The account (passwordless_pin:<user_id>) |
3 per 10 minutes | Nothing | A message on the form |
| Password reset request |
The account (password_reset:<user_id>). An email with no account: password_reset_unknown:<email> |
3 per 10 minutes | Nothing | Back to the sign-in page with a flash |
Confirmation email resend, the browser form and POST /api/send-instructions together |
The account (confirm_instructions:<user_id>). An email with no account: confirm_instructions_unknown:<email> |
3 per 10 minutes | Nothing | Browser: back to the home page with a flash. API: a 429 |
| Feedback form |
User (feedback_user:<user_id>) |
10 per day | Nothing | A flash |
| Admin chat |
Admin user (admin_chat:<user_id>) |
10 messages per minute | Nothing | A message in the chat |
In the keys:
-
<user_id>is the account the email belongs to, found through the database. See Counted on the Account. -
<email>is only used when no account matches. It’s the email trimmed and lower-cased by the database, orsha256:and a hash of it when that’s longer than 320 bytes, so a caller can’t fill the table with long keys. -
<ip>is the client addressPetalProWeb.ClientIpresolves, throughPetalProWeb.ClientIp.rate_limit_key/2. An IPv4 address is used as it is. An IPv6 address is cut to its /64 (2001:db8:1:2::/64), the block a provider usually gives one customer, so one subscriber doesn’t get a fresh count from each of its addresses. An IPv4 address written as IPv6 (IPv4-mapped or NAT64) counts as the IPv4 address it carries.last_signed_in_ipand the audit log still record the full address.
“Client address” is the same address sign-ins record in last_signed_in_ip. Since 4.5.1 the address limits use it. Before that they keyed on conn.remote_ip, which behind a proxy is the proxy, so every visitor shared one budget. It only follows the visitor once you set CLIENT_IP_HEADER (fly-client-ip on Fly) or TRUSTED_PROXY_HOPS. With neither set it is still the connection peer. See Limits per Address.
Every request counts, right or wrong, and it’s counted before the password, pin or code is compared, so guesses sent in parallel can’t all slip past one check. A refused request counts too. A few details worth knowing:
- Browser sign-in is new in 4.5.2, and counts inside the action rather than in a plug, because which count a request uses depends on the account and the browser. A post with no email or password, or with a list where text should be, gets “Invalid email or password” and isn’t counted.
-
API sign-in checks the address limit first, then the account limit. A request with no
emailparam only meets the address limit. -
Passkeys only count the sign-in attempt. The challenge (
GET /auth/passkey/challenge) is asked for on every sign-in page load and isn’t limited, since 4.5.1. -
Passwordless pins are limited twice. Each pin allows three guesses (counted atomically by
UserPin.check_pin/3) and expires after 10 minutes, and a new pin, resend included, goes through the request limit above. That caps an account at nine guesses per ten-minute window, since 4.5.1. 4.5.2 closes a way round it: on some databases the same account could be reached under another spelling of its email, each with a count of its own. On 4.5.2 the count is kept on the account. - Two-factor is keyed on the user, so it needs no proxy setting. Getting to the code form takes the first sign-in step (the password, a passwordless pin or an OAuth login), so only someone who got past that can use up the five tries. It’s new in 4.5.1.
- Confirmation resends are new in 4.5.2. The browser form and the API share one count, and an email with no account, or one already confirmed, spends it the same way. The first email, sent at registration, isn’t counted.
What a refusal looks like:
- Browser password sign-in: a redirect back to the sign-in page with “Too many attempts. Please try again later.” The answer is the same for an email with no account, so a refusal doesn’t show which emails have accounts.
-
API sign-in, registration and Send Instructions: a 429 with
{"errors": {"detail": "Too many requests"}}. - Passkey sign-in: a redirect back to the sign-in page with a “Too many attempts. Please try again later.” flash. In 4.5.0 and earlier this was a 500.
- Two-factor: a 429 that renders the code form with “Too many attempts. Please try again later.”
- Passwordless pin request: the form shows “Too many attempts. Please try again later.” and no pin is sent.
- Password reset request: a redirect to the sign-in page with a “Too many attempts. Please try again later.” flash.
- Confirmation resend in the browser: a redirect to the home page with a “Too many attempts. Please try again later.” flash.
The counts live in ETS on each machine, so with two machines a caller gets twice the number, and a deploy starts every count again. Windows are also fixed and line up with the clock, so a caller who straddles a window boundary can get up to twice a limit in a short burst.
Counted on the Account
Since 4.5.2, a limit that protects an account is counted on the account’s id, found through the database with the same lookup the sign-in uses, never on the text that was typed. That covers browser and API sign-in, pins, password reset requests and confirmation resends.
The reason: the email column is citext, so Postgres decides which spellings are one email, and it doesn’t always agree with Elixir’s String.downcase/1. On common database setups a few spellings that String.downcase/1 keeps apart find the same account, and a count kept on the text gave each of them a fresh budget. In 4.5.1 that applied to the pin and API sign-in limits. The password reset limit was keyed on the text exactly as typed, so capitals alone got round it.
An email that matches no account is counted on its text, folded by the database (SELECT lower($1::text)) the same way the column compares it. Every request does that fold, known email or not, so a refusal looks the same and takes the same work for both. Your own limits should follow the same rule, see Adding Rate Limiting to a Controller.
Trusted Browsers
A count on an account could be turned against its owner: anyone who knows an email could keep the count full. So when a password sign-in works, the browser gets a cookie, _petal_pro_web_sign_in_device (encrypted, HttpOnly, SameSite=Lax, one year, Secure over https). A browser that holds it for an account is counted on its own first, with ten tries per ten minutes, and once those are used up it’s counted like any other browser. So a stranger who uses up the account’s count can only block browsers that have never signed in to it, and someone who mistypes on their own laptop is never worse off than in a private window.
- The cookie only picks which count a request uses. It grants nothing else.
- It remembers up to five accounts, newest first, so a shared computer works for a few people.
- Each successful sign-in writes a new entry for the account, with a count of its own.
- An entry stops counting as soon as the account’s password changes, so a password change or reset ends the trust of every browser at once.
- Only the password form sets it. People who sign in with OAuth, a passkey or a pin don’t get one, and don’t need one, because those doors don’t use the password count.
-
Rotating
secret_key_basemakes every cookie unreadable. Nothing breaks: browsers are counted like new ones until their next sign-in.
List it in your cookie policy as a security cookie. A password reset also starts the account’s browser and API sign-in counts again, so someone who has just proved they own the email isn’t refused.
Limits per Address
Four limits count per address. Two of them, browser password sign-in (100 failed tries per ten minutes from one address, across every account) and passkey sign-in (10 a minute), only apply since 4.5.2 once the app knows the client’s address. The API sign-in and API registration limits apply either way, see below. That means CLIENT_IP_HEADER or TRUSTED_PROXY_HOPS is set, and the request’s address came from it. A request whose header was missing, or that reached the app’s port without going through the proxy, falls back to the peer and is left out.
-
With neither setting made, every visitor behind your proxy has the proxy’s address, and one caller could use either count up for all of them, so both are off. The app logs one warning per boot when a sign-in arrives with proxy headers:
Browser sign-in has no per-address limit: proxy headers are present but neither CLIENT_IP_HEADER nor TRUSTED_PROXY_HOPS is set. See DEPLOYMENT.md.A script trying one password against many accounts is then only limited per account. - The browser sign-in count is failures only. A sign-in that works gives back its own hit, never more, so signing in to your own account between guesses doesn’t clear it, and an office behind one address isn’t refused for its own sign-ins.
- Some sign-ins skip it. A browser trusted for the account skips it while its own count lasts. So does the sign-in straight after registration, so a full address count can’t strand someone who has just registered.
- The API sign-in (5 a minute) and API registration (3 an hour) limits still apply with no setting, as one budget for your whole app, the same as in 4.5.1.
-
A wrong setting is worse than none. A hop count too low can land on one of your proxies, and the count is then shared by every visitor who isn’t trusted. A hop count too high, or a header your proxy doesn’t overwrite, lets a caller pick their own address. Check
last_signed_in_ipon your own user shows your public address.
What Isn’t Limited
-
Browser registration (
/auth/register), and the account passwordless sign-in creates for a new email. Each sends one email to the address it was given. Resends are limited; the first email isn’t. - Email a signed-in user can send by changing their email address or inviting people to an org.
- The current-password check on the settings pages, for someone who already has a signed-in session.
Put a limit in front of those yourself if your app is a target, or use your proxy’s rate limiting.
How It Works
The rate limiter is defined in lib/petal_pro/rate_limiter.ex:
defmodule PetalPro.RateLimiter do
use Hammer, backend: :ets
end
It starts as part of the application supervision tree. All state lives in ETS — no Redis or external dependency needed.
Call hit/3 with a key, time window (in milliseconds), and request limit:
PetalPro.RateLimiter.hit("some_key", :timer.minutes(1), 10)
# => {:allow, count} | {:deny, retry_after_ms}
Adding Rate Limiting to a Controller
Use a plug that calls hit/3 and halts on denial:
defmodule MyAppWeb.MyController do
use MyAppWeb, :controller
plug :rate_limit when action in [:create]
defp rate_limit(conn, _opts) do
# "my_action:<client ip>", the same address sign-ins record. It honours
# CLIENT_IP_HEADER / TRUSTED_PROXY_HOPS, so behind Fly or nginx you count the visitor
# and not your proxy.
key = PetalProWeb.ClientIp.rate_limit_key(conn, "my_action")
case PetalPro.RateLimiter.hit(key, to_timeout(minute: 1), 10) do
{:allow, _count} ->
conn
{:deny, _retry_after} ->
conn
|> put_status(:too_many_requests)
|> json(%{errors: %{detail: "Too many requests"}})
|> halt()
end
end
end
Don’t key a limit on conn.remote_ip. Behind a proxy that’s the proxy’s address, so every visitor shares one bucket. Pro’s own address limits use rate_limit_key/2 since 4.5.1. If you copied one of the 4.5.0 plugs, swap its conn.remote_ip line for it.
Key naming
Use a descriptive prefix with a per-user or per-IP discriminator:
# Per IP
PetalProWeb.ClientIp.rate_limit_key(conn, "sign_in")
# Per user
"api:#{user_id}"
# Per account, found by the email that was typed (good for password reset)
"reset:#{user.id}"
A limit that protects an account goes on the account’s id, never on the email as typed, even trimmed and lower-cased: the database treats some spellings as one email that String.downcase/1 doesn’t (see Counted on the Account). Look the account up first, the way the sign-in does, and for an email with no account count its text the way the database folds it, so a refusal doesn’t show which emails have accounts:
user = PetalPro.Accounts.get_user_by_email(String.trim(email))
key =
case user do
%PetalPro.Accounts.User{id: id} -> "reset:" <> id
nil -> "reset_unknown:" <> limit_email(email)
end
# The same helper as in Pro's forgot-password LiveView
defp limit_email(email) do
%{rows: [[folded]]} = PetalPro.Repo.query!("SELECT lower($1::text)", [String.trim(email)])
if byte_size(folded) <= 320 do
folded
else
"sha256:" <> Base.url_encode64(:crypto.hash(:sha256, folded), padding: false)
end
end
Adding Rate Limiting to a LiveView
LiveViews don’t have plugs, so check the limit inside the event handler:
def handle_event("submit", _params, socket) do
user_id = socket.assigns.current_user.id
case PetalPro.RateLimiter.hit("my_form:#{user_id}", to_timeout(minute: 1), 5) do
{:allow, _count} ->
# proceed
{:noreply, do_the_thing(socket)}
{:deny, _retry_after} ->
{:noreply, put_flash(socket, :error, "You're doing that too fast. Try again in a minute.")}
end
end
Time Windows
Use to_timeout/1 (available in Phoenix controllers) or :timer functions:
to_timeout(minute: 1) # 60_000 ms
to_timeout(hour: 1) # 3_600_000 ms
:timer.minutes(1) # same as above, works anywhere
:timer.hours(1)
Response When Rate Limited
API controllers return HTTP 429 with a JSON body:
{"errors": {"detail": "Too many requests"}}
A browser controller should answer the way its other failures do. Pro’s two-factor form re-renders with a 429 and an error, and browser and passkey sign-in redirect to the sign-in page with a flash.
LiveViews should use put_flash/3 to show an error message — there’s no HTTP status code to set.
Clearing a Rate Limit
In dev, restart your server. ETS is in-memory and doesn’t persist across restarts. That’s the fastest way to clear all limits. In production a deploy or a restart does the same.
If you need to clear a specific key without restarting, reset its count to zero from IEx, passing the same window the call site uses:
PetalPro.RateLimiter.set("api_sign_in:127.0.0.1", to_timeout(minute: 1), 0)
To let a locked-out user back in to password sign-in, clear the account’s browser and API counts in a remote IEx shell (on Fly, fly ssh console then /app/bin/your_app remote). The counts are per machine, so do it on each one:
user = PetalPro.Accounts.get_user_by_email("someone@example.com")
PetalPro.RateLimiter.set("web_sign_in_account:" <> user.id, to_timeout(minute: 10), 0)
PetalPro.RateLimiter.set("api_sign_in_account:" <> user.id, to_timeout(minute: 10), 0)
Or ask the user to reset their password, which does the same on the machine that serves the reset. Browser sign-in, two-factor and the API account limit also clear their own counts in code when a sign-in succeeds.
Configuration
There’s no central config file for limits — each call site defines its own window and limit inline. This is intentional: different actions have different risk profiles, and collocating the limit with the code that enforces it makes it easier to reason about.
To change a limit, find the RateLimiter.hit/3 call and update the second (window) or third (max requests) argument. Browser sign-in keeps its numbers in module attributes at the top of PetalProWeb.UserSessionController (@window, @attempt_limit and @address_limit). If you change @window, change the window in clear_sign_in_limit/1 in PetalProWeb.UserResetPasswordLive to match, and use the new one when you clear a count from IEx. Hammer files each count under its window length, so clearing with a different one clears a count nothing reads. The API account limit has its own @account_window in PetalProApi.SessionController, which the same helper clears.