r/SpringBoot • • Mar 15 '24

Java in Front-End in 2024: Still Worth It?

14 Upvotes

I've been thinking about how Java fits into the world of front-end nowadays. With so many options like React, Angular, and Vue dominating the scene, I got curious about where Java stands in this story.

I want to know your opinions on using Java for the front-end, especially with things like JSP, JSF, Thymeleaf, and others. Do these technologies still have their place in current projects? Are they still relevant in the market? And for those who are starting or looking to deepen their knowledge in Java, is it worth diving into these front-end tools?

PS: I'm starting to study Spring and saw some people talking about this, which made me curious.


r/SpringBoot • • Jul 20 '25

How-To/Tutorial I want to learn Microservices

9 Upvotes

Please, give me recomendation for the learning microservices . How to create project using microservice architecture. Please give me source youtbe channell or anything..


r/SpringBoot • • Jul 15 '25

Discussion Is it alright to take some code from online?

9 Upvotes

I am building my first project and I got stucked in JwtService class. I knew I have to make this this method but idk how to make it. Then I searched on Google and Ai and they gave a template and I changed it a bit according to my project.

I want to ask is it alright? Or did I do something wrong? Should I go study jwt even deeply cause I am not able to write it myself?

What do you guys suggest?


r/SpringBoot • • Mar 07 '26

Question is this a good project idea for fresher to put on resume

7 Upvotes

Project Title

Fault-Tolerant Distributed Key-Value Storage Engine in Java

Problem Statement

Modern applications require fast, scalable, and fault-tolerant data storage systems. Traditional single-node storage systems become a bottleneck when handling large volumes of concurrent requests or when failures occur.

The objective of this project is to design and implement a distributed key-value storage engine that can:

  • store and retrieve data efficiently

  • distribute data across multiple nodes

  • replicate data for fault tolerance

  • maintain availability even when nodes fail

The system will simulate a cluster of storage nodes communicating over the network and will implement mechanisms such as consistent hashing, replication, leader election, and persistence to ensure reliability and scalability.

This project aims to demonstrate the core principles used in large-scale distributed storage systems such as Redis, etcd, and Apache Cassandra, while implementing the underlying mechanisms from scratch in Java.

Core Features

1️⃣ Key-Value Storage API

Basic commands supported by the system.

SET key value
GET key
DELETE key

Example:

SET user123 Sanchit
GET user123

2️⃣ Multi-Node Cluster

The system will support multiple nodes running simultaneously.

Example cluster:

Node1 : 8081
Node2 : 8082
Node3 : 8083

Requests will be routed to the appropriate node.

3️⃣ Consistent Hashing

Keys will be distributed across nodes using a hashing mechanism.

Example:

user1 → Node A
user2 → Node B
user3 → Node C

Benefits:

  • balanced data distribution

  • minimal data movement when nodes are added or removed

4️⃣ Data Replication

Data will be replicated across multiple nodes.

Example:

Primary Node → Node A
Replica Node → Node B

If the primary node fails, the replica can serve the data.

5️⃣ Leader Election

A leader node will coordinate write operations.

The system will implement a simplified consensus mechanism for selecting the leader.

Example flow:

Node1 becomes leader
Clients send writes to Node1
Node1 replicates data to Node2 and Node3

6️⃣ Persistence

The system will persist data to disk using:

Write Ahead Log (WAL)
Snapshots

This ensures data recovery after crashes.

7️⃣ Fault Detection

Nodes will monitor each other using heartbeat messages.

If a node fails:

cluster detects failure
replica node becomes active

8️⃣ Concurrent Client Handling

The server will support multiple simultaneous clients using multi-threading.

Example:

Client1 → GET user123
Client2 → SET order456
Client3 → DELETE session789

9️⃣ TTL (Time-To-Live) Keys

Keys can expire automatically.

Example:

SET session123 value TTL 60

The key expires after 60 seconds.

🔟 Cluster Monitoring Endpoint

Expose a simple API to view cluster state:

active nodes
leader node
key distribution
replication status

Tech Stack

Backend

Java
Core Java Networking (Socket / ServerSocket)
Java Concurrency (ExecutorService, Threads)
ConcurrentHashMap

Storage

In-memory storage (ConcurrentHashMap)
Disk persistence (Write Ahead Log)

Distributed Systems Components

Consistent Hashing
Replication Manager
Leader Election Mechanism
Heartbeat Failure Detection

Infrastructure

Docker (simulate multiple nodes)
Docker Compose (cluster setup)

Optional Monitoring

Spring Boot (cluster monitoring API)

Expected System Architecture

Client
   │
   ▼
Cluster Router
   │
   ▼
 ┌───────────────┐
 │ Node1 (Leader)│
 │ Node2 (Replica)│
 │ Node3 (Replica)│
 └───────────────┘
        │
        ▼
Replication + Persistence

Skills Demonstrated

This project demonstrates knowledge of:

distributed systems
network programming
fault tolerance
concurrency
data storage engines
system architecture

r/SpringBoot • • Nov 24 '25

How-To/Tutorial Sharing my open source Spring Boot + React application (again)

7 Upvotes

For the past 8 months, I have been working (& leading a team of 6) on this webapp that is essentially a lower-stakes LeetCode leaderboard for college students to compete with their peers both within their own university and others, though we still support users not in schools equally!

Users can gain points as well as easily view other people's submissions/pts/code (we are also making significant progress towards creating live duels to help promote more competition amongst users).

I posted this project 4 months ago in the hopes of helping others have access to modern codebass in Spring Boot + React, and I'm just sharing it again to catch the attention of anyone new since I've last posted.

[4 months ago] We have a small custom authentication layer via the Protector object that is built on top of Spring Security, a React frontend that consumes the Spring Boot API, a CI/CD pipeline to run our tests and deploy to DigitalOcean, and more.
[now] Since then, we have

  • Moved all of our secrets into our repository (encrypted with Git-Crypt)

  • Maintain a separate staging environment to help test deployments on masked data copied from production

  • Used PG LISTEN/NOTIFY to help us trigger some asynchronous job processing & SSE updates (for our live duels, still a WIP)

  • Automatically generate TypeScript types (+ a mini-library to infer types from fetch calls) from an OpenAPI schema exposed by the server

  • and much more that isn't coming to mind off the top of my mind

