Become a member!

Server-Side Session Management in DMVCFramework: A Deep Dive into Database Sessions and Community Contributions

With the continuous evolution of DMVCFramework, one of the most appreciated frameworks for building web applications in Delphi, a significant change has been introduced: the new server-side session management system. This update represents a major step forward in terms of modularity and flexibility, allowing developers to choose from different session storage modes based on their project’s specific needs.

In this article, we will explore how this new session management system works, with a particular focus on database sessions, which are especially useful in cluster environments and load-balancing scenarios. Additionally, we will highlight how the development of this feature was made possible thanks to the support of a Patreon supporter, showcasing the power of community-driven development.

We will provide detailed explanations, practical examples in Delphi, and insights into why this new approach is a game-changer for modern web applications (expecially those based on HTMX).


Introduction to the New Session Management System

In previous versions of DMVCFramework, session management was built directly into the framework’s core. While functional, this approach limited flexibility and scalability in case you need to share server session data among a cluster of server. This was not a problem when you use JWT (which allows a stateless API) but in case of server session in a clustered environment that maybe a problem. With the new version under development (soon to be released as stable), session management has been externalized into middleware, making the framework more modular and adaptable.

In this case, middleware session engines act as intermediaries between the framework and external resources, such as databases or file systems, to handle specific operations. For sessions, middleware allows developers to choose from different storage modes, each with its own advantages and trade-offs.

Currently, DMVCFramework supports three session storage modes:

  1. In-Memory: Session data is stored in the server’s RAM. This mode is fast but not persistent, meaning data is lost if the server restarts.
  2. File-Based: Session data is stored in files on the server’s file system. This mode is persistent but may be slower compared to in-memory storage.
  3. Database: Session data is stored in a database. This mode is persistent, scalable, and ideal for distributed applications or scenarios requiring session sharing across multiple servers. It is slower compared to the other two.

Why Database Session Management is a Game-Changer

Database session management is one of the most awaited features introduced in DMVCFramework. Unlike in-memory or file-based sessions, this mode stores session data directly in a database, making it accessible from multiple servers. This is particularly useful in complex scenarios, such as:

  1. Cluster Environments: In a cluster setup, multiple instances of an application run on different servers. Database session management ensures that all servers can access the same session data, avoiding inconsistencies or data loss.
  2. Load Balancing: When an application is distributed across multiple servers with load balancing, user requests may be handled by different servers. Database session management ensures that session data remains consistent, regardless of which server handles the request.
  3. Data Persistence: Session data stored in a database is persistent, meaning it survives server restarts. This is critical for applications requiring high reliability.

🔔 In the next weeks the PATREON community supporters (All-Access-Level+) will get a new video explaining all the news about sessions.


Community-Driven Development: A Patreon Supporter’s Contribution

The development of database session management was made possible thanks to the support of a Patreon supporter. This community member needed a robust solution for session management in their software for a distributed environment with load balancing.

Their contribution funded the development of the session based middleware, which integrates session management with DMVCFramework’s ActiveRecord system. This is a great example of how the community can positively influence the development of an open-source project by funding specific features that address real-world needs.


Configuring Database Session Management

To use database session management, you need to configure the TMVCSessionDBActiveRecordMiddleware and create a table in your database to store session data.

Database Table Script

Here is the SQL script to create the session table in PostgreSQL:

