Postgres connection pooling is a nightmare, am I the only one?

marcus1987

New Member
Messages
66
Reaction score
0
Location
Sydney, NSW

Been running a side project on a $12 VPS with Postgres and I keep hitting max_connections errors the second traffic ticks up. Spent last weekend digging into pgbouncer configs and honestly half the docs read like they were written by someone who hates people.

The annoying part is everyone online just says "use pgbouncer lol" like it's one line. Then you get into transaction mode and suddenly your prepared statements explode, your session-level temp tables vanish, and your app throws weird "prepared statement already exists" errors that Google has like 3 results for, all from 2016.

I ended up going transaction mode with max_client_conn=200 and default_pool_size=20. Which feels completely made up. It works now but I have zero confidence it'll survive an actual traffic spike. My longest running query sits around 400ms so transaction mode was basically forced on me, session mode kept running out.

For people actually running pgbouncer in prod: do you just tune this once and forget it, or is it a constant moving target? And does anyone here bother with the newer native pooling in things like Supavisor or pgcat vs old faithful pgbouncer? Kinda tempted to rip out pgbouncer and try pgcat but I don't want to rebuild this whole thing for the fourth time this year.

Also mildly ranting: why is connection pooling still this painful in 2024. Feels like it should be a config flag by now.

LisaW_

New Member
Messages
53
Reaction score
0
Location
Edinburgh, UK

Wait you're running this on a $12 VPS? How much RAM does that thing even have? I tried Postgres on a cheap droplet last year and it fell over constantly, though looking back I think I just had no idea what I was doing with shared_buffers.

On the pgbouncer thing, I'm only a few weeks in myself so take this with a grain of salt, but the "prepared statement already exists" errors nearly broke me. What fixed it for me was setting max_prepared_statements in pgbouncer itself instead of letting the app handle it, but I'm on Django so your mileage may vary depending on your stack.

Also lol at "fourth time this year." I feel that in my bones. What made you land on default_pool_size=20? Just vibes or did you actually test it?

mike_t_2019

Member
Messages
60
Reaction score
0
Location
Leeds, UK

Not the OP but I'm running basically the same setup, 2GB box, Postgres plus a little provably-fair crash game backend on it. The RAM question is the real killer. I had shared_buffers at 512MB because some blog said "25% of RAM" and Postgres got OOM killed every time a whale showed up and hammered spins. Dropped it to 128MB and the random deaths just stopped. Counterintuitive as hell.

On the prepared statement thing, I actually went the opposite direction from you. Setting max_prepared_statements in pgbouncer works right up until transaction mode starts handing your connection to somebody else mid-query, then the bookkeeping gets weird. I just killed server-side prepares in the app layer instead, prepare: false in node-pg, prepare_threshold=None if you're on psycopg. Zero errors since. You lose a little perf on repeat queries but I'd rather lose 5% than debug "prepared statement already exists" at 3am while people are screaming about a stuck withdrawal.

default_pool_size=20 is pure vibes for me too, ngl. I bumped it to 30 over a bonus weekend, nothing exploded, so 30 it stays. Zero science involved. My spikes are nasty because they aren't gradual either. One big Plinko run and suddenly 400 people are in the same seed loop at once. And honestly a chunk of my traffic is people rage-quitting the regulated Ontario sites and coming offshore, so the load curve is basically tied to how insulting their promo terms are that week. Impossible to forecast.

Haven't touched pgcat. Read the migration docs, closed the tab, went outside. Fourth rebuild is where I draw the line lol. There's decent back and forth on pooling configs in the db section if you want more opinions than the 2016 StackOverflow graveyard:
https://websiteforums.info/forums/databases-and-apis.9/

And if you're tuning the box itself and not just the pooler, the server admin board has some VPS threads that stopped me from buying a bigger droplet for no reason:
https://websiteforums.info/forums/server-administration.3/

bananapeel42

New Member
Messages
53
Reaction score
0
Location
Manchester, UK

The "25% of RAM" shared_buffers thing isn't wrong so much as hilariously misapplied. That rule assumes a dedicated DB box, not a $12 VPS where Postgres is fighting your node process, nginx and the OS for the same 2GB. On a box like that, 512MB of shared_buffers is basically a loaded gun pointed at the OOM killer. So mike's 128MB isn't counterintuitive to me, it's just the correct number for that hardware.

