https://www.xenonstack.com/insights/stateful-and-stateless-applications/

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/b4eaa261-af89-4964-949d-075a51071534/Untitled.png

What are Stateful and Stateless Applications?

A Stateful application remembers specific details of a user like profile, preferences, and user actions. This information is considered as the ‘Status’ of a system.

쇼핑카트를 예시로 들 수 있다. 아이템을 추가할 때 마다 카트에 추가가 되고 추가한 아이템들은 계속해서 카트에 누적된다.

A Stateless application is something that does not save or reference information about previous operations. Instead, each operation starts from the scratch just like the first time.

주로 short-term request를 처리하는 웹서버에 사용된다. 예시로, 검색엔진에 검색어를 입력하여 서치를 할 때, 검색 도중에 멈추더라도 다시 검색버튼을 누르면 기존 request와 독립적인 새로운 request가 생성되어 처리한다.

Stateful vs Stateless Session

Stateful and Stateless applications store state from client requests on the server itself and use that state to process further requests.

예시로, 유저가 login request를 하면 login 변수가 true가 되고 두번 째 request부터 dashboard의 내용을 볼 수 있다고 한다.

Stateless application의 경우, 백엔드에 DB를 사용하여 로그인 시 세션 정보를 DB에 저장한다. 두번 째 request에서는 세션 정보를 DB로부터 가져와서 인증 완료 후 처리한다. 여기에는 DB lookup 오버헤드가 발생한다.

Stateful application은 로그인 시 세션 정보를 서버 자체적으로 저장해 두기 때문에, 두번 째 request에서 DB콜을 할 필요가 없어서 성능이 상대적으로 빠르다.

하지만 stateful application은 horizontally scale이 불가능하다. 즉, 로드밸런싱을 위해 두개 이상의 서버가 돌아간다면 두 서버의 state가 동기화가 안된다. 예를 들어, 첫번 째 login request는 1번 서버로, 두번 째 dashboard request는 2번 서버로 간다면 문제가 생길 것이다.

Stateless Container Management

Stateless application은 다양한 방식으로 동작하지만, 기본적으로 서버에 state를 보관하지 않는다. 대신, stateful한 DB를 별도로 이용하여 state를 보관한다.

예시로, client가 로그인을 할 때 로그인 인증 정보를 제공하면 stateless application은 인증토큰을 생성하여 DB에 저장하고 해당 인증토큰을 다시 client에게 리턴한다. 그 이후부터 client는 인증토큰과 함께 request를 하며, stateless application의 어떤 서버가 request를 받아도 DB에 있는 인증토큰과 비교한다. 즉, stateless한 인증서버의 모든 client request는 REST와 같이 독립적이다.

Stateless application은 DB를 호출해야 한다는 오버헤드가 있지만, 수백만 유저들이 사용하는 앱에서는 horizontal scaling을 통해 트래픽을 로드밸런싱 할 수 있다는 큰 장점이 있다.

Stateless application은 monolithic 설계에서 microservice 설계로 넘어가게 해준다.

<aside> 🤔 Stateful한 서버(DB)를 이용하지 않는 stateless application이 있을까?

</aside>

Difference Between Stateful vs. Stateless Applications