0

I'm building my own HTTP request via .NET C# (HttpWebRequest) to post data to the google analytics measurement protocol. I've set the http timeout to 30 seconds, which is pretty huge. Yet I often see timeouts occurring in my environment and on customer environments. This isn't consistent, which means its probably not a firewall thing.

I don't believe google defines what timeout to use. Any ideas on what I might be doing wrong or if I should increase the timeout (30 seconds should really be enough).

var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com/collect");
request.Method = "POST";

// the request body we want to send
var postData = new Dictionary<string, string>
{
   { "v", "1" },
   { "tid", "UA-XXXXXXXX-X" },
   { "cid", userID.HasValue ? userID.Value.ToString() : "555"},
   { "t", type.ToString() },
   { "cd", screenName },
   { "cd1", "Custom 1"},
   { "cd2", "Custom 2"},
   { "cd3", "Custom 3 }
};

if (string.IsNullOrEmpty(postData["cd"]))
   postData.Remove("cd");

foreach (var keyValue in keyValues)
{
   postData.Add(keyValue.Key, keyValue.Value);
}

var postDataString = postData
            .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
             HttpUtility.UrlEncode(next.Value)))
            .TrimEnd('&');

// set the Content-Length header to the correct value
request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);
request.Timeout = 30000;
// write the request body to the request
using (var writer = new StreamWriter(request.GetRequestStream()))
{
   writer.Write(postDataString);
}

try
{
   var webResponse = (HttpWebResponse)request.GetResponse();
   if (webResponse.StatusCode != HttpStatusCode.OK)
   {
      throw new ApplicationException("Google Analytics tracking did not return OK 200. Instead it returned " + webResponse.StatusCode.ToString());
   }
}
catch (Exception ex)
{
   logger.Error(ex.ToString());
}
Mark
  • 5,223
  • 11
  • 51
  • 81

1 Answers1

1

Web browsers generally have a 30 second timeout. That might be a good place to start. This says 1-2 minutes: Browser Timeouts

$ time telnet google-analytics.com 80
Trying 173.194.79.103...
Connected to google-analytics.com.
Escape character is '^]'.
Connection closed by foreign host.

real    4m0.212s
user    0m0.012s
sys 0m0.012s

Looks like 4 minutes is the max you should use. You could also consider retrying if you are worried the data was not sent.

Community
  • 1
  • 1
David Pattison
  • 269
  • 1
  • 3
  • How did you come up with the 4 minutes. I'm not exactly sure what time telnet does. – Mark Oct 29 '14 at 17:06
  • man time - run programs and summarize system resource usage man telnet - used for interactive communication with another host – David Pattison Nov 05 '14 at 23:02