Video in progress

How do you do long polling in Spring MVC without using WebSocket?

The controller returns a DeferredResult<T> and stores it in a map, so the servlet thread is freed immediately. When data appears, another thread calls setResult() and the response goes out. On timeout an empty response (for example 204) is returned and the client asks again.

📖 Answer

@RestController
public class InboxController {
    private final Map<Long, List<DeferredResult<List<Message>>>> waiters = new ConcurrentHashMap<>();

    @GetMapping("/api/inbox/poll")
    public DeferredResult<List<Message>> poll(@RequestParam long afterId,
                                              @AuthenticationPrincipal AppUser user) {
        var result = new DeferredResult<List<Message>>(25_000L, List.of());

        List<Message> ready = messageRepo.findNewer(user.getId(), afterId);
        if (!ready.isEmpty()) {
            result.setResult(ready);   // no need to wait
            return result;
        }

        waiters.computeIfAbsent(user.getId(), k -> new CopyOnWriteArrayList<>()).add(result);
        result.onCompletion(() -> waiters.computeIfPresent(user.getId(), (k, list) -> {
            list.remove(result);
            return list.isEmpty() ? null : list; // don't leave an empty list in the map
        }));
        return result;
    }

    public void onNewMessage(Long userId) {
        var list = waiters.remove(userId);
        if (list != null) list.forEach(r -> r.setResult(messageRepo.findLatest(userId)));
    }
}

afterId is very important: the client sends the ID of the last message it saw. That way a message that arrives between two requests isn't lost; the next request finds it in the database right away.

Pick a timeout smaller than the proxy idle timeout (if Nginx is 60s, 25 to 30s). Otherwise the proxy closes the request with a 504.

With several instances, onNewMessage must be heard by all of them, through Redis pub/sub or a broker. Otherwise, if the waiting request is on a different server, it only gets the message at timeout.