← Назад к вопросам
Сформулируй нефункциональные требования для отображения суммы в иностранной валюте
2.0 Middle🔥 271 комментариев
#User Story и Use Case#Требования и их анализ
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI29 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Нефункциональные требования для отображения суммы в иностранной валюте
Это хороший пример задачи, где NFR часто игнорируют, но они оказывают большое влияние. Поделюсь как я бы подошел к этому вопросу.
Сначала: Функциональные требования
FR-001: Currency Display
- User can select currency to display (USD, EUR, GBP, JPY, RUB, etc.)
- System converts amount from base currency (USD) to selected currency
- Exchange rate used for conversion is displayed
- User sees formatted amount with currency symbol
Пример:
Base amount: 100 USD
User selects: EUR
Exchange rate: 1 USD = 0.92 EUR
Displayed: EUR 92.00
Теперь: Нефункциональные требования
NFR-CUR-001: Accuracy (Точность)
Requirement:
Currency conversion must be accurate to 2 decimal places
for standard currencies, 0-3 for others.
Rounding rule: HALF_UP (standard for finance)
Example: EUR 92.456 -> EUR 92.46
Acceptable rounding error: 0.01 (0.01% of amount)
For $1000 order, max error: $0.10
Test:
1000 USD = ? EUR
Using external API rate: 920.00 EUR
Using our system: 920.00 EUR (match)
Why important:
- Financial regulations require accurate calculations
- Customers complain if there's even 0.1% difference
- Tax calculations depend on accuracy
- Audit trails need to match
NFR-CUR-002: Performance (Производительность)
Requirement:
Currency conversion must complete in < 50ms (P99)
Including:
- Exchange rate lookup
- Conversion calculation
- Formatting
- API call to rate provider (if needed)
Performance SLA:
Single conversion: < 50ms
Page with 10 items (each with price): < 200ms total
Bulk conversion (1000 items): < 2 seconds
Testing:
Load test: 10,000 concurrent users
Each user converts 5 different currencies
Measure P95, P99 latency
Optimization strategies:
- Cache exchange rates (in-memory cache)
- Batch conversions when possible
- Async rate updates (don't block on fresh rates)
- CDN for client-side calculations
NFR-CUR-003: Freshness (Свежесть данных)
Requirement:
Exchange rates must be updated regularly:
Forex (major currencies): every 1 minute
USD/EUR, USD/GBP, USD/JPY, etc.
Source: Real-time API (e.g., Alpha Vantage, OANDA)
Crypto: every 10 seconds
BTC/USD, ETH/USD, etc.
Source: Cryptocurrency exchange API
Emerging markets: every 1 hour
USD/INR, USD/MXN, etc.
Source: Daily updates from World Bank
Max staleness (oldest rate is used):
Before 1 hour: Use latest rate
1-3 hours old: Use with "rates are delayed" warning
3+ hours old: Show error, don't convert
Monitoring:
Alert if rate is older than max staleness
Alert if rate provider API is down
Track rate freshness metrics
Why important:
- Stale rates lead to unfair pricing
- Customers see wrong amounts
- Arbitrage opportunities if rates are old
- Regulatory compliance requires fresh rates
NFR-CUR-004: Consistency (Согласованность)
Requirement:
All conversions in user's session must use same exchange rate:
Scenario:
User adds item 1: 100 USD -> 92 EUR (rate: 0.92)
User adds item 2: 50 USD -> 46 EUR (rate: 0.92) [SAME RATE]
User views cart: 150 USD = 138 EUR ✓ (100*0.92 + 50*0.92)
User clicks Pay: Rate updates to 0.91
Payment should use 0.91 (most recent)
Where rate is locked:
- User selects currency: lock rate for 15 minutes
- User proceeds to checkout: lock rate for 30 minutes
- User confirms payment: lock rate for final calculation
- After payment: unlock, use current rate for history
Rate versioning:
Each rate has timestamp
Store which rate was used for each order
For disputes: can show exact rate used
NFR-CUR-005: Availability (Доступность)
Requirement:
Currency conversion service must be available 99.9% of time
Fallback when rate provider is down:
Option 1: Use cached rate (last known good rate)
Display "rates from X minutes ago"
Option 2: Use average rate (from last 24 hours)
Display "estimated, not real-time"
Option 3: Show error and prevent conversion
"Exchange rates unavailable, please try later"
Preferred: Option 1 (with warning)
Maximum fallback duration:
1 hour: use cached rate
1-3 hours: show warning, allow conversion
3+ hours: block conversion, show error
RTO (Recovery Time Objective): 5 minutes
RPO (Recovery Point Objective): 1 minute
NFR-CUR-006: Reliability (Надежность)
Requirement:
Failed conversions must not break the system:
Error handling:
If rate lookup fails:
- Retry up to 3 times (exponential backoff)
- After 3 retries: use cached rate
- Log error for ops team
- Show user message: "Using cached rates"
If calculation fails:
- Fall back to default currency (USD)
- Log error with details
- Alert ops team
- Never show wrong amount
Zero-error guarantee:
If we can't determine rate: DON'T guess
Show error rather than wrong amount
NFR-CUR-007: Scalability (Масштабируемость)
Requirement:
System must handle:
Currency volume:
- Support 150+ currencies
- 50+ major forex pairs
- 1000+ crypto pairs
- Data size: < 1 MB in memory
User scale:
- 10,000 concurrent users converting currencies
- Each user converts 5+ different currencies
- = 50,000+ conversion requests per second
Scaling solution:
- In-memory cache (Redis): store all rates
- Rate limiting: 100 conversions per user per second
- Batch conversions: combine requests from same user
- Rate updates: async, don't block requests
Cost optimization:
- Cache hit rate: 99% (avoid expensive API calls)
- API calls: < 10,000 per day (paid API)
NFR-CUR-008: Security (Безопасность)
Requirement:
Exchange rate data must be protected:
Data protection:
- Rates are public data (can be cached)
- But integrity must be verified
- Sign rate updates with HMAC
- Verify signature before using rate
Rate manipulation protection:
- Rates must come from trusted sources only
- Don't accept rates from user input
- Don't accept rates from untrusted APIs
- Have whitelist of approved rate providers
Audit trail:
- Log every rate update
- Log every conversion for financial audit
- Store rate history for minimum 7 years
- Include which rate was used for each transaction
Example audit log:
2024-01-15 10:30:00 UTC
Transaction: PAY-12345
Amount: 100 USD
Target currency: EUR
Rate used: 0.92
Rate source: OANDA API
Rate timestamp: 2024-01-15 10:29:45 UTC
Conversion: 100 * 0.92 = 92 EUR
NFR-CUR-009: User Experience (Опыт пользователя)
Requirement:
Currency display must be clear:
Formatting:
USD 100.00 (for US)
$100.00 (for Canada)
EUR 92.00 (for EU)
€92.00 (alternative)
100.00 USD (some markets)
Locale-specific:
Thousands separator: 1,234.56 (US) vs 1.234,56 (EU)
Decimal separator: . (US) vs , (EU)
Currency position: USD 100 (US) vs 100 USD (EU)
Rate display:
Show: "Rate: 1 USD = 0.92 EUR (updated 2 min ago)"
Show warning if rate > 1 hour old
Link to rate history (last 24 hours)
Mobile responsiveness:
Currency selector: accessible on mobile
Conversion must work offline (with cached rates)
Display must fit small screens
NFR-CUR-010: Compliance (Соответствие)
Requirement:
Financial regulations:
For financial transactions:
- Follow bank regulations for currency conversion
- Disclose exchange rate markup (if any)
- PCI-DSS compliance
- Financial reporting standards (GAAP)
For different regions:
- EU: GDPR for storing user currency preferences
- US: FinCEN reporting for large transactions
- China: CNY conversion limits (max $50k per year)
- Russia: limitations on USD/EUR conversion
Documentation:
- Exchange rate methodology: documented
- Rounding rules: documented
- Rate sources: disclosed
- Fee structure: transparent
Testing compliance:
- Quarterly audit of conversion calculations
- Verify rates match market rates
- Check for regulatory violations
- Document all exceptions
Таблица всех NFR
| NFR ID | Category | Requirement | Metric | Target |
|---|---|---|---|---|
| NFR-CUR-001 | Accuracy | Conversion precision | Error rate | 0.01% max |
| NFR-CUR-002 | Performance | Conversion speed | Latency P99 | <50ms |
| NFR-CUR-003 | Freshness | Rate update frequency | Staleness | 1h max |
| NFR-CUR-004 | Consistency | Same rate in session | Rate locking | 15min |
| NFR-CUR-005 | Availability | System uptime | Availability | 99.9% SLA |
| NFR-CUR-006 | Reliability | Error handling | Zero data loss | 100% |
| NFR-CUR-007 | Scalability | Concurrent users | Throughput | 50k req/sec |
| NFR-CUR-008 | Security | Rate integrity | Audit trail | 7 years |
| NFR-CUR-009 | UX | Clear display | Formatting | Locale-specific |
| NFR-CUR-010 | Compliance | Regulations | Audit | Quarterly |
Как я бы реализовал это
Architecture:
Rate Provider API
| (every 1 min)
↓
Rate Cache (Redis)
↓
Conversion Service
↓
Client (Web/Mobile)
Audit Log
↑
| (every conversion)
|
Conversion Service
Tech Stack:
- Redis: store rates, cache conversions
- PostgreSQL: audit log, rate history
- API: OpenAPI documented
- Monitoring: track rate freshness, conversion errors
- Testing: unit tests (accuracy), load tests (performance)
Вывод
НFR для отображения валюты требует:
- Точность (Financial precision)
- Свежесть (Real-time rates)
- Надежность (Fallback strategies)
- Производительность (Sub-100ms)
- Масштабируемость (Thousands of conversions/sec)
- Безопасность (Audit trails)
- Соответствие (Regulatory requirements)
Игнорирование любого из этих требований может привести к потере денег, судебным разбирательствам или регуляторным штрафам.