Ship the policy, not the code

The article discusses strategies for managing shared logic between frontend and backend systems, using the context of API interactions as an example. Specifically, it examines how to handle business rules that dictate behavior across these systems, such as when an order can be canceled.

Key Issues:

  • Often, the same rule (e.g., order cancelation conditions) is implemented separately on both frontend and backend, leading to potential discrepancies.
  • Sharing the actual code can be problematic due to version drift and language differences across platforms.

Strategies Discussed:

  1. Sharing Code:

    • This involves using shared packages or modules in a monorepo.
    • Challenges include potential differences in deployment versions, language compatibility issues, and the risk of divergence.
  2. Shipping Data Instead of Code:

    • The backend evaluates the rule and sends the result or the driving spec to the frontend.
    • This allows the frontend to render states without re-deriving logic.
    • A simple boolean may be insufficient; detailed status and reasons are often necessary for UI and UX.
  3. HATEOAS:

    • The server explicitly informs the client about available actions, thus eliminating the need for the client to infer possible state changes.
  4. Policy Shipping:

    • The backend sends serialized policies evaluated by a lightweight shared evaluator, rather than the policy logic itself.
    • Tools like CASL for permissions or JSON Schema for validation illustrate this approach.
    • The advantage is sharing only stable evaluators, not the volatile business logic.
  5. Avoiding Redundancy:

    • Sharing data or policy rather than duplicating logic helps maintain consistency.
    • The article stresses avoiding "WET" (write every time) practices for business invariants.

Overall, the article recommends prioritizing the sharing of data or policy specs over raw code to maintain synchronization and reduce errors in systems where backend and frontend react to shared business logic.

Visit

Do you like my content?

Sponsor Me On Github