Posts Tagged ‘Transactions’

Recently I was working on a strange problem faced by a development team.They had used .NET 2.0 Lightweight Transaction Manager provided by the classes under System.Transaction namespace.Within the TransactionScope a long running database job was executing.They faced an intermittent TransactionAbortedException saying “Transaction has been aborted”.

After taking a look into the code it was found that they are using a ADO.NET Command Timeout of about 900s.But there is no command timeout set for the Transaction.The default timeout period of Transaction is 60s.So there can be a situation where the database job is taking more than a minute to complete and Transaction Manager is aborting the transaction as transaction timeout has expired even though database process has not timed out.

We can set the Transaction timeout in two ways using the constructor of the TransactionScope class or config.

  • The following two constructors of TransactionScope class accepts a TimeSpan parameter which defines the timeout period for the code executing within the context of that TransactionScope.
    • public TransactionScope(Transaction transactionToUse,TimeSpan scopeTimeout)
    • public TransactionScope(TransactionScopeOption scopeOption,TimeSpan scopeTimeout)
  • We can also define the timeout in the application configuration (web.config or app.config) as shown

                 <system.transactions>

                       <defaultSettings timeout=”02:00:00″/>

                </system.transactions>

            We need to define the max timeout setting at machine level in machine.config

            <system.transactions>
                    <machineSettings maxTimeout=”02:00:00″/>
            </system.transactions>

But it was very surprising that there was no timeout exception instead a transaction aborted message which was very confusing.Then I came to know from the following MSDN Forum post that timeout is actually wrapped as an inner exception:

http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/9f9c1d11-6c0d-423e-bffc-4d1957e9bdd7

Then I wrote the following snippet to simulate the situation:

using(TransactionScope scope = new TransactionScope(
                                TransactionScopeOption.RequiresNew,
                                new TimeSpan(0,0,30)))
{
     Console.WriteLine(“Entered Transaction Scope”);
     System.Threading.Thread.Sleep(60000);
     Console.WriteLine(“Start Commit”);
     scope.Complete();
     Console.WriteLine(“Transaction Complete.”);
}

Here I have set transaction timeout 30 s and the code block will take 60 s to execute.

The program threw an exception as shown below:

timeout

But surprisingly the exception was not thrown just after 30 s elapsed.The exception was thrown after the entire code block completed it’s execution.The exception was thrown while exiting from the using {} block.So I changed the code as follows:

try
          {
              Console.WriteLine(“Entered Transaction Scope”);
              System.Threading.Thread.Sleep(60000);
              Console.WriteLine(“Start Commit”);
              scope.Complete();
              Console.WriteLine(“Transaction Complete.”);
          }
          catch
          {
              throw;
          }
          finally
          {
              scope.Dispose();
          }

Then I found out that this exception is thrown from scope.Dispose();

Advertisements

WCF Transactions-Part I

Posted: August 20, 2008 in Transactions, WCF
Tags: ,

In this post I will discuss about the basics of implementing a transaction aware WCF Service.Like many other features of WCF a transaction aware service can be very easily implemented using the declarative programming model and configuration settings.
The important attributes related to transaction are:

TransactionFlow

This attribute determines how a transaction should flow from client to the service.The three options specified by the TransactionFlowOption enumeration are
1)Mandatory
This makes transaction flow from client mandatory.If there is no transaction flowing from the client then an exception will be thrown.Making TransactionFlow mandatory for a service operation makes the service too tightly coupled with the client as clients without a transaction will never be able to use this method.
2)Allowed
This indicates that a transaction may or not flow from the client and this is the most flexible of the three options.
3)Not Allowed
This indicates any client transaction flowing will not be allowed and an exception will be thrown.

To create a transaction aware service we have to make the TransactionFlow attribute of the service operation mandatory/allowed:

[TransactionFlow(TransactionFlowOption.Allowed)]  
[TransactionFlow(TransactionFlowOption.Mandatory)]

We also have set the transactionFlow attribute of the binding in the configuration to true

<wsHttpBinding>
 <binding name=”wsHttp” transactionFlow=”true” />
</wsHttpBinding>

These settings needs to be applied both at the client as well as server end.

TransactionScope parameter of OperationBehavior Attribute

This parameter of OperationBehavior attribute if set to true then the service will join the transaction flowing from the client else it will create a new transaction.If set to false then it will never participate in a transaction.The default value is false.

TransactionAutocomplete parameter of OperationBehavior Attribute


This parameter if set to true the transaction will complete if the operation executes without any exception.By default this is set to true.If  it is false then the transaction completion has to be done programmatically using the SetTransactionComplete method of the OperationContext class.

We need to perform the following steps to make a service transaction aware:
Server Side

  1. Set TransactionFlow attribute to Allowed/Mandatory.
  2. Set transactionFlow attribute of the binding in the configuration to true.
  3. Set the TransactionScope to true and TransactionAutocomplete to true.

Client side

  1. Set TransactionFlow attribute to Allowed/Mandatory in the generated proxy class.
  2. Set transactionFlow attribute of the binding in the configuration to true.
  3. Invoke the service operation within a TransactionScope