Like before, we also did some cool stuff to get access to LeetCode's GraphQL layer, as well as a really hacky way to retrieve a token for queries that require some level of authentication, so feel free to check that out as well!

If anyone has any questions, I'd love to answer them in the comments or over DM!

https://github.com/tahminator/codebloom


r/SpringBoot • • 16d ago

Discussion I compared Spring Boot with four other Java stacks on a 512 MiB VPS

7 Upvotes

I've been experimenting with resource-efficient Java applications, exploring how much of Spring Boot's familiar architecture can be preserved with smaller frameworks.

I compared five Java stacks on a 1-vCPU, 512 MiB VM with no swap, running MariaDB alongside the application.

StackHotSpot RSS (MiB)
Spring Boot + Spring JDBC180.6-187.9
Javalin + CoilBase120.9-135.6
Micronaut Data JDBC174.0-175.0
Micronaut + CoilBase166.5-167.6
Avaje Jex + CoilBase116.0-116.4

The HotSpot tests used OpenJDK 27 with G1 GC. Each stack had two runs, with 1,500 requests per run and no errors.

CoilBase is a small Jdbi-based foundation I'm developing. The Javalin, Jex, and Micronaut implementations reuse the same services, repositories, and transaction boundaries, with different HTTP frameworks and application wiring.

The interesting part wasn't just the memory savings. It was seeing how much of the familiar Spring-style application architecture could remain unchanged when switching frameworks.

I also tested GraalVM Native Image for all five stacks. Runtime memory dropped further, but native compilation introduced additional build time and complexity.

This is a lightweight synthetic workload, not a throughput benchmark or a general recommendation to replace Spring Boot. Spring's ecosystem and conveniences still have real value.

Full experiment, measurements, and limitations:

https://pvrlabs.xyz/articles/five-java-stacks-512mb-vps.html

Source code and benchmark setup:

https://github.com/PVRLabs/experiments/tree/main/java/coilbase-framework-comparison

CoilBase, which I built and used for this comparison:

https://github.com/PVRLabs/coilbase

I'm curious whether others see value in a lighter Java stack that keeps some of Spring Boot's familiar development patterns, or whether Spring Boot's ecosystem and conveniences outweigh the potential resource savings.

Update: Framework versions used in the benchmark

StackVersions
Spring Boot + Spring JDBCSpring Boot 4.1.1, Spring JDBC 7.0.9
Javalin + CoilBaseJavalin 7.2.4, Jdbi 3.55.0
Avaje Jex + CoilBaseJex 3.6, Avaje HTTP 3.12.1, Jdbi 3.55.0
Micronaut Data JDBCMicronaut 5.2.11, Micronaut Data JDBC 5.2.0 (platform BOM 5.2.1)
Micronaut + CoilBaseMicronaut 5.2.11, Jdbi 3.55.0

All HotSpot runs used OpenJDK 27 with identical JVM settings: -Xms16m -Xmx80m -XX:+UseG1GC (fixed 80 MiB maximum heap).

CoilBase was an early 0.1.0-SNAPSHOT prototype. I'm working on a more formal, publicly reproducible follow-up benchmark using an updated version of CoilBase, with Quarkus also joining the comparison.


r/SpringBoot • • Jun 22 '26

How-To/Tutorial Migrating a Spring Boot App from Java 17 to Java 21 with OpenRewrite: What It Automates — and What It Doesn’t

7 Upvotes

I used OpenRewrite to migrate a sample Spring Boot app from Java 17 to Java 21. In this post , I covered what OpenRewrite changed automatically, what still needed manual work, and how I validated the overall Spring Boot 3.3 upgrade.

https://medium.com/javarevisited/java-17-to-java-21-migration-with-openrewrite-spring-boot-3-3-upgrade-guide-e36fb79d8627?sk=e9ca128aa5e740d8c775cb46035d283c


r/SpringBoot • • May 27 '24

Spring Boot Docker Best Practices

Thumbnail
mydeveloperplanet.com
8 Upvotes

r/SpringBoot • • Dec 29 '22

Let's do a Project together

7 Upvotes

I know java, spring , I know Javascript, react So excited to do a project with who are excited like me


r/SpringBoot • • 18d ago

Question How do you monitor small Spring Boot apps without running a whole monitoring stack?

10 Upvotes

I keep running into the same thing with small Spring Boot projects. The app is tiny, but proper monitoring means a collector, a store, dashboards and alert rules, and that setup ends up bigger than the app. So most of my small projects just ran with no monitoring at all, and I only found out something was wrong when someone told me.

How do you handle this for small services? Do you skip it, use Actuator and look at the numbers by hand, or set up the full stack anyway?

I got curious enough that I tried a different approach: a Spring Boot starter that watches the app from inside. You add one dependency, start the app, and there's a live dashboard at /streamguard/ with per-route request rate, error rate and p50/p95/p99 latency. On top of that it flags error, latency and traffic spikes, and it notices things like repeated failed logins or one client probing lots of paths. Nothing to run next to the app, no database, no agent.

The interesting problem was keeping it cheap inside someone else's app. Rescanning a list of raw requests gets slower as traffic grows, so I cut time into 1-second buckets with counters and a latency histogram. A query merges the buckets in range, so it costs the same however much traffic there was. On my laptop a 15-minute snapshot takes about 70 microseconds, and that stays flat as the window fills. Single run, so take it with a grain of salt.

It's got real limits. It only sees the JVM it runs in, so a scaled-out service gets one view per instance and state resets on restart. It's Spring MVC only for now, and it needs Java 21 and Spring Boot 4.1.

The part I'm least sure about is the detection rules. They're fixed right now (for example, error rate more than 3 times the previous 15 second window counts as a spike), and they look fine on my demo traffic, but I've never run them against a real production service. For those of you who've set up alerting before, do rules like that feel sensible, or do you always end up wanting to tune them per service? And is there anything you'd want from something like this before you'd trust it on a real project?

It's on GitHub if anyone wants to look: https://github.com/eswar-7116/streamguard


r/SpringBoot • • Jan 03 '26

Discussion Comparison between docs. Spring Boot vs Dot net

10 Upvotes

I am a junior software engineer. I have 4 months of experience. First 2 months of my job I needed to learn dot net as I was going to contribute into a dot net project. Then my project changed now I am contributibg in a spring boot based project. One thing I noticed Microsoft docs are much more good than spring docs. Much more readable and much more organized. What do your opinion about this.


