java 33 lines · 7 steps

Idempotent webhooks with Redis in Spring

A Spring service uses an atomic Redis SETNX guard to process each webhook delivery exactly once.

Explained by highlit
1@Service
2public class WebhookDedupService {
3 
4 private static final Logger log = LoggerFactory.getLogger(WebhookDedupService.class);
5 private static final Duration GUARD_TTL = Duration.ofSeconds(30);
6 
7 private final StringRedisTemplate redis;
8 private final ApplicationEventPublisher events;
9 
10 public WebhookDedupService(StringRedisTemplate redis, ApplicationEventPublisher events) {
11 this.redis = redis;
12 this.events = events;
13 }
14 
15 public void handle(String deliveryId, StripeEvent event) {
16 String key = "webhook:seen:" + deliveryId;
17 Boolean firstDelivery = redis.opsForValue()
18 .setIfAbsent(key, Instant.now().toString(), GUARD_TTL);
19 
20 if (!Boolean.TRUE.equals(firstDelivery)) {
21 log.info("Ignoring duplicate webhook delivery {} for event {}", deliveryId, event.getId());
22 return;
23 }
24 
25 try {
26 events.publishEvent(new WebhookReceivedEvent(event));
27 log.info("Accepted webhook delivery {} for event {}", deliveryId, event.getId());
28 } catch (RuntimeException ex) {
29 redis.delete(key);
30 throw ex;
31 }
32 }
33}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1An atomic set-if-absent with a TTL turns Redis into a lightweight, self-expiring dedup guard.
  2. 2Deleting the guard key on failure lets a retried delivery be reprocessed instead of silently dropped.
  3. 3Publishing an application event decouples receiving a webhook from the work that handles it.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Idempotent webhooks with Redis in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code