Polly | NET resilience and transient-fault-handling library | Testing library
kandi X-RAY | Polly Summary
kandi X-RAY | Polly Summary
Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, Rate-limiting and Fallback in a fluent and thread-safe manner. Polly targets .NET Standard 1.1 (coverage: .NET Core 1.0, Mono, Xamarin, UWP, WP8.1+) and .NET Standard 2.0+ (coverage: .NET Core 2.0+, .NET Core 3.0, and later Mono, Xamarin and UWP targets). The NuGet package also includes direct targets for .NET Framework 4.6.1 and 4.7.2. For versions supporting earlier targets such as .NET4.0 and .NET3.5, see the supported targets grid.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample of Polly
Polly Key Features
Polly Examples and Code Snippets
Community Discussions
Trending Discussions on Polly
QUESTION
I'm just trying to create a simple test where I use DelegateHandlers
to instantiate a HttpClient
without bringing Asp.net Core packages.
I have 2 deletage handlers
ThrottlingDelegatingHandler
PolicyHttpMessageHandler
(from Polly package)
How can I combine both and pass to the HttpClient
?
ANSWER
Answered 2022-Mar-21 at 09:59You have to set the InnerHandler
in your most inner handler to HttpClientHandler
like this:
QUESTION
I'm having a problem using Polly while trying to accomplish the following:
Reconnect logic - I tried to create a Polly policy which works when you try to execute
StartAsync
without Internet connection. However, when it reachesReceiveLoop
, the policy has no longer impact over that method and if our connection stops at that point, it never tries to reconnect back. It simply throws the following exception:Disconnected: The remote party closed the WebSocket connection without completing the close handshake.
. Perhaps I should have two policies: one inStartAsync
and one inReceiveLoop
, but for some reason it doesn't feel right to me, so that's why I ask the question.Timeouts - I want to add timeouts for each
ClientWebSocket
method call e.g. ConnectAsync, SendAsync, etc. I'm not so familiar with Polly but I believe this policy automatically does that for us. However, I need someone to confirm that. By timeout, I mean similar logic to_webSocket.ConnectAsync(_url, CancellationToken.None).TimeoutAfter(timeoutMilliseconds)
, TimeoutAfter implementation can be found here. An example how other repos did it can be found here.
Simplified, I want to make this class resilient, which means instead of trying to connect to a dead web socket server for 30 seconds without success, no matter what the reason is, it should fail fast -> retry in 10 seconds -> fail fast -> retry again and so on. This wait and retry logic should be repeated until we call StopAsync
or dispose the instance.
You can find the WebSocketDuplexPipe class on GitHub.
...ANSWER
Answered 2022-Mar-19 at 18:00Let me capture in an answer the essence of our conversation via comments.
ReceiveLoop
with retry
Your retry policy will exit with success from the ExecuteAsync
while you are waiting for the input.ReadAsync
to finish. The reason is that you are not awaiting the ReceiveLoop
rather you just kick it off in a fire and forget manner.
In other words, your retry logic will only apply for the StartAsync
and the code before the await inside the ReceiveLoop
.
The fix is to move the retry logic inside ReceiveLoop
.
Polly's Timeout policy can use either optimistic or pessimistic strategy. The former one heavily relies on the CancellationToken
.
- So, if you pass for example
CancellationToken.None
to theExecuteAsync
then you basically says let TimeoutPolicy handle cancellation process. - If you pass an already existing token then the decorated Task can be cancelled by the TimeoutPolicy or by the provided token.
Please bear in mind that it will throw TimeoutRejectedException
not OperationCanceledException
.
onTimeoutAsync
TimeoutAsync
has several overloads which can accept one of the two onTimeoutAsync
delegates
QUESTION
I have implemented Polly in it's own "retry" HttpClient DelegateHandler
in a dll written to .NET Standard 2.0. I have the Polly v7.2.3 package. My HttpClient
is running separate from an HttpClientFactory
since only one instance will ever exist during the short lifetime of the dll.
My problem is this: The code executes great when my internet is working. However, when I disconnect my internet it throws a TaskCanceledException
on the first retry and does not retry any more. Here are the relevant parts of my code...
inside the ctor of my typed HttpClient:
...ANSWER
Answered 2022-Jan-28 at 16:55All you need to do is to specify the HttpResponseMessage
as a return type when you declare your policy.
QUESTION
Although High Sierra is no longer supported by Homebrew, but I need to install llvm@13
formula as a dependency for other formulas. So I tried to install it this way:
ANSWER
Answered 2021-Nov-26 at 08:27Install llvm with debug mode enabled:
QUESTION
I'm inspecting some code that seems to throw
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at times.
We use the library Polly for auto retries for HttpClient requests.
- I'm starting to wonder if it has to do with the
HttpClient.PostAsync
not being awaited below? - Would that cause any connection exhaustion?
Any guidance would be appreciated.
...ANSWER
Answered 2022-Jan-04 at 16:32The two code blocks you show here are effectively identical. Internally, Polly will await
the delegate anyway, and multiple await
s on a Task
don't have any affect.
However, if you're only using Polly to make resilient HTTP calls with HttpClient
, then I would consider using the library itself to handle that. There are examples here https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly
QUESTION
I have a workflow like this:
- call an API method
- if any exception is thrown but timeout, the program logs that exception and throws it.
- if timeout is thrown, the program has to call another API method.
- after calling another API method, if everything goes true, the program returns a result.
- otherwise the program throws an exception and log it.
both API methods have the same type of result. I want to implement this with polly policies.
This is my sample code:
...ANSWER
Answered 2021-Jul-29 at 08:25If I understand your workflow correctly then you don't need the retry policy at all. The Fallback policy is enough for this.
So, let suppose that the CallApi
and CallAnotherApi
are implemented like this:
QUESTION
Currently, Polly Retry policy retires all the failed requests independently. So, if there are 10 requests failing and I have set the retry forever policy then it will send 10 more requests every time a retry happens and the server will never heal.
How to asynchronously pass all failed requests and retry only one request and resume the normal flow if a retry is successful?
I can't (don't want to) use Circuit Breaker because my service is a Background worker service and Circuit Breaker breaks the whole background service logic.
...ANSWER
Answered 2021-Dec-19 at 10:12According to my understanding you have a single HttpClient
which is used to issue N rate-limited, concurrent requests against the same downstream system.
You want to handle the following failure scenarios:
- If there is a transient network issue you want to retry an individual request
- If the downstream system gets overloaded (so most of the concurrent requests fail) then you want to back off and use only a single request for probing its healthiness
The Circuit Breaker policy works as a proxy. It tracks the outgoing communication and if there are too much successive failures then it prevents further requests. It does that by short-cutting the requests by throwing an BrokenCircuitException
.
After a certain period of time CB will allow a single request to go out against the downstream system and if it succeeds then it allows all outgoing communication but if it fails then it will short-cut them. Here I have detailed how does CB work.
You can adjust your retry policy to be aware of this exception. This means that your retry requests will be still issued but will not leave your application domain. Fortunately in Polly you can define multiple triggers for a policy:
QUESTION
Need to make all the existing repos (around 30+) fault tolerant to deadlock and recover from it with log and wait approach.
Tried with success: I've answered below a custom SqlResiliencyPolicy using Polly after some research and tailored it to the project.
But, what I seek: The present way (PFB answered), demands me to either
- Wrap all the existing DB calls with
await _policy.ExecuteAsync
OR - Provide custom overloads which accepts
IAsyncPolicy
param. and later call the intended method. Sort of extension to IDbConnection:
public static Task GetAsync(this IDbConnection connection, object primaryKey, IAsyncPolicy policy) =>
return await _policy.ExecuteAsync(async () => GetAsync (...));
In both ways, I need to change all my 30+ repos. But, is there a built-in way in dapper/some-other-approaches, where we can
"configure a Policy in startup and auto-magically all DB calls via dapper become resilient (fall backs to their fault tolerant mechanism) Similar to the ways of http clients resilience where policy is added while you register a client"
By this: will've code changes to minimum, need not touch repos but only the startup.
I've a below approach and sort of need an improvement over it.
...ANSWER
Answered 2021-Nov-24 at 17:49My approach after following some research:
QUESTION
We started using the Polly library in our legacy WinForms project which still runs on the .NET 4.0 framework (is a requisite).
The problem is that we have to use version 4.3 of the Polly library and it is difficult to find solutions to the problems because all the documentation we find is about more recent versions of the library.
For example we can't pass Context
values from retry callback to execute because Context
is readonly and we can't pass parameters to execute delegate because it use an Action
type.
To all these problems we have find a creative solution but we can't still found a way to stop the execution on certain condition.
In Polly 5, CancellationToken
was introduced for this purpose but I guess there were ways to force the retry to stop in previous versions as well.
ANSWER
Answered 2021-Nov-29 at 15:40I think you have tried to solve the problem from the wrong angle.
Rather than trying to cancel a retry, try to avoid triggering the retry.
I've created a sample application in dotnetfiddle to make sure that my proposed solution work with Polly version 4.3 as well
QUESTION
I've been reading this which seems to have a way of doing what I want.
I've got something similar obviously, but within the PolicyContextExtensions
the context.TryGetValue
takes PolicyContextItems
. This shows as an undefined object for me.
Where does this come from and how is this set?
For reference here is the PolicyContextExtensions
class:
ANSWER
Answered 2021-Nov-25 at 16:04The Polly's Context class is basically a Dictionary
.
Which means you can register any kind of data with an arbitrary string.
In the tutorial Stephen has created a new context like this:
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install Polly
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page