On the actual question nobody's answering, the pgcat one: I moved a project off pgbouncer last year and it does handle transaction-mode prepared statements way more sanely. That part alone killed the 3am "prepared statement already exists" circus for good. But it's younger, the docs are thinner, and you're swapping battle-tested weirdness for newer weirdness. If pgbouncer is working and you're already on rebuild number four, stay put. The migration is easy, it's the debugging when something subtle breaks at 2am that eats you.

Also "pure vibes" pool sizing is how like 90% of prod actually runs and nobody will admit it publicly lol.

@mike_t_2019 did you actually try anything between 128 and 512? Genuinely curious if 128 was the real sweet spot or if anything under 512 would've stopped the deaths.

rk_designs

New Member
Messages
68
Reaction score
0
Location
Vancouver, BC

mike that crash game backend detail is what got me. I run a similar thing, small offshore skin, tiny player pool, and my OOM kills always lined up with a single whale session. Took me embarrassingly long to connect "big balance hits the table" with "box dies." Everyone in my discord kept swearing it was a leak in my node process. It was shared_buffers. So bananapeel42 is right, 128 on a 2GB box isn't counterintuitive, it's just the correct number. 512 is a number from a blog written for a guy with 32GB and nothing else running on the machine.

But I'll push back on the "stay put" advice. It's fine until it isn't. I sat on pgbouncer for like a year because it "worked," and what finally broke me wasn't prepared statements at all. It was reboots. Every time the host bounced the box, the pool would come up before Postgres was actually accepting connections and just sit there throwing errors until I manually restarted it. 3am, every time, and no retry config fixed it cleanly. So "it works now" and "it survives an unattended reboot" are two different claims and I only learned that the hard way. Switched the pool layer after that and haven't touched it since.

Also default_pool_size=20 is vibes for basically everyone, mine included. Nobody wants to admit they tuned a prod pool size by changing a number, watching graphs, and going "eh, looks fine."

Side note, I went Postgres after a Mongo detour a while back and would do it again, rambled about it here if anyone's bored
https://websiteforums.info/threads/ditched-mongodb-for-postgres-no-regrets.20

@LisaW_ what's that droplet actually packing RAM wise? Because under 2GB none of this tuning saves you, you just gotta move up a tier.

tallguy_tx

New Member
Messages
61
Reaction score
0
Location
Austin, TX

The reboot thing is what nobody warns you about and rk_designs is dead right that "works now" and "survives a 3am unattended reboot" are two completely different claims. I've lost count of how many mornings I've woken up to a dead pool because the box came back and pgbouncer beat postgres to the port. Added a retry wrapper, still had it happen. It's just a coin flip.

Venting for a sec since the $12 VPS keeps coming up: the reason I'm on trash hardware at all is that every host I'd actually want either won't touch the app once they figure out what it is, or boots me the second a processor flags it. So I'm stuck hand-tuning configs on a 2GB box where postgres is fighting nodee, nginx and the OS for scraps. If I could just rent a normal box from someone who didn't care, half this thread wouldn't exist. Nobody talks about that part because it's not a config problem.

mike_t_2019 killing server-side prepares is the move imo. I did the same and the "prepared statement already exists" circus just stopped. Everyone tries to fix it inside pgbouncer first because it feels like the right layer, but you're fighting the tool at that point.

And bananapeel42's line about swapping battle-tested weirdness for newer weirdness is the realest thing in here. Every time I've chased the shinier pooler I crawled back to pgbouncer two weekends later. Just get the retry right and walk away lol.

danielp77

New Member
Messages
51
Reaction score
0
Location
Melbourne, AU

The reboot thing is the one that'd get me. rk_designs, I'll push back a little though: a retry wrapper is the wrong layer. You want to stop the race from ever happening. If pgbouncer lives on the same box as postgres, systemd unit with After=postgresql.service and Requires=postgresql.service, plus an ExecStartPre that loops on pg_isready until it actually returns 0. pg_isready flips to success the second the postmaster opens the socket, which is exactly the second pgbouncer needs it. Did that about eight months ago, maybe a dozen reboots since, zero dead pool mornings. Retry wrappers treat the symptom, ordering kills the cause.

Now the thing nobody in this thread has said yet and it's the one that actually bit me: pgbouncer caches DNS forever. No TTL by default. So the day your DB host gets a new IP (failover, migration, host moves you to a new node at 4am), pgbouncer just keeps hammering the dead address and the logs tell you absolutely nothing useful. dns_nxdomain_ttl covers NXDOMAIN but NOT "the A record silently changed," which is the case that actually kills you. If you're pointing pgbouncer at a hostname instead of a raw IP, go read up on it before you need it. Cost me a whole evening staring at a pool that was "fine" but connecting to a ghost.

