June 06, 2003

Forking hazardous to database connections

This is something I should have known but I don’t write forking servers very often, or use them close enough to the metal to care. But this time I was testing out the HTTP::Daemon interface for OpenInteract 2 (which is nearing beta, more soon). This allows us to run OpenInteract entirely standalone, as opposed to running it inside Apache using mod_perl or (god forbid) as a one-off CGI process. It’s not going to break any speed records, but it makes for a great OOBE and is also extremely useful for testing :-)

So the server started fine but I kept getting the following error:

DBD::Pg::st execute failed: server closed the connection unexpectedly

And I couldn't figure out what was going on. The same code worked fine in Apache, worked fine in CGI. So what's up?

The thing is, when the server starts up OI2 creates a database connection so we can read metadata from the tables and use it to create the persistence classes on the fly. (Using SPOPS, naturally.) This is done in the parent.

We then fork off a child to handle incoming requests. Children inherit all the parent data structures, but some 'live' structures (sockets, database connections, etc.) don't make the transition. So there was an entry in the datasource manager referring to the parent's live database connection, but there was no longer a connection there. Thus, the message. Forcibly closing all database connections before forking fixed the problem -- each child reconnected on its own and happily served up requests. But the googlespace on the message was no help at all, so here's a potential nudge...

Next: Trickles rolling downhill
Previous: JBoss Group forking