Redis Connection - Multiplex it or not? - c#

In terms of performance, is it better to multiplex 1 connection object across multiple requests or to give each request it's own connection?

Well, what redis client are you using? StackExchange.Redis is explicitly designed to be multiplexed and shared between multiple requests (or any other parallel load); other clients may not be, and may require you to lease from a pool per request (or for some portion of a request). There is quite a lot of overhead involved in establishing a connection with redis (optionally DNS, sockets, optionally TLS, and a bit of chit-chat backwards and forwards to determine the redis server configuration), so you don't want to completely establish a new underlying connection per request (even if it is fast).

Related

Any Downside to Increasing "maxconnection" Setting in system.net?

Our system was having a problem with WCF connections being limited, which was solved by this answer. We added this setting to the client's web.config, and the limit of two concurrent connections went away:
Outside of the obvious impacts (e.g. overloading the server), are there any downsides to setting this limit to a number (possibly much) higher than the default "2"? Any source on the reasoning for having the default so low to begin with?
In general, it's OK to raise the client connection limit, with a few caveats:
If you don't own the server, then be careful because your client app might be confused with a DoS attack which might lead to your client IP address being blocked by the server. Even if you own the server, this is sometimes a risk-- for example, we've had cases where a bug in our app's login page caused multiple requests to be issued when the user held down the Enter key. This caused these users to get blocked from our app because of our firewall's DoS protection!
Connections aren't free. They take up RAM, CPU, and other scarce resources. Having 5 or 10 client connections isn't a problem, but when you have hundreds of open client connections then you risk running out of resources on the client.
Proxies or edge servers between client and server may impose their own limits. So you may try to open 1,000 simultaneous connections only to have #5 and later refused by the proxy.
Sometimes, adding more client connections is a workaround for an architectural problem. Consider fixing the architectural problem instead. For example, if you're opening so many connections because each request takes 10 minutes to return results, then you really should look at a more loosely-coupled solution (e.g. post requests to a server queue and come back later to pick up results) because long-lived connections are vulnerable to network disruption, transient client or server outages, etc.
Being able to open many simultaneous connections can make it risky to restart your client or server app, because even if your "normal" load is only X requests/sec, if either client or server has been offline for a while, then the client may try to catch up on pending requests by issuing hundreds or thousands of requests all at once. Many servers have a non-linear response to overload conditions, where an extra 10% of load may reduce response time by 100%, creating a runaway overload condition.
The solution to all these risks is to carefully load-test both client and server with the maximum # of connections you want to support... and don't set your connection limit higher than what you've tested. Don't just crank the connection limit to 1,000,000 just because you can!
To answer the other part of your question, the default limit of 2 connections goes back to a very old version of the HTTP specification which limited clients to 2 connections per domain, so that web browsers wouldn't swamp servers with a lot of simultaneous connections. For more details, see this answer: https://stackoverflow.com/a/39520881/126352

Websockets persistant connection

Since the connection is persistent, i understand a lot of network congestion is prevented in setting up the new connection, in cases like periodic polling of hundreds of servers.
I have a simple question. Does not it put load on the both server and client to keep the connection persistent for a long time ? Is the gain made lost??
A TCP (and hence WebSocket) connection established to a server, but not sending or receiving (sitting idle), does consume memory on the server, but no CPU cycles.
To keep the TCP connection alive (and also "responsive") on certain network environment like mobile may require periodic sending/receiving of small amounts of data. E.g. WebSocket has built-in ping/pong (non app data) messages for that. Doing so then will consume some CPU cycles, but not a lot.
Persistent connections are a tradoff.
Yes, they require the server to store the state associated with each connection, they require maintenance (such as keep-alive packets or websocket pings), and they require monitoring (to detect state changes or arriving information). So you spend some memory and CPU resources per connection.
BUT they save a lot of time, and often resources, on connection re-initializations; once established, they allow both parties to send and receive information as opposed to non-persistent client-server systems like classic HTTP.
So it really depends on the system you're building. If your system has millions of users that need connectivity to the server only once in a while, then the benefit of keeping these connections open is probably not worth the extra resources. But if you're designing something like a chat server for hundred people, then the additional responsiveness is probably worth it.

