Thursday, July 13, 2006

Web server and database server time difference

Time difference between web server and database server can cause hard-to-find bugs. This is what I experienced recently after deploying a web application to a live server. Unlike our development server where IIS and SQL Server reside in one machine, in the live server we have a SQL Server sitting in one machine and IIS sitting in another machine.

For some reasons, time syncronization in both servers (Windows 2003) did not work and as a result there was significant time difference between the two servers.
Because of the time difference, application features that depend on comparison between current time and stored datetime value will not work properly. For example, when I save User's password expiry date, I call DateTime.Now from the application (using the web server's time) and save the value to the database. In the stored procedure, I check if a password is expired using statement like:

-- check if password is expired
IF @PwdExpDate <= GETDATE()
    
-- password is expired
    
ELSE
    
-- password is still valid



Since Password Expiry Date is set in the web server and then compared in the database server, this comparison does not work properly due to the time difference.

Although fixing time difference between the two servers is easy, I started to think whether we can always safely assume that both the web server and database server has the same time. Or do we need to introduce a programming guideline here:

"Datetime that is set in one machine can only be safely compared to the current time from the same machine"

In my case, the above guideline implies to moving the comparison logic from stored procedure to the application layer, or the other way around, setting the expiry date at the stored procedure and perform the comparison in the stored procedure as well.

No comments: