If you have ever developed and worked with a WCF service you may have noticed that the very first time you connect to a newly started instance of the service there can sometimes be a noticeable delay before the service responds. But invoking subsequent operations often seems almost instantaneous. Usually the delay is relatively short, perhaps even just a fraction of a second, but still noticeable. Well earlier this week I encountered a WCF service that exhibited this behavior, but the delay for the first operation was almost three minutes! Something had to be done.
Some time later, after much debugging, web searching and more than a little head scratching, we realized that the “problem” that we were seeing was actually “by design” in WCF and was related to the generation of metadata for the service. It turns out that if “metadata exchange” is enabled for the service then WCF generates the metadata, regardless of whether anyone is currently requesting it or not, at the time that the first operation is requested by a client. Often the generation of the metadata takes almost no time at all, but as the size and complexity of a service grows (in terms of the number of operations exposed, the number of parameters, the number and nature of complex types exposed, etc.) the time taken to generate the metadata grows. In the case of this particular service there were over 800 individual operations defined, with lots and lots of complex types being exposed, and the service was still growing!
The only time you need metadata exchange enabled is when you need to access the WSDL for the service, so in simple terms whenever you need to do an “Add Service Reference” or “Update Service Reference”. The rest of the time having it enabled is just slowing things down at runtime.
I can’t tell you exactly how to enable and disable metadata exchange with your service, because there are several different ways it can be configured, but it’s likely going to be one of these:
- A <serviceMetadata/> token used in the <serviceBehaviors> section of a Web.config or App.config file.
- An <endpoint/> token that uses the IMetaDataExchange contract defined in a <service/>section of a Web.config or App.config file.
- Code that does the equivalent of one of the two options above.
So the lesson learned was to enable metadata exchange only when it is needed, for the purpose of creating or updating client proxy code; the result was an almost instantaneous response from the service once metadata exchange had been disabled. Of course it goes without saying that metadata exchange should NEVER be enabled on production services.