Search code examples
spring-session

Spring Session In Paas Sticky Session


so I have deployed my spring app on Heroku with 2 nodes and I noticed that if I add a product in the basket and I start refreshing the cart page, sometimes I see the product, sometimes the product is not there. So I'm thinking that maybe the request is hitting different nodes every time.

On the spring-session website I can see This can make clustering much easier. This is nice because the clustering setup is done in a vendor neutral way. Furthermore, in some environments (i.e. PaaS solutions) developers cannot modify the cluster settings easily. But I couldn't find how to make the settings for a sticky session with spring-session. My setup is just the one ouf of the box:

@Bean(name = { "defaultRedisSessionRepository", "sessionRepository" })
@ConditionalOnProperty(name = { "nemesis.platform.redis.url" })
public SessionRepository defaultRedisSessionRepository(RedisTemplate<String,ExpiringSession> redisTemplate) throws Exception {
    return new RedisOperationsSessionRepository(redisTemplate);
}

then in my MVC config:

@Bean(name = {"defaultSessionFilter", "sessionFilter"})
public Filter sessionFilter() {
    CompositeFilter compositeFilter = new CompositeFilter();
    compositeFilter.setFilters(Arrays.asList(new SessionRepositoryFilter(applicationContext.getBean("sessionRepository", SessionRepository.class)), applicationContext.getBean(UrlEncoderFilter.NAME, UrlEncoderFilter.class)));

    return compositeFilter;
}

and then in my WebApplicationInitializer:

    final FilterRegistration sessionFilterChainReg = servletContext.addFilter("sessionFilter", DelegatingFilterProxy.class);
    sessionFilterChainReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, dispatcherServletReg.getName());

Solution

  • Spring Session does not setup sticky sessions. Instead, it allows any JVM to lookup the session object by placing it in a central datastore (i.e. Redis).