Skip to content
Skills Library
Programming · Building & coding

Matex Setup Resilience

/Matex Setup Resilience

在 matex 中给服务加稳定性防护:接口限流(本地/redis)、写请求幂等、下游熔断、退避重试。当用户说"加限流 / 限流 / rate limit / 防刷 / 幂等 / idempotency / 重复提交 / 熔断 / circuit breaker / 重试 / retry / 退避 / 稳定性 / 防护"时使用。

Repository
matex ↗
Licence
MIT
Last repository change
20.10.2026

Assessment and security

90/ 100Class: good
Format15 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 20.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

在 matex 中给服务加稳定性防护:接口限流(本地/redis)、写请求幂等、下游熔断、退避重试。当用户说"加限流 / 限流 / rate limit / 防刷 / 幂等 / idempotency / 重复提交 / 熔断 / circuit breaker / 重试 / retry / 退避 / 稳定性 / 防护"时使用。

Original author description

在 matex 中给服务加稳定性防护:接口限流(本地/redis)、写请求幂等、下游熔断、退避重试。当用户说"加限流 / 限流 / rate limit / 防刷 / 幂等 / idempotency / 重复提交 / 熔断 / circuit breaker / 重试 / retry / 退避 / 稳定性 / 防护"时使用。

How it works

  1. 1. 限流
  2. 2. 幂等
  3. 3. 熔断 + 4. 重试:顺序和参数
  4. 5. 数据库约束冲突
  5. 约定(必须遵守)
  6. 验证
Original SKILL.md headings · 122 lines, 402 words
SKILL.md preview
---
name: Matex Setup Resilience
description: 在 matex 中给服务加稳定性防护:接口限流(本地/redis)、写请求幂等、下游熔断、退避重试。当用户说"加限流 / 限流 / rate limit / 防刷 / 幂等 / idempotency / 重复提交 / 熔断 / circuit breaker / 重试 / retry / 退避 / 稳定性 / 防护"时使用。
---

# 接入稳定性防护

四个工具,两个作用点。别一次全上 —— 按需要选。

| 工具 | 包 | 作用点 | 何时用 |
|---|---|---|---|
| 限流 | `pkg/core/ratelimit` | httpx 中间件 | 登录、短信、查询类接口怕被刷 |
| 幂等 | `pkg/core/idempotency` | httpx 中间件 | 支付、下单、扣款这类写操作 |
| 熔断 | `pkg/core/breaker` | 出站调用外 | 下游挂了还一直打 |
| 重试 | `pkg/core/retry` | 出站调用外 | 下游偶发抖动 |

## 1. 限流

```go
srv.Use(ratelimit.Middleware(ratelimit.NewLocal(2, 2), ratelimit.ByIP))
srv.Handle("POST", "/api/v1/login", s.login)
```

- 单实例用 `NewLocal(rate, burst)`;要全集群共享额度用
  `NewRedis(rc, limit, window)`(固定窗口,边界最多 2×limit;`rc` 用 `env.Redis()` 在 `Setup` 里取好)。
- key:`ByIP` / `ByHeader("X-API-Key")` / `ByRoute`,或自己写一个;返回 `""` 不限流。
- 注意 `ByIP` 用 `RemoteAddr`,在 LB 后面是代理地址。要信 `X-Forwarded-For` 就显式写
  `ByHeader("X-Forwarded-For")`。
- 超限返回 `429 {"code":42901}`;限流器故障时**放行**。

## 2. 幂等

```go
rc, _ := env.Redis() // 在 Setup 里取;未配 redis 时用 NewMemory()(仅单实例)
srv.Use(idempotency.Middleware(idempotency.NewRedis(rc), idempotency.Config{}))
srv.Handle("POST", "/api/v1/payments", s.pay)
```

客户端送 `Idempotency-Key`(建议用 UUID)。语义:

- 首次执行并存储结果;同 key 后续请求**重放**该结果;
- 首次还在执行时来的重复请求 → `409 {"code":40902}`;
- 首次是 **5xx** → 释放 key(允许重试成功);4xx 和成功 → 重放。

默认只覆盖 POST/PATCH/DELETE。`NewMemory()` 只适合单实例/测试,多副本必须 `NewRedis`。

写操作**必须**配合这个,而不是赌重试无害。

## 3. 熔断 + 4. 重试:顺序和参数

```go
v, err := retry.DoValue(ctx, retry.Config{
    Attempts:  3,
    BaseDelay: 50 * time.Millisecond,
    Retryable: func(err error) bool { return !errors.Is(err, breaker.ErrOpen) },
}, func(ctx context.Context) (string, error) {
    return breaker.DoValue(ctx, s.circuit, func(context.Context) (string, error) {
        return s.downstream.call(ctx)
    })
})
if errors.Is(err, breaker.ErrOpen) {
    return nil, errs.Unavailable(50302, "downstream is unavailable")
}
```

两条必须记住的:

- **retry 在外、breaker 在内**,并让 `Retryable` 放行 `breaker.ErrOpen` 之外的都重试、
  `ErrOpen` 直接停。反过来会把熔断放大成重试风暴。
- **熔断阈值 ≥ Attempts**(示例:`Failures: 3` 对 `Attempts: 3`)。阈值小于重试次数时,
  熔断器会在重试循环中间打开,最后一次尝试连机会都没有 —— 这个 bug 只在有抖动的环境下
  才暴露,容易漏掉。

`retry` 默认全抖动(把延迟摊到 `[0, d)`),不要关掉:同一瞬间失败的一批客户端若无抖动
会在同一瞬间重试。

### 熔断的两种触发模型

| 模型 | 配置 | 什么时候打开 |
|---|---|---|
| 错误率滑窗(推荐,线上用) | `Ratio: 0.5, Window: 60s, MinSamples: 20` | 窗口内 ≥ MinSamples 次调用且失败率 ≥ Ratio |
| 连续失败 | `Failures: 5`(不设 Ratio) | 连续 Failures 次失败 |

```go
breaker.New(breaker.Config{
    Ratio: 0.5, Window: 60 * time.Second, MinSamples: 20,
    Successes: 2, Cooldown: 10 * time.Second,
    OnStateChange: func(from, to breaker.State) { /* 打日志 + 上报 gauge */ },
})
```

- **什么算失败**:默认只计服务端错误(`errs` 中 HTTP ≥ 500,以及非 matex 的普通 error);
  400/404 之类的客户端错误不打开熔断。需要别的口径时传 `IsFailure`。
- 低流量下 `MinSamples` 防止"一次失败就熔断";高流量下几个 5xx 不会误触发。
- 断路器本身不依赖 obs:指标在 `OnStateChange` 里上报(例如 `breaker_state{name}` gauge)。
- 错误率模型打开/关闭时窗口会清空,恢复后的流量从零开始统计。

## 5. 数据库约束冲突

唯一键冲突(postgres 23505 / mysql 1062 / sqlite 2067)由 `pkg/core/db` 映射成
`errs.KindConflict`(409),不用自己判断驱动错误:

```go
if _, err := s.dao.Create(ctx, s.db, in); err != nil && errs.KindOf(err) == errs.KindConflict {
	return nil, errs.Conflict(40901, "name already exists")
}
```

## 约定(必须遵守)

- **降级优先**:限流器/幂等存储故障时放行 + 记 warn,绝不因为防护组件挂掉而拒绝正常流量。
- **包裹范围小**:breaker/retry 只包住那一次出站调用,不要包整个 handler。
- **只重试幂等操作**:写操作配 `idempotency`。
- 熔断的 `OnStateChange` 在锁内调用:只记日志/打点,别回调 Breaker。

## 验证

```sh
go test ./pkg/core/ratelimit ./pkg/core/breaker ./pkg/core/retry ./pkg/core/idempotency
go test ./examples/resilience
make ci
```

参考 `examples/resilience`(四个工具在一条链路上的集成测试,含"熔断打开后不再调用下游"
的断言)。

Versions

The database has no other skills named Matex Setup Resilience.

Database snapshot: 13.11.2026 · package version d8f4c259d090 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 2 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 90Matex Setup Redis
    在 matex 中接入 Redis:配置 redis 段、缓存读写、分布式锁。当用户说"接 redis / 配 redis / setup redis / 缓存 / 分布式锁 / 加缓存"时使用。
  • 90Matex Setup Auth
    在 matex 中接入认证与授权:配置 auth 段、验签 Bearer token、按路由分级保护、读取当前主体。当用户说"加认证 / 加鉴权 / 接 auth / setup auth / JWT / OIDC / 登录校验 / token 校验 / 权限控制 / RBAC"时使用。
  • 90Integration Specialist Agent
    Resilient third-party integration patterns — API clients, webhooks, MCP server wiring, retries/circuit-breakers, and idempotency. Use when connecting to an external service (Stripe/GitHub/Slack/S3/etc.), building or verifying a webhook receiver, adding retry/backoff or…
  • 100resilience
    Resilience patterns for .NET 10 applications using Polly v8. Covers retry, circuit breaker, timeout, fallback, rate limiter, hedging, and composing resilience pipelines. Load this skill when implementing retry logic, circuit breakers, handling transient failures, or when the…
  • 100perplexity-reliability-patterns
    Implement Perplexity reliability patterns including circuit breakers, idempotency, and graceful degradation. Use when building fault-tolerant Perplexity integrations, implementing retry strategies, or adding resilience to production Perplexity services. Trigger with phrases like…
  • 100http-resilience
    Make outbound HTTP calls resilient in an existing Spring Boot 4 Maven project — circuit breakers, retries, and timeouts with RestClient and Resilience4j, plus tests that prove failures degrade gracefully. Use when asked to add retries or a circuit breaker, call external APIs…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.