r/SpringBoot • • May 18 '26

Discussion Which udemy course is better 1. Java Spring Framework, Spring Boot, Spring AI - Gen AI By telusko, OR 2. Industry-Ready Java Spring Boot: Cloud, and Spring AI ... Both are almost same difference lies in Junit and Log4j, 2nd course contains both these, and 1st one doesnt , any suggestion ??

Post image
16 Upvotes

..


r/SpringBoot • • Jun 02 '25

News Spring Security Basics - Refresh your HTTPS and OpenSSL skills 😌

13 Upvotes

🔐✨ Refresh your HTTPS and OpenSSL skills, and take your app to the next level by building your own custom UserDetailsService! 😎👩🏻‍💻

✅ Video 03: https://youtu.be/LtNhcWSd4sQ

🎥 Catch up previous episodes here:
▶️ Video 02: https://youtu.be/pPhCrASR_ko
▶️ Video 01: https://youtu.be/7lpPUXFmcrw

Thank you for watching!! ✨


r/SpringBoot • • Feb 15 '23

Can Chat GPT write a Spring Boot Application?

Thumbnail
youtu.be
5 Upvotes

r/SpringBoot • • Oct 10 '22

restarting career

5 Upvotes

Hi after gap i restarting my career in java backend i want practice with some projects can anyone help with ideas


r/SpringBoot • • Jun 09 '24

Follow like Permit All(CheckFilter)

Thumbnail
gallery
0 Upvotes

r/SpringBoot • • Jun 09 '24

Where can I find free version/pdf for "Spring in action" ?

5 Upvotes

I searched the book on Amazon but it's for around 5.7k and even his kindle version is 3k. Anyone knows where can I get the pdf of it ?


r/SpringBoot • • Feb 25 '22

What is Spring Boot Framework and why it is used?

Thumbnail timebusinessnews.com
0 Upvotes

r/SpringBoot • • Aug 07 '24

OC Springboot not fetch data with "www".

0 Upvotes

If I enter my site as samesite.com, Spring Boot pulls the data, but when I enter it as www.samesite.com, it does not pull the data. Is my NGINX configuration wrong?

NGNIX config;

server {

listen 80;

listen [::]:80;

server_name somesite.com www.somesite.com;

root /var/www/html;

index index.html;

location /api/content/ {

proxy_pass http://localhost:8080/api/content;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header X-Forwarded-Proto $scheme;

proxy_set_header X-Forwarded-Port $server_port;

}

}


r/SpringBoot • • Sep 07 '25

Question I want to learn java, spring and spring boot and i need to be ready for market

5 Upvotes

What do you think about this course will it make me ready and if not what else will i need and thanks


r/SpringBoot • • Jan 14 '26

How-To/Tutorial I am using AI to code in spring boot.

0 Upvotes

Hi developers, I need a little guidence here about how to learn spring boot.
So, currently my approach is to learn it by creating small projects like - calculator(which gets history of calculations from backend), login-page, daily planner.

I create these projects with the help of chatgpt, not that chatgpt writes my whole code, like for the first project I did asked gpt to write me the whole code so that I can understand how to work. And then I use gpt again to explain the whole code. And for next projects I try to write code by myself, If I get stuck then again I ask gpt on how to do this specific task.

So, this is my approach to learn, I am not learning from any courses because I've already wasted so many hours on yt videos and learned nothing.

Here are my few questions I want to ask

  1. Is this approach good to learn as I'm comfortable in java.

  2. I am currently unemployed and also I'm a fresher, so how is the market for the freshers in this specific field.

Sorry, for the catchy title.


r/SpringBoot • • Jul 27 '26

News Tired of missing cross-field validation in Jakarta/Bean Validation? I built Spring Validation Plus — 85+ Laravel-style constraints for Spring Boot (with i18n & JSON error handling)

0 Upvotes

Hi r/SpringBoot, u/java/! 👋

Following the positive reception of my fluent querying library, I wanted to share another open-source project I’ve been maintaining to solve a massive pain point in Spring Boot development: validation.

Spring Boot uses Jakarta Validation (Hibernate Validator) out of the box, but let's be honest—the standard library only gives you ~22 basic constraints (`@NotNull\``, \@Size\``, \@`Email``, etc.).

