Database notifications

Using a database queue for distributing CPU intensive workload might be a good idea. But there is one problem. How consumers find that there is some work to be done? Of course, we can repeatedly check the database queue, but it consumes database resources. There is one simple solution. Database notifications.

After putting work to the queue, we can notify our workers via database (PostgreSQL syntax):

NOTIFY my_notification;

You can find more information in PostgreSQL documentation. Let’s focus on Java now.

Send event

pgNotifyService.notify("myEvent", "myEventParameter");


The listeners may be running on another machine in the network. Try to start several backends simultaneously. Notifications will be shared between backends 🙂

private final PgCallback eventListener = (eventParameter) -> {
 System.out.println("Event received, parameter: " + eventParameter);

Complete Java Example

package com.goodbackend;

import com.goodbackend.notify.PgCallback;
import com.goodbackend.notify.PgNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class ExampleNotify {

private PgNotifyService pgNotifyService;

private final String EVENT_NAME = "myEvent";

private final PgCallback eventListener = (eventParameter) -> {
//this code can be run in different java backend, different machine over network
System.out.println("Event received with parameter: " + eventParameter);

public void start() {
//send event notification. All java backend connected to the same database will receive this notification
pgNotifyService.notify("myEvent", "myEventParameter");
System.out.println("Event sent..");

private void init() {
//register listener

private void destroy() {
//unregister listener

public static void main(final String[] args) {, args);


Here you can download complete PostgreSQL java notification implementation.

One thought on “Database notifications”

Leave a Reply