Essential API Facade Patterns: Session Management (Episode 2)


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Design related- How do I design the right kind of interfaces on the server side?When should I really rely on Session Management, notwithstanding the How about authenticated sessions?How long the session should live?How much context data can be stored?Implementation relatedHow do I implement thisServer / Client In case of APIs what are the other considerations?How about persistence of session?How about scalability?
  • Back-endsProduct catalogueInventory ManagementPricing engine, Promotion / Tax rulesERPthe Backend stack here would beshared by multiple channels– Online ecommerce could be one of them. Hence The backend is not dedicated for the eCommerce and the problems associated with allowing such transaction flow through.
  • The backend is not designed for Storing client contextor managing sessionsNot enough resourceThe interfaces are stateless, by design
  • The eCommerce application While the backend is the master of records, the application layer does quite a lotIt manages all user centric resources…. Presentation managementManage user profile & preferences, identity management Campaign management Content management on top of the product catalogueManage eCommerce workflow & session ( provide store, shopping cart and all that Allow scale for Web Channel – The implementations of the Web Layer are quite crafty – but finally it works for the developers quite easilyThe two most basic techniques for Server Session State are using the http session and using a stateful session bean. The http session is the simple route and causes the session data to be stored by the Web server. In most cases this leads to server affinity and it can't cope with failover. Most app server vendors have implemented a shared http session capability that allows you to store http session data in a database that's available to all application servers.
  • So these Applications are capable of serving pages which contains state transitions ( or session embedded in the page responses)
  • How do we reuse this capability while exposing the APIsAll REST definitions are supposed to have resources – but the implementations provide no framework to link between resourcesThe implementations are quite crafty – but finally it works for the developers quite easily – session management is provided by the container.
  • How do I manage client state & session? Changing backend is toughHow do I manage HUGE VOLUMEs of such sessions?My backend does not do analytics!
  • We need a services layer in the middle to manage session state. So the solution will work by exposing RESTful APIs and managing stateful interactions by REST But before we go there – What is this services layer consisting of?
  • The services layer is a logical architecture component. It can be implemented by number of components such as Application servers, databases, API management & exposure layer, analytics and so on. The good news is that the Façade Layer does not need to rebuild all the existing capabilities. The API Service Layer is a Façade on top of the existing capabilities.
  • We need a Façade layer in the middle toHold the transient resources – which represents the state Expose REST APIs that allows access to these transient resource in RESTful mannerProtect the backend from the overhead of managing client stateIt is more of design principle – not so much about the actual implementation.
  • This gels in well with the concept ofhypermedia as the engine of stateI am not going to dig into what HATEOAS and what it is not. It is one of the principles or constraints of REST -REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.I would rather just use the most basic definition of Roy Fielding's often cited HATEOAS The next control state of an application resides in the representation of the first requested resourceEssentially every page representing a state and links in that page representing every possible transition from the current state.On a side note – why is HATEOAS difficult? Or for that matter REST difficult? Because there is no enforcement of the REST principle as a protocol or standard.
  • Next action can be adding the product to a cart
  • HATEOAS and REST is great, but,So what does it have to do with Session Management?
  • What are the solution benefits of this pattern of introducing a API Façade in the middle & exposing REST APIsThat manages session state as part of state transition of the resourceLet us dig a little more to understand the responsibilities of the “ API Façade “ in this particular design pattern
  • Let us again hypothetically take the shopping cart scenarioWhat all happens in the middle?Master system of record is somewhere out side the API Façade in the backendThe API Façade is however creating and managing the state transition of the cartIt manages the cart as a REST resourceThe stress of this diagram is the point that the stateful resources are mostly transient in nature. That is kept separate from the master records and transaction systems.
  • Especially the stateful transient resources --- In other words, a server should not have to retain some sort of communication state for any of the clients it communicates with beyond a single request. REST sort of mandates that state be turned into resource state or the interaction be stateless. creating these resources and managing session in the middle has benefits for the Developer What is it?REST itself
  • The greatest case in point for Session State in the facade is its simplicity State transition is easy – as each representation has the state transitions embedded as linksDeveloper does not have to control the stateDoes not have to maintain the entire state information and resubmit each timeLess network data to be submitted. Less programming over headCrafty APIPotentially the Developers would Love this kind of any API
  • For the API team the benefits are even broaderThe API Façade can be implemented as highly scalable set of infrastructure – which is generally available as part of the platform. And importantly – like mentioned before - API Façade can have state persistent behind the Façade or it can reuse existing session management infrastructure ( like an App server running in the back)The developer or the provider does not have to to code for this Also the backend is not impactedMost of the time backend legacy systems are not designed to support these types of session state management, nor it is scalable for the backend to do so. The Services Layer introduced in the middle to handle millions of calls per day is able to manage the state information for such scenarios.
  • The API Façade has additional capabilities to protect a session state ….Often we need a session parameter to be sent over the network…. Provides SSL offloading to secure session parametersCan provide time-expiry based sessionsCan identify replay attacks based on source and known request patternsCan disable specific clients by disabling rogue usersCan throttle illegally high request volumes so that backend is protected
  • There are choices – How much data to be persisted in the sessionHow much can be in-memory How much should be persisted in the DBWhat should be sticky ( as in sticky session)It is easy to implement Business rules or data mapping rules on the server side.In the context of session / state – it is often required to think about different implementations.Session at http levelSession implementation at a container level – e.g. a java session beanSession in the DBDifferent implementation approaches are possible.
  • API usage Analytics is a broad area. We know It is done well by introducing an API Façade in the middleWhen it comes to a session based interactions – we have an unique opportunity to track the entire session and generate analytics on progress of a workflow or a sequential transaction…Like what % of clients did progress halfway through but did not complete a transactions?
  • when session management would be used versus when it's not? what are the key characteristics? how do i decide?
  • If it is too much overhead to send back the entire context data each timeThere are two options to authenticationAuthenticate once and issue an authenticated session and continue to use that. Or. Each request will need to be authenticatedIf the interactions do not mandate a sequence of calls - or you do not require three legged Oauth kind of authentication - I would recommend sessionless interactionSometimes authentication in each request is costlyIn case of Oauth you can not avoid the authentication in a simple way. Authentication of developer and the user is concerned. You can not do the Oauth dance for every single request. It is very costly to do Oauth. So you want to reuse the authenticated token for longer than one interaction. In a way that is a session. BTW, Signed requests are much stronger than mere session ids. { Cross-site request forgeries will be mitigated with this scheme. By authenticating all requests with a shared secret we don't have any time-bound sessions or timeouts. Just fire whenever you want. The persistent shared secret is much more sensitive than a temporary session id. A cross-site scripting attack will steal the shared secret which is much worse than session hijacking. This means the scheme is less suitable for browsing sessions and more suitable for machine-to-machine communication. }Evidently signed request is a good approach over authenticated session, but too much for a phone based application to implement
  • Information associated with Session or “transient resource” should be minimalHandling larger chunks of session data is obviously heavy on performance
  • Rules to expire session must be appliedUsability vs PerformanceIf the cart has to be long lived resource – it should be persisted outside the API Façade. Only transitional state should be persisted in the API Façade.
  • Essential API Facade Patterns: Session Management (Episode 2)

    1. 1. Essential API Facade PatternsEpisode 2 – Session ManagementSantanu Dey Apigee@Santanu_Dey @apigee
    2. 2.
    3. 3.
    4. 4.
    5. 5. @Santanu_Dey Santanu Dey
    6. 6. Webcast Series: API Facade PatternsEpisode 1CompositionEpisode 2Session ManagementEpisode 3One Phase to Two Phase ConversionEpisode 4Synchronous to Asynchronous
    7. 7. Episode 2 : Session ManagementProblemSolutionBenefitsConsiderations
    8. 8. ProblemUse Session Management toenable API teams and app developers to implementand improve their API designs and apps
    9. 9. Session ManagementManaging the state of dynamically created resources(per client) through a series of client-server interactions
    10. 10. Services are best kept stateless
    11. 11. But . . . sometimes stateful services are really needed
    12. 12. Example: shopping cart
    13. 13. Stateful interaction requires session Add / Check outCreate cart Track order remove Shopping Cart items Cart updated Order received Created
    14. 14. Example: room booking
    15. 15. Example: job application
    16. 16. Even OAuth requires a session
    17. 17. Session management helps in maintaining clientcontext (on the server)
    18. 18. State management and session managementare not the same
    19. 19. Session Managementis one of the ways of managing client state
    20. 20. In the context of APIs how to design Session Management? how to implement Session Management?
    21. 21. Application Servers solve this issue for the Web bymanaging client sessions
    22. 22. Application servers solved this problem for the Web Backend Browser App Server Server Users
    23. 23. Application servers solved this problem for the Web No stored client contextEach request must contain all on the transaction server state information Backend Browser App Server Server Users Order Processing Server • Server is stateless to be scalable • Not designed to handle client specific resource state
    24. 24. Application servers solved this problem for the Web Each request No stored client must contain all context on the state information transaction server Backend Browser App Server Server Users Web Order Processing Server Application • Server is stateless to be Manages user scalable sessions • Not designed to handle client specific resource state
    25. 25. Application servers solved this problem for the Web Each request must No stored client contain all state context on the information transaction server Backend Browser App Server Server Users Web Order Processing Server Very close to Application • Server is stateless to be Hypermedia Manages user scalable Interface sessions • Not designed to handle client specific resource state
    26. 26. But, we need an App!
    27. 27. Solution
    28. 28. If application servers solved this problem for the Web How do we reuse this capability when exposing APIs? Each request must No stored client contain all state context on the information transaction server Backend Browser App Server Server Users Web Order Processing Server Very close to Application • Server is stateless to be Hypermedia Manages user scalable Interface sessions • Not designed to handle client specific resource state
    29. 29. In mobile applications parlance managing client stateon the device is expensive Requires more local processing Requires more local storage Requires more date exchange over the network
    30. 30. Managing client state on the back-end server isexpensive too.
    31. 31. Stateful interaction with RESTful APIs API Façade Backend ServerApp relies onREST
    32. 32. Example of the API Façade API Façade API Existing Backend Exposure & Capabilities Server MgmtApp relies on REST
    33. 33. Stateful interaction with RESTful APIs Totally Stateless Interface API Façade Backend ServerApp relies on REST
    34. 34. Stateful interaction with RESTful APIs Provide HATEOAS Totally stateless Interface API Façade Backend Server Holds transient stateApp relies on REST information & provides the hyperlinks for the state transition
    35. 35. View a productReturns the details of a product along with hypermedia to allowinteraction with the product resource.GET http://yourhost/products/sku/098430?user=123&cart=2235{ "Product":{ "item-name":"MTune MP3 Player", "description":"2GB MP3 Player", "unit-price":"34.56", "sku":"098430", "link":{ "@attributes":{ "url":"/cart/id/2235/addProduct/sku/098430?user=123" } } }}
    36. 36. Add a productAdds a Product to an existing shopping cart & returns the cart.POST http://yourhost/cart/2235/addProduct/sku/098430?user=123 { "Cart":{ "id":"2235", "Name":"Christmas Shopper", "link":{ "@attributes":{ "url":"/cart/id/2235" } }, "items":{ "item":{ "item-name":"MTune 2GB MP3 Player", "description":"MTune, MP3 player", "unit-price":"34.56", "quantity":"1" } } } }
    37. 37. State of the cart helps represent the shopping session
    38. 38. Benefits
    39. 39. Manages session state as part of state transition ofthe resource API Façade Backend Server
    40. 40. Warning! UML Ahead
    41. 41. API Façade provides access to transient resourcesthrough RESTful APIs
    42. 42. App Developers consume REST more easilyApp Developer Doesn’t have to control the state Doesn’t have to maintain the entire state information Doesn’t have to resubmit each time Less programming overhead
    43. 43. The API Façade addresses scalability while managingtransient resources API Façade Backend Server
    44. 44. The API Façade addresses replay attack, sessionhijacking concerns API Façade Backend Server Malicious user
    45. 45. Programmable
    46. 46. Can capture analytics around session usage
    47. 47. Other Considerations
    48. 48. When should we really think about SessionManagement?
    49. 49. If it is too much overhead to send back the entirecontext data each time
    50. 50. Information associated with Session or “transitresource” should be minimal
    51. 51. Session should be expired within a short time (securityconcern)
    52. 52. Questions?
    53. 53. THANK YOUSubscribe to API webcasts Apigee @apigee
    54. 54. THANK YOUQuestions and ideas Apigee @apigee
    55. 55. THANK YOUContact me Apigee @apigee