Are TCP Connections resource intensive?

I have a TCP server that gets data from one (and only one) client. When this client sends the data, it makes a connection to my server, sends one (logical) message and then does not send any more on that connection.
It will then make another connection to send the next message.
I have a co-worker who says that this is very bad from a resources point of view. He says that making a connection is resource intensive and takes a while. He says that I need to get this client to make a connection and then just keep using it for as long as we need to communicate (or until there is an error).
One benefit of using separate connections is that I can probably multi-thread them and get more throughput on the line. I mentioned this to my co-worker and he told me that having lots of sockets open will kill the server.
Is this true? Or can I just allow it to make a separate connection for each logical message that needs to be sent. (Note that by logical message I mean an xml file that is of variable length.)
It depends entirely on the number of connections that you are intending to open and close and the rate at which you intend to open them.
Unless you go out of your way to avoid the TIME_WAIT state by aborting the connections rather than closing them gracefully you will accumulate sockets in TIME_WAIT state on either the client or the server. With a single client it doesn't actually matter where these accumulate as the issue will be the same. If the rate at which you use your connections is faster than the rate at which your TIME_WAIT connections close then you will eventually get to a point where you cannot open any new connections because you have no ephemeral ports left as all of them are in use with sockets that are in TIME_WAIT.
I write about this in much more detail here: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html
In general I would suggest that you keep a single connection and simply reopen it if it gets reset. The logic may appear to be a little more complex but the system will scale far better; you may only have one client now and the rate of connections may be such that you do not expect to suffer from TIME_WAIT issues but these facts may not stay the same for the life of your system...
The initiation sequence of a TCP connection is a very simple 3 way handshake which has very low overhead. No need to maintain a constant connection.
Also having many TCP connections won't kill your server so fast. modern hardware and operating systems can handle hundreds of concurrect TCP connections, unless you are afraid of Denial of service attacks which are out of the scope of this question obviously.
If your server has only a single client, I can't imagine in practice there'd be any issues with opening a new TCP socket per message. Sounds like your co-worker likes to prematurely optimize.
However, if you're flooding the server with messages, it may become an issue. But still, with a single client, I wouldn't worry about it.
Just make sure you close the socket when you're done with it. No need to be rude to the server :)
In addition to what everyone said, consider UDP. It's perfect for small messages where no response is expected, and on a local network (as opposed to Internet) it's practically reliable.
From the servers perspective, it not a problem to have a very large number of connections open.
How many socket connections can a web server handle?
From the clients perspective, if measuring shows you need to avoid the time initiate connections and you want parallelism, you could create a connection pool. Multiple threads can re-use each of the connections and release them back into the pool when they're done. That does raise the complexity level so once again, make sure you need it. You could also have logic to shrink and grow the pool based on activity - it would be ashame to hold connections open to the server over night while the app is just sitting their idle.

How can I optimize SSL session so I can reuse it later (if needed) to improve Client Server performance

