spring-session icon indicating copy to clipboard operation
spring-session copied to clipboard

Spring-Session does not allow the use of read replicas

Open osvso opened this issue 8 months ago • 4 comments

Describe the bug At some point around the release of Spring Boot 3, we tracked changes in spring data in the hope that the base implementation would be redesigned, but unfortunately this did not happen. The existing implementation does not allow deterministic use of read replicas. The problem is caused by the fact that when the session is first created, so a request is sent without a session identifier attribute (in any supported form), the implementation will attempt to save the session object twice.

	@Override
	public void save(RedisSession session) {
		if (!session.isNew) {
			String key = getSessionKey(session.hasChangedSessionId() ? session.originalSessionId : session.getId());
			Boolean sessionExists = this.sessionRedisOperations.hasKey(key);
			if (sessionExists == null || !sessionExists) {
				throw new IllegalStateException("Session was invalidated");
			}
		}
		session.save();
	}

On the first attempt, the session still has the isNew flag set to true, which causes it to be saved immediately. The second save is triggered by the `SessionRepositoryFilter' as soon as the response is committed.

As a result, in the context of a single HTTP request, the service will first store the session in Redis (executed against the master node), then check if a session with a given id exists (executed against the read replica), and if it does, it will store it again. Otherwise it throws an IllegalStateException("Session was invalidated").

I've seen this issue was reported earlier by other developers, for more context please check the following items:

To Reproduce Setup a simple app that uses Spring-Session with backed by Redis and read replicas. I'm using AWS Elasticache, when read-replicas are enabled around 2% for requests fail due to replication not being fast enough.

Expected behavior Spring-Session works efficiently and does not attempt to store the session data and almost immediately read right after.

osvso avatar Jun 11 '24 05:06 osvso