spring-projects / spring-projects/spring-session

Spring-Session does not allow the use of read replicas

Open
#3,026 5 comments 0 reactions 1 assignee View on GitHub

@marcusdacoregio is already working on this.

Since Jun 25, 2024.

in: redis type: enhancement
Dominant language
Java
Stars
1.9k
Forks
1.2k
Avg merge
4h 27m
Merged PRs (30d)
55

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.