I have a server running on Windows Azure here with a large key (link is intended to demonstrate large key in SSL cert). Based on this Security.SE conversation the larger key will be more expensive to setup and tear down from a CPU perspective.
Assuming I'm using a .NET client and a .NET server; what changes should I make (if any) to reduce the overhead of connecting / disconnecting an SSL perspective.
For the purpose of this conversation let's include these scenarios (add more if you can think of them)
WebBrowser to IIS
WCF client to WCF Server (IIS)
WCF client to WCF TCP
Sockets-based client to Sockets-based server
The cost of an initial handshake is basically fixed (given certain parameters). The cost of a resumed handshake is approximately zero.
The way to improve performance is to increase the amount of sessions that are resumed sessions, and not initial sessions. This amortizes the cost of the initial handshake across the resumed handshakes, reducing the average handshake cost.
The easiest way to increase the resumed handshake rate is to have a larger session cache size/timeout. Of course, having a large session cache can create its own performance issues. One needs to find a good balance between these two, and the best way to do that is with testing.
If the application is made to keep the WCF connections open, it may make sense to enable KeepAlive (it's disabled by default).
The TCP connection will be reused automatically when the keep-alive switch is turned on. For the ‘ServicePoint Manager, you can use theSetTcpKeepAlive method to turn on the keep-alive option for a TCP connection. Refer to the following MSDN article:
ServicePointManager.SetTcpKeepAlive Method
http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.settcpkeepalive.aspx
From Microsoft:
Generally the difference, in the perspective of performance, between common HTTP and HTTPS lies in the handshake of a TCP connection. It takes longer time for an HTTPS handshake, than HTTP. However, after the TCP connection is established, their difference is very trivial as a block cipher will be used in this connection. And the difference between a ‘very high bit’ cert and a common cert is more trivial. We’ve dealt with a lot of slow performance cases, but we seldom haves cases whose slow-performance problem is caused by more stronger cert, as the network congestion, the CPU high utilization, a large portion of ViewState data etc. are main characters of slow performance.
In the perspective of IIS, notice that in the IIS manager, there will be an option checked by default for a website, as ‘Enable HTTP Keep-Alives’. This option ensures that the IIS and the client browser would keep the TCP connection alive for a time for certain HTTP requests. That is to say, for round-trips between an IIS server and the client, only the first request will be obviously slower than others, while the rest won’t.
You can refer to following article about this setting:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/d7e13ea5-4350-497e-ba34-b25c0e9efd68.mspx?mfr=true
Of course, I know for WCF, IIS is not a must to host applications for many scenarios, but on this point, I think they work similarly.

Does WCF optimize the client's connection under the hood?

We are currently working on an application that will use a WCF service. The host (the client) is using the excellent WCF Service Proxy Helper from Erwyn van der Meer.
What I would like to know... is if I open this object multiple times... will it lead to multiple (expensive) connections or will WCF manage it and pool the connections.
The reason why I want to know this is because we will be calling methods of the service at different point in time within the same web request and we currently have wrapped the instanciation of the Service proxy class within the call.
Eg.:
MyService.MyMethod1() // wraps the connection usage as well as the call to the service
Any suggestions about how I would go to minimize the amount of connection while keeping the code conform with SRP would be excellent.
So? Any idea?
You should try to minimize the number of proxy objects you create. Proxies in WCF are quite expensive to set up, so creating one and calling functions on it multiple times is definitely more efficient than creating a new one for each method invocation.
The relationship between proxy objects and connections depends on the transport used. For http transports, an HTTP connection is initiated for each function invocation. For the net.tcp transport, the connection is established at Open() time and kept until a Close(). Certain binding settings (eg those supporting WS-SecureConversation) will incur extra "housekeeping" connections and message exchanges.
AKAIK, none of the out-of-the-box bindings perform connection pooling.
It doesn't do pooling like SqlConnection, if that is what you mean.
[caveat: I use "connection" here loosely to mean a logical connection, not necessarily a physical connection]
Between using a connection on-demand, and keeping one around, there are advantages and disadvantages to both approaches. There is some overhead in initializing a connection, so if you are doing 5 things you should try to do them on the same proxy - but I wouldn't keep a long term proxy around just for the sake of it.
In particular, in terms of life-cycle management, once a proxy has faulted, it stays faulted - so you need to be able to recover from the occasional failure (which should be expected). Equally, in some configurations (some combinations of session/instancing), a connection has a definite footprint on the server - so to improve scalability you should keep connections short-lived. Of course, for true scalability you'd usually want to disable those options anyway!
The cost of creating a connection also depends on things like the security mode. IIRC, it will be more expensive to open a two-way validated connection using message security than it will to set up a TransportWithMessageCredential connection - so "YMMV" is very much the case here.
Personally, I find that the biggest common issue with proxy performance isn't anything to do with the time to set up a conncetion - it is the chattiness of the API. i.e.
Scenario A:
open a connection
perform 1 operation with a large payload (i.e. a message that means "do these 19 things")
close the proxy
Scenario B:
open a connecton
perform 19 operations with small payloads
close the connection
Then scenario A will usually be significantly faster due to latency etc. And IMO don't even think about distributed transactions over WCF ;-p

Categories

Resources