In the next post I will discuss about the TransactionIsolation/Timeout and Session.

In my last post I had discussed about the Lightweight Transaction Manager(LTM) introduced with .NET 2.0.In this post we will take a look at MSDTC and how we can handle distributed transactions.
Microsoft Distributed Transaction Coordinator(MSDTC) can handle transactions with
1) Multiple Durable Resource Managers
2) Transaction Flow crossing process and machine boundaries.

As we have seen in the first post, in a transaction which is distributed across machines every box has a local transaction manager.The local transaction manager of the machine which initiates the transaction is called root transaction manager and it coordinates with local transaction managers in other machines.So all the transaction managers need to have a communication protocol for interacting messages over the network.For a distributed transaction across multiple windows machines each machine will have MSDTC as it’s local transaction manager and one of them will be the root.This is not a problem as MSDTC running on windows can communicate over network using RPC.

But what happens if one of the machines is running on Unix with a different transaction manager?

This is a question cross platform communication for distributed transaction related messages.Here also the Web Services standards come to our rescue.

There are two web Services standards for implementing this WS-coordination and WS-AtomicTransactions.
I will try to explain them briefly below:

WS-Coordination(WS-COOR)

This protocol defines an extensible coordination framework among different Web Services.It introduces a new SOAP Header block called Coordination Context.
The Web Service acting as a coordinator sends a Coordination context header to the target services.The target services upon receiving the coordination context analyses the information contained in the Coordination context header and decides to join the coordination or not.
The information contained in the coordination context depends upon the coordination type.The coordination types are open ended and new ones can be added.

WS-AtomicTransaction(WS-AT)

Atomic Transaction is one coodination type.This is built upon WS-Coordination framework and supports 2PC.But the messages are exchanged in SOAP format and thus achieving platform interoperability.

so to have distributed transactions with machines running on different platforms the local transaction manager supported by each platform should be able send and receive WS-COOR and WS-AT compliant XML messages over HTTP.

Transactions

Posted: August 4, 2008 in Transactions
Tags: ,

Transaction

By transaction we mean a group of tasks which are executed together.If anything goes wrong in any one of them then outcome of the entire set is rolled back.After rollback the system returns to it’s original state i.e. the state before execution of transaction started.Changes are only committed if all the tasks are completed without any problem or failure.

ACID Properties

  1. Atomic – This describes the all or nothing feature of transaction.For example a transaction in document upload may contain two steps saving the file in server disk and inserting a record for the document in database.Here the transaction will be successful if both file and database record is successfully saved,if there is a problem in any one operation none will be saved.
  2. Consistent- Transaction should always leave the system in consistent state.Think of the above example if the database record is saved and file is not then the system would have become inconsistent having metadata for document whose actual file is missing.
  3. Isolated-Transactions has to operate in isolation until they are complete.For example when the file is not saved yet,database record for document is saved and it is visible to other users in document list screen.Other user might click that link to find that no file is attached and it will appear like a phantom record.
  4. Durable-No information should be lost even if the machine goes down when a transaction is executing.

Distributed Transactions

A transaction when involves multiple persistent resources(e.g. databases) or spans across process/machine boundary is referred to as a distributed transaction.

Transaction Management

Transaction Management is neccessary to maintain the ACID properties of the distributed transaction.The two key components  of transaction management are:

  1. Transaction Manager – A transaction manager manages commit/abort and monitors status of each task by coordinating with the corresponding resource managers.
  2. Resource Manager – A resource manages state of a particular resource based on the instructions from the transaction manager.
    • Durable Resource Manager – Manages persistent resource
    • Volatile Resource Manager – Manages in-memory resource

Two Phase Commit(2PC) Protocol

Phase 1

  • Coordinator asks each of the resource managers to commit
  • Each resource manager responds whether they are about to commit or abort.
  • Coordinator collects the responses and decides whether to commit/rollback the transaction as a whole.

Phase2

  • Coordinator informs the resource manager it’s decision to commit/rollback
  • Resource managers acknolwdges the message to commit/rollback
  • Coordinator waits for acknowledgement of the resource managers

In a distributed transaction spanning across multiple server each server has  a local transaction manager and all resource managers in that server enlists with that local transaction manager.The local transaction managers in turn communicate with each other.There is superior/subordinate relationship  between each local transaction manager and the corresponding resource managers in that box.The local transaction manager of the server where the transaction is initiated is called root transaction manager or the global commit coordinator.So this is the root of the commit tree and the enlisted resource managers and other local transaction managers are it’s children.Each resource manager depends on it’s local transaction manager for commit/abort decision and each local transaction manager depends upon it’s superior transaction manager (if any) for the commit/abort decision.

The transaction manager maintains a log on disk. The log is a sequential file with transaction events. The transaction manager records transaction starts, enlistments, and commit decisions in the log. During normal processing, the transaction manager only writes to the log. However, if the transaction manager fails, it reads the log when it restarts to reconstruct the most recent state, using the log to make its state durable.