Friday, April 12, 2013

Show blocking Postgres processes and kill them

Have you ever had to kill your Postgres cluster because one hanging client starved other processes until most clients became unresponsive blocking on this one pesky process?

There is a very nice way to show currently blocked queries and the processes those are blocking on slightly adapted from this query posted on the Postgres mailing list. I suggest putting it into a view so you can easily access it when you need it:

CREATE VIEW blocking_procs AS
SELECT as blocking_pid,
    ka.usename as blocking_user,
    ka.current_query as blocking_query, as blocked_pid,
    a.usename as blocked_user, 
    a.current_query as blocked_query, 
    to_char(age(now(), a.query_start),'HH24h:MIm:SSs') as age
FROM pg_catalog.pg_locks bl
    JOIN pg_catalog.pg_stat_activity a 
        ON = a.procpid
    JOIN pg_catalog.pg_locks kl 
        ON bl.locktype = kl.locktype
        and bl.database is not distinct from kl.database
        and bl.relation is not distinct from kl.relation
        and is not distinct from
        and bl.tuple is not distinct from kl.tuple
        and bl.virtualxid is not distinct from kl.virtualxid
        and bl.transactionid is not distinct from kl.transactionid
        and bl.classid is not distinct from kl.classid
        and bl.objid is not distinct from kl.objid
        and bl.objsubid is not distinct from kl.objsubid
        and <> 
    JOIN pg_catalog.pg_stat_activity ka 
        ON = ka.procpid
WHERE kl.granted and not bl.granted
ORDER BY a.query_start;

How to test the query on a testing server (not your production DB server)

Connect to your database open a transaction and manually lock a table:

LOCK your_table;

Leave the transaction and connection open.

Open another client that accesses that data:

# SELECT count(*) from your_table;

It now should be blocked.

View the currently held locks with a third client:

# SELECT * FROM blocking_procs;
blocking_pid   | 25842
blocking_user  | postgres
blocking_query | in transaction
blocked_pid    | 25844
blocked_user   | postgres
blocked_query  | SELECT COUNT(*) FROM "your_table"
age            | 00h:00m:23s

It's now possible to kill the offending process holding the lock using:

# SELECT pg_terminate_backend(25842);

This will kill the connection where you've set the lock and the open transaction is rolled back but it seems to leave everything else intact. The second client should now get the response from the server.

Tested on Postgres 9.1.

Sunday, March 24, 2013

Android apps and databases

As a web developer I was always intrigued to learn more about mobile app development. Unfortunately, my early attempts with my first smartphone - a Palm Pre running Web OS - suffered from company politics and I decided to stop developing apps for an awesome but abandoned platform. So here I am - roughly two years later - contemplating to buy a new smartphone.

While my Pre Plus is still working the lack of apps and slow demise of the underpowered hardware became too annoying. For a change, I didn't want to go with an underdog and ended up ordering a Motorola Razr i. While waiting for the shipment to arrive I started writing my first app for Android 4. The first lesson I learnt is that looking after a wailing baby leaves little time and less focus to get anything done on top of that.

Then there's Java - an old acquaintance from more than a decade ago. I never liked it, never hated it either, but I've always been put off by the enterprise nature of everything surrounding it. It's also one of the few languages that requires an IDE. After a few hours trying to put together the simplest Android app with vim and a console and failing to figure out simple things like where to import classes from I installed Eclipse.

I must admit Eclipse does not suck as much as it used to (as in the room's light bulbs do not dim anymore when you fire it up). With Eclipse things got more fluent and I especially liked the way the UI designer works and keeps you at a safe distance from XML. I must admit I haven't used a visual UI designer that actually worked since Delphi 4. Everything was going well until it came to persisting structured data. You would assume that in 2013 a smartphone with its abundance of sensors has an OS that makes aggregating and sharing that data as easy as possible. So how do you store structured data? Easy: Just use sqlite and implement DAOs for your tables. It's as easy as that. Seriously, I feel like someone has given me the latest Makita multitool and just a bunch of nails and expects me to build some awesome stuff with that.

Maybe I spent too much time with web frameworks like TurboGears and Django but reinventing (shitty) ORMs for every app I write is not something I want to do in my free time. Scratch that: I don't want to do that at all. And this is just for storing data locally. I probably want to sync that data to the cloud, a web application or other devices later on.

Maybe I should just save data to a remote web application? The question then is: Why bother with a mobile app at all? Sounds like pouring your time into making one web app work well with mobile devices is time better spent than implementing about four different apps for the currently relevant mobile platforms. Plus this gives you the option to use your favorite language and best available technology to implement the web app.

That sounds like a good idea until you want to make the app work in offline mode or with low latency in the outback of Brandenburg (make that Wyoming if you're in the US). Then building a dedicated app is the only option but can be limited to the features that are relevant in these usage scenarios, e.g. gathering data like miles walked through the woods or number of diapers changed can be logged in the mobile app but displaying statistics can be restricted to the web application. That's what apps like Baby Connect seem to do (yes, that's the most interesting app for me right now). I'm just amazed on what kind of libraries these things are built on.

IMHO it doesn't have to be that complicated. Android could sync CSV data to a Google Drive spreadsheet which would make sharing data with different devices easy and wouldn't require a dedicated web application.

One could also let apps connect to a pre-installed SQL database running on the device and make a light-weight ORM part of the standard library. This wouldn't solve the problem of syncing the data to a remote server but wouldn't require ridiculous amounts of code to solve simple problems.

Ultimately I could also imagine having a distributed database node (let's say Riak) on the device and which would allow syncing with remote nodes.

Do I ask for too much? Maybe that's already possible in Android and I just didn't get it? Or maybe the grass is greener on the other side and these things have been solved in iOS, Windows Mobile or BlackBerry?

Wednesday, January 19, 2011

Postgres deadlock debugging

Update:  There is a better way to view Postgres locks and blocking chains.

Found a nice SQL query for debugging deadlocks hidden deep in the postgres docs:

substr(pg_stat_activity.current_query,1,40) as current_query,
age(now(),pg_stat_activity.query_start) as "age",
from pg_stat_activity,pg_locks
left outer join pg_class on (pg_locks.relation = pg_class.oid)
where order by query_start;

Tuesday, August 10, 2010

Cyberpunk coding fonts - monofur on Linux

If you ever grow weary of Inconsolata, try monofur. Adding Truetype fonts to Linux is a piece of cake with fontypython. Just install it via Synaptic or apt-get.

Sunday, August 8, 2010

Tuesday, May 11, 2010