With a lock:
http://www.the-art-of-web.com/sql/upsert/
Discussion:
http://www.depesz.com/2012/06/10/why-is-upsert-so-complicated/
PostgreSQL doc.:
http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE