โ† Integrations

Backend ยท Java

Batch Ashtakoot matching from a Spring Boot service

A matrimony backend rarely scores one couple at a time. POST /v1/compatibility/batch takes up to 500 pairs and returns a report id you poll. Here is the Spring Boot wiring for it - configuration, a client with timeouts, a service that waits for the report, a controller - and the serialisation detail that turns every request into a 400.

Updated

How this page was checked: AstroNodeClient was compiled with javac (Java 17) and run against the in-memory API: it queued the two-pair batch, polled the report and sent the camelCase body that produced the 400 below. The Spring classes (properties, service, controller) need Spring Boot and Jackson on the classpath and were not compiled - there is no Maven or Gradle on the build machine.

Configuration

src/main/resources/application.yml:

yaml
astronode:
  base-url: ${ASTRONODE_BASE_URL:https://api.astronode.dev}
  api-key: ${ASTRONODE_API_KEY:}

AstroNodeConfig.java:

java
@ConfigurationProperties(prefix = "astronode")
public record AstroNodeProperties(String baseUrl, String apiKey) {}

@Configuration
@EnableConfigurationProperties(AstroNodeProperties.class)
class AstroNodeConfig {
    @Bean
    AstroNodeClient astroNodeClient(AstroNodeProperties props) {
        if (props.apiKey() == null || props.apiKey().isBlank()) {
            throw new IllegalStateException("ASTRONODE_API_KEY is not set");
        }
        return new AstroNodeClient(props.baseUrl(), props.apiKey());
    }
}

The empty default (:}) plus the explicit check means a missing key stops the application at startup with a clear message, rather than starting fine and answering every match request with a 401 from upstream.

The HTTP client - plain java.net.http

AstroNodeClient.java - no Spring types, so it compiles and tests on its own:

java
public class AstroNodeClient {

    public record Result(int status, String body) {
        public boolean ok() { return status >= 200 && status < 300; }
    }

    private final HttpClient http = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(5))
            .build();
    private final String baseUrl;
    private final String apiKey;

    public AstroNodeClient(String baseUrl, String apiKey) {
        this.baseUrl = baseUrl;
        this.apiKey = apiKey;
    }

    public Result post(String path, String json) throws IOException, InterruptedException {
        return send(HttpRequest.newBuilder(URI.create(baseUrl + path))
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .header("Content-Type", "application/json"));
    }

    public Result get(String path) throws IOException, InterruptedException {
        return send(HttpRequest.newBuilder(URI.create(baseUrl + path)).GET());
    }

    private Result send(HttpRequest.Builder builder) throws IOException, InterruptedException {
        HttpRequest request = builder
                .header("Authorization", "Bearer " + apiKey)
                .timeout(Duration.ofSeconds(15))
                .build();
        HttpResponse<String> res = http.send(request, HttpResponse.BodyHandlers.ofString());
        return new Result(res.statusCode(), res.body());
    }
}

HttpClient has no request timeout by default - connectTimeout covers only the TCP connect, so the per-request .timeout(...) is the one that stops a hung call. One client instance is shared by the whole application; it is thread-safe and keeps its connection pool.

Queue the batch, poll the report

MatchService.java - Jackson maps the snake_case wire names explicitly:

java
public record Birth(String date, String time,
        @JsonProperty("tz_offset_minutes") int tzOffsetMinutes, double lat, double lng) {}

public record Pair(String id,
        @JsonProperty("person_a") Birth personA,
        @JsonProperty("person_b") Birth personB) {}

@JsonIgnoreProperties(ignoreUnknown = true)
public record MatchResult(String id, int score, int max, String bucket,
        @JsonProperty("match_percentage") int matchPercentage) {}

@Service
public class MatchService {
    private final AstroNodeClient client;
    private final ObjectMapper mapper;

    public MatchService(AstroNodeClient client, ObjectMapper mapper) {
        this.client = client;
        this.mapper = mapper;
    }

    public List<MatchResult> score(List<Pair> pairs) throws Exception {
        var queued = client.post("/v1/compatibility/batch", mapper.writeValueAsString(Map.of("pairs", pairs)));
        if (!queued.ok()) throw new ResponseStatusException(HttpStatus.valueOf(queued.status()), queued.body());
        String id = mapper.readTree(queued.body()).at("/data/id").asText();

        for (int attempt = 0; attempt < 12; attempt++) {
            var polled = client.get("/v1/reports/" + id);
            if (!polled.ok()) throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, polled.body());
            JsonNode data = mapper.readTree(polled.body()).path("data");
            switch (data.path("status").asText()) {
                case "ready" -> {
                    return mapper.convertValue(data.at("/result/results"), new TypeReference<List<MatchResult>>() {});
                }
                case "failed" -> throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, data.path("error_message").asText());
                default -> Thread.sleep(Math.min(500L << attempt, 10_000L)); // "pending"
            }
        }
        throw new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, "report " + id + " still pending");
    }
}

MatchController.java:

java
@RestController
@RequestMapping("/matches")
class MatchController {
    private final MatchService matches;

    MatchController(MatchService matches) {
        this.matches = matches;
    }

    @PostMapping("/score")
    List<MatchResult> score(@RequestBody List<Pair> pairs) throws Exception {
        if (pairs.isEmpty() || pairs.size() > 500) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "send 1 to 500 pairs");
        }
        return matches.score(pairs);
    }
}

The batch call answered 202 with "status": "pending" and a rep_... id; the report moves to ready or failed. The in-memory API had it ready on the first poll - a queued production batch can take longer, which is why the loop backs off. Each poll is a billed call, so do not poll in a tight loop, and for nightly runs over thousands of profiles call the service from a @Scheduled job rather than holding an HTTP request open.

One profile (Bengaluru, 11 Jun 1992) against two candidates
PairScoreBucketWeak koot
m-101 (Chennai, 27 Jan 1994)30 / 36 (83%)Excellentvashya 0 / 2
m-102 (Hyderabad, 3 Sep 1993)26 / 36 (72%)Goodvashya 0 / 2

Each result also carries the eight koots with initial_score (before cancellations) and manglik_match with a plain-English note. For m-102, bhakoot scored 0 before adjustments and 4 after - show both numbers if your users compare against a printed chart (how the 36 points are scored).

The mistake that bites first: Jackson's camelCase

A Java record field called tzOffsetMinutes is serialised by Jackson as "tzOffsetMinutes". The birth input is strict, so the API rejects the unknown key and reports the required one as missing:

What the client got back for a camelCase pair (abridged):

json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      { "instancePath": "/pairs/0/person_a/tz_offset_minutes",
        "message": "Invalid input: expected number, received undefined" },
      { "instancePath": "/pairs/0/person_a",
        "message": "Unrecognized key: \"tzOffsetMinutes\"" }
    ]
  }
}
  • Annotate the wire names with @JsonProperty, as the records above do. Setting spring.jackson.property-naming-strategy: SNAKE_CASE also works, but it renames the JSON of every controller in your own API too.
  • Inject Spring's ObjectMapper rather than writing new ObjectMapper(). A bare mapper fails on unknown properties, so the first field the API adds to a match result would break deserialisation; @JsonIgnoreProperties(ignoreUnknown = true) makes the record safe either way.
  • Both endpoints need the Starter plan: POST /v1/compatibility/batch and GET /v1/reports/:id. For one couple at a time on a lower plan, use POST /v1/compatibility.

Questions

Which AstroNode endpoints does the Spring Boot example call?
2 endpoints: Bulk Kundli Matching (POST /v1/compatibility/batch); Report Status and Download (GET /v1/reports/:id).
Was the Spring Boot code on this page actually run?
AstroNodeClient was compiled with javac (Java 17) and run against the in-memory API: it queued the two-pair batch, polled the report and sent the camelCase body that produced the 400 below. The Spring classes (properties, service, controller) need Spring Boot and Jackson on the classpath and were not compiled - there is no Maven or Gradle on the build machine.