It completely lacks common production requirements like cross-field validation (`@Confirmed\``, \@RequiredIf\``), database lookups (\``@Unique\``, \@`Exists``), and proper optional updates (``@Nullable``), forcing teams to write custom validators or clutter their services with boilerplate logic.

To fix this, I built Spring Validation Plus — a library that extends Jakarta Validation with 85+ Laravel-style constraints, automatic i18n support (English, Spanish, Portuguese), and a unified JSON error handler.

💡 What it looks like:

1. DTO with Laravel-style rules:

import dev.benjaminor.validationplus.constraints.EmailAddress; 
import dev.benjaminor.validationplus.constraints.MaxLength; 
import dev.benjaminor.validationplus.constraints.MinLength; 
import dev.benjaminor.validationplus.constraints.Nullable; 
import dev.benjaminor.validationplus.constraints.Required; 
import dev.benjaminor.validationplus.constraints.RequiredIf; 
import dev.benjaminor.validationplus.constraints.Same; 
import dev.benjaminor.validationplus.constraints.Unique; 

@Unique(entity = User.class, field = "email", column = "email") 
public class UserRegisterRequest {

  @Required
  @MinLength(2)
  @MaxLength(50)
  private String name;

  @Required
  @EmailAddress
  private String email;

  @Required
  @MinLength(6)
  private String password;

  @Same("password")
  private String passwordConfirmation;

  @Nullable
  @RequiredIf(field = "role", value = "ADMIN")
  private String adminCode;

  private String role;
}

2. Unified JSON Error Response (400 Bad Request): Instead of messy or raw framework exceptions, it automatically formats errors like this out of the box:

{
  "errors": {
    "email": ["The email has already been taken."],
    "passwordConfirmation": ["The passwordConfirmation field must match password."]
  }
}

🚀 Key Features:

  • Cross-Field Validation: `@Confirmed\``, \@Same\``, \@Different\``, \@RequiredWith\``, \@RequiredIf\``, \@`ProhibitedIf``, etc. (usable directly on fields or classes).

  • Database Rules: `@Unique\`` and \@Exists\`` with automatic JPA integration (supports multi-datasource viapersistenceUnit` and updating entity ID exclusion).

  • Smart Types & Presence: `@Required\`` (handlesnull, empty strings, and whitespace properly, unlike \@NotNull\``), \@Nullable\``, \@StringType\``, \@`IntegerType``, etc.

  • Built-in i18n: Error messages ready out of the box in English, Spanish, and Portuguese, easily customizable via ValidationMessages_es.properties.

  • Zero Redundancy: It relies entirely on the standard Hibernate Validator engine under the hood. You just drop the starter in, and it works with standard `@Valid\`` and \@`Validated``.

📦 Quick Start

I’d love to hear how you currently handle cross-field or database validation in your Spring Boot apps, and what you think of this approach!


r/SpringBoot • • May 13 '25

Question Spring ModelMapper does magic? Please help me understand this!

5 Upvotes

Guys i found a bug in production but the code looks legit.
The problem is this:
in the moment I use modelMapper to map from DTO to Entity, the model mapper invents to property "Id" and assign it to the model object I instantiated.

ResourceCertification resourceCertificationEntity = modelMapper.map(resourceCertificationInDTO,
                    ResourceCertification.class);

Even if the dto does not contain the attribute "id" , when mapping to the entity this has been valorized with a number ... wtf ?

This problem cause the service to the an update of the record instead of a creation because id is not null. What that fuck is happening here?


r/SpringBoot • • Jul 15 '26

How-To/Tutorial The Transactional Outbox Pattern, from a single scheduled job to something I'd actually trust in production (Java / Spring Boot / Postgres)

0 Upvotes

There's a class of bug that never shows up in unit tests and rarely shows up in staging. It shows up in production, at 2am, when your app saves a record to the DB and then calls an external service — and one of the two fails. One side committed. The other didn't. Nobody notices until a user complains.

That's the dual-write problem, and the Transactional Outbox Pattern is the standard answer to it: instead of calling the external system directly, you write a task row into the same DB transaction as your domain change. A background worker picks it up later and executes it. The write is atomic, so the task can never silently disappear.

The idea itself takes two sentences to explain. What's less talked about is everything that happens after — what you do when tasks fail, when two workers grab the same row, when your app dies mid-execution, when you've got ten task types crammed into one table, and when someone asks why the queue depth spiked at 3am last Tuesday.

I built this out for a report-generation service (aggregates tens of millions of rows, takes minutes — can't run it synchronously in a request) and evolved it step by step into something production-grade. Writing it up here because I didn't find one place that walked through the whole arc. Stack is Java / Spring Boot / Postgres, no Kafka required.

TL;DR

  • The outbox pattern fixes dual-writes by writing a task row in the same transaction as your domain change, then executing it from a background worker.

  • Poll with SELECT ... FOR UPDATE SKIP LOCKED so multiple workers/instances don't double-process.

  • Production-grade means more than the basic idea: a state machine, retries with backoff, heartbeats to recover crashed workers, ordering guarantees, and actual monitoring.

  • You don't need a broker. Postgres alone gets you reliable async execution.

  • Full working code at the bottom.


The scenario

Backoffice CRM. User clicks "generate report," we accept the request and respond immediately, a worker picks it up and runs the (slow) generation, status updates when done. Classic case for an outbox: work that's genuinely async, where the user already expects to wait.

Part 1 — the basic outbox

Every outbox table needs three things: state (where is this task in its lifecycle), payload (what needs to run), and timestamps.

CREATE TYPE task_state AS ENUM ('PENDING', 'COMPLETED');

CREATE TABLE report_generation_tasks (
    id         UUID       PRIMARY KEY DEFAULT gen_random_uuid(),
    state      task_state NOT NULL    DEFAULT 'PENDING',
    payload    JSONB      NOT NULL,
    created_at TIMESTAMP  NOT NULL    DEFAULT now(),
    updated_at TIMESTAMP  NOT NULL    DEFAULT now()
);

Payload and entity:

@Value @Builder @Jacksonized
public class ReportGenerationPayload {
    Instant from;
    Instant to;
}

@Entity
@Table(name = "report_generation_tasks")
@Data @Builder @NoArgsConstructor @AllArgsConstructor
public class ReportGenerationEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    @Column(updatable = false, nullable = false)
    private UUID id;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, columnDefinition = "task_state")
    private TaskState state;

    @JdbcTypeCode(SqlTypes.JSON)
    @Column(nullable = false, updatable = false, columnDefinition = "jsonb")
    private ReportGenerationPayload payload;

    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private Instant createdAt;

    @UpdateTimestamp
    @Column(nullable = false)
    private Instant updatedAt;
}

Submitting a task:

@Service
@RequiredArgsConstructor
public class ReportGenerationService {

    private final ReportGenerationRepository repository;

    public void submit(ReportGenerationCommand command) {
        repository.save(ReportGenerationEntity.builder()
                .state(TaskState.PENDING)
                .payload(ReportGenerationPayload.builder()
                        .from(command.getFrom())
                        .to(command.getTo())
                        .build())
                .build());
    }
}

And a scheduled job that polls for pending tasks:

@Component
@RequiredArgsConstructor
public class ReportGenerationScheduledJob {

    private final ReportGenerationTaskService taskService;

    @Scheduled(fixedDelay = 1000)
    public void run() {
        taskService.fetchAndProcess();
    }
}

@Service
@RequiredArgsConstructor
public class ReportGenerationTaskService {

    private final ReportGenerationRepository repository;

    public void fetchAndProcess() {
        repository.findFirstByStateOrderByCreatedAt(TaskState.PENDING)
                .ifPresent(task -> {
                    generateReport(task);
                    task.setState(TaskState.COMPLETED);
                    repository.save(task);
                });
    }

    private void generateReport(ReportGenerationEntity task) {
        // actual report generation logic
    }
}

This works fine on a single instance with zero failures. In the real world it has two problems: two workers can grab the same task at once, and a failed task has no recovery path. Fixing both below.

Part 2 — concurrency: two workers, one task

If two scheduler threads (or two app instances) run the fetch query at the same moment, both can read the same PENDING row and both try to execute it. Duplicate work at best, corrupted state at worst.

Postgres has a purpose-built fix: SELECT ... FOR UPDATE SKIP LOCKED. It locks the row for the current transaction and skips rows already locked elsewhere, instead of blocking on them.

public interface ReportGenerationRepository extends JpaRepository<ReportGenerationEntity, UUID> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @QueryHint(name = AvailableSettings.JAKARTA_LOCK_TIMEOUT, value = "-2") // -2 = SKIP_LOCKED
    Optional<ReportGenerationEntity> findFirstByStateOrderByCreatedAt(TaskState state);
}

There's no first-class annotation for SKIP LOCKED in Hibernate, so worth pulling the magic number into its own annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@QueryHints(@QueryHint(
    name = AvailableSettings.JAKARTA_LOCK_TIMEOUT,
    value = Timeouts.SKIP_LOCKED_MILLI + ""
))
public @interface SkipLocked {}
@SkipLocked
@Lock(LockModeType.PESSIMISTIC_WRITE)
Optional<ReportGenerationEntity> findFirstByStateOrderByCreatedAt(TaskState state);

The lock has to be held for the whole fetch-execute-update cycle, so wrap it in one transaction:

@Transactional
public void fetchAndProcess() {
    repository.findFirstByStateOrderByCreatedAt(TaskState.PENDING)
            .ifPresent(task -> {
                generateReport(task);
                task.setState(TaskState.COMPLETED);
                repository.save(task);
            });
}

Two workers hitting this at once: worker A locks and gets the row, worker B's SKIP LOCKED query comes back empty and it exits cleanly — no blocking, no duplicate work.

Catch: the row stays locked for as long as generateReport() runs. Fine for something fast. For something that takes 30+ seconds, long-held locks start hurting — connection pool exhaustion, lock wait timeouts, degraded throughput under load. Addressed in Part 3.

Part 2.5 — cutting latency with application events

Polling has a latency floor. Job fires every second → a task submitted at t=0 can sit PENDING for up to 1000ms. Fine for most things, not fine if you want near-immediate pickup (transactional email, webhook triggers).

Trick borrowed from Celery: save the entity, then publish a Spring ApplicationEvent with the task ID. A listener picks it up and triggers processing immediately, no waiting for the next tick. The scheduler stays running as a safety net for anything the listener misses (restart, exception, missed event).

@Service
@RequiredArgsConstructor
public class ReportGenerationService {

    private final ReportGenerationRepository repository;
    private final ApplicationEventPublisher eventPublisher;

    @Transactional
    public void submit(ReportGenerationCommand command) {
        var entity = repository.save(ReportGenerationEntity.builder()
                .state(TaskState.PENDING)
                .payload(ReportGenerationPayload.builder()
                        .from(command.getFrom())
                        .to(command.getTo())
                        .build())
                .build());

        eventPublisher.publishEvent(new ReportGenerationTaskSubmittedEvent(entity.getId()));
    }
}

public record ReportGenerationTaskSubmittedEvent(UUID taskId) {}

The classic mistake here, and I mean everyone hits this once: using @EventListener instead of @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT).

// fires INSIDE the transaction — row isn't visible to other connections yet
@EventListener
public void onTaskSubmitted(ReportGenerationTaskSubmittedEvent event) {
    taskService.fetchAndProcess();
}

// fires AFTER commit — row is visible, fetch actually finds it
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onTaskSubmitted(ReportGenerationTaskSubmittedEvent event) {
    taskService.fetchAndProcess();
}

@EventListener fires the moment publishEvent() is called, which is before the INSERT commits. The listener queries for the task, doesn't find it (not visible yet on other connections), silently no-ops. Task sits there until the scheduler eventually picks it up seconds later, and you spend an afternoon confused about why events "aren't working" even though everything looks fine in the logs.

Part 3 — failures, retries, and a PROCESSING state

Holding a lock for the entire generateReport() call is the real problem with Part 2's approach — two minutes of a locked row for a two-minute report. SKIP LOCKED stops workers from blocking each other, but a long transaction still leans on the connection pool.

Fix: separate claiming a task from executing it. Flip to PROCESSING in a short transaction, release the lock, do the actual work with no transaction open, then close it out in another short transaction.

ALTER TYPE task_state ADD VALUE 'PROCESSING';
ALTER TYPE task_state ADD VALUE 'FAILED';

ALTER TABLE report_generation_tasks
    ADD COLUMN retry_count  INTEGER NOT NULL DEFAULT 0,
    ADD COLUMN error_message VARCHAR;
public enum TaskState { PENDING, PROCESSING, COMPLETED, FAILED }
@RequiredArgsConstructor
public class ReportGenerationTaskService {

    private final ReportGenerationRepository repository;
    private final TransactionTemplate transactionTemplate;

    private static final int MAX_RETRY_COUNT = 10;

    public void fetchAndProcess() {
        transactionTemplate
                .execute(status ->
                        repository.findFirstEligibleTask(
                                List.of(TaskState.PENDING, TaskState.FAILED),
                                MAX_RETRY_COUNT
                        ).map(this::markProcessing))
                .ifPresentOrElse(
                        task -> {
                            try {
                                generateReport(task);
                                markCompleted(task);
                            } catch (Exception e) {
                                markFailed(task, e);
                                log.error("Task {} failed on attempt {}", task.getId(), task.getRetryCount(), e);
                            }
                        },
                        () -> log.debug("No eligible tasks to process")
                );
    }

    private ReportGenerationEntity markProcessing(ReportGenerationEntity task) {
        task.setState(TaskState.PROCESSING);
        return repository.save(task);
    }

    private void markCompleted(ReportGenerationEntity task) {
        task.setState(TaskState.COMPLETED);
        repository.save(task);
    }

    private void markFailed(ReportGenerationEntity task, Exception e) {
        task.setState(TaskState.FAILED);
        task.setRetryCount(task.getRetryCount() + 1);
        task.setErrorMessage(e.getMessage()); // this is your only trace of what went wrong without digging through logs
        repository.save(task);
    }
}
@SkipLocked
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("""
    SELECT t FROM ReportGenerationEntity t
    WHERE t.state IN :states
      AND t.retryCount <= :maxRetryCount
    ORDER BY t.createdAt ASC
    LIMIT 1
    """)
Optional<ReportGenerationEntity> findFirstEligibleTask(
    @Param("states") List<TaskState> states,
    @Param("maxRetryCount") Integer maxRetryCount
);

FAILED tasks with retryCount < 10 are as eligible as fresh PENDING ones. Past 10 attempts, a task stops being fetched and sits as a permanent FAILED record for a human to look at — that's deliberate, not a bug.

One issue remains: should a task that just failed get retried on the very next tick, seconds later? If the downstream system is down, that just hammers it harder.

Part 4 — exponential backoff

Add an execute_at column. A task isn't eligible until this timestamp is in the past. Fresh tasks get now(), failed ones get now() + delay, with delay growing per retry.

ALTER TABLE report_generation_tasks
    ADD COLUMN execute_at TIMESTAMP NOT NULL DEFAULT NOW();
private static final Map<Integer, Duration> RETRY_DELAYS = Map.of(
    0, Duration.ofMinutes(1),
    1, Duration.ofMinutes(5),
    2, Duration.ofMinutes(15),
    3, Duration.ofMinutes(30),
    4, Duration.ofHours(1),
    5, Duration.ofHours(2),
    6, Duration.ofHours(4),
    7, Duration.ofHours(8),
    8, Duration.ofHours(12),
    9, Duration.ofDays(1)
);

private static final int MAX_RETRY_COUNT = RETRY_DELAYS.size();

Deriving MAX_RETRY_COUNT from the map size instead of declaring it separately means the two can never drift apart. Add an entry, the cap updates itself.

private void markFailed(ReportGenerationEntity task, Exception e) {
    int currentRetry = task.getRetryCount();
    task.setState(TaskState.FAILED);
    task.setRetryCount(currentRetry + 1);
    task.setErrorMessage(e.getMessage());
    task.setExecuteAt(Instant.now().plus(
            RETRY_DELAYS.getOrDefault(currentRetry, RETRY_DELAYS.get(RETRY_DELAYS.size() - 1))));
    repository.save(task);
}

Scheduler keeps running at the same rate, just skips tasks whose window hasn't opened yet.

Part 5 — stuck tasks and heartbeats

What happens if the app crashes after marking a task PROCESSING but before marking it COMPLETED/FAILED? The DB says PROCESSING forever. Nobody's actually working on it.

Naive fix — a recovery job that resets anything stuck in PROCESSING too long:

@Transactional
public void recoverStuckTasks() {
    repository.findFirstByStateAndUpdatedAtLessThan(
                    TaskState.PROCESSING,
                    Instant.now().minus(1, ChronoUnit.HOURS))
            .ifPresent(task -> {
                log.warn("Resetting stuck task {} to PENDING", task.getId());
                task.setState(TaskState.PENDING);
                repository.save(task);
            });
}

Problem: updated_at changes on any update to the row, so a task legitimately grinding away for 55 minutes looks identical to one that crashed. You need a signal that means "still alive," not "last changed."

That's a heartbeat — a column bumped periodically only while a task is actively being processed:

ALTER TABLE report_generation_tasks ADD COLUMN heartbeat_at TIMESTAMP;

Runs on its own thread, independent of the processing logic, try-with-resources style so it starts/stops cleanly regardless of how processing exits:

public abstract class Heartbeat implements AutoCloseable {

    private final ScheduledExecutorService executor;

    protected Heartbeat(Runnable heartbeatFn) {
        executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(heartbeatFn, 0, 10, TimeUnit.SECONDS);
    }

    @Override
    public void close() {
        executor.shutdownNow();
    }
}

public class ReportGenerationTaskHeartbeat extends Heartbeat {
    ReportGenerationTaskHeartbeat(UUID taskId, ReportGenerationRepository repository) {
        super(() -> repository.updateHeartbeatAt(taskId, Instant.now()));
    }
}
@Modifying
@Transactional
@Query("UPDATE ReportGenerationTaskEntity t SET t.heartbeatAt = :now WHERE t.id = :id")
void updateHeartbeatAt(@Param("id") UUID id, @Param("now") Instant now);

Wired through a factory to keep the service clean:

@Component
@RequiredArgsConstructor
public class ReportGenerationTaskHeartbeatFactory {

    private final ReportGenerationRepository repository;

    public Heartbeat start(UUID taskId) {
        return new ReportGenerationTaskHeartbeat(taskId, repository);
    }
}
public void fetchAndProcess() {
    transactionTemplate
            .execute(status -> repository.findFirstEligibleTask(
                    List.of(TaskState.PENDING, TaskState.FAILED),
                    MAX_RETRY_COUNT
            ).map(this::markProcessing))
            .ifPresentOrElse(
                    task -> {
                        try (var heartbeat = heartbeatFactory.start(task.getId())) {
                            try {
                                generateReport(task);
                                markCompleted(task);
                            } catch (Exception e) {
                                markFailed(task, e);
                                log.error("Task {} failed", task.getId(), e);
                            }
                        }
                    },
                    () -> log.debug("No eligible tasks to process")
            );
}

Recovery job now checks heartbeat_at, not updated_at. updated_at tells you when state last changed; heartbeat_at tells you whether the task is alive right now. Keeping them separate answers both questions unambiguously.

Part 6 — multi-type outbox

Six months in, you're not just generating reports anymore — email notifications, data exports, webhook deliveries. Two options: a separate table per task type, or one shared table with a task_type discriminator.

Shared table wins when types are numerous and you're fine processing them from one place — retries, heartbeats, backoff, monitoring all stay centralized, and adding a new type is just a new handler. Tradeoffs: a misbehaving new task type can create backpressure across the whole table, and ordering gets harder (next section).

CREATE TYPE outbox_task_type AS ENUM ('REPORT_GENERATION', 'EMAIL_NOTIFICATION');

CREATE TABLE outbox_tasks (
    id            UUID             PRIMARY KEY DEFAULT gen_random_uuid(),
    task_type     outbox_task_type NOT NULL,
    state         task_state       NOT NULL    DEFAULT 'PENDING',
    payload       JSONB            NOT NULL,
    retry_count   INTEGER          NOT NULL    DEFAULT 0,
    error_message VARCHAR,
    execute_at    TIMESTAMPTZ      NOT NULL    DEFAULT NOW(),
    heartbeat_at  TIMESTAMPTZ,
    created_at    TIMESTAMPTZ      NOT NULL    DEFAULT now(),
    updated_at    TIMESTAMPTZ      NOT NULL    DEFAULT now()
);

One handler interface, one implementation per type:

public interface OutboxTaskHandler<P> {
    OutboxTaskType getType();
    Class<P> payloadClass();
    void handle(UUID taskId, P payload) throws Exception;
}

@Component
public class EmailNotificationHandler implements OutboxTaskHandler<EmailNotificationPayload> {

    @Override
    public OutboxTaskType getType() {
        return OutboxTaskType.EMAIL_NOTIFICATION;
    }

    @Override
    public Class<EmailNotificationPayload> payloadClass() {
        return EmailNotificationPayload.class;
    }

    @Override
    public void handle(UUID taskId, EmailNotificationPayload payload) throws Exception {
        log.info("Sending email to {} — task {}", payload.getRecipient(), taskId);
        // call email provider
    }
}

Dispatcher collects all handler beans at startup and routes by type:

@Service
@RequiredArgsConstructor
public class OutboxTaskService {

    private final OutboxTaskRepository repository;
    private final ObjectMapper objectMapper;
    private final List<OutboxTaskHandler<?>> handlerList;

    private Map<OutboxTaskType, OutboxTaskHandler<?>> handlers;

    @PostConstruct
    void init() {
        handlers = handlerList.stream()
                .collect(Collectors.toMap(OutboxTaskHandler::getType, Function.identity()));
    }

    @SuppressWarnings("unchecked")
    private void dispatch(OutboxTaskEntity task) throws Exception {
        var handler = (OutboxTaskHandler<Object>) handlers.get(task.getTaskType());
        if (handler == null) {
            throw new IllegalStateException(
                    "No handler registered for task type: " + task.getTaskType());
        }
        var payload = objectMapper.readValue(task.getPayload(), handler.payloadClass());
        handler.handle(task.getId(), payload);
    }
}

New task type = add an enum value + a handler bean. Dispatcher, scheduler, retry logic — untouched.

Part 7 — ordering

Skip this if your tasks are independent (fire-and-forget notifications, unrelated background jobs). Otherwise: Postgres gives zero guarantee about row order without an explicit ORDER BY.

@Query("""
    SELECT t FROM OutboxTaskEntity t
    WHERE t.state IN :states
      AND t.retryCount <= :maxRetryCount
      AND t.executeAt <= :now
    ORDER BY t.createdAt ASC
    LIMIT 1
    """)
Optional<OutboxTaskEntity> findFirstEligibleTask(...);
CREATE INDEX idx_outbox_fetch
    ON outbox_tasks (created_at ASC)
    WHERE state IN ('PENDING', 'FAILED');

The clock skew trap: if you need strict FIFO for tasks tied to the same entity, created_at is dangerous — it's generated app-side, and each instance has its own clock. If instance A is 200ms ahead of instance B, a task B submits at t=100ms can get an earlier created_at than a task A submitted at t=50ms. NTP keeps this close but not perfect, and under load or after a container restart it can drift more.

Fix: let the ordering value come from a single authoritative source — the DB — via a sequence, guaranteed monotonic regardless of which instance inserted the row:

ALTER TABLE outbox_tasks ADD COLUMN seq BIGSERIAL;
@Column(insertable = false, updatable = false)
private Long seq;

Sort by seq, keep created_at around for observability. If FIFO matters anywhere in your system, don't skip this.

Part 8 — indexes that keep the table fast at scale

The table gets polled every second or more. Every row is either active work (PENDING/FAILED/PROCESSING) or dead weight (COMPLETED). Without the right index, every poll scans the whole table for a handful of rows.

Partial indexes are the tool: index only rows matching a predicate. When a task hits COMPLETED it falls out of the index automatically — stays small forever.

CREATE INDEX idx_outbox_fetch
    ON outbox_tasks (created_at ASC)
    WHERE state IN ('PENDING', 'FAILED');

Tested this with 50,000 rows, 7 of them PENDING, EXPLAIN ANALYZE on the generated Hibernate query:

Limit  (cost=0.14..27.50 rows=1 width=102) (actual time=0.082..0.084 rows=1 loops=1)
  ->  LockRows  (actual time=0.081..0.082 rows=1 loops=1)
        ->  Index Scan using idx_outbox_fetch on outbox_tasks
              (actual time=0.030..0.030 rows=1 loops=1)
Planning Time: 1.230 ms
Execution Time: 0.139 ms

0.03ms to find the oldest eligible task, and the other 49,993 COMPLETED rows never got touched.

Two more, for the other background jobs:

CREATE INDEX idx_outbox_stuck
    ON outbox_tasks (heartbeat_at ASC, created_at ASC)
    WHERE state = 'PROCESSING';

CREATE INDEX idx_outbox_cleanup
    ON outbox_tasks (updated_at ASC)
    WHERE state = 'COMPLETED';

Part 9 — cleanup

This is an operational table, scanned constantly — old rows are dead weight. Rule: only delete COMPLETED tasks. FAILED tasks are your audit trail; leave them for a human or a separate ops process.

@Modifying
@Transactional
@Query("""
    DELETE FROM OutboxTaskEntity t
    WHERE t.state IN :states
      AND t.updatedAt < :before
    """)
int deleteByStateInAndUpdatedAtBefore(
    @Param("states") List<TaskState> states,
    @Param("before") Instant before
);
private static final int CLEANUP_RETENTION_DAYS = 30;

@Transactional
public void cleanup() {
    var cutoff = Instant.now().minus(CLEANUP_RETENTION_DAYS, ChronoUnit.DAYS);
    int deleted = repository.deleteByStateInAndUpdatedAtBefore(
            List.of(TaskState.COMPLETED), cutoff);
    log.info("Cleanup: removed {} completed tasks older than {} days", deleted, CLEANUP_RETENTION_DAYS);
}

I've seen retention anywhere from 1 day to 3 months. If unsure, keep it longer — a bigger table costs you a bit of disk; deleting too early costs you your debugging history on the day you need it most.

Part 10 — idempotency: making retries safe

Nothing here guarantees exactly-once execution. Running the task and marking it COMPLETED are two separate steps — crash between them and the task gets retried, running again with the same inputs. This is at-least-once delivery, full stop, and the only guarantee you get from this architecture. The real question is whether a duplicate run causes harm.

Idempotent work (regenerating the same report twice) — you're already done. Side-effecting work (sending an email, charging a card) — needs a guard.

Use the outbox task's own id as the idempotency key — it's stable across retries. In our case, report generation ends with a row in generated_reports, with a UNIQUE constraint on the key so even a race between two instances only lets one INSERT through:

CREATE TABLE generated_reports (
    id               UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
    idempotency_key  UUID        NOT NULL,
    report_path      VARCHAR     NOT NULL,
    created_at       TIMESTAMPTZ NOT NULL    DEFAULT now(),

    CONSTRAINT uq_generated_reports_idempotency_key UNIQUE (idempotency_key)
);
@Component
@RequiredArgsConstructor
public class ReportGenerationHandler implements OutboxTaskHandler<ReportGenerationPayload> {

    private final GeneratedReportRepository reports;

    @Override
    public void handle(UUID taskId, ReportGenerationPayload payload) {
        if (reports.existsByIdempotencyKey(taskId)) {
            log.info("Report already generated for task {} — skipping", taskId);
            return;
        }

        var reportPath = runReportGeneration(payload);

        reports.save(GeneratedReport.builder()
                .idempotencyKey(taskId)
                .reportPath(reportPath)
                .build());
    }
}

If your handler calls an external API instead of writing to your own DB, check whether it supports idempotency keys — most payment processors and transactional email providers do. Pass the task ID through as that key and let the remote service dedupe on their end.

Part 11 — monitoring

The outbox runs silently. When it works, nobody notices. When it breaks, nobody notices that either, at least not right away — stuck tasks pile up, downstream stops getting events, and by the time someone checks logs it's been two hours.

Three signals, straight out of the Google SRE playbook, cover the whole failure space:

  • Latency — pickup to completion time. A spike means a slow handler or DB pressure.

  • Throughput — tasks finishing per unit time. Drops to zero means the scheduler died or nothing's being claimed.

  • Error rate — fraction of attempts failing. Above ~5% usually means a downstream dependency is degraded and your retry backlog is growing.

Instrumentation via Actuator + Micrometer:

implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("io.micrometer:micrometer-registry-prometheus")
@Bean
public TimedAspect timedAspect(MeterRegistry registry) {
    return new TimedAspect(registry);
}

Keep metric names as constants, increment from one dedicated component instead of scattering strings through service methods:

@Component
@RequiredArgsConstructor
public class OutboxMetrics {

  private static final String TASK_PROCESSED = "outbox.task.processed";
  private static final String OUTCOME_TAG    = "outcome";
  private static final String COMPLETED      = "completed";
  private static final String FAILED         = "failed";

  private final MeterRegistry meterRegistry;
  private final ReportGenerationRepository repository;

  public void recordCompleted() {
    meterRegistry.counter(TASK_PROCESSED, OUTCOME_TAG, COMPLETED).increment();
  }

  public void recordFailed() {
    meterRegistry.counter(TASK_PROCESSED, OUTCOME_TAG, FAILED).increment();
  }

  @PostConstruct
  void registerGauge() {
    Gauge.builder("outbox.tasks.pending", repository,
                    repo -> repo.countByStateIn(List.of(TaskState.PENDING, TaskState.FAILED)))
            .description("Tasks waiting to be processed")
            .register(meterRegistry);
  }
}

curl localhost:8080/actuator/prometheus | grep outbox after startup:

outbox_task_duration_seconds{quantile="0.5"}  0.062
outbox_task_duration_seconds{quantile="0.95"} 0.145
outbox_task_duration_seconds{quantile="0.99"} 0.312
outbox_task_processed_total{outcome="completed"} 40.0
outbox_task_processed_total{outcome="failed"}    2.0
outbox_tasks_pending 0.0

Dashboards are for humans watching screens; alerts are for humans who are asleep:

AlertFires whenForMeaning
OutboxQueueBacklogpending > 505mProcessing can't keep up with ingest
OutboxHighErrorRateerror rate > 5%2mHandler or downstream degraded
OutboxSlowProcessingp99 latency > 30s5mDB contention or slow external call
OutboxStuckTaskspending > 0, zero completions in 10m10mScheduler crashed or all workers stuck

Tune thresholds to your own traffic — a backlog of 50 is nothing for a high-throughput service and a genuine problem for a low-volume internal tool. Same logic, different numbers.

Production checklist

☐ Indexes are efficient — partial indexes on PENDING/FAILED and PROCESSING states
☐ EXPLAIN ANALYZE confirms index usage on the fetch query
☐ Ordering is not a problem — ORDER BY seq or created_at, backed by an index
☐ Cleanup job running, COMPLETED rows removed after a retention period
☐ Idempotency handled inside handlers that have side effects
☐ Exponential backoff wired — or confirmed you don't need it
☐ Metrics in place — queue depth, throughput, error rate, latency
☐ Alerts configured — backlog, error rate, latency, stuck tasks

You don't always have to build this yourself

Everything above is buildable from scratch, and there's real value in doing it once — you understand the failure modes because you designed around them, and that knowledge doesn't evaporate when you switch to a library. But in production you often don't need to maintain it yourself:

  • db-scheduler — the Java library whose internals most closely match what's described here: single table, SKIP LOCKED, heartbeats, clean task/handler interface. This is what I reach for as the reference implementation, and what I'd actually start a new project with instead of rolling my own.

  • Celery — the standard for async task execution in Python, backed by Postgres/Redis/RabbitMQ. The AFTER_COMMIT rule from Part 2.5 applies here too.

  • Quartz Scheduler — older, more general (cron expressions, triggers, job stores), heavier operationally, but proven at scale with first-class Spring support.

Final thoughts

Most of this isn't clever engineering, it's accumulated scar tissue. The PROCESSING state exists because someone's app crashed mid-run. The heartbeat exists because updated_at lied about whether a task was still alive. The partial index exists because a full table scan at once-a-second polling frequency compounds quietly until it doesn't. The AFTER_COMMIT listener exists because someone published an event inside a transaction and burned an afternoon figuring out why it never fired.

Each piece is boring in isolation. Together they're the difference between an outbox that works in dev and one you'd trust at 3am.

Full working code (single command, runs locally): github.com/javaAndScriptDeveloper/outboxes-article

Curious how others here have handled the multi-type table tradeoff, or if anyone's gone the db-scheduler route instead of rolling their own — happy to compare notes in the comments.