Do you need Redis? PostgreSQL does queuing, locking, and pub/sub

There’s a tried-and-true architecture that I’ve seen many times for supporting your web services and applications:

  • PostgreSQL for data storage
  • Redis for coordinating background job queues (and some limited atomic operations)

Redis is fantastic, but what if I told you that its most common use cases for this stack could actually be achieved using only PostgreSQL?

Use Case 1: Job Queuing

Perhaps the most common use of Redis I’ve seen is to coordinate dispatching of jobs from your web service to a pool of background workers. The concept is that you’d like to record the desire for some background job to be performed (perhaps with some input data) and to ensure that only one of your many background workers will pick it up. Redis helps with this because it provides a rich set of atomic operations for its data structures.

But since the introduction of version 9.5, PostgreSQL has a SKIP LOCKED option for the SELECT ... FOR ...statement (here’s the documentation). When this option is specified, PostgreSQL will just ignore any rows that would require waiting for a lock to be released.

Consider this example from the perspective of a background worker:


BEGIN;

WITH job AS (
  SELECT
    id
  FROM
    jobs
  WHERE
    status='pending'
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE
  jobs
SET
  status='running'
WHERE
  jobs.id=job.id
RETURNING
  jobs.*;
  
COMMIT;

By specifying FOR UPDATE SKIP LOCKED, a row-level lock is implicitly acquired for any rows returned from the SELECT. Further, because you specified SKIP LOCKED, there’s no chance of this statement blocking on another transaction. If there’s another job ready to be processed, it will be returned. There’s no concern about multiple workers running this command receiving the same row because of the row-level lock.

The biggest caveat for this technique is that, if you have a large number of workers trying to pull off this queue and a large number of jobs feeding them, they may spend some time stepping through jobs and trying to acquire a lock. In practice, most of the apps I’ve worked on have fewer than a dozen background workers, and the cost is not likely to be significant.

Use Case 2: Application Locks

Let’s imagine that you have a synchronization routine with a third-party service, and you only want one instance of it running for any given user across all server processes. This is another common application I’ve seen for Redis: distributed locking.

PostgreSQL can achieve this as well using its advisory locks. Advisory locks allow you to leverage the same locking engine PostgreSQL uses internally for your own application-defined purposes.

Use Case 3: Pub/Sub

I saved the coolest example for last: pushing events to your active clients. For example, say you need to notify a user that they have a new message available to read. Or perhaps you’d like to stream data to the client as it becomes available. Typically, web sockets are the transport layer for these events while Redis serves as the Pub/Sub engine.

However, since version 9, PostgreSQL also provides this functionality via the LISTEN and NOTIFY statements. Any PostgreSQL client can subscribe (LISTEN) to a particular message channel, which is just an arbitrary string. When any other client sends a message (NOTIFY) on that channel, all other subscribed clients will be notified. Optionally, a small message can be attached.

If you happen to be using Rails and ActionCable, using PostgreSQL is even supported out of the box.

Taking Full Advantage of PostgreSQL

Redis fundamentally fills a different niche than PostgreSQL and excels at things PostgreSQL doesn’t aspire to. Examples include caching data with TTLs and storing and manipulating ephemeral data.

However, PostgreSQL has a lot more capabilities than you may expect when you approach it from the perspective of just another SQL database or some mysterious entity that lives behind your ORM.

There’s a good chance that the things you’re using Redis for may actually be good tasks for PostgreSQL as well. It may be a worthy tradeoff to skip Redis and save on the operational costs and development complexity of relying on multiple data services.

Note: This article have been indexed to our site. We do not claim legitimacy, ownership or copyright of any of the content above. To see the article at original source Click Here

Related Posts
Galaxy S22 aluminum alloy machine model, almost unchanged design thumbnail

Galaxy S22 aluminum alloy machine model, almost unchanged design

近日,不少媒體指出 Samsung Galaxy S22 系列的發佈時間將定於明年的第一季度,這也使得人們的目光再次投向了 Galaxy 機型上。而現在外媒 coverpigtou.it 攜手知名爆料人士 @xleaks7 在網上展示了 Samsung Galaxy S22 手機的鋁製金屬模型,圖片十分清晰。這款手機的外觀設計與上一代非常相似,手機寬度較窄,整體比較小巧。從機模正面看,Galaxy S22 採用了四邊等寬的直屏設計,但是屏幕與邊框的間距並沒有傳言中的那樣窄。而在屏幕中間可以看到一個用於放置前置鏡頭的打孔。而手機側面依舊採用了圓潤的邊框,電源及音量按鍵位於右側,底部為 USB Type-C 和揚聲器格柵。該機模的背面可以看出,新機的後置鏡頭模組略微凸起於機身,輪廓與機身邊框合一。據了解 S22 可能會有三個鏡頭,並在相機凸點外有閃光燈,與 Galaxy S21 的設計非常相似。而目前在售的 Galaxy S21 5G 手機尺寸為 151.7×71.2×7.9mm,重169g。但 Galaxy S22 將有可能會比這更小,機身大小與 iPhone 13 相似。並且從目前曝光的新手機電池中可以看出其容量也將減少,容量為 3700mAh,比 S21 少了300mAh。
Read More
Can artificially altered clouds save the great barrier reef? thumbnail

Can artificially altered clouds save the great barrier reef?

In place of its normal load of cars and vans, the repurposed ferry boat sported a mobile science laboratory and a large fan on its deck as it left Townsville, Australia, in March. Researchers dropped anchor in a coral lagoon some 100 kilometres offshore and then fired up the cone-shaped turbine, which blew a mist…
Read More
Spider-Man: No Way Home Writers On Venom's MCU Future and the Ending thumbnail

Spider-Man: No Way Home Writers On Venom’s MCU Future and the Ending

Image: Sony Pictures/Marvel2021 was a big year for superhero movies, particularly for Marvel and its webheads. In addition to the massive, nostalgia-fueled juggernaut Spider-Man: No Way Home, Tom Hardy and his massive chompers chewed up Venom: Let There Be Carnage to sizable box office success. The conversation surrounding both films was if Sony’s Eddie Brock…
Read More
Index Of News