{"id":24123813,"url":"https://github.com/grelinfo/grelmicro","last_synced_at":"2026-05-16T13:04:40.792Z","repository":{"id":263688132,"uuid":"875906397","full_name":"grelinfo/grelmicro","owner":"grelinfo","description":"Grelmicro is a lightweight framework/toolkit which is ideal for building async microservices in Python.","archived":false,"fork":false,"pushed_at":"2026-03-12T22:39:40.000Z","size":1244,"stargazers_count":2,"open_issues_count":5,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-13T04:57:49.668Z","etag":null,"topics":["anyio","asyncio","circuit-breaker","fastapi","faststream","leader-election","lock","microservice","pydantic","python","resilience"],"latest_commit_sha":null,"homepage":"https://grelmicro.grel.info/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/grelinfo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-10-21T04:31:31.000Z","updated_at":"2026-03-12T22:39:43.000Z","dependencies_parsed_at":"2024-12-23T21:28:32.895Z","dependency_job_id":"3acb002f-aff0-44b0-b3ee-61d1631d6d00","html_url":"https://github.com/grelinfo/grelmicro","commit_stats":null,"previous_names":["grelinfo/grelmicro"],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/grelinfo/grelmicro","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grelinfo%2Fgrelmicro","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grelinfo%2Fgrelmicro/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grelinfo%2Fgrelmicro/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grelinfo%2Fgrelmicro/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/grelinfo","download_url":"https://codeload.github.com/grelinfo/grelmicro/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grelinfo%2Fgrelmicro/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30477241,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-13T20:45:58.186Z","status":"ssl_error","status_checked_at":"2026-03-13T20:45:20.133Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["anyio","asyncio","circuit-breaker","fastapi","faststream","leader-election","lock","microservice","pydantic","python","resilience"],"created_at":"2025-01-11T13:18:17.193Z","updated_at":"2026-05-16T13:04:40.785Z","avatar_url":"https://github.com/grelinfo.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://grelinfo.github.io/grelmicro\"\u003e\n    \u003cimg alt=\"grelmicro\" class=\"grel-wordmark\" src=\"docs/img/logo/wordmark.svg\" width=\"360\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cem\u003eAsync-first toolkit. Microservice patterns inside.\u003c/em\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  A Python toolkit for distributed systems: microservices, modular monoliths, and self-contained systems.\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://pypi.org/project/grelmicro/\"\u003e\u003cimg alt=\"PyPI - Version\" src=\"https://img.shields.io/pypi/v/grelmicro\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://pypi.org/project/grelmicro/\"\u003e\u003cimg alt=\"PyPI - Python Version\" src=\"https://img.shields.io/pypi/pyversions/grelmicro\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/grelinfo/grelmicro/blob/main/LICENSE\"\u003e\u003cimg alt=\"License: MIT\" src=\"https://img.shields.io/badge/License-MIT-green.svg\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://codecov.io/gh/grelinfo/grelmicro\"\u003e\u003cimg alt=\"codecov\" src=\"https://codecov.io/gh/grelinfo/grelmicro/graph/badge.svg?token=GDFY0AEFWR\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/astral-sh/uv\"\u003e\u003cimg alt=\"uv\" src=\"https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/astral-sh/ruff\"\u003e\u003cimg alt=\"Ruff\" src=\"https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json\"\u003e\u003c/a\u003e\n  \u003ca href=\"https://github.com/astral-sh/ty\"\u003e\u003cimg alt=\"ty\" src=\"https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ty/main/assets/badge/v0.json\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003e **Project status: Active development.** grelmicro is pre-1.0. The public API is not yet stable. Breaking changes are allowed on `MINOR` bumps (`0.14.0` → `0.15.0`) and never on `PATCH`. Pin the minor: `grelmicro\u003e=0.14.0,\u003c0.15.0`. After `1.0.0`, standard semver applies. See the [versioning policy](https://github.com/grelinfo/grelmicro/blob/main/CONTRIBUTING.md#about-grelmicro-versions).\n\n______________________________________________________________________\n\n**Documentation**: [https://grelinfo.github.io/grelmicro/](https://grelinfo.github.io/grelmicro)\n\n**Source Code**: [https://github.com/grelinfo/grelmicro](https://github.com/grelinfo/grelmicro)\n\n______________________________________________________________________\n\n## Why grelmicro\n\nStop reinventing the wheel. grelmicro ships microservice patterns as small, composable modules with pluggable backends: locks, rate limits, circuit breakers, cache, logging, health checks, and task scheduling. Async-first, type-safe, and battle-tested in production.\n\nIt is built for any Python application that coordinates work across processes, workers, or replicas. The same primitives serve every **distributed system**, whether you call it **microservices**, a **modular monolith**, or a **self-contained system**. A distributed lock is a distributed lock whether your system is one process or fifty. It fits naturally into **cloud-native applications**, **containerized apps**, and **Kubernetes** deployments.\n\n- **Micro**: one focused primitive per module, each a canonical microservice pattern (distributed lock, leader election, rate limiter, circuit breaker, health check API, externalised configuration).\n- **Fast**: small footprint by design. We keep the layers thin so your code stays quick.\n- **Async-first**: every I/O call is `async` / `await`. Drops into FastAPI, FastStream, and any asyncio-based stack.\n- **Backend-agnostic**: each primitive is a protocol. Swap Redis for PostgreSQL or SQLite without touching application code.\n- **Railguarded**: 100% pytest coverage, ty-checked, ruff-linted, Pydantic-validated. Pre-1.0 API may shift on minor bumps. `1.x` commits to standard semver.\n\nAlready using `aiocache`, `slowapi`, `pybreaker`, `tenacity`, or `aioredlock`? See the [comparison page](docs/comparison.md) for a per-domain breakdown.\n\n## Modules\n\n| Module | Summary |\n|---|---|\n| [**Cache**](docs/cache.md) | `@cached` decorator with per-key stampede protection. In-memory `TTLCache` or `RedisCacheAdapter`. |\n| [**Synchronization**](docs/sync.md) | Distributed `Lock`, `TaskLock`, `LeaderElection`. Redis, PostgreSQL, SQLite, Kubernetes, in-memory. |\n| [**Task Scheduler**](docs/task.md) | Periodic task execution with optional distributed locking. Lightweight, not a Celery replacement. |\n| [**Resilience**](docs/resilience/index.md) | [Circuit Breaker](docs/resilience/circuit-breaker.md) and [Rate Limiter](docs/resilience/rate-limiter.md) with pluggable algorithms (`TokenBucketConfig`, `GCRAConfig`). |\n| [**Logging**](docs/logging.md) | 12-factor logging with JSON, LOGFMT, TEXT, or PRETTY output, structured error rendering, and OpenTelemetry trace context. |\n| [**Tracing**](docs/tracing.md) | Unified instrumentation. `@instrument` creates OpenTelemetry spans and enriches log records with structured context. |\n| [**Health**](docs/health.md) | Health check registry with concurrent runners and FastAPI liveness / readiness integration. |\n| [**JSON**](docs/json.md) | Fast JSON via `orjson` when available, with automatic fallback to stdlib `json`. |\n\n## Installation\n\n```bash\npip install grelmicro\n```\n\nSee the [Installation guide](https://grelinfo.github.io/grelmicro/installation/) for `uv` and `poetry` commands, plus optional extras for Redis, PostgreSQL, SQLite, Kubernetes, OpenTelemetry, and structlog.\n\n## Example\n\n### FastAPI integration\n\nCreate a file `main.py` with:\n\n```python\nimport logging\nfrom contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI, HTTPException, Request\n\nfrom grelmicro import Grelmicro\nfrom grelmicro.cache import Cache, JsonSerializer, TTLCache, cached\nfrom grelmicro.health import HealthChecks\nfrom grelmicro.log import configure as configure_logging\nfrom grelmicro.providers.redis import RedisProvider\nfrom grelmicro.resilience import (\n    CircuitBreaker,\n    RateLimit,\n    RateLimitExceededError,\n    RateLimiter,\n)\nfrom grelmicro.sync import LeaderElection, Lock, Sync\nfrom grelmicro.task import Tasks\n\nlogger = logging.getLogger(__name__)\n\n# === grelmicro app: one container, one lifespan ===\ntasks = Tasks()\nhealth = HealthChecks()\nleader = LeaderElection(\"leader-election\")\ntasks.add_task(leader)\n\nredis = RedisProvider(\"redis://localhost:6379/0\")\n\nmicro = Grelmicro(uses=[\n    redis,\n    Sync(redis),\n    Cache(redis),\n    RateLimit(redis),\n    tasks,\n    health,\n])\n\n# === Patterns declared once at module load, resolved at use time ===\nttl_cache = TTLCache(ttl=300, serializer=JsonSerializer())\nlock = Lock(\"shared-resource\")\ncb = CircuitBreaker(\"my-service\")\napi_limiter = RateLimiter.gcra(\"api\", limit=100, window=60)\n\n\n# === FastAPI lifespan ===\n@asynccontextmanager\nasync def lifespan(app):\n    configure_logging()\n    async with micro:\n        yield\n\n\napp = FastAPI(lifespan=lifespan)\n\n\n# --- Cache: avoid redundant database queries ---\n@cached(ttl_cache)\nasync def get_user(user_id: int) -\u003e dict:\n    return {\"id\": user_id, \"name\": \"Alice\"}\n\n\n@app.get(\"/users/{user_id}\")\nasync def read_user(user_id: int):\n    return await get_user(user_id)\n\n\n# --- Circuit Breaker: protect calls to an unreliable service ---\n@app.get(\"/\")\nasync def read_root():\n    async with cb:\n        return {\"Hello\": \"World\"}\n\n\n# --- Rate Limiter: protect endpoints from overload ---\n@app.get(\"/api\")\nasync def api_endpoint(request: Request):\n    try:\n        await api_limiter.acquire_or_raise(key=request.client.host)\n    except RateLimitExceededError as exc:\n        raise HTTPException(\n            status_code=429,\n            detail=\"Too many requests\",\n            headers={\"Retry-After\": str(int(exc.retry_after))},\n        )\n    return {\"status\": \"ok\"}\n\n\n# --- Distributed Lock: synchronize access to a shared resource ---\n@app.get(\"/protected\")\nasync def protected():\n    async with lock:\n        return {\"status\": \"ok\"}\n\n\n# --- Interval Task: run locally on every worker ---\n@tasks.interval(seconds=5)\ndef heartbeat():\n    logger.info(\"heartbeat\")\n\n\n# --- Distributed Task: run once per interval across all workers ---\n@tasks.interval(seconds=60, max_lock_seconds=300)\ndef cleanup():\n    logger.info(\"cleanup\")\n\n\n# --- Leader-gated Task: only the leader executes ---\n@tasks.interval(seconds=10, leader=leader)\ndef leader_only_task():\n    logger.info(\"leader task\")\n```\n\nThe key shape:\n\n- **One container, one lifespan.** `Grelmicro(uses=[...])` lists every Provider, Component, and active manager. `async with micro:` opens them all in order, closes in reverse.\n- **One Provider, many Components.** `Sync(redis)`, `Cache(redis)`, `RateLimit(redis)` all share the same `RedisProvider` pool. The Provider holds the connection, the Components attach to it.\n- **Patterns are declared at module load.** `Lock(\"cart\")`, `TTLCache(ttl=60)`, `CircuitBreaker(\"svc\")` carry no backend reference. They resolve through the active app inside `async with`. The same `Lock` works in production with Redis and in tests with `MemorySyncAdapter`, no rewiring.\n- **Pay only for what you import.** `import grelmicro` does not pull in `redis`, `psycopg`, or any other vendor SDK. First-party Providers live under `grelmicro.providers.{vendor}` and load only when you import them.\n\nFor multiple Redis instances, separate names, or test overrides, see the [docs](https://grelinfo.github.io/grelmicro/).\n\n## License\n\nThis project is licensed under the terms of the [MIT license](https://github.com/grelinfo/grelmicro/blob/main/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgrelinfo%2Fgrelmicro","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgrelinfo%2Fgrelmicro","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgrelinfo%2Fgrelmicro/lists"}