CREATE TABLE dmvc_sessions (
    session_id VARCHAR(40) PRIMARY KEY,
    session_data BYTEA,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

The table is very simple. Here’s the script for:

Any other db engine supported by TMVCActiveRecord works without any known issues.

Configuration in Delphi

Here’s how to configure the middleware for database session management:

uses
  MVCFramework, MVCFramework.Middleware.Session;

procedure TMyWebModule.WebModuleCreate(Sender: TObject);
begin
  fMVC := TMVCEngine.Create(Self,
    procedure(Config: TMVCConfig)
    begin
      //code generated by the wizard, omitted for brevity
      //...
    end);

  // Controllers
  fMVC.AddController(TMyController);
  // Controllers - END

  // Middleware
  // To use memory session uncomment the following line
  // fMVC.AddMiddleware(UseMemorySessionMiddleware);
  //
  // To use file based session uncomment the following line
  // fMVC.AddMiddleware(UseFileSessionMiddleware);

  // To use database based session use the following lines
  fMVC.AddMiddleware(TMVCActiveRecordMiddleware.Create('FireDACConDefName')); {session table must exists}   
  fMVC.AddMiddleware(UseDatabaseSessionMiddleware(0)); {0 means "no timeout" a.k.a. "session cookie"}  
  // Middleware - END

end;

In this example:

  • UseDatabaseSessionMiddleware is a function which creates and configure all the objects that handles database sessions.
    • In this configuration sessions are going to be stored in the default database configured by the TMVCActiveRecordMiddleware connection. In this case is the connection identified by ‘FireDACConDefName’;
  • 0 is the session timeout in minutes. 0 (the default value) means “no timeout”.

WARNING: the configuration key Config[TMVCConfigKey.Session_Timeout] has been removed, so you will get a compilation error if you use it in your code. Just remove it from your code (if you use it) and configure your server as explained in the sample. The new Wizard has been updated to doesn’t generate the line which refers to TMVCConfigKey.Session_Timeout.


Using Database Sessions in a Cluster Environment

In a cluster or load-balancing environment, database session management ensures that all servers can access the same session data. Here’s an example of how to use sessions in a controller:

uses
  MVCFramework, MVCFramework.Commons;

type
  TMyController = class(TMVCController)
  public
    [MVCHTTPMethods([httpPOST])]        
    [MVCPath('/session')]
    procedure SetSession;
    [MVCHTTPMethods([httpGET])]    
    [MVCPath('/session')]
    procedure GetSession;
  end;

procedure TMyController.SetSession;
begin
  // Store a value in the session
  Session['username'] := 'JohnDoe';
  Render('Session value set.');
end;

procedure TMyController.GetSession;
var
  Username: string;
begin
  // Retrieve a value from the session
  Username := Session['username'];
  Render('Session value: ' + Username);
end;

In this example:

  • The SetSession action stores a value (username) in the session.
  • The GetSession action retrieves the value from the session and returns it as a response.

Thanks to database session management, this data will be accessible from any server in the cluster, ensuring consistency and persistence.


Benefits of Database Session Management

Here are some of the key benefits of this mode:

  1. Scalability: Ideal for applications distributed across multiple servers.
  2. Persistence: Session data survives server restarts.
  3. Sharing: Session data is accessible from all servers in the cluster.
  4. Reliability: Reduces the risk of session data loss in case of server failures.

Acknowledging the Community

The development of database session management is a concrete example of how the community can actively contribute to improving an open-source project. Thanks to the support of a Patreon member, DMVCFramework was able to implement an advanced feature that addresses real-world, complex needs.

If you have specific requirements or want to contribute to the development of DMVCFramework, consider supporting the project on Patreon. Every contribution makes a difference!


Practical Examples: Configuring All Session Modes

To give you a complete understanding, let’s look at how to configure all three session modes in DMVCFramework.

1. In-Memory Session Management

uses
  MVCFramework, MVCFramework.Middleware.Session;

procedure TWebModule1.WebModuleCreate(Sender: TObject);
begin
  FMVC := TMVCEngine.Create(Self);
  //Other configurations...
  // Configure the middleware for in-memory session management
  FMVC.AddMiddleware(UseMemorySessionMiddleware);
end;

2. File-Based Session Management

uses
  MVCFramework, MVCFramework.Middleware.Session;

procedure TWebModule1.WebModuleCreate(Sender: TObject);
begin
  FMVC := TMVCEngine.Create(Self);

  // Configure the middleware for file-based session management
  FMVC.AddMiddleware(UseFileSessionMiddleware);
  //Other configurations...
  //Optionally you can define the path where the session files are stored
  // FMVC.AddMiddleware(UseFileSessionMiddleware(0, 'MySessionFolder'));
end;

3. Database Session Management

uses
  MVCFramework, MVCFramework.Middleware.Session, MVCFramework.Middleware.ActiveRecord;

procedure TWebModule1.WebModuleCreate(Sender: TObject);
begin
  FMVC := TMVCEngine.Create(Self);
  //Other configurations...
  // Configure the middleware for database session management
  FMVC.AddMiddleware(TMVCActiveRecordMiddleware.Create('FireDACConDefName')); {session table must exists} 
  FMVC.AddMiddleware(UseDatabaseSessionMiddleware);
end;

Conclusion

The new server-side session management system in DMVCFramework, particularly the database session mode, is a powerful and versatile feature that addresses the needs of modern web applications (expecially those based on HTMX). Its ability to handle cluster environments and load-balancing scenarios makes it an essential tool for developers building scalable and reliable systems.

Thanks to the support of the community, this feature was developed to meet real-world needs, demonstrating once again the importance of collaboration in the open-source world.

🔔 In the next weeks the PATREON community supporters (All-Access-Level+) will get a new video explaining all the news about sessions.

We hope this guide has been helpful and encourage you to experiment with database session management in your projects. If you have any questions or need further clarification, feel free to ask! Happy coding!

Need More?

Join PATREON Community to get support the project and access to premium contents as articles, video and misc insigth. Remember to join PATREON community to get valuable informations, tutorials, insight, get priority support and more. You can also support the project through Buy Me a Coffe and gets the same benefits.

Enjoy!

– Daniele Teti

Comments

comments powered by Disqus