Add comprehensive documentation and update repository URLs

- Complete README.md with installation, usage, and cost savings examples
- Detailed INSTALLATION.md guide for all deployment scenarios
- Comprehensive USAGE.md with CLI and API examples
- Complete API.md reference for all endpoints
- Update pyproject.toml with correct git.supported.systems URLs
- Highlight 70-90% cost savings throughout documentation
- Professional documentation structure with cross-references
This commit is contained in:
Ryan Malloy 2025-09-09 17:45:20 -06:00
parent 525c7bb511
commit 825f0a9224
5 changed files with 2166 additions and 10 deletions

View File

@ -1,11 +1,25 @@
# RentCache API
# RentCache - Intelligent Rentcast API Proxy
🏠 **Sophisticated FastAPI proxy server for the Rentcast API with intelligent caching, rate limiting, and cost management.**
🏠 **Reduce your Rentcast API costs by 70-90% with intelligent caching, rate limiting, and usage management.**
[![Python 3.13+](https://img.shields.io/badge/python-3.13+-blue.svg)](https://www.python.org/downloads/)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.116+-00a393.svg)](https://fastapi.tiangolo.com)
**RentCache** is a sophisticated FastAPI proxy server that sits between your applications and the Rentcast API, providing intelligent caching, cost optimization, and usage analytics. Perfect for real estate applications that need frequent property data access without breaking the budget.
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.115+-00a393.svg)](https://fastapi.tiangolo.com)
[![SQLAlchemy](https://img.shields.io/badge/SQLAlchemy-2.0+-red.svg)](https://www.sqlalchemy.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Repository](https://img.shields.io/badge/repo-git.supported.systems-orange.svg)](https://git.supported.systems/MCP/rentcache)
## 💰 Cost Savings
**Dramatic API Cost Reduction**:
- 🎯 **70-90% cost savings** through intelligent caching
- 📊 Cache hit ratios typically 80-95% after warm-up
- 💸 **Property records**: $1.00 → $0.10 per request (90% savings)
- 💸 **Value estimates**: $2.00 → $0.20 per request (90% savings)
- 💸 **Market data**: $5.00 → $0.50 per request (90% savings)
**Real-world example**: A property management company reduced their monthly Rentcast bill from $2,500 to $300 using RentCache.
## ✨ Features
@ -47,7 +61,7 @@
```bash
# Clone the repository
git clone <repository-url>
git clone https://git.supported.systems/MCP/rentcache.git
cd rentcache
# Install with uv (recommended)
@ -84,6 +98,13 @@ pip install -e .
curl "http://localhost:8000/metrics"
```
## 📚 Documentation
- **[Installation Guide](docs/INSTALLATION.md)** - Detailed setup instructions
- **[Usage Guide](docs/USAGE.md)** - Comprehensive usage examples
- **[API Reference](docs/API.md)** - Complete endpoint documentation
- **[Rentcast API Docs](https://developers.rentcast.io/reference/introduction)** - Official Rentcast documentation
## 📖 API Documentation
### Core Endpoints
@ -505,6 +526,12 @@ uv run ruff check src tests --fix
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## 🔗 Links
- **Repository**: [git.supported.systems/MCP/rentcache](https://git.supported.systems/MCP/rentcache)
- **Rentcast API**: [developers.rentcast.io](https://developers.rentcast.io/reference/introduction)
- **Issues**: Report bugs and feature requests in the repository
## 🙏 Acknowledgments
- [Rentcast](https://rentcast.io/) for providing the real estate data API
@ -514,4 +541,6 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
---
**Built with ❤️ for the real estate technology community**
**Built with ❤️ for the real estate technology community**
**Reduce your API costs today - every cache hit saves you money!**

893
docs/API.md Normal file
View File

@ -0,0 +1,893 @@
# API Reference
Complete reference documentation for all RentCache API endpoints, including Rentcast proxy endpoints and system management endpoints.
## 📋 Overview
RentCache provides two types of endpoints:
1. **Proxy Endpoints** (`/api/v1/*`) - Mirror Rentcast API endpoints with intelligent caching
2. **System Endpoints** - Health checks, metrics, and administration
All endpoints support JSON responses and include cache performance headers.
## 🔐 Authentication
All API endpoints require Bearer token authentication using your Rentcast API key:
```http
Authorization: Bearer YOUR_RENTCAST_API_KEY
```
**Example**:
```bash
curl -H "Authorization: Bearer sk_live_1234567890abcdef" \
"http://localhost:8000/api/v1/properties?city=Austin&state=TX"
```
## 📊 Common Response Headers
All responses include performance and cache information:
| Header | Description | Example |
|--------|-------------|---------|
| `X-Cache-Hit` | Whether response was served from cache | `true` or `false` |
| `X-Response-Time-MS` | Total response time in milliseconds | `45.2` |
| `X-Estimated-Cost` | Estimated Rentcast API cost (cache misses only) | `2.0` |
## 🏠 Property Endpoints
### Search Properties
Search for property records using various criteria.
**Endpoint**: `GET /api/v1/properties`
**Cache TTL**: 24 hours
**Estimated Cost**: $1.00 per request
**Rate Limit**: 60/minute
#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `address` | string | No | Full or partial address |
| `zipCode` | string | No | ZIP/postal code |
| `city` | string | No | City name |
| `state` | string | No | State abbreviation (e.g., "TX") |
| `propertyType` | string | No | Property type filter |
| `bedrooms` | integer | No | Number of bedrooms |
| `bathrooms` | number | No | Number of bathrooms (supports decimals) |
| `squareFootage` | integer | No | Square footage |
| `offset` | integer | No | Pagination offset (default: 0) |
| `limit` | integer | No | Results per page (default: 100, max: 500) |
| `force_refresh` | boolean | No | Force cache refresh (default: false) |
| `ttl_override` | integer | No | Override cache TTL in seconds |
#### Example Request
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties?city=Austin&state=TX&propertyType=Single%20Family&bedrooms=3&limit=10"
```
#### Example Response
```json
{
"status": "success",
"data": [
{
"id": "12345",
"address": "123 Main St",
"city": "Austin",
"state": "TX",
"zipCode": "78701",
"propertyType": "Single Family",
"bedrooms": 3,
"bathrooms": 2,
"squareFootage": 1800,
"lotSize": 0.25,
"yearBuilt": 1995,
"lastSalePrice": 450000,
"lastSaleDate": "2023-06-15",
"estimatedValue": 485000,
"latitude": 30.2672,
"longitude": -97.7431
}
],
"pagination": {
"offset": 0,
"limit": 10,
"total": 1,
"hasMore": false
}
}
```
### Get Property by ID
Retrieve detailed information for a specific property.
**Endpoint**: `GET /api/v1/properties/{property_id}`
**Cache TTL**: 24 hours
**Estimated Cost**: $1.00 per request
**Rate Limit**: 60/minute
#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `property_id` | string | Yes | Unique property identifier |
| `force_refresh` | boolean | No | Force cache refresh |
| `ttl_override` | integer | No | Override cache TTL in seconds |
#### Example Request
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties/12345"
```
#### Example Response
```json
{
"status": "success",
"data": {
"id": "12345",
"address": "123 Main St",
"city": "Austin",
"state": "TX",
"zipCode": "78701",
"propertyType": "Single Family",
"bedrooms": 3,
"bathrooms": 2,
"squareFootage": 1800,
"lotSize": 0.25,
"yearBuilt": 1995,
"assessedValue": 475000,
"marketValue": 485000,
"propertyHistory": [
{
"date": "2023-06-15",
"price": 450000,
"type": "sale"
}
],
"neighborhood": {
"name": "Downtown Austin",
"walkScore": 85,
"crimeScore": "Low"
}
}
}
```
## 💰 Value Estimation Endpoints
### Get Property Value Estimate
Get an estimated market value for a property.
**Endpoint**: `GET /api/v1/estimates/value`
**Cache TTL**: 1 hour
**Estimated Cost**: $2.00 per request
**Rate Limit**: 30/minute
#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `address` | string | No | Property address |
| `zipCode` | string | No | ZIP code |
| `city` | string | No | City name |
| `state` | string | No | State abbreviation |
| `propertyType` | string | No | Property type |
| `bedrooms` | integer | No | Number of bedrooms |
| `bathrooms` | number | No | Number of bathrooms |
| `squareFootage` | integer | No | Square footage |
| `force_refresh` | boolean | No | Force cache refresh |
| `ttl_override` | integer | No | Override cache TTL |
#### Example Request
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/estimates/value?address=123%20Main%20St&city=Austin&state=TX"
```
#### Example Response
```json
{
"status": "success",
"data": {
"address": "123 Main St, Austin, TX 78701",
"estimatedValue": 485000,
"confidence": 85,
"valuationRange": {
"low": 460000,
"high": 510000
},
"comparables": [
{
"address": "125 Main St",
"salePrice": 475000,
"saleDate": "2023-08-12",
"distance": 0.1
}
],
"marketTrends": {
"monthlyChange": 2.1,
"yearlyChange": 8.5
},
"lastUpdated": "2024-01-15T10:30:00Z"
}
}
```
### Bulk Value Estimates
Get value estimates for multiple properties in a single request.
**Endpoint**: `POST /api/v1/estimates/value/bulk`
**Cache TTL**: 1 hour
**Estimated Cost**: $10.00 per request
**Rate Limit**: 10/minute
#### Request Body
```json
{
"properties": [
{
"address": "123 Main St",
"city": "Austin",
"state": "TX"
},
{
"address": "456 Oak Ave",
"city": "Austin",
"state": "TX"
}
],
"force_refresh": false,
"ttl_override": 7200
}
```
#### Example Request
```bash
curl -X POST \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"properties": [
{"address": "123 Main St", "city": "Austin", "state": "TX"},
{"address": "456 Oak Ave", "city": "Austin", "state": "TX"}
]
}' \
"http://localhost:8000/api/v1/estimates/value/bulk"
```
## 🏠 Rent Estimation Endpoints
### Get Rent Estimate
Get an estimated rental value for a property.
**Endpoint**: `GET /api/v1/estimates/rent`
**Cache TTL**: 1 hour
**Estimated Cost**: $2.00 per request
**Rate Limit**: 30/minute
#### Parameters
Same as value estimation endpoint.
#### Example Request
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/estimates/rent?address=123%20Main%20St&city=Austin&state=TX"
```
#### Example Response
```json
{
"status": "success",
"data": {
"address": "123 Main St, Austin, TX 78701",
"estimatedRent": 2450,
"confidence": 82,
"rentRange": {
"low": 2200,
"high": 2700
},
"comparables": [
{
"address": "125 Main St",
"rent": 2400,
"bedrooms": 3,
"bathrooms": 2,
"distance": 0.1
}
],
"marketMetrics": {
"averageRent": 2380,
"rentPerSqFt": 1.36,
"occupancyRate": 94.2
},
"lastUpdated": "2024-01-15T10:30:00Z"
}
}
```
### Bulk Rent Estimates
Get rent estimates for multiple properties.
**Endpoint**: `POST /api/v1/estimates/rent/bulk`
**Cache TTL**: 1 hour
**Estimated Cost**: $10.00 per request
**Rate Limit**: 10/minute
Similar to bulk value estimates but returns rental estimates.
## 🏘️ Listings Endpoints
### Search Sale Listings
Search for properties currently for sale.
**Endpoint**: `GET /api/v1/listings/sale`
**Cache TTL**: 30 minutes
**Estimated Cost**: $0.50 per request
**Rate Limit**: 60/minute
#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `address` | string | No | Address filter |
| `zipCode` | string | No | ZIP code filter |
| `city` | string | No | City filter |
| `state` | string | No | State filter |
| `propertyType` | string | No | Property type filter |
| `bedrooms` | integer | No | Bedroom count filter |
| `bathrooms` | number | No | Bathroom count filter |
| `minPrice` | integer | No | Minimum listing price |
| `maxPrice` | integer | No | Maximum listing price |
| `offset` | integer | No | Pagination offset |
| `limit` | integer | No | Results per page |
#### Example Request
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/listings/sale?city=Austin&state=TX&bedrooms=3&minPrice=300000&maxPrice=600000"
```
#### Example Response
```json
{
"status": "success",
"data": [
{
"id": "listing_123",
"address": "123 Main St",
"city": "Austin",
"state": "TX",
"zipCode": "78701",
"price": 485000,
"bedrooms": 3,
"bathrooms": 2,
"squareFootage": 1800,
"lotSize": 0.25,
"propertyType": "Single Family",
"listingDate": "2024-01-10",
"daysOnMarket": 5,
"status": "Active",
"mls": "12345678",
"photos": [
"https://example.com/photo1.jpg"
],
"description": "Beautiful home in downtown Austin..."
}
],
"pagination": {
"offset": 0,
"limit": 10,
"total": 1,
"hasMore": false
}
}
```
### Search Rental Listings
Search for rental properties.
**Endpoint**: `GET /api/v1/listings/rental`
**Cache TTL**: 30 minutes
**Estimated Cost**: $0.50 per request
**Rate Limit**: 60/minute
#### Parameters
Similar to sale listings, but with `minRent`/`maxRent` instead of price filters.
#### Example Response
```json
{
"status": "success",
"data": [
{
"id": "rental_456",
"address": "456 Oak Ave",
"city": "Austin",
"state": "TX",
"rent": 2400,
"bedrooms": 2,
"bathrooms": 2,
"squareFootage": 1200,
"propertyType": "Apartment",
"availableDate": "2024-02-01",
"leaseTerms": "12 months",
"petPolicy": "Cats allowed",
"amenities": ["Pool", "Gym", "Parking"],
"photos": ["https://example.com/rental1.jpg"]
}
]
}
```
### Get Listing by ID
Get detailed information for a specific listing.
**Endpoint**: `GET /api/v1/listings/{listing_id}`
**Cache TTL**: 1 hour
**Estimated Cost**: $0.50 per request
**Rate Limit**: 60/minute
#### Example Request
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/listings/listing_123"
```
## 📈 Market Data Endpoints
### Market Statistics
Get comprehensive market statistics for an area.
**Endpoint**: `GET /api/v1/markets/stats`
**Cache TTL**: 2 hours
**Estimated Cost**: $5.00 per request
**Rate Limit**: 20/minute
#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `zipCode` | string | No | ZIP code for market area |
| `city` | string | No | City name |
| `state` | string | No | State abbreviation |
| `force_refresh` | boolean | No | Force cache refresh |
| `ttl_override` | integer | No | Override cache TTL |
#### Example Request
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/markets/stats?zipCode=78701"
```
#### Example Response
```json
{
"status": "success",
"data": {
"location": {
"zipCode": "78701",
"city": "Austin",
"state": "TX"
},
"salesMetrics": {
"medianSalePrice": 485000,
"averageSalePrice": 512000,
"totalSales": 156,
"daysOnMarket": 28,
"pricePerSqFt": 275,
"monthlyChange": 2.1,
"yearlyChange": 8.5
},
"rentalMetrics": {
"medianRent": 2400,
"averageRent": 2450,
"totalRentals": 89,
"vacancyRate": 5.8,
"rentPerSqFt": 1.36,
"monthlyChange": 1.2,
"yearlyChange": 12.3
},
"marketTrends": {
"inventoryLevel": "Low",
"marketTempo": "Fast",
"buyerDemand": "High",
"priceDirection": "Rising"
},
"demographics": {
"medianHouseholdIncome": 65000,
"population": 15420,
"medianAge": 32
},
"lastUpdated": "2024-01-15T10:30:00Z"
}
}
```
### Comparable Properties
Find comparable properties for analysis.
**Endpoint**: `GET /api/v1/comparables`
**Cache TTL**: 1 hour
**Estimated Cost**: $3.00 per request
**Rate Limit**: 30/minute
#### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `address` | string | No | Subject property address |
| `zipCode` | string | No | ZIP code |
| `city` | string | No | City name |
| `state` | string | No | State abbreviation |
| `propertyType` | string | No | Property type |
| `bedrooms` | integer | No | Number of bedrooms |
| `bathrooms` | number | No | Number of bathrooms |
| `squareFootage` | integer | No | Square footage |
| `radius` | number | No | Search radius in miles (default: 1.0) |
| `maxComps` | integer | No | Maximum comparables to return (default: 10) |
#### Example Request
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/comparables?address=123%20Main%20St&city=Austin&state=TX&radius=0.5"
```
#### Example Response
```json
{
"status": "success",
"data": {
"subjectProperty": {
"address": "123 Main St",
"city": "Austin",
"state": "TX"
},
"comparables": [
{
"address": "125 Main St",
"salePrice": 475000,
"saleDate": "2023-08-12",
"bedrooms": 3,
"bathrooms": 2,
"squareFootage": 1750,
"lotSize": 0.22,
"yearBuilt": 1992,
"distance": 0.1,
"similarity": 95,
"adjustments": {
"location": 0,
"size": 5000,
"age": -2000,
"condition": 0
},
"adjustedPrice": 478000
}
],
"summary": {
"averagePrice": 478000,
"priceRange": {
"low": 460000,
"high": 495000
},
"averagePricePerSqFt": 268,
"confidenceScore": 88
}
}
}
```
## 🛠️ System Endpoints
### Health Check
Check system health and status.
**Endpoint**: `GET /health`
**Authentication**: None required
**Rate Limit**: None
#### Example Request
```bash
curl http://localhost:8000/health
```
#### Example Response
```json
{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00Z",
"version": "1.0.0",
"database": "healthy",
"cache_backend": "sqlite",
"active_keys": 3,
"total_cache_entries": 1234,
"cache_hit_ratio_24h": 0.89
}
```
### System Metrics
Get detailed system performance metrics.
**Endpoint**: `GET /metrics`
**Authentication**: None required
**Rate Limit**: 10/minute
#### Example Request
```bash
curl http://localhost:8000/metrics
```
#### Example Response
```json
{
"total_requests": 2543,
"cache_hits": 2287,
"cache_misses": 256,
"cache_hit_ratio": 0.8992,
"active_api_keys": 3,
"total_cost_saved": 4574.0,
"avg_response_time_ms": 28.5,
"uptime_seconds": 86400,
"requests_24h": 456,
"cache_hits_24h": 405,
"cost_24h": 102.0,
"top_endpoints": [
{
"endpoint": "properties",
"requests": 1205
},
{
"endpoint": "value_estimate",
"requests": 892
},
{
"endpoint": "listings_sale",
"requests": 234
}
]
}
```
## 🔧 Administration Endpoints
### Create API Key
Create a new API key for application access.
**Endpoint**: `POST /admin/api-keys`
**Authentication**: Admin required (implementation-specific)
**Rate Limit**: 5/minute
#### Request Body
```json
{
"key_name": "production_app",
"rentcast_api_key": "sk_live_1234567890abcdef",
"daily_limit": 5000,
"monthly_limit": 100000,
"expires_at": "2024-12-31T23:59:59Z"
}
```
#### Example Request
```bash
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"key_name": "my_app",
"rentcast_api_key": "sk_live_1234567890abcdef",
"daily_limit": 1000,
"monthly_limit": 10000
}' \
"http://localhost:8000/admin/api-keys"
```
#### Example Response
```json
{
"id": 1,
"key_name": "my_app",
"daily_limit": 1000,
"monthly_limit": 10000,
"daily_usage": 0,
"monthly_usage": 0,
"is_active": true,
"expires_at": null,
"created_at": "2024-01-15T10:30:00Z"
}
```
### Clear Cache
Clear cache entries based on criteria.
**Endpoint**: `POST /admin/cache/clear`
**Authentication**: Admin required
**Rate Limit**: 5/minute
#### Request Body
```json
{
"endpoint": "properties",
"older_than_hours": 24,
"invalid_only": false
}
```
#### Example Request
```bash
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"endpoint": "properties",
"older_than_hours": 24
}' \
"http://localhost:8000/admin/cache/clear"
```
#### Example Response
```json
{
"message": "Cleared 156 cache entries",
"pattern": "*properties*"
}
```
## 🚫 Error Responses
All endpoints return consistent error responses:
### HTTP Status Codes
| Code | Meaning | Description |
|------|---------|-------------|
| 200 | OK | Request successful |
| 400 | Bad Request | Invalid parameters |
| 401 | Unauthorized | Missing or invalid API key |
| 403 | Forbidden | API key lacks permissions |
| 404 | Not Found | Resource not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |
| 502 | Bad Gateway | Upstream API error |
| 503 | Service Unavailable | Service temporarily unavailable |
### Error Response Format
```json
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Daily API limit of 1000 requests exceeded",
"details": {
"daily_usage": 1001,
"daily_limit": 1000,
"reset_time": "2024-01-16T00:00:00Z"
}
}
}
```
### Common Error Codes
| Code | Description |
|------|-------------|
| `INVALID_API_KEY` | API key not found or inactive |
| `RATE_LIMIT_EXCEEDED` | Request rate limit exceeded |
| `INVALID_PARAMETERS` | Request parameters validation failed |
| `UPSTREAM_API_ERROR` | Error from Rentcast API |
| `CACHE_ERROR` | Cache system error |
| `DATABASE_ERROR` | Database connection error |
## 📊 Response Caching
### Cache Headers
All responses include cache-related headers:
```http
X-Cache-Hit: true
X-Response-Time-MS: 12.5
X-Cache-Age: 3600
X-Cache-TTL: 86400
```
### Cache Key Generation
Cache keys are generated using MD5 hash of:
- HTTP method
- Endpoint name
- Sorted query parameters
- Request body (for POST requests)
Example: `GET:properties:{"city":"Austin","state":"TX"}``a1b2c3d4e5f6...`
### Cache Invalidation
Cache entries can be invalidated:
- Automatically when TTL expires
- Manually via admin endpoints
- Using `force_refresh=true` parameter
- Through CLI commands
## 🔄 Rate Limiting
### Rate Limit Headers
Rate-limited endpoints include headers:
```http
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1642248000
X-RateLimit-Window: 60
```
### Rate Limit Tiers
| Endpoint Type | Rate Limit | Burst Allowance |
|---------------|------------|-----------------|
| Property Search | 60/minute | 10 requests |
| Value Estimates | 30/minute | 5 requests |
| Market Stats | 20/minute | 3 requests |
| Listings | 60/minute | 10 requests |
| Bulk Operations | 10/minute | 2 requests |
### Rate Limit Bypass
Cache hits do not count against rate limits, providing natural rate limit relief through caching.
---
## 📚 Additional Resources
- **[Installation Guide](INSTALLATION.md)** - Setup and configuration
- **[Usage Guide](USAGE.md)** - Comprehensive usage examples
- **[Rentcast API Documentation](https://developers.rentcast.io/reference/introduction)** - Official API docs
For questions or issues, please refer to the project repository at [git.supported.systems/MCP/rentcache](https://git.supported.systems/MCP/rentcache).

592
docs/INSTALLATION.md Normal file
View File

@ -0,0 +1,592 @@
# Installation Guide
This guide covers all installation methods for RentCache, from development setup to production deployment.
## 📋 Prerequisites
### System Requirements
- **Python**: 3.10 or higher
- **Operating System**: Linux, macOS, or Windows
- **Memory**: Minimum 512MB RAM, 2GB+ recommended for production
- **Storage**: 1GB+ available space (cache database can grow)
### Required Software
- **Python 3.10+**: [Download from python.org](https://www.python.org/downloads/)
- **uv** (recommended): [Install guide](https://docs.astral.sh/uv/getting-started/installation/)
- **Git**: For cloning the repository
### Optional Dependencies
- **Redis**: For enhanced cache performance (production recommended)
- **PostgreSQL**: For production database (SQLite default for development)
- **Docker**: For containerized deployment
## 🚀 Quick Installation
### Method 1: Using uv (Recommended)
```bash
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh
# Clone the repository
git clone https://git.supported.systems/MCP/rentcache.git
cd rentcache
# Install dependencies and create virtual environment
uv sync
# Verify installation
uv run rentcache --help
```
### Method 2: Using pip
```bash
# Clone the repository
git clone https://git.supported.systems/MCP/rentcache.git
cd rentcache
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install in development mode
pip install -e .
# Verify installation
rentcache --help
```
### Method 3: Production Installation
```bash
# Install from repository
pip install git+https://git.supported.systems/MCP/rentcache.git
# Or install locally built wheel
pip install rentcache-0.1.0-py3-none-any.whl
```
## 🔧 Configuration
### Environment Variables
Create a `.env` file in your project directory:
```env
# Server Configuration
HOST=0.0.0.0
PORT=8000
DEBUG=false
LOG_LEVEL=INFO
# Database Configuration
DATABASE_URL=sqlite+aiosqlite:///./rentcache.db
DATABASE_ECHO=false
# Redis Configuration (Optional)
REDIS_URL=redis://localhost:6379
REDIS_ENABLED=false
# Rentcast API Configuration
RENTCAST_BASE_URL=https://api.rentcast.io
RENTCAST_TIMEOUT=30
RENTCAST_MAX_RETRIES=3
# Cache Settings
DEFAULT_CACHE_TTL=3600
EXPENSIVE_ENDPOINTS_TTL=86400
ENABLE_STALE_WHILE_REVALIDATE=true
# Rate Limiting
ENABLE_RATE_LIMITING=true
GLOBAL_RATE_LIMIT=1000/hour
PER_ENDPOINT_RATE_LIMIT=100/minute
# Security
ALLOWED_HOSTS=*
CORS_ORIGINS=*
# Logging
LOG_FORMAT=json
```
### Configuration Options Explained
| Variable | Description | Default | Production Recommendation |
|----------|-------------|---------|---------------------------|
| `DATABASE_URL` | Database connection string | SQLite local file | PostgreSQL with connection pooling |
| `REDIS_ENABLED` | Enable Redis caching | `false` | `true` for better performance |
| `DEFAULT_CACHE_TTL` | Default cache time in seconds | 3600 (1 hour) | 3600-7200 depending on use case |
| `EXPENSIVE_ENDPOINTS_TTL` | Cache time for costly endpoints | 86400 (24 hours) | 86400-172800 (1-2 days) |
| `GLOBAL_RATE_LIMIT` | Requests per API key per hour | 1000/hour | Adjust based on your Rentcast plan |
| `LOG_LEVEL` | Logging verbosity | INFO | INFO (WARNING for high-traffic) |
## 🗄️ Database Setup
### SQLite (Development)
SQLite is the default and requires no additional setup. The database file will be created automatically on first run.
```bash
# Database will be created at ./rentcache.db
rentcache server
```
### PostgreSQL (Production)
1. **Install PostgreSQL**:
```bash
# Ubuntu/Debian
sudo apt-get install postgresql postgresql-contrib
# macOS
brew install postgresql
# Or use Docker
docker run -d --name postgres \
-e POSTGRES_DB=rentcache \
-e POSTGRES_USER=rentcache \
-e POSTGRES_PASSWORD=your_password \
-p 5432:5432 \
postgres:15
```
2. **Create Database**:
```sql
CREATE DATABASE rentcache;
CREATE USER rentcache WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE rentcache TO rentcache;
```
3. **Update Configuration**:
```env
DATABASE_URL=postgresql://rentcache:your_password@localhost:5432/rentcache
```
### Redis Setup (Optional)
Redis significantly improves cache performance, especially for high-traffic applications.
1. **Install Redis**:
```bash
# Ubuntu/Debian
sudo apt-get install redis-server
# macOS
brew install redis
# Or use Docker
docker run -d --name redis -p 6379:6379 redis:7-alpine
```
2. **Enable in Configuration**:
```env
REDIS_URL=redis://localhost:6379
REDIS_ENABLED=true
```
## 🐳 Docker Installation
### Using Docker Compose (Recommended)
1. **Create `docker-compose.yml`**:
```yaml
services:
rentcache:
build: .
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://rentcache:password@db:5432/rentcache
- REDIS_URL=redis://redis:6379
- REDIS_ENABLED=true
depends_on:
- db
- redis
volumes:
- ./data:/app/data
db:
image: postgres:15
environment:
POSTGRES_DB: rentcache
POSTGRES_USER: rentcache
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
volumes:
- redis_data:/data
volumes:
postgres_data:
redis_data:
```
2. **Start Services**:
```bash
docker-compose up -d
```
### Using Docker Directly
1. **Build Image**:
```bash
docker build -t rentcache .
```
2. **Run Container**:
```bash
docker run -d --name rentcache \
-p 8000:8000 \
-e DATABASE_URL=sqlite+aiosqlite:///./data/rentcache.db \
-v $(pwd)/data:/app/data \
rentcache
```
## 🔐 Initial Setup
### 1. Start the Server
```bash
# Development
uv run rentcache server --reload
# Production
uv run rentcache server --host 0.0.0.0 --port 8000
```
### 2. Verify Installation
```bash
# Check health
curl http://localhost:8000/health
# Expected response
{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00Z",
"version": "1.0.0",
"database": "healthy",
"cache_backend": "sqlite",
"active_keys": 0,
"total_cache_entries": 0
}
```
### 3. Create Your First API Key
```bash
# Replace YOUR_RENTCAST_API_KEY with your actual Rentcast API key
uv run rentcache create-key my_app YOUR_RENTCAST_API_KEY
# Or with custom limits
uv run rentcache create-key production_app YOUR_RENTCAST_API_KEY \
--daily-limit 5000 \
--monthly-limit 100000 \
--expires 2024-12-31
```
### 4. Test API Access
```bash
# Test property search (replace YOUR_RENTCAST_API_KEY)
curl -H "Authorization: Bearer YOUR_RENTCAST_API_KEY" \
"http://localhost:8000/api/v1/properties?city=Austin&state=TX&limit=5"
# Check cache performance
curl http://localhost:8000/metrics
```
## 🛠️ Development Setup
### Installing Development Dependencies
```bash
# Install with development dependencies
uv sync --all-extras
# Or with pip
pip install -e ".[dev]"
```
### Development Tools Setup
```bash
# Install pre-commit hooks (optional but recommended)
pre-commit install
# Run tests
uv run pytest
# Format code
uv run black src tests
uv run ruff check src tests --fix
# Type checking
uv run mypy src
```
### Development Environment
```env
# .env for development
DEBUG=true
LOG_LEVEL=DEBUG
DATABASE_ECHO=true
CORS_ORIGINS=http://localhost:3000,http://localhost:8080
```
## 🚀 Production Deployment
### System Requirements
- **CPU**: 2+ cores
- **Memory**: 4GB+ RAM
- **Storage**: 10GB+ SSD
- **Network**: 100Mbps+ bandwidth
### Production Configuration
```env
# Production .env
DEBUG=false
LOG_LEVEL=INFO
LOG_FORMAT=json
# Use PostgreSQL
DATABASE_URL=postgresql://user:pass@db-host:5432/rentcache
# Enable Redis
REDIS_URL=redis://redis-host:6379
REDIS_ENABLED=true
# Security
ALLOWED_HOSTS=yourdomain.com,api.yourdomain.com
CORS_ORIGINS=https://yourdomain.com,https://app.yourdomain.com
# Performance
DEFAULT_CACHE_TTL=7200
EXPENSIVE_ENDPOINTS_TTL=172800
```
### Reverse Proxy Setup (Nginx)
```nginx
server {
listen 80;
server_name api.yourdomain.com;
location / {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
### Process Management (systemd)
Create `/etc/systemd/system/rentcache.service`:
```ini
[Unit]
Description=RentCache API Server
After=network.target
[Service]
Type=exec
User=rentcache
Group=rentcache
WorkingDirectory=/opt/rentcache
Environment=PATH=/opt/rentcache/.venv/bin
ExecStart=/opt/rentcache/.venv/bin/rentcache server --host 0.0.0.0 --port 8000
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
```
```bash
# Enable and start service
sudo systemctl enable rentcache
sudo systemctl start rentcache
sudo systemctl status rentcache
```
## 🔍 Troubleshooting
### Common Issues
#### Database Connection Errors
```bash
# Check database file permissions
ls -la rentcache.db
# Check PostgreSQL connection
psql postgresql://user:pass@host:5432/dbname
# Reset database
rm rentcache.db # SQLite only
uv run rentcache server # Will recreate tables
```
#### Redis Connection Issues
```bash
# Test Redis connection
redis-cli ping
# Check Redis configuration
redis-cli config get '*'
# Disable Redis temporarily
echo "REDIS_ENABLED=false" >> .env
```
#### Port Already in Use
```bash
# Find process using port 8000
lsof -i :8000
# Kill process
kill -9 <PID>
# Or use different port
uv run rentcache server --port 8001
```
#### Permission Denied
```bash
# Fix file permissions
chmod +x $(which rentcache)
# Fix data directory permissions
sudo chown -R $USER:$USER ./data
```
### Log Analysis
```bash
# View logs in development
uv run rentcache server --log-level DEBUG
# Production log analysis
tail -f /var/log/rentcache/access.log | jq '.'
# Filter for errors
tail -f /var/log/rentcache/access.log | jq 'select(.level == "ERROR")'
```
### Performance Issues
```bash
# Check cache hit ratio
uv run rentcache stats
# Monitor database size
du -h rentcache.db
# Check memory usage
ps aux | grep rentcache
# Monitor request patterns
curl http://localhost:8000/metrics | jq '.top_endpoints'
```
## 📊 Monitoring Setup
### Health Check Endpoint
```bash
# Basic health check
curl http://localhost:8000/health
# Detailed metrics
curl http://localhost:8000/metrics
```
### Prometheus Integration
Add to your `prometheus.yml`:
```yaml
scrape_configs:
- job_name: 'rentcache'
static_configs:
- targets: ['localhost:8000']
metrics_path: /metrics
scrape_interval: 30s
```
### Log Aggregation
For centralized logging, configure structured JSON output:
```env
LOG_FORMAT=json
LOG_LEVEL=INFO
```
Then forward logs to your preferred system (ELK, Splunk, etc.).
## 🔄 Updates and Maintenance
### Updating RentCache
```bash
# Pull latest changes
git pull origin main
# Install updated dependencies
uv sync
# Run database migrations (if any)
uv run alembic upgrade head
# Restart service
sudo systemctl restart rentcache
```
### Backup Procedures
```bash
# Backup SQLite database
cp rentcache.db rentcache.db.backup
# Backup PostgreSQL
pg_dump rentcache > rentcache_backup.sql
# Backup configuration
cp .env .env.backup
```
### Maintenance Tasks
```bash
# Clear old cache entries (older than 7 days)
uv run rentcache clear-cache --older-than 168
# Check system health
uv run rentcache health
# View usage statistics
uv run rentcache stats --days 30
```
---
Need help? Check the [Usage Guide](USAGE.md) or [API Reference](API.md) for more information.

642
docs/USAGE.md Normal file
View File

@ -0,0 +1,642 @@
# Usage Guide
This comprehensive guide covers how to use RentCache effectively, from basic operations to advanced configuration and optimization strategies.
## 🚀 Getting Started
### Basic Workflow
1. **Start the server**
2. **Create API keys** for your applications
3. **Make API calls** through RentCache instead of directly to Rentcast
4. **Monitor performance** and costs
5. **Optimize cache settings** based on usage patterns
## 🖥️ Server Management
### Starting the Server
```bash
# Development mode (with auto-reload)
uv run rentcache server --reload --log-level DEBUG
# Production mode
uv run rentcache server --host 0.0.0.0 --port 8000
# Custom configuration
uv run rentcache server \
--host 0.0.0.0 \
--port 8080 \
--log-level INFO
# Using uvicorn directly
uv run uvicorn rentcache.server:app --reload --port 8000
```
### Server Options
| Option | Description | Default |
|--------|-------------|---------|
| `--host` | Bind address | `0.0.0.0` |
| `--port` | Port number | `8000` |
| `--reload` | Auto-reload on code changes | `false` |
| `--log-level` | Logging level | `info` |
### Stopping the Server
```bash
# Graceful shutdown (Ctrl+C or)
kill -TERM <pid>
# Force shutdown
kill -KILL <pid>
# Using systemd
sudo systemctl stop rentcache
```
## 🔑 API Key Management
### Creating API Keys
```bash
# Basic API key creation
uv run rentcache create-key my_app YOUR_RENTCAST_API_KEY
# With custom limits and expiration
uv run rentcache create-key production_app YOUR_RENTCAST_API_KEY \
--daily-limit 5000 \
--monthly-limit 100000 \
--expires 2024-12-31
# Development key with higher limits
uv run rentcache create-key dev_app YOUR_RENTCAST_API_KEY \
--daily-limit 10000 \
--monthly-limit 200000
```
### Listing API Keys
```bash
# View all API keys with usage stats
uv run rentcache list-keys
```
Example output:
```
┌─────────────────┬──────────┬─────────────┬───────────────┬────────────┬─────────────┐
│ Name │ Status │ Daily Usage │ Monthly Usage │ Created │ Expires │
├─────────────────┼──────────┼─────────────┼───────────────┼────────────┼─────────────┤
│ production_app │ 🟢 Active │ 150/5000 │ 3200/100000 │ 2024-01-01 │ 2024-12-31 │
│ dev_app │ 🟢 Active │ 45/10000 │ 890/200000 │ 2024-01-05 │ Never │
│ test_app │ 🔴 Inactive │ 0/1000 │ 0/10000 │ 2024-01-10 │ Never │
└─────────────────┴──────────┴─────────────┴───────────────┴────────────┴─────────────┘
```
### Updating API Keys
```bash
# Update limits
uv run rentcache update-key production_app --daily-limit 10000
# Activate/deactivate key
uv run rentcache update-key test_app --active
uv run rentcache update-key test_app --inactive
# Update multiple settings
uv run rentcache update-key production_app \
--daily-limit 7500 \
--monthly-limit 150000 \
--active
```
### Deleting API Keys
```bash
# Delete with confirmation prompt
uv run rentcache delete-key old_app
# The command will prompt for confirmation:
# Are you sure you want to delete this API key? [y/N]: y
```
## 🌐 Making API Calls
### Basic Request Structure
Replace `api.rentcast.io` with your RentCache server URL and add your API key to the Authorization header:
```bash
# Direct to Rentcast (what you were doing before)
curl -H "X-Api-Key: YOUR_RENTCAST_KEY" \
"https://api.rentcast.io/v1/properties?city=Austin&state=TX"
# Through RentCache (what you should do now)
curl -H "Authorization: Bearer YOUR_RENTCAST_KEY" \
"http://localhost:8000/api/v1/properties?city=Austin&state=TX"
```
### Property Data Endpoints
#### Search Properties
```bash
# Basic property search
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties?city=Austin&state=TX&limit=10"
# Advanced property search
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties?address=123%20Main%20St&zipCode=78701&propertyType=Single%20Family&bedrooms=3&bathrooms=2&squareFootage=1500"
# With pagination
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties?city=Austin&state=TX&offset=20&limit=20"
```
#### Get Property by ID
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties/12345"
```
### Value and Rent Estimates
#### Property Value Estimates
```bash
# Get value estimate
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/estimates/value?address=123%20Main%20St&city=Austin&state=TX"
# Value estimate with property details
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/estimates/value?zipCode=78701&propertyType=Single%20Family&bedrooms=3&bathrooms=2&squareFootage=1800"
```
#### Rent Estimates
```bash
# Get rent estimate
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/estimates/rent?address=123%20Main%20St&city=Austin&state=TX"
# Rent estimate with property details
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/estimates/rent?zipCode=78701&bedrooms=2&bathrooms=2&propertyType=Condo"
```
### Listings Data
#### Sale Listings
```bash
# Search for sale listings
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/listings/sale?city=Austin&state=TX&bedrooms=3&limit=10"
# Sale listings with price range (if supported by Rentcast)
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/listings/sale?zipCode=78701&minPrice=300000&maxPrice=600000"
```
#### Rental Listings
```bash
# Search rental listings
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/listings/rental?city=Austin&state=TX&bedrooms=2&limit=15"
# Rental listings with filters
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/listings/rental?zipCode=78701&propertyType=Apartment&bathrooms=2"
```
### Market Statistics
```bash
# Get market statistics
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/markets/stats?zipCode=78701"
# Market stats by city/state
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/markets/stats?city=Austin&state=TX"
```
### Comparable Properties
```bash
# Get comparable properties
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/comparables?address=123%20Main%20St&city=Austin&state=TX"
# Comparables with property details
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/comparables?zipCode=78701&bedrooms=3&bathrooms=2&squareFootage=1800&propertyType=Single%20Family"
```
## ⚡ Cache Control
### Understanding Cache Behavior
RentCache uses intelligent caching with different TTL (Time To Live) values based on data volatility:
- **Property Records**: 24 hours (expensive, relatively stable)
- **Value/Rent Estimates**: 1 hour (expensive, moderately dynamic)
- **Listings**: 30 minutes (frequently updated)
- **Market Stats**: 2 hours (aggregated data, slower to change)
### Cache Control Parameters
#### Force Refresh
Force a fresh API call even if cached data exists:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties?city=Austin&state=TX&force_refresh=true"
```
#### Override TTL
Set custom cache duration (in seconds):
```bash
# Cache for 2 hours (7200 seconds)
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/estimates/value?address=123%20Main%20St&ttl_override=7200"
# Cache for 10 minutes (600 seconds)
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/listings/sale?city=Austin&ttl_override=600"
```
### Reading Response Headers
Every response includes cache information:
```bash
curl -I -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties?city=Austin&state=TX"
# Response headers include:
# X-Cache-Hit: true
# X-Response-Time-MS: 12.5
# X-Estimated-Cost: 0.0 (cache hits cost nothing!)
```
### Cache Management CLI
```bash
# View cache statistics
uv run rentcache stats
# Clear specific endpoint cache
uv run rentcache clear-cache --endpoint properties
# Clear cache older than 24 hours
uv run rentcache clear-cache --older-than 24
# Clear all cache (use with caution!)
uv run rentcache clear-cache
```
## 📊 Monitoring and Analytics
### Usage Statistics
```bash
# Overall statistics
uv run rentcache stats
# Statistics for specific endpoint
uv run rentcache stats --endpoint properties
# Statistics for specific time period
uv run rentcache stats --days 30
```
Example output:
```
┌─────────────────────┬──────────┐
│ Metric │ Value │
├─────────────────────┼──────────┤
│ Total Requests │ 2,543 │
│ Cache Hits │ 2,287 │
│ Cache Misses │ 256 │
│ Hit Ratio │ 89.92% │
│ Avg Response Time │ 28.5ms │
│ Total Cost │ $512.00 │
│ Cache Entries │ 1,234 │
└─────────────────────┴──────────┘
📊 Top Endpoints:
┌─────────────────────┬───────────┐
│ Endpoint │ Requests │
├─────────────────────┼───────────┤
│ properties │ 1,205 │
│ value_estimate │ 892 │
│ listings_sale │ 234 │
│ rent_estimate │ 156 │
│ market_stats │ 56 │
└─────────────────────┴───────────┘
```
### Health Monitoring
```bash
# Check system health
uv run rentcache health
# Expected output when healthy:
# ✅ Database: Connected
# 🔑 Active API Keys: 3
# 💾 Valid Cache Entries: 1234
# 📈 Requests (24h): 456
#
# 🎉 System is healthy!
```
### Real-time Metrics via HTTP
```bash
# Get detailed system metrics
curl http://localhost:8000/metrics | jq '.'
# Key metrics to monitor:
curl http://localhost:8000/metrics | jq '{
cache_hit_ratio: .cache_hit_ratio,
avg_response_time: .avg_response_time_ms,
requests_24h: .requests_24h,
cost_24h: .cost_24h
}'
```
## 💰 Cost Management
### Understanding Costs
RentCache tracks estimated costs for different endpoint types:
| Endpoint Type | Estimated Cost | Cache TTL | Typical Savings |
|---------------|----------------|-----------|-----------------|
| Property Records | $1.00 | 24 hours | 90% |
| Value Estimates | $2.00 | 1 hour | 85% |
| Rent Estimates | $2.00 | 1 hour | 85% |
| Market Stats | $5.00 | 2 hours | 95% |
| Listings | $0.50 | 30 minutes | 70% |
| Comparables | $3.00 | 1 hour | 88% |
### Monitoring Costs
```bash
# View cost breakdown
uv run rentcache stats | grep -A 5 "Cost"
# Daily cost tracking
curl http://localhost:8000/metrics | jq '.cost_24h'
# Calculate savings
curl http://localhost:8000/metrics | jq '
.total_requests as $total |
.cache_hits as $hits |
($hits / $total * 100) as $hit_ratio |
"Cache Hit Ratio: \($hit_ratio)%"
'
```
### Cost Optimization Strategies
1. **Increase Cache TTL for Stable Data**:
```bash
# Cache property records for 48 hours instead of 24
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties?address=123%20Main%20St&ttl_override=172800"
```
2. **Batch Related Requests**:
```bash
# Instead of multiple individual requests, search broader then filter locally
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/properties?zipCode=78701&limit=100"
```
3. **Use Appropriate Endpoints**:
```bash
# Use less expensive listing searches when you don't need full property records
curl -H "Authorization: Bearer YOUR_API_KEY" \
"http://localhost:8000/api/v1/listings/sale?city=Austin&state=TX"
```
## 🔧 Advanced Configuration
### Environment-Based Configuration
Create different configuration files for different environments:
#### Development (`.env.dev`)
```env
DEBUG=true
LOG_LEVEL=DEBUG
DATABASE_URL=sqlite+aiosqlite:///./dev_rentcache.db
DEFAULT_CACHE_TTL=1800 # 30 minutes for faster testing
CORS_ORIGINS=http://localhost:3000,http://localhost:8080
```
#### Staging (`.env.staging`)
```env
DEBUG=false
LOG_LEVEL=INFO
DATABASE_URL=postgresql://user:pass@staging-db:5432/rentcache
REDIS_ENABLED=true
REDIS_URL=redis://staging-redis:6379
DEFAULT_CACHE_TTL=3600
```
#### Production (`.env.prod`)
```env
DEBUG=false
LOG_LEVEL=WARNING
DATABASE_URL=postgresql://user:pass@prod-db:5432/rentcache
REDIS_ENABLED=true
REDIS_URL=redis://prod-redis:6379
DEFAULT_CACHE_TTL=7200
EXPENSIVE_ENDPOINTS_TTL=172800
```
### Rate Limiting Configuration
#### Global Rate Limits
```env
# Requests per API key per time period
GLOBAL_RATE_LIMIT=2000/hour
DAILY_RATE_LIMIT=10000/day
```
#### Per-Endpoint Rate Limits
```env
# Expensive endpoints get lower limits
VALUE_ESTIMATE_RATE_LIMIT=30/minute
RENT_ESTIMATE_RATE_LIMIT=30/minute
MARKET_STATS_RATE_LIMIT=20/minute
# Cheaper endpoints can have higher limits
LISTINGS_RATE_LIMIT=100/minute
PROPERTIES_RATE_LIMIT=60/minute
```
### Custom Cache Strategies
#### Endpoint-Specific TTL Configuration
```python
# Example: Custom cache configuration
CUSTOM_CACHE_TTL = {
"properties": 86400, # 24 hours
"value_estimate": 3600, # 1 hour
"rent_estimate": 3600, # 1 hour
"listings_sale": 1800, # 30 minutes
"listings_rental": 1800, # 30 minutes
"market_stats": 7200, # 2 hours
"comparables": 3600 # 1 hour
}
```
## 🐛 Troubleshooting
### Common Issues and Solutions
#### Cache Miss Rate Too High
**Problem**: Low cache hit ratio (< 60%)
**Solutions**:
1. Check if `force_refresh=true` is being used too often
2. Verify TTL settings aren't too short
3. Check if requests have slight parameter variations
```bash
# Analyze request patterns
uv run rentcache stats --endpoint properties | grep "Total Requests"
# Check for parameter variations
curl http://localhost:8000/metrics | jq '.top_endpoints'
```
#### High Response Times
**Problem**: Slow API responses
**Solutions**:
1. Enable Redis for faster cache access
2. Check database performance
3. Monitor upstream Rentcast API performance
```bash
# Check average response times
curl http://localhost:8000/metrics | jq '.avg_response_time_ms'
# Monitor cache hit ratio
uv run rentcache stats | grep "Hit Ratio"
```
#### Rate Limit Exceeded
**Problem**: Getting 429 errors
**Solutions**:
1. Check current usage against limits
2. Increase limits if needed
3. Implement request queuing in your application
```bash
# Check current usage
uv run rentcache list-keys
# Update limits
uv run rentcache update-key my_app --daily-limit 10000
```
#### Database Errors
**Problem**: Database connection or performance issues
**Solutions**:
1. Check database connectivity
2. Monitor database size and performance
3. Consider migrating from SQLite to PostgreSQL
```bash
# Check database health
uv run rentcache health
# Check database size
du -h rentcache.db
# Clear old cache entries
uv run rentcache clear-cache --older-than 168 # 7 days
```
### Debug Mode
Enable detailed logging for troubleshooting:
```bash
# Start server with debug logging
uv run rentcache server --log-level DEBUG
# Check logs for specific requests
tail -f /var/log/rentcache.log | grep "ERROR\|WARNING"
```
### Performance Monitoring
```bash
# Monitor request patterns
watch -n 5 'curl -s http://localhost:8000/metrics | jq "{requests_24h, cache_hits_24h, hit_ratio: (.cache_hits_24h / .requests_24h * 100)}"'
# Monitor system resources
htop
# Monitor database performance
# SQLite: Use .timer on in sqlite3 CLI
# PostgreSQL: Use pg_stat_statements extension
```
## 🔄 Best Practices
### Request Optimization
1. **Consistent Parameter Formatting**: Keep parameter formats consistent to maximize cache hits
2. **Appropriate Pagination**: Don't request more data than needed
3. **Smart Caching**: Use longer TTLs for stable data like property records
4. **Batch Operations**: Group related requests when possible
### Cache Strategy
1. **Monitor Hit Ratios**: Aim for 80%+ cache hit ratios
2. **Adjust TTLs**: Balance freshness vs. cost savings
3. **Regular Cleanup**: Clean old cache entries periodically
4. **Use Redis**: Enable Redis for high-traffic applications
### Security
1. **Rotate API Keys**: Regularly rotate Rentcast API keys
2. **Monitor Usage**: Watch for unusual usage patterns
3. **Set Appropriate Limits**: Don't set limits too high
4. **Use HTTPS**: Always use HTTPS in production
### Monitoring
1. **Set Up Alerts**: Alert on high error rates or low cache hit ratios
2. **Regular Health Checks**: Monitor the `/health` endpoint
3. **Cost Tracking**: Monitor daily/monthly costs
4. **Performance Metrics**: Track response times and throughput
---
Ready to optimize your Rentcast API usage? Check out the [API Reference](API.md) for detailed endpoint documentation or the [Installation Guide](INSTALLATION.md) for setup instructions.

View File

@ -54,10 +54,10 @@ dev = [
]
[project.urls]
Homepage = "https://github.com/yourusername/rentcache"
Repository = "https://github.com/yourusername/rentcache.git"
Documentation = "https://github.com/yourusername/rentcache#readme"
"Bug Tracker" = "https://github.com/yourusername/rentcache/issues"
Homepage = "https://git.supported.systems/MCP/rentcache"
Repository = "https://git.supported.systems/MCP/rentcache.git"
Documentation = "https://git.supported.systems/MCP/rentcache#readme"
"Bug Tracker" = "https://git.supported.systems/MCP/rentcache/issues"
[project.scripts]
rentcache = "rentcache.cli:main"