Download the PHP package antikirra/probability without Composer
On this page you can find all versions of the php package antikirra/probability. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download antikirra/probability
More information about antikirra/probability
Files in antikirra/probability
Package probability
Short Description Lightweight PHP micro-library for probabilistic and deterministic code execution โ feature flags, A/B testing, gradual rollouts and sampling.
License MIT
Informations about the package probability
Make your code work spontaneously ๐
A lightweight PHP library for probabilistic code execution and deterministic feature distribution. Perfect for A/B testing, gradual feature rollouts, performance sampling, and controlled chaos engineering.
Quick Start
Install
Requires PHP 8.2 or newer. Zero runtime dependencies.
๐ Key Features
- Zero Dependencies - Pure PHP implementation
- Deterministic Distribution - Consistent results for the same input keys
- High Performance - Minimal overhead, suitable for high-traffic applications
- Simple API - Just one function with intuitive parameters
- Battle-tested - Production-ready with predictable behavior at scale
๐ก Use Cases
-
Performance Sampling - Log only a fraction of requests to reduce storage costs while maintaining system visibility. Sample database queries, API calls, or user interactions for performance monitoring without overwhelming your logging infrastructure.
-
A/B Testing - Run controlled experiments with consistent user experience. Test new features, UI changes, or algorithms on a specific percentage of users while ensuring each user always sees the same variant throughout their session.
-
Feature Flags - Gradually roll out new features with fine-grained control. Start with a small percentage of users and increase over time, or enable features for specific user segments based on subscription tiers or other criteria.
-
Chaos Engineering - Test system resilience by introducing controlled failures. Simulate random delays, service outages, or cache misses to ensure your application handles edge cases gracefully in production.
-
Rate Limiting - Implement soft rate limits without additional infrastructure. Control access to expensive operations or API endpoints based on user tiers, preventing abuse while maintaining a smooth experience for legitimate users.
-
Load Balancing - Distribute traffic across different backend services or database replicas probabilistically, achieving simple load distribution without complex routing rules.
-
Canary Deployments - Route a small percentage of traffic to new application versions or infrastructure, monitoring for issues before full rollout.
-
Analytics Sampling - Reduce analytics data volume and costs by tracking only a representative sample of events while maintaining statistical significance.
-
Content Variation - Test different content strategies, email templates, or notification messages to optimize engagement metrics.
- Resource Optimization - Selectively enable resource-intensive features like real-time updates, advanced search, or AI-powered suggestions based on server load or user priority.
๐ฌ How It Works
The library uses two strategies for probability calculation:
1. Pure Random (No Key)
When called without a key, uses PHP's mt_rand() for true randomness:
2. Deterministic (With Key)
When provided with a key, uses CRC32 hashing for consistent results:
Technical Details:
- Uses
crc32()to hash the key into a 32-bit unsigned integer (0 to 4,294,967,295) - Normalizes the hash by dividing by the bucket count
2ยณยฒ(4,294,967,296) to get an unbiased value in[0.0, 1.0) - Compares the normalized value against the probability threshold
- Same key โ same hash โ same normalized value โ deterministic result
The deterministic approach ensures:
- Same input always produces same output
- Uniform distribution across large datasets
- No need for external storage or coordination
- Fast performance (CRC32 is optimized in PHP)
๐ API Reference
Parameters
-
$probability(float): A value between 0.0 and 1.00.0= Never returns true (0% chance)0.5= Returns true half the time (50% chance)1.0= Always returns true (100% chance)
$key(string): Optional. When provided (non-empty), ensures deterministic behavior- Same key always produces same result
- Different keys distribute uniformly
- An empty string (the default) falls back to random behavior
Returns
bool:trueif the event should occur,falseotherwise
Examples
๐ฏ Best Practices
1. Use Meaningful Keys
2. Separate Features
3. Consider Scale
๐ When to Use: Random vs Deterministic
| Scenario | Use Random (no key) | Use Deterministic (with key) |
|---|---|---|
| Performance sampling | โ Sample random requests | โ Would sample same requests |
| Logging/Debugging | โ Random sampling | โ Not needed for logs |
| A/B Testing | โ Inconsistent UX | โ User sees same variant |
| Feature Rollout | โ Unpredictable access | โ Stable feature access |
| Chaos Engineering | โ Random failures | โ ๏ธ Depends on use case |
| Load Testing | โ Random distribution | โ Predictable patterns |
| Canary Deployment | โ Unstable routing | โ Consistent routing |
| User Segmentation | โ Segments change | โ Stable segments |
๐ป Real-World Examples
Laravel: Feature Flag Middleware
Symfony: Performance Monitoring
WordPress: A/B Testing
API Rate Limiting by Tier
๐งช Testing
The library includes a comprehensive Pest test suite covering edge cases, statistical correctness, and deterministic behavior.
Test coverage includes:
- Edge cases (0.0, 1.0, epsilon boundaries)
- Input validation and error handling
- Deterministic key behavior
- Statistical correctness over large sample sizes
- Hash collision handling
- Type coercion
โก Performance
Benchmarks on PHP 8.4 (Apple M4 Pro):
| Operation | Time per call | Ops/sec |
|---|---|---|
| Random (no key) | ~0.12 ฮผs | ~8.4M |
| Deterministic (with key) | ~0.15 ฮผs | ~6.7M |
Memory usage: 0 bytes (no allocations)
The library is optimized for high-throughput scenarios:
- Fast-path optimization for edge cases (0.0, 1.0)
- Minimal function calls
- No object instantiation
- CRC32 is faster than other hash functions
Run php benchmark.php to test performance on your hardware.
โ FAQ / Troubleshooting
Why do I get different results in different environments?
Q: Same key returns different results on different servers.
A: This is expected! CRC32 implementation is consistent, but you might be using different keys. Ensure you're using the exact same key string across environments.
Why is my A/B test showing 52% instead of 50%?
Q: I'm using probability(0.5, $userId) but getting uneven distribution.
A: With small sample sizes, variance is normal. The distribution converges to 50% with larger samples (law of large numbers). For 100 users, expect 45-55%. For 10,000 users, expect 49-51%.
Can I use this for cryptographic purposes?
Q: Is this secure for generating random tokens?
A: No! This library is NOT cryptographically secure. CRC32 is predictable and mt_rand() is not suitable for security. Use random_bytes() or random_int() for security purposes.
How do I gradually increase rollout percentage?
Q: I want to go from 10% to 50% to 100%.
A: Just change the probability value in your code/config. Users in the 0-10% hash range stay enabled, users in 10-50% get added, etc.
What about hash collisions?
Q: Can different keys produce the same result?
A: Yes, CRC32 has only 2ยณยฒ (~4.3 billion) possible values. With many keys, collisions are possible but rare for typical use cases. For most applications this is acceptable. If you need collision-resistant hashing, fork and replace CRC32 with MD5 or SHA256.
Why not use a database for feature flags?
Q: Isn't a feature flag service better?
A: Depends on your needs:
- Use this library: Simple rollouts, performance sampling, no persistence needed, minimal dependencies
- Use feature flag service: Complex targeting, runtime changes, analytics, team collaboration
This library excels at simplicity and performance, not flexibility.