ConcurrencyLimit returns a handler that limits the number of concurrent requests. When the limit is exceeded, it returns HTTP 503 Service Unavailable.
(maxConcurrent int64, resourceName string)
| 140 | // ConcurrencyLimit returns a handler that limits the number of concurrent |
| 141 | // requests. When the limit is exceeded, it returns HTTP 503 Service Unavailable. |
| 142 | func ConcurrencyLimit(maxConcurrent int64, resourceName string) func(http.Handler) http.Handler { |
| 143 | if maxConcurrent <= 0 { |
| 144 | return func(handler http.Handler) http.Handler { |
| 145 | return handler |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | var current atomic.Int64 |
| 150 | return func(next http.Handler) http.Handler { |
| 151 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 152 | c := current.Add(1) |
| 153 | defer current.Add(-1) |
| 154 | |
| 155 | if c > maxConcurrent { |
| 156 | httpapi.Write(r.Context(), w, http.StatusServiceUnavailable, codersdk.Response{ |
| 157 | Message: fmt.Sprintf("%s is currently at capacity. Please try again later.", resourceName), |
| 158 | }) |
| 159 | return |
| 160 | } |
| 161 | next.ServeHTTP(w, r) |
| 162 | }) |
| 163 | } |
| 164 | } |