Also while we're on pgbouncer gotchas: set query_wait_timeout. Defaults to 120s. If you leave it there your clients just queue in silence and your app's own timeout fires first with a way more confusing error than the pool would've given you. 15-30s and you fail fast with something readable. mike_t_2019's prepare: false call is correct imo, that one's settled, but these two are the ones that ambush people after they think they're done.

@bananapeel42 since you've actually run pgcat in prod, does it resolve the host per-connection or does it cache like pgbouncer? That's honestly the one thing that'd make me do a fifth rebuild.

tallguy_tx

New Member
Messages
61
Reaction score
0
Location
Austin, TX

danielp77 the DNS thing is the one that actually got me and I never would've found it on my own. My host moved my box to a new node during "maintenance" (read: someone else's abuse complaint probably) and pgbouncer just sat there hammering the old IP for like six hours. Logs showed connection refused, nothing about DNS, nothing about a stale address. I'm sitting there checking firewall rules, restarting postgres, checking the wrong layer entirely. Now I point it at a raw IP and eat the 2am surprise when failover happens anyway. Pick your poison.

On the systemd ordering, works great until it doesn't. Half the cheap hosts I've been on, the unit isn't called postgresql.service, or postgres is running under some docker-compose nonsense the panel manages, and now you're writing an override for a service name that changes when the host migrates you. The pg_isready loop is the right idea though, I'll give you that. Retry wrapper inside the app is a bandaid. Just doesn't help when the box itself OOM kills postgres ten minutes after boot, which on 2GB is a real Tuesday.

Honestly the whole thread is making the case that the config was never the hard part. The hard part is running this on hardware and hosts you don't actually control, where you can't guarantee the service name, the IP, or that postgres is even alive at boot. bananapeel42 called it, you're just choosing which weirdness to live with.

mike_t_2019

Member
Messages
60
Reaction score
0
Location
Leeds, UK

Yeah I did, bananapeel42. Ran 256 for like two weeks, and it was better than 512 but still got the occasional OOM when a whale stacked a bunch of wins back to back. 128 was just where the random deaths stopped completely. So it wasn't some calculated sweet spot, it was the number where I stopped getting 3am "site is down" pings. 192 might be fine, I never bothered, at some point you just want the bleeding to stop and move on.

danielp77 the systemd ordering is clean in theory but tallguy_tx nailed why it falls apart in practice. Half these offshore boxes run postgres inside some panel-managed docker thing where the unit isn't even called postgresql.service, and the moment the host migrates you it's a different name again. So now your "correct" fix is a script that breaks silently on a Tuesday. The pg_isready loop is the right idea, I'll take that part, but hardcoding Requires=postgresql.service is the kind of thing that works until the box gets moved and then you're back to dead pool mornings wondering what changed.

The DNS thing though, that one got me. Never hit it yet but now I'm sitting here wondering if my current host has silently swapped nodes on me before and I just blamed it on the box. Probably did.

danielp77

New Member
Messages
51
Reaction score
0
Location
Melbourne, AU

Fair, the unit name thing is a real hole in my advice and mike_t_2019 is right that hardcoding Requires=postgresql.service is a Tuesday time bomb. But here's the thing, you don't actually need the unit name at all. Ditch the Requires= and just put the pg_isready loop in ExecStartPre pointed at the host and port pgbouncer is already configured to talk to. Docker, panel-managed, whatever, that loop still works because it doesn't care who started postgres, only that the socket answers. The ordering was the nice-to-have. The readiness gate is the actual fix. My bad for smashing them together like they were the same thing.

tallguy_tx six hours of connection refused with zero DNS signal in the logs is exactly the trap, and the part that makes it evil is pgbouncer only re-resolves on RELOAD. If nothing ever reloads it, it holds that stale A record forever. You bounce it manually and think you fixed it, when really you just reset the clock.

The cheap hack if you can't move off hostnames: cron a RELOAD against the admin console every few minutes. It's ugly and it's a workaround, but it caps your worst case at "a few minutes of stale IP" instead of six hours. Has anyone actually measured whether that's enough though? I set it up, felt clever, and then realized I have no idea what the reload interval should even be. Five minutes felt right. I have zero data behind that.

You must log